| 1 | use std::fmt::Write; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | |
| 4 | fn main() { |
| 5 | // Cargo can reuse this build-script binary across worktrees sharing a |
| 6 | // target directory. Resolve the package being built at execution time. |
| 7 | let manifest_dir = |
| 8 | PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("manifest directory")); |
| 9 | println!("cargo:rerun-if-env-changed=CARGO_MANIFEST_DIR"); |
| 10 | codewhale_build_support::declare_rerun_conditions(&manifest_dir); |
| 11 | generate_localization(&manifest_dir); |
| 12 | } |
| 13 | |
| 14 | fn generate_localization(manifest_dir: &Path) { |
| 15 | let locales = manifest_dir.join("locales"); |
| 16 | println!("cargo:rerun-if-changed={}", locales.display()); |
| 17 | // Use the same loader as rust-i18n's macro, including flattening and |
| 18 | // locale merging. Store entries in static data rather than emitting one |
| 19 | // map.insert statement per translation into a huge debug-stack frame. |
| 20 | let translations = rust_i18n_support::try_load_locales( |
| 21 | locales.to_str().expect("UTF-8 locale path"), |
| 22 | |_| false, |
| 23 | true, |
| 24 | ) |
| 25 | .expect("valid translation catalog"); |
| 26 | assert!(!translations.is_empty(), "translation catalog is empty"); |
| 27 | let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")); |
| 28 | let mut data = String::from("static LOCALES: &[(&str, Messages)] = &[\n"); |
| 29 | for (locale, entries) in translations { |
| 30 | writeln!(data, "({locale:?}, &[").unwrap(); |
| 31 | for (key, value) in entries { |
| 32 | writeln!(data, "({key:?}, {value:?}),").unwrap(); |
| 33 | } |
| 34 | data.push_str("]),\n"); |
| 35 | } |
| 36 | data.push_str("];\n"); |
| 37 | std::fs::write(out.join("i18n_data.rs"), data).expect("write translation data"); |
| 38 | |
| 39 | let bootstrap = out.join("i18n_bootstrap"); |
| 40 | std::fs::create_dir_all(&bootstrap).expect("create i18n bootstrap directory"); |
| 41 | std::fs::write( |
| 42 | out.join("i18n_init.rs"), |
| 43 | format!( |
| 44 | "i18n!({:?}, fallback = [\"en\"], backend = crate::localization_backend::new());\n", |
| 45 | bootstrap.to_str().expect("UTF-8 build path") |
| 46 | ), |
| 47 | ) |
| 48 | .expect("write i18n bootstrap"); |
| 49 | } |
| 50 |