Debian Codegraph @

third_party/rust/fluent-fallback/examples/simple-fallback.rs

raw
1 //! This is an example of a simple application
2 //! which calculates the Collatz conjecture.
3 //!
4 //! The function itself is trivial on purpose,
5 //! so that we can focus on understanding how
6 //! the application can be made localizable
7 //! via Fluent.
8 //!
9 //! To try the app launch `cargo run --example simple-fallback NUM (LOCALES)`
10 //!
11 //! NUM is a number to be calculated, and LOCALES is an optional
12 //! parameter with a comma-separated list of locales requested by the user.
13 //!
14 //! Example:
15 //!
16 //! cargo run --example simple-fallback 123 de,pl
17 //!
18 //! If the second argument is omitted, `en-US` locale is used as the
19 //! default one.
20
21 use std::{env, fs, io, path::PathBuf, str::FromStr};
22
23 use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};
24 use fluent_fallback::{
25 generator::{BundleGenerator, FluentBundleResult},
26 types::ResourceId,
27 Localization,
28 };
29 use fluent_langneg::{negotiate_languages, NegotiationStrategy};
30
31 use rustc_hash::FxHashSet;
32 use unic_langid::{langid, LanguageIdentifier};
33
34 /// This helper struct holds the scheme for converting
35 /// resource paths into full paths. It is used to customise
36 /// `fluent-fallback::SyncLocalization`.
37 struct Bundles {
38 res_path_scheme: PathBuf,
39 }
40
41 /// This helper function allows us to read the list
42 /// of available locales by reading the list of
43 /// directories in `./examples/resources`.
44 ///
45 /// It is expected that every directory inside it
46 /// has a name that is a valid BCP47 language tag.
47 fn get_available_locales() -> io::Result<Vec<LanguageIdentifier>> {
48 let mut dir = env::current_dir()?;
49 if dir.to_string_lossy().ends_with("fluent-rs") {
50 dir.push("fluent-fallback");
51 }
52 dir.push("examples");
53 dir.push("resources");
54 let res_dir = fs::read_dir(dir)?;
55
56 let locales = res_dir
57 .into_iter()
58 .filter_map(|entry| entry.ok())
59 .filter(|entry| entry.path().is_dir())
60 .filter_map(|dir| {
61 let file_name = dir.file_name();
62 let name = file_name.to_str()?;
63 Some(name.parse().expect("Parsing failed."))
64 })
65 .collect();
66 Ok(locales)
67 }
68
69 fn resolve_app_locales<'l>(args: &[String]) -> Vec<LanguageIdentifier> {
70 let default_locale = langid!("en-US");
71 let available = get_available_locales().expect("Retrieving available locales failed.");
72
73 let requested: Vec<LanguageIdentifier> = args.get(2).map_or(vec![], |arg| {
74 arg.split(",")
75 .map(|s| s.parse().expect("Parsing locale failed."))
76 .collect()
77 });
78
79 negotiate_languages(
80 &requested,
81 &available,
82 Some(&default_locale),
83 NegotiationStrategy::Filtering,
84 )
85 .into_iter()
86 .cloned()
87 .collect()
88 }
89
90 fn get_resource_manager() -> Bundles {
91 let mut res_path_scheme = env::current_dir().expect("Failed to retrieve current dir.");
92
93 if res_path_scheme.to_string_lossy().ends_with("fluent-rs") {
94 res_path_scheme.push("fluent-fallback");
95 }
96 res_path_scheme.push("examples");
97 res_path_scheme.push("resources");
98
99 res_path_scheme.push("{locale}");
100 res_path_scheme.push("{res_id}");
101
102 Bundles { res_path_scheme }
103 }
104
105 static L10N_RESOURCES: &[&str] = &["simple.ftl"];
106
107 fn main() {
108 let args: Vec<String> = env::args().collect();
109
110 let app_locales: Vec<LanguageIdentifier> = resolve_app_locales(&args);
111
112 let bundles = get_resource_manager();
113
114 let loc = Localization::with_env(
115 L10N_RESOURCES.iter().map(|&res| res.into()),
116 true,
117 app_locales,
118 bundles,
119 );
120 let bundles = loc.bundles();
121
122 let mut errors = vec![];
123
124 match args.get(1) {
125 Some(input) => match isize::from_str(&input) {
126 Ok(i) => {
127 let mut args = FluentArgs::new();
128 args.set("input", i);
129 args.set("value", collatz(i));
130 let value = bundles
131 .format_value_sync("response-msg", Some(&args), &mut errors)
132 .unwrap()
133 .unwrap();
134 println!("{}", value);
135 }
136 Err(err) => {
137 let mut args = FluentArgs::new();
138 args.set("input", input.as_str());
139 args.set("reason", err.to_string());
140 let value = bundles
141 .format_value_sync("input-parse-error-msg", Some(&args), &mut errors)
142 .unwrap()
143 .unwrap();
144 println!("{}", value);
145 }
146 },
147 None => {
148 let value = bundles
149 .format_value_sync("missing-arg-error", None, &mut errors)
150 .unwrap()
151 .unwrap();
152 println!("{}", value);
153 }
154 }
155 }
156
157 /// Collatz conjecture calculating function.
158 fn collatz(n: isize) -> isize {
159 match n {
160 1 => 0,
161 _ => match n % 2 {
162 0 => 1 + collatz(n / 2),
163 _ => 1 + collatz(n * 3 + 1),
164 },
165 }
166 }
167
168 /// Bundle iterator used by BundleGeneratorSync implementation for Locales.
169 struct BundleIter {
170 res_path_scheme: String,
171 locales: <Vec<LanguageIdentifier> as IntoIterator>::IntoIter,
172 res_ids: FxHashSet<ResourceId>,
173 }
174
175 impl Iterator for BundleIter {
176 type Item = FluentBundleResult<FluentResource>;
177
178 fn next(&mut self) -> Option<Self::Item> {
179 let locale = self.locales.next()?;
180 let res_path_scheme = self
181 .res_path_scheme
182 .as_str()
183 .replace("{locale}", &locale.to_string());
184 let mut bundle = FluentBundle::new(vec![locale]);
185
186 let mut errors = vec![];
187
188 for res_id in &self.res_ids {
189 let res_path = res_path_scheme.as_str().replace("{res_id}", &res_id.value);
190 let source = fs::read_to_string(res_path).unwrap();
191 let res = match FluentResource::try_new(source) {
192 Ok(res) => res,
193 Err((res, err)) => {
194 errors.extend(err.into_iter().map(Into::into));
195 res
196 }
197 };
198 bundle.add_resource(res).unwrap();
199 }
200
201 if errors.is_empty() {
202 Some(Ok(bundle))
203 } else {
204 Some(Err((bundle, errors)))
205 }
206 }
207 }
208
209 impl futures::Stream for BundleIter {
210 type Item = FluentBundleResult<FluentResource>;
211
212 fn poll_next(
213 self: std::pin::Pin<&mut Self>,
214 _cx: &mut std::task::Context<'_>,
215 ) -> std::task::Poll<Option<Self::Item>> {
216 todo!()
217 }
218 }
219
220 impl BundleGenerator for Bundles {
221 type Resource = FluentResource;
222 type LocalesIter = std::vec::IntoIter<LanguageIdentifier>;
223 type Iter = BundleIter;
224 type Stream = BundleIter;
225
226 fn bundles_iter(
227 &self,
228 locales: std::vec::IntoIter<LanguageIdentifier>,
229 res_ids: FxHashSet<ResourceId>,
230 ) -> Self::Iter {
231 BundleIter {
232 res_path_scheme: self.res_path_scheme.to_string_lossy().to_string(),
233 locales,
234 res_ids,
235 }
236 }
237 }