Debian Codegraph @

src/uucore/build.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 use std::env;
7 use std::fs::File;
8 use std::io::Write;
9 use std::path::{Path, PathBuf};
10
11 pub fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let out_dir = env::var("OUT_DIR")?;
13
14 let mut embedded_file = File::create(Path::new(&out_dir).join("embedded_locales.rs"))?;
15 writeln!(embedded_file, "// Generated at compile time - do not edit")?;
16 writeln!(
17 embedded_file,
18 "// This file contains embedded English locale files"
19 )?;
20 writeln!(embedded_file)?;
21 // No imports needed for match-based lookup
22 writeln!(embedded_file)?;
23
24 // Generate optimized lookup function instead of HashMap
25 writeln!(embedded_file, "#[expect(clippy::match_same_arms)]")?; // needed for dir and vdir aliases for ls
26 writeln!(
27 embedded_file,
28 "pub fn get_embedded_locale(key: &str) -> Option<&'static str> {{"
29 )?;
30 writeln!(embedded_file, " match key {{")?;
31
32 // Try to detect if we're building for a specific utility by checking build configuration
33 // This attempts to identify individual utility builds vs multicall binary builds
34 let target_utility = detect_target_utility();
35 let locales_to_embed = get_locales_to_embed(env::var("LANG").ok());
36
37 match target_utility {
38 Some(util_name) => {
39 // Embed only the specific utility's locale (cat.ftl for cat for example)
40 embed_single_utility_locale(
41 &mut embedded_file,
42 &project_root()?,
43 &util_name,
44 &locales_to_embed,
45 )?;
46 }
47 None => {
48 // Embed all utility locales (multicall binary or fallback)
49 embed_all_utility_locales(&mut embedded_file, &project_root()?, &locales_to_embed)?;
50 }
51 }
52
53 writeln!(embedded_file, " _ => None,")?;
54 writeln!(embedded_file, " }}")?;
55 writeln!(embedded_file, "}}")?;
56
57 embedded_file.flush()?;
58 Ok(())
59 }
60
61 /// Get the project root directory
62 ///
63 /// # Errors
64 ///
65 /// Returns an error if the `CARGO_MANIFEST_DIR` environment variable is not set
66 /// or if the current directory structure does not allow determining the project root.
67 fn project_root() -> Result<PathBuf, Box<dyn std::error::Error>> {
68 let manifest_dir = env::var("CARGO_MANIFEST_DIR")?;
69 let uucore_path = Path::new(&manifest_dir);
70
71 // Navigate from src/uucore to project root
72 let project_root = uucore_path
73 .parent() // src/
74 .and_then(|p| p.parent()) // project root
75 .ok_or("Could not determine project root")?;
76
77 Ok(project_root.to_path_buf())
78 }
79
80 /// Attempt to detect which specific utility is being built
81 fn detect_target_utility() -> Option<String> {
82 use std::fs;
83
84 // Tell Cargo to rerun if this environment variable changes
85 println!("cargo:rerun-if-env-changed=UUCORE_TARGET_UTIL");
86
87 // First check if an explicit environment variable was set
88 if let Some(target_util) = env::var("UUCORE_TARGET_UTIL")
89 .ok()
90 .filter(|t| !t.is_empty())
91 {
92 return Some(target_util);
93 }
94
95 // Auto-detect utility name from CARGO_PKG_NAME if it's a uu_* package
96 if let Some(util_name) = env::var("CARGO_PKG_NAME")
97 .ok()
98 .and_then(|pkg| pkg.strip_prefix("uu_").map(String::from))
99 {
100 println!("cargo:warning=Auto-detected utility name: {util_name}");
101 return Some(util_name);
102 }
103
104 // Check for a build configuration file in the target directory
105 if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
106 let config_path = Path::new(&target_dir).join("uucore_target_util.txt");
107 if let Ok(content) = fs::read_to_string(&config_path) {
108 let util_name = content.trim();
109 if !util_name.is_empty() && util_name != "multicall" {
110 return Some(util_name.to_string());
111 }
112 }
113 }
114
115 // Fallback: Check the default target directory
116 if let Ok(project_root) = project_root() {
117 let config_path = project_root.join("target/uucore_target_util.txt");
118 if let Ok(content) = fs::read_to_string(&config_path) {
119 let util_name = content.trim();
120 if !util_name.is_empty() && util_name != "multicall" {
121 return Some(util_name.to_string());
122 }
123 }
124 }
125
126 // If no configuration found, assume multicall build
127 None
128 }
129
130 /// Embed locale for a single specific utility
131 ///
132 /// # Errors
133 ///
134 /// Returns an error if the locales for `util_name` or `uucore` cannot be found
135 /// or if writing to the `embedded_file` fails.
136 fn embed_single_utility_locale(
137 embedded_file: &mut File,
138 project_root: &Path,
139 util_name: &str,
140 locales_to_embed: &(String, Option<String>),
141 ) -> Result<(), Box<dyn std::error::Error>> {
142 // Embed utility-specific locales
143 embed_component_locales(embedded_file, locales_to_embed, util_name, |locale| {
144 project_root
145 .join("src/uu")
146 .join(util_name)
147 .join(format!("locales/{locale}.ftl"))
148 })?;
149
150 if util_name.ends_with("sum") {
151 embed_component_locales(
152 embedded_file,
153 locales_to_embed,
154 "checksum_common",
155 |locale| project_root.join(format!("src/uu/checksum_common/locales/{locale}.ftl")),
156 )?;
157 }
158
159 // Always embed uucore locale file if it exists
160 embed_component_locales(embedded_file, locales_to_embed, "uucore", |locale| {
161 project_root.join(format!("src/uucore/locales/{locale}.ftl"))
162 })?;
163
164 embed_error_locales(embedded_file, project_root, locales_to_embed)?;
165
166 Ok(())
167 }
168
169 /// Embed the strings only an error path asks for.
170 ///
171 /// They are embedded like any other component but parsed only when something
172 /// actually looks one up, so the common bundle every utility builds at startup
173 /// stays small.
174 ///
175 /// # Errors
176 ///
177 /// Returns an error if writing to the `embedded_file` fails.
178 fn embed_error_locales(
179 embedded_file: &mut File,
180 project_root: &Path,
181 locales_to_embed: &(String, Option<String>),
182 ) -> Result<(), Box<dyn std::error::Error>> {
183 embed_component_locales(embedded_file, locales_to_embed, "uucore-errors", |locale| {
184 project_root.join(format!("src/uucore/locales/errors/{locale}.ftl"))
185 })
186 }
187
188 /// Embed locale files for all utilities (multicall binary).
189 ///
190 /// # Errors
191 ///
192 /// Returns an error if the `src/uu` directory cannot be read, if any utility
193 /// locales cannot be embedded, or if flushing the `embedded_file` fails.
194 fn embed_all_utility_locales(
195 embedded_file: &mut File,
196 project_root: &Path,
197 locales_to_embed: &(String, Option<String>),
198 ) -> Result<(), Box<dyn std::error::Error>> {
199 use std::fs;
200
201 // Discover all uu_* directories
202 let src_uu_dir = project_root.join("src/uu");
203 if !src_uu_dir.exists() {
204 // When src/uu doesn't exist (e.g., standalone uucore from crates.io),
205 // embed a static list of utility locales that are commonly used
206 embed_static_utility_locales(embedded_file, locales_to_embed)?;
207 return Ok(());
208 }
209
210 let mut util_dirs = Vec::new();
211 for entry in fs::read_dir(&src_uu_dir)? {
212 let entry = entry?;
213 if entry.file_type()?.is_dir()
214 && let Some(dir_name) = entry.file_name().to_str()
215 {
216 util_dirs.push(dir_name.to_string());
217 }
218 }
219 util_dirs.sort();
220
221 // Embed locale files for each utility
222 for util_name in &util_dirs {
223 embed_component_locales(embedded_file, locales_to_embed, util_name, |locale| {
224 src_uu_dir
225 .join(util_name)
226 .join(format!("locales/{locale}.ftl"))
227 })?;
228 }
229
230 // Also embed uucore locale file if it exists
231 embed_component_locales(embedded_file, locales_to_embed, "uucore", |locale| {
232 project_root.join(format!("src/uucore/locales/{locale}.ftl"))
233 })?;
234
235 embed_error_locales(embedded_file, project_root, locales_to_embed)?;
236
237 embedded_file.flush()?;
238 Ok(())
239 }
240
241 /// Embed static utility locales for crates.io builds.
242 ///
243 /// # Errors
244 ///
245 /// Returns an error if the directory containing the crate cannot be read or
246 /// if writing to the `embedded_file` fails.
247 fn embed_static_utility_locales(
248 embedded_file: &mut File,
249 locales_to_embed: &(String, Option<String>),
250 ) -> Result<(), Box<dyn std::error::Error>> {
251 use std::env;
252
253 writeln!(
254 embedded_file,
255 " // Static utility locales for crates.io builds"
256 )?;
257
258 let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
259 let Some(registry_dir) = Path::new(&manifest_dir).parent() else {
260 return Ok(()); // nothing to scan
261 };
262
263 // Which utilities we embed here depends on the crates unpacked next to us
264 // in the registry, i.e. on what the consumer depends on. Cargo only knows
265 // about the files we declare, so without watching the consumer's lock file
266 // a utility added after the first build would keep printing raw message
267 // ids until uucore is rebuilt by hand.
268 if let Some(lock_file) = consumer_lock_file(env::var_os("OUT_DIR").as_deref()) {
269 println!("cargo:rerun-if-changed={}", lock_file.display());
270 }
271
272 // First, try to embed uucore locales - critical for common translations like "Usage:"
273 embed_component_locales(embedded_file, locales_to_embed, "uucore", |locale| {
274 Path::new(&manifest_dir).join(format!("locales/{locale}.ftl"))
275 })?;
276
277 embed_component_locales(embedded_file, locales_to_embed, "uucore-errors", |locale| {
278 Path::new(&manifest_dir).join(format!("locales/errors/{locale}.ftl"))
279 })?;
280
281 // Collect and sort for deterministic builds
282 let mut entries: Vec<_> = std::fs::read_dir(registry_dir)?
283 .filter_map(Result::ok)
284 .collect();
285 entries.sort_by_key(std::fs::DirEntry::file_name);
286
287 for entry in entries {
288 let file_name = entry.file_name();
289 if let Some(dir_name) = file_name.to_str() &&
290 // Match uu_<util>-<version>
291 let Some((util_part, _)) = dir_name.split_once('-') &&
292 let Some(util_name) = util_part.strip_prefix("uu_")
293 {
294 embed_component_locales(embedded_file, locales_to_embed, util_name, |locale| {
295 entry.path().join(format!("locales/{locale}.ftl"))
296 })?;
297 }
298 }
299
300 Ok(())
301 }
302
303 /// Find the `Cargo.lock` of the project we are being built for, by walking up
304 /// from `OUT_DIR` (`<target>/<profile>/build/uucore-<hash>/out`) until a lock
305 /// file shows up next to a target directory.
306 ///
307 /// Returns `None` when there is none to watch, e.g. for a build with a target
308 /// directory outside of the project.
309 fn consumer_lock_file(out_dir: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
310 Path::new(out_dir?)
311 .ancestors()
312 .map(|dir| dir.join("Cargo.lock"))
313 .find(|lock| lock.is_file())
314 }
315
316 /// Determines which locales to embed into the binary.
317 ///
318 /// To support localized messages in installed binaries (e.g., via `cargo install`),
319 /// this function identifies the user's current locale from the `LANG` environment
320 /// variable.
321 ///
322 /// It always includes "en-US" to ensure that a fallback is available if the
323 /// system locale's translation file is missing or if `LANG` is not set.
324 fn get_locales_to_embed(env: Option<String>) -> (String, Option<String>) {
325 let system_locale = env
326 .as_deref()
327 .and_then(|s| s.split('.').next())
328 .map(|s| s.replace('_', "-"))
329 .filter(|s| !s.is_empty() && s != "en-US");
330
331 ("en-US".to_string(), system_locale)
332 }
333
334 /// Helper function to iterate over the locales to embed.
335 ///
336 /// # Errors
337 ///
338 /// Returns an error if the provided closure `f` returns an error when called
339 /// on either the primary or system locale.
340 fn for_each_locale<F>(
341 locales: &(String, Option<String>),
342 mut f: F,
343 ) -> Result<(), Box<dyn std::error::Error>>
344 where
345 F: FnMut(&str) -> Result<(), Box<dyn std::error::Error>>,
346 {
347 f(&locales.0)?;
348 if let Some(ref system_locale) = locales.1 {
349 f(system_locale)?;
350 }
351 Ok(())
352 }
353
354 /// Helper function to embed a single locale file.
355 ///
356 /// # Errors
357 ///
358 /// Returns an error if the file at `locale_path` cannot be read or if
359 /// writing to `embedded_file` fails.
360 fn embed_locale_file(
361 embedded_file: &mut File,
362 locale_path: &Path,
363 locale_key: &str,
364 locale: &str,
365 component: &str,
366 ) -> Result<(), Box<dyn std::error::Error>> {
367 use std::fs;
368
369 if locale_path.exists() || locale_path.is_file() {
370 let content = fs::read_to_string(locale_path)?;
371 writeln!(
372 embedded_file,
373 " // Locale for {component} ({locale})"
374 )?;
375 // Never a raw string: `r#"..."#` ends at `"#`, so content holding that
376 // pair closes the literal and the rest is compiled as Rust. `{:?}`
377 // escapes every quote and has no terminator the content can reach.
378 writeln!(
379 embedded_file,
380 " {locale_key:?} => Some({content:?}),"
381 )?;
382
383 // Tell Cargo to rerun if this file changes
384 println!("cargo:rerun-if-changed={}", locale_path.display());
385 }
386 Ok(())
387 }
388
389 /// Higher-level helper to embed locale files for a component with a path pattern.
390 ///
391 /// This eliminates the repetitive `for_each_locale` + `embed_locale_file` pattern.
392 ///
393 /// # Errors
394 ///
395 /// Returns an error if `for_each_locale` fails, which typically happens if
396 /// reading a locale file or writing to the `embedded_file` fails.
397 /// Check if we are cross-compiling for WASI (build.rs runs on the host,
398 /// so `#[cfg(target_os = "wasi")]` does not work here).
399 fn is_wasi_target() -> bool {
400 env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "wasi")
401 }
402
403 /// For WASI/WASM builds, embed ALL available .ftl files in a locale
404 /// directory so the playground can switch languages at runtime.
405 fn embed_all_locales_for_component<F>(
406 embedded_file: &mut File,
407 component_name: &str,
408 path_builder: &F,
409 ) -> Result<(), Box<dyn std::error::Error>>
410 where
411 F: Fn(&str) -> PathBuf,
412 {
413 let en_path = path_builder("en-US");
414 if let Some(locale_dir) = en_path.parent().filter(|l| l.exists()) {
415 for entry in std::fs::read_dir(locale_dir)? {
416 let entry = entry?;
417 let path = entry.path();
418 if path.extension().is_some_and(|e| e == "ftl")
419 && let Some(locale) = path.file_stem().and_then(|s| s.to_str())
420 {
421 embed_locale_file(
422 embedded_file,
423 &path,
424 &format!("{component_name}/{locale}.ftl"),
425 locale,
426 component_name,
427 )?;
428 }
429 }
430 }
431 Ok(())
432 }
433
434 fn embed_component_locales<F>(
435 embedded_file: &mut File,
436 locales: &(String, Option<String>),
437 component_name: &str,
438 path_builder: F,
439 ) -> Result<(), Box<dyn std::error::Error>>
440 where
441 F: Fn(&str) -> PathBuf,
442 {
443 if is_wasi_target() {
444 return embed_all_locales_for_component(embedded_file, component_name, &path_builder);
445 }
446
447 for_each_locale(locales, |locale| {
448 let locale_path = path_builder(locale);
449 embed_locale_file(
450 embedded_file,
451 &locale_path,
452 &format!("{component_name}/{locale}.ftl"),
453 locale,
454 component_name,
455 )
456 })
457 }
458
459 #[cfg(test)]
460 mod tests {
461 use super::*;
462
463 #[test]
464 fn consumer_lock_file_found_above_target_dir() {
465 let tmp = std::env::temp_dir().join(format!("uucore-build-{}", std::process::id()));
466 let out_dir = tmp.join("target/debug/build/uucore-1234/out");
467 std::fs::create_dir_all(&out_dir).unwrap();
468 assert_eq!(consumer_lock_file(Some(out_dir.as_os_str())), None);
469
470 let lock = tmp.join("Cargo.lock");
471 std::fs::write(&lock, "").unwrap();
472 assert_eq!(consumer_lock_file(Some(out_dir.as_os_str())), Some(lock));
473
474 assert_eq!(consumer_lock_file(None), None);
475 std::fs::remove_dir_all(&tmp).unwrap();
476 }
477
478 #[test]
479 fn get_locales_to_embed_no_lang() {
480 let (en_locale, system_locale) = get_locales_to_embed(None);
481 assert_eq!(en_locale, "en-US");
482 assert_eq!(system_locale, None);
483
484 let (en_locale, system_locale) = get_locales_to_embed(Some(String::new().into()));
485 assert_eq!(en_locale, "en-US");
486 assert_eq!(system_locale, None);
487
488 let (en_locale, system_locale) = get_locales_to_embed(Some("en_US.UTF-8".to_string()));
489 assert_eq!(en_locale, "en-US");
490 assert_eq!(system_locale, None);
491 }
492
493 #[test]
494 fn get_locales_to_embed_with_lang() {
495 let (en_locale, system_locale) = get_locales_to_embed(Some("fr_FR.UTF-8".to_string()));
496 assert_eq!(en_locale, "en-US");
497 assert_eq!(system_locale, Some("fr-FR".to_string()));
498
499 let (en_locale, system_locale) = get_locales_to_embed(Some("zh_CN.UTF-8".to_string()));
500 assert_eq!(en_locale, "en-US");
501 assert_eq!(system_locale, Some("zh-CN".to_string()));
502
503 let (en_locale, system_locale) = get_locales_to_embed(Some("de".to_string()));
504 assert_eq!(en_locale, "en-US");
505 assert_eq!(system_locale, Some("de".to_string()));
506 }
507
508 #[test]
509 fn get_locales_to_embed_invalid_lang() {
510 // invalid locale format
511 let (en_locale, system_locale) = get_locales_to_embed(Some("invalid".to_string()));
512 assert_eq!(en_locale, "en-US");
513 assert_eq!(system_locale, Some("invalid".to_string()));
514
515 // numeric values
516 let (en_locale, system_locale) = get_locales_to_embed(Some("123".to_string()));
517 assert_eq!(en_locale, "en-US");
518 assert_eq!(system_locale, Some("123".to_string()));
519
520 // special characters
521 let (en_locale, system_locale) = get_locales_to_embed(Some("@@@@".to_string()));
522 assert_eq!(en_locale, "en-US");
523 assert_eq!(system_locale, Some("@@@@".to_string()));
524
525 // malformed locale (no country code but with encoding)
526 let (en_locale, system_locale) = get_locales_to_embed(Some("en.UTF-8".to_string()));
527 assert_eq!(en_locale, "en-US");
528 assert_eq!(system_locale, Some("en".to_string()));
529
530 // valid format but unusual locale
531 let (en_locale, system_locale) = get_locales_to_embed(Some("XX_YY.UTF-8".to_string()));
532 assert_eq!(en_locale, "en-US");
533 assert_eq!(system_locale, Some("XX-YY".to_string()));
534 }
535
536 #[test]
537 fn for_each_locale_basic() {
538 let locales = ("en-US".to_string(), Some("fr-FR".to_string()));
539 let mut collected = Vec::new();
540
541 for_each_locale(&locales, |locale| {
542 collected.push(locale.to_string());
543 Ok(())
544 })
545 .unwrap();
546
547 assert_eq!(collected, vec!["en-US", "fr-FR"]);
548 }
549
550 #[test]
551 fn for_each_locale_no_system_locale() {
552 let locales = ("en-US".to_string(), None);
553 let mut collected = Vec::new();
554
555 for_each_locale(&locales, |locale| {
556 collected.push(locale.to_string());
557 Ok(())
558 })
559 .unwrap();
560
561 assert_eq!(collected, vec!["en-US"]);
562 }
563
564 #[test]
565 fn for_each_locale_error_handling() {
566 let locales = ("en-US".to_string(), Some("fr-FR".to_string()));
567
568 let result = for_each_locale(&locales, |_locale| Err("test error".into()));
569
570 assert!(result.is_err());
571 }
572 }