|
| 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 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 | +//! caron run --example simple 123 de,pl |
| 17 | +//! |
| 18 | +//! If the second argument is omitted, `en-US` locale is used as the |
| 19 | +//! default one. |
| 20 | +use fluent_bundle::bundle::FluentBundle; |
| 21 | +use fluent_bundle::types::FluentValue; |
| 22 | +use fluent_locale::{negotiate_languages, NegotiationStrategy}; |
| 23 | +use std::collections::HashMap; |
| 24 | +use std::env; |
| 25 | +use std::fs; |
| 26 | +use std::fs::File; |
| 27 | +use std::io; |
| 28 | +use std::io::prelude::*; |
| 29 | +use std::str::FromStr; |
| 30 | + |
| 31 | +/// We need a generic file read helper function to |
| 32 | +/// read the localization resource file. |
| 33 | +/// |
| 34 | +/// The resource files are stored in |
| 35 | +/// `./examples/resources/{locale}` directory. |
| 36 | +fn read_file(path: &str) -> Result<String, io::Error> { |
| 37 | + let mut f = File::open(path)?; |
| 38 | + let mut s = String::new(); |
| 39 | + f.read_to_string(&mut s)?; |
| 40 | + Ok(s) |
| 41 | +} |
| 42 | + |
| 43 | +/// This helper function allows us to read the list |
| 44 | +/// of available locales by reading the list of |
| 45 | +/// directories in `./examples/resources`. |
| 46 | +/// |
| 47 | +/// It is expected that every directory inside it |
| 48 | +/// has a name that is a valid BCP47 language tag. |
| 49 | +fn get_available_locales() -> Result<Vec<String>, io::Error> { |
| 50 | + let mut locales = vec![]; |
| 51 | + |
| 52 | + let res_dir = fs::read_dir("./examples/resources/")?; |
| 53 | + for entry in res_dir { |
| 54 | + if let Ok(entry) = entry { |
| 55 | + let path = entry.path(); |
| 56 | + if path.is_dir() { |
| 57 | + if let Some(name) = path.file_name() { |
| 58 | + if let Some(name) = name.to_str() { |
| 59 | + locales.push(String::from(name)); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + return Ok(locales); |
| 66 | +} |
| 67 | + |
| 68 | +/// This function negotiates the locales between available |
| 69 | +/// and requested by the user. |
| 70 | +/// |
| 71 | +/// It uses `fluent-locale` library but one could |
| 72 | +/// use any other that will resolve the list of |
| 73 | +/// available locales based on the list of |
| 74 | +/// requested locales. |
| 75 | +fn get_app_locales(requested: &[&str]) -> Result<Vec<String>, io::Error> { |
| 76 | + let available = get_available_locales()?; |
| 77 | + let resolved_locales = negotiate_languages( |
| 78 | + requested, |
| 79 | + &available, |
| 80 | + Some("en-US"), |
| 81 | + &NegotiationStrategy::Filtering, |
| 82 | + ); |
| 83 | + return Ok(resolved_locales |
| 84 | + .into_iter() |
| 85 | + .map(|s| String::from(s)) |
| 86 | + .collect::<Vec<String>>()); |
| 87 | +} |
| 88 | + |
| 89 | +static L10N_RESOURCES: &[&str] = &["simple.ftl"]; |
| 90 | + |
| 91 | +fn main() { |
| 92 | + // 1. Get the command line arguments. |
| 93 | + let args: Vec<String> = env::args().collect(); |
| 94 | + let mut sources: Vec<String> = vec![]; |
| 95 | + |
| 96 | + // 2. If the argument length is more than 1, |
| 97 | + // take the second argument as a comma-separated |
| 98 | + // list of requested locales. |
| 99 | + // |
| 100 | + // Otherwise, take ["en-US"] as the default. |
| 101 | + let requested = args |
| 102 | + .get(2) |
| 103 | + .map_or(vec!["en-US"], |arg| arg.split(",").collect()); |
| 104 | + |
| 105 | + // 3. Negotiate it against the avialable ones |
| 106 | + let locales = get_app_locales(&requested).expect("Failed to retrieve available locales"); |
| 107 | + |
| 108 | + // 4. Create a new Fluent FluentBundle using the |
| 109 | + // resolved locales. |
| 110 | + let mut bundle = FluentBundle::new(&locales); |
| 111 | + |
| 112 | + // 5. Load the localization resource |
| 113 | + for path in L10N_RESOURCES { |
| 114 | + let full_path = format!( |
| 115 | + "./examples/resources/{locale}/{path}", |
| 116 | + locale = locales[0], |
| 117 | + path = path |
| 118 | + ); |
| 119 | + let source = read_file(&full_path).unwrap(); |
| 120 | + sources.push(source); |
| 121 | + } |
| 122 | + |
| 123 | + for source in &sources { |
| 124 | + bundle.add_messages(&source).unwrap(); |
| 125 | + } |
| 126 | + |
| 127 | + // 6. Check if the input is provided. |
| 128 | + match args.get(1) { |
| 129 | + Some(input) => { |
| 130 | + // 6.1. Cast it to a number. |
| 131 | + match isize::from_str(&input) { |
| 132 | + Ok(i) => { |
| 133 | + // 6.2. Construct a map of arguments |
| 134 | + // to format the message. |
| 135 | + let mut args = HashMap::new(); |
| 136 | + args.insert("input", FluentValue::from(i)); |
| 137 | + args.insert("value", FluentValue::from(collatz(i))); |
| 138 | + // 6.3. Format the message. |
| 139 | + println!("{}", bundle.format("response-msg", Some(&args)).unwrap().0); |
| 140 | + } |
| 141 | + Err(err) => { |
| 142 | + let mut args = HashMap::new(); |
| 143 | + args.insert("input", FluentValue::from(input.to_string())); |
| 144 | + args.insert("reason", FluentValue::from(err.to_string())); |
| 145 | + println!( |
| 146 | + "{}", |
| 147 | + bundle |
| 148 | + .format("input-parse-error-msg", Some(&args)) |
| 149 | + .unwrap() |
| 150 | + .0 |
| 151 | + ); |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + None => { |
| 156 | + println!("{}", bundle.format("missing-arg-error", None).unwrap().0); |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +/// Collatz conjecture calculating function. |
| 162 | +fn collatz(n: isize) -> isize { |
| 163 | + match n { |
| 164 | + 1 => 0, |
| 165 | + _ => match n % 2 { |
| 166 | + 0 => 1 + collatz(n / 2), |
| 167 | + _ => 1 + collatz(n * 3 + 1), |
| 168 | + }, |
| 169 | + } |
| 170 | +} |
0 commit comments