Skip to main content

Library/Fn/NLS/
Replace.rs

1//! NLS key replacement transform
2//!
3//! Replaces NLS keys with actual localized strings at build time.
4//! This is used when inlining translations into the output.
5
6use std::collections::HashMap;
7
8use regex::Regex;
9
10/// Replaces NLS localization calls with actual string values
11pub struct NLSReplacer {
12	/// The localization bundle to use for replacements
13	bundle:HashMap<String, String>,
14
15	/// Whether to preserve the localize call structure
16	preserve_calls:bool,
17
18	/// Regex patterns for localize calls
19	localize_pattern:Regex,
20
21	_localize2_pattern:Regex,
22}
23
24impl NLSReplacer {
25	pub fn new(bundle:HashMap<String, String>) -> Self {
26		Self {
27			bundle,
28
29			preserve_calls:false,
30
31			localize_pattern:Regex::new(r#"(?:nls\.)?localize\s*\(\s*['"]([^'"]+)['"]"#).unwrap(),
32
33			_localize2_pattern:Regex::new(r#"(?:nls\.)?localize2\s*\(\s*['"]([^'"]+)['"]"#).unwrap(),
34		}
35	}
36
37	pub fn with_preserve_calls(mut self, preserve:bool) -> Self {
38		self.preserve_calls = preserve;
39		self
40	}
41
42	/// Replace NLS keys in source code
43	pub fn replace(&self, source:&str) -> String {
44		let mut result = source.to_string();
45
46		// Replace localize calls
47		if let Some(caps) = self.localize_pattern.captures(&result) {
48			if let Some(key) = caps.get(1) {
49				let key_str = key.as_str();
50				if let Some(value) = self.bundle.get(key_str) {
51					let pattern = format!(r#"nls.localize\s*\(\s*['"]{}.*?\)"#, regex::escape(key_str));
52					let re = Regex::new(&pattern).unwrap();
53					if self.preserve_calls {
54						// Keep the call but with replacement
55						result = re
56							.replace_all(&result, format!("/* localize('{}') */ '{}'", key_str, value))
57							.to_string();
58					} else {
59						// Replace with just the string value
60						result = re.replace_all(&result, format!("'{}'", value)).to_string();
61					}
62				}
63			}
64		}
65
66		result
67	}
68}
69
70/// Replace NLS keys in source code with translations
71pub fn replace_nls_keys(source:&str, bundle:&HashMap<String, String>) -> String {
72	let replacer = NLSReplacer::new(bundle.clone());
73	replacer.replace(source)
74}
75
76#[cfg(test)]
77mod tests {
78	use super::*;
79
80	#[test]
81	fn test_replacer_creation() {
82		let bundle = HashMap::new();
83		let replacer = NLSReplacer::new(bundle);
84		assert!(!replacer.preserve_calls);
85	}
86
87	#[test]
88	fn test_replacer_with_preserve() {
89		let bundle = HashMap::new();
90		let replacer = NLSReplacer::new(bundle).with_preserve_calls(true);
91		assert!(replacer.preserve_calls);
92	}
93
94	#[test]
95	fn test_replace_keys() {
96		let mut bundle = HashMap::new();
97		bundle.insert("hello".to_string(), "Hello World".to_string());
98
99		let source = r#"nls.localize('hello', 'default')"#;
100		let result = replace_nls_keys(source, &bundle);
101
102		assert!(result.contains("Hello World"));
103	}
104}