Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove snafu #60

Merged
merged 2 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Remove unused `lazy_static`, replace `snafu` with `thiserror`, bump `flume` to `0.11`

## [0.9.1](https://github.com/XAMPPRocky/fluent-templates/compare/fluent-templates-v0.9.0...fluent-templates-v0.9.1) - 2024-03-10

### Other
Expand Down
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ license.workspace = true
repository.workspace = true
version.workspace = true
resolver = "2"
rust-version = "1.70.0"

[workspace.package]
edition = "2021"
Expand All @@ -37,18 +38,17 @@ use-ignore = ["ignore", "fluent-template-macros/ignore"]

[dependencies]
handlebars = { version = "5", optional = true }
lazy_static = "1.2.0"
fluent = "0.16"
fluent-bundle = "0.15.2"
fluent-syntax = "0.11"
fluent-langneg = "0.13"
serde_json = "1.0.79"
unic-langid = { version = "0.9.0", features = ["macros"] }
snafu = "0.7.0"
thiserror = "1.0.58"
tera = { version = "1.15.0", optional = true, default-features = false }
heck = "0.4.0"
ignore = { version = "0.4.18", optional = true }
flume = { version = "0.10.12", default-features = false }
flume = { version = "0.11.0", default-features = false }
log = "0.4.14"
fluent-template-macros = { path = "./macros", optional = true, version = "0.9.1" }
once_cell = "1.10.0"
Expand Down
5 changes: 4 additions & 1 deletion macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,10 @@ pub fn static_loader(input: proc_macro::TokenStream) -> proc_macro::TokenStream

let mut insert_resources: Vec<_> = build_resources(locales_directory).into_iter().collect();

if insert_resources.iter().find(|(lang, _)| *lang == fallback_language.value()).is_none() {
if !insert_resources
.iter()
.any(|(lang, _)| *lang == fallback_language.value())
{
return syn::Error::new(
fallback_language.span(),
"Fallback language not found in locales directory",
Expand Down
11 changes: 5 additions & 6 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
use std::fmt;

/// Errors that can occur when loading or parsing fluent resources.
#[derive(Debug, snafu::Snafu)]
#[snafu(visibility(pub(crate)))]
#[derive(Debug, thiserror::Error)]
pub enum LoaderError {
/// An `io::Error` occurred while interacting with `path`.
#[snafu(display("Error with {}\n: {}", path.display(), source))]
#[error("Error with {}\n: {}", path.display(), source)]
Fs {
/// The path to file with the error.
path: std::path::PathBuf,
/// The error source.
source: std::io::Error,
},
/// An error was found in the fluent syntax.
#[snafu(display("Error parsing Fluent\n: {}", source))]
#[error("Error parsing Fluent\n: {}", source)]
Fluent {
/// The original parse errors
#[snafu(source(from(Vec<fluent_syntax::parser::ParserError>, FluentError::from)))]
#[from]
source: FluentError,
},
/// An error was found whilst loading a bundle at runtime.
#[snafu(display("Failed to add FTL resources to the bundle"))]
#[error("Failed to add FTL resources to the bundle")]
FluentBundle {
/// The original bundle errors
errors: Vec<fluent_bundle::FluentError>,
Expand Down
11 changes: 7 additions & 4 deletions src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@ use std::fs;
use std::path::Path;

use fluent_bundle::FluentResource;
use snafu::*;
pub use unic_langid::{langid, langids, LanguageIdentifier};

use crate::error;

pub fn read_from_file<P: AsRef<Path>>(path: P) -> crate::Result<FluentResource> {
let path = path.as_ref();
resource_from_str(&fs::read_to_string(path).context(error::FsSnafu { path })?)
resource_from_str(
&fs::read_to_string(path).map_err(|source| error::LoaderError::Fs {
path: path.into(),
source,
})?,
)
}

pub fn resource_from_str(src: &str) -> crate::Result<FluentResource> {
FluentResource::try_new(src.to_owned())
.map_err(|(_, errs)| errs)
.context(error::FluentSnafu)
.map_err(|(_, errs)| error::FluentError::from(errs).into())
}

pub fn resources_from_vec(srcs: &[String]) -> crate::Result<Vec<FluentResource>> {
Expand Down
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,6 @@
//! [`handlebars::Context`]: https://docs.rs/handlebars/3.1.0/handlebars/struct.Context.html
#![warn(missing_docs)]

#[doc(hidden)]
pub extern crate lazy_static;

#[doc(hidden)]
pub extern crate fluent_bundle;

Expand Down
16 changes: 4 additions & 12 deletions src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,16 +225,8 @@ pub fn build_bundles(
bundles
}

fn map_to_fluent_args<'map, T: AsRef<str>>(
map: Option<&'map HashMap<T, FluentValue>>,
) -> Option<FluentArgs<'map>> {
let mut new = FluentArgs::new();

if let Some(map) = map {
for (key, value) in map {
new.set(key.as_ref(), value.clone());
}
}

Some(new)
fn map_to_fluent_args<'map, T: AsRef<str>>(map: &'map HashMap<T, FluentValue>) -> FluentArgs<'map> {
map.iter()
.map(|(key, value)| (key.as_ref(), value.clone()))
.collect()
}
2 changes: 1 addition & 1 deletion src/loader/arc_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl super::Loader for ArcLoader {
return val;
}
}
format!("Unknown localization {}", text_id)
format!("Unknown localization {text_id}")
}

// Traverse the fallback chain,
Expand Down
15 changes: 5 additions & 10 deletions src/loader/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,23 @@ pub fn lookup_single_language<T: AsRef<str>, R: Borrow<FluentResource>>(
) -> Option<String> {
let bundle = bundles.get(lang)?;
let mut errors = Vec::new();
let pattern = if text_id.contains('.') {
// TODO: #![feature(str_split_once)]
let ids: Vec<_> = text_id.splitn(2, '.').collect();
let pattern = if let Some((msg, attr)) = text_id.split_once('.') {
bundle
.get_message(ids[0])?
.get_message(msg)?
.attributes()
.find(|attribute| attribute.id() == ids[1])?
.find(|attribute| attribute.id() == attr)?
.value()
} else {
bundle.get_message(text_id)?.value()?
};

let args = super::map_to_fluent_args(args);
let args = args.map(super::map_to_fluent_args);
let value = bundle.format_pattern(pattern, args.as_ref(), &mut errors);

if errors.is_empty() {
Some(value.into())
} else {
panic!(
"Failed to format a message for locale {} and id {}.\nErrors\n{:?}",
lang, text_id, errors
)
panic!("Failed to format a message for locale {lang} and id {text_id}.\nErrors\n{errors:?}")
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/loader/static_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl super::Loader for StaticLoader {
return val;
}
}
format!("Unknown localization {}", text_id)
format!("Unknown localization {text_id}")
}

// Traverse the fallback chain,
Expand Down
19 changes: 9 additions & 10 deletions src/loader/tera.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use fluent_bundle::FluentValue;
use serde_json::Value as Json;
use snafu::OptionExt;
use std::collections::HashMap;
use unic_langid::LanguageIdentifier;

Expand All @@ -9,15 +8,15 @@ use crate::Loader;
const LANG_KEY: &str = "lang";
const FLUENT_KEY: &str = "key";

#[derive(Debug, snafu::Snafu)]
#[derive(Debug, thiserror::Error)]
enum Error {
#[snafu(display("No `lang` argument provided."))]
#[error("No `lang` argument provided.")]
NoLangArgument,
#[snafu(display("`lang` must be a valid unicode language identifier."))]
#[error("`lang` must be a valid unicode language identifier.")]
LangArgumentInvalid,
#[snafu(display("No `id` argument provided."))]
#[error("No `id` argument provided.")]
NoFluentArgument,
#[snafu(display("Couldn't convert JSON to Fluent value."))]
#[error("Couldn't convert JSON to Fluent value.")]
JsonToFluentFail,
}

Expand All @@ -38,10 +37,10 @@ fn json_to_fluent(json: Json) -> crate::Result<FluentValue<'static>, Error> {

fn parse_language(arg: &Json) -> crate::Result<LanguageIdentifier, Error> {
arg.as_str()
.context(self::LangArgumentInvalidSnafu)?
.ok_or(Error::LangArgumentInvalid)?
.parse::<LanguageIdentifier>()
.ok()
.context(self::LangArgumentInvalidSnafu)
.ok_or(Error::LangArgumentInvalid)
}

impl<L: Loader + Send + Sync> tera::Function for crate::FluentLoader<L> {
Expand All @@ -50,12 +49,12 @@ impl<L: Loader + Send + Sync> tera::Function for crate::FluentLoader<L> {
let lang = lang_arg
.as_ref()
.or(self.default_lang.as_ref())
.context(self::NoLangArgumentSnafu)?;
.ok_or(Error::NoLangArgument)?;

let id = args
.get(FLUENT_KEY)
.and_then(Json::as_str)
.context(self::NoFluentArgumentSnafu)?;
.ok_or(Error::NoFluentArgument)?;

/// Filters kwargs to exclude ones used by this function and tera.
fn is_not_tera_key((k, _): &(&String, &Json)) -> bool {
Expand Down
Loading