This repository was archived by the owner on Mar 11, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 213
I18n #434
Draft
jhoobergs
wants to merge
3
commits into
askama-rs:main
Choose a base branch
from
jhoobergs:i18n-check
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
I18n #434
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -135,3 +135,86 @@ pub mod mime { | |
| note = "file-level dependency tracking is handled automatically without build script" | ||
| )] | ||
| pub fn rerun_if_templates_changed() {} | ||
|
|
||
| #[macro_export] | ||
| macro_rules! init_translation { | ||
| ( | ||
| $v: vis $n: ident { | ||
| static_loader_name: $static_loader_name: ident, | ||
| locales: $locales: expr, | ||
| fallback_language: $fallback_language: expr, | ||
| customise: $customise: expr | ||
| } | ||
| ) => { | ||
| use fluent_templates::Loader; | ||
| fluent_templates::static_loader! { | ||
| // Declare our `StaticLoader` named `LOCALES`. | ||
| static $static_loader_name = { | ||
| // The directory of localisations and fluent resources. | ||
| locales: $locales, | ||
| // The language to falback on if something is not present. | ||
| fallback_language: $fallback_language, | ||
| // Optional: A fluent resource that is shared with every locale. | ||
| //core_locales: "/core.ftl", | ||
| // Removes unicode isolating marks around arguments, you typically | ||
| // should only set to false when testing. | ||
| customise: $customise, | ||
| }; | ||
| } | ||
| $v struct $n { | ||
| language: unic_langid::LanguageIdentifier, | ||
| loader: &'static fluent_templates::once_cell::sync::Lazy<fluent_templates::StaticLoader> | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need to be able to access this loader somehow. That's the reason for this struct. |
||
| } | ||
| impl $n { | ||
| pub fn new(language: unic_langid::LanguageIdentifier) -> $n { | ||
| $n { | ||
| language, | ||
| loader: & $static_loader_name | ||
| } | ||
| } | ||
| pub fn default() -> $n { | ||
| $n { | ||
| language: unic_langid::langid!($fallback_language), | ||
| loader: & $static_loader_name | ||
| } | ||
| } | ||
| } | ||
| impl $n { | ||
| fn get_fallback_language(&self) -> unic_langid::LanguageIdentifier { | ||
| unic_langid::langid!($fallback_language) | ||
| } | ||
|
|
||
| fn get_language(&self) -> unic_langid::LanguageIdentifier { | ||
| self.language.clone() | ||
| } | ||
|
|
||
| fn translate( | ||
| &self, | ||
| text_id: &str, | ||
| args: | ||
| &std::collections::HashMap<String, fluent_templates::fluent_bundle::FluentValue<'_>>, | ||
| ) -> String { | ||
| self.loader.lookup_with_args(&self.language, text_id, args) | ||
| } | ||
|
|
||
| fn has_default_translation(&self, m: &str) -> bool { | ||
| // lookup_single_language panic's when invalid args are given | ||
| std::panic::set_hook(Box::new(|_info| { | ||
| // do nothing | ||
| })); | ||
|
|
||
| let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | ||
| self.loader.lookup_single_language(&self.get_fallback_language(), m, None) | ||
| })); | ||
|
|
||
| let _ = std::panic::take_hook(); | ||
|
|
||
| match result { | ||
| Ok(None) => false, | ||
| _ => true | ||
| } | ||
| } | ||
| } | ||
|
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,7 +10,7 @@ use proc_macro2::Span; | |
|
|
||
| use quote::{quote, ToTokens}; | ||
|
|
||
| use std::collections::HashMap; | ||
| use std::collections::{BTreeSet, HashMap}; | ||
| use std::path::PathBuf; | ||
| use std::{cmp, hash, mem, str}; | ||
|
|
||
|
|
@@ -48,6 +48,8 @@ struct Generator<'a, S: std::hash::BuildHasher> { | |
| buf_writable: Vec<Writable<'a>>, | ||
| // Counter for write! hash named arguments | ||
| named: usize, | ||
| // Messages used with localize() | ||
| localized_messages: BTreeSet<String>, | ||
| } | ||
|
|
||
| impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { | ||
|
|
@@ -69,6 +71,7 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { | |
| super_block: None, | ||
| buf_writable: vec![], | ||
| named: 0, | ||
| localized_messages: BTreeSet::new(), | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -94,6 +97,7 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { | |
|
|
||
| self.impl_template(ctx, &mut buf)?; | ||
| self.impl_display(&mut buf)?; | ||
| self.impl_tests(&mut buf)?; | ||
|
|
||
| if self.integrations.actix { | ||
| self.impl_actix_web_responder(&mut buf)?; | ||
|
|
@@ -211,6 +215,53 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { | |
| buf.writeln("}") | ||
| } | ||
|
|
||
| // Implement Tests | ||
| fn impl_tests(&mut self, buf: &mut Buffer) -> Result<(), CompileError> { | ||
| buf.writeln(&format!( | ||
| "#[cfg(test)] mod __{}_tests_generated {{", | ||
| self.input.ast.ident.to_string().to_lowercase() | ||
| ))?; | ||
| // TODO | ||
| //if cfg!(feature = "with-i18n") { | ||
| self.impl_i18n_tests(buf)?; | ||
| //} | ||
|
|
||
| buf.writeln("}") | ||
| } | ||
|
|
||
| fn impl_i18n_tests(&mut self, buf: &mut Buffer) -> Result<(), CompileError> { | ||
| let messages = &self.localized_messages; | ||
| if messages.len() > 0 { | ||
| let loc_ty = self.input.localizer.as_ref().unwrap().1; | ||
| let ast = (quote! { | ||
|
|
||
|
|
||
| #[test] | ||
| fn test_i18n_default_coverage() { | ||
| let messages = &[ | ||
| #(#messages),* | ||
| ][..]; | ||
|
|
||
| // create default localizer | ||
| let localizer = super::#loc_ty::default(); | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here we need to be able to somehow access the static loader. Currently an object of the generated struct type is used for that. |
||
|
|
||
| let bad = messages.iter().filter(|m| !localizer.has_default_translation(m)).collect::<Vec<_>>(); | ||
|
|
||
| if bad.len() > 0 { | ||
| panic!("Missing translations in default locale ({}) for messages: {:?} ", | ||
| localizer.get_language().to_string(), bad); | ||
| } | ||
| } | ||
| }) | ||
| .to_string(); | ||
|
|
||
| buf.writeln(&ast) | ||
| } else { | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
|
|
||
| // Implement Actix-web's `Responder`. | ||
| fn impl_actix_web_responder(&mut self, buf: &mut Buffer) -> Result<(), CompileError> { | ||
| self.write_header(buf, "::actix_web::Responder", None)?; | ||
|
|
@@ -1118,6 +1169,9 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { | |
| self.visit_method_call(buf, obj, method, args)? | ||
| } | ||
| Expr::RustMacro(name, args) => self.visit_rust_macro(buf, name, args), | ||
| Expr::Localize(message, attribute, ref args) => { | ||
| self.visit_localize(buf, message, attribute, args)? | ||
| } | ||
| }) | ||
| } | ||
|
|
||
|
|
@@ -1367,6 +1421,60 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { | |
| Ok(DisplayWrap::Unwrapped) | ||
| } | ||
|
|
||
| fn visit_localize( | ||
| &mut self, | ||
| buf: &mut Buffer, | ||
| message: &str, | ||
| attribute: Option<&str>, | ||
| args: &[(&str, Expr)], | ||
| ) -> Result<DisplayWrap, CompileError> { | ||
| /* TODO | ||
| if !cfg!(feature = "with-i18n") { | ||
| panic!( | ||
| "The askama feature 'with-i18n' must be activated to enable calling `localize`." | ||
| ); | ||
| } | ||
| */ | ||
|
|
||
| // TODO | ||
| let localizer = self.input.localizer.as_ref().expect( | ||
| "A template struct must have a member with the `#[localizer]` \ | ||
| attribute that implements `askama::Localize` to enable calling the localize() filter", | ||
| ); | ||
|
|
||
| let mut message = message.to_string(); | ||
| if let Some(attribute) = attribute { | ||
| message.push_str("."); | ||
| message.push_str(attribute); | ||
| } | ||
|
|
||
| assert!( | ||
| message.chars().find(|c| *c == '"').is_none(), | ||
| "message ids with quotes in them break the generator, please remove" | ||
| ); | ||
|
|
||
| self.localized_messages.insert(message.clone()); | ||
|
|
||
| buf.write(&format!( | ||
| "self.{}.translate(\"{}\", &std::iter::FromIterator::from_iter(vec![", | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here we need to be able to call the translate method. Currently it uses the Localizer object that has to be added to all Template structs. |
||
| localizer.0, message | ||
| )); | ||
|
|
||
| for (i, (name, value)) in args.iter().enumerate() { | ||
| if i > 0 { | ||
| buf.write(", "); | ||
| } | ||
| buf.write(&format!( | ||
| "(\"{}\".to_string(), ({}).into())", | ||
| name, | ||
| self.visit_expr_root(value)? | ||
| )); | ||
| } | ||
| buf.write("]))"); | ||
|
|
||
| Ok(DisplayWrap::Unwrapped) | ||
| } | ||
|
|
||
| fn visit_unary( | ||
| &mut self, | ||
| buf: &mut Buffer, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The fallback language can be added to the toml file.