diff options
Diffstat (limited to 'android')
| -rw-r--r-- | android/translations-converter/src/android/string_value.rs | 35 |
1 files changed, 33 insertions, 2 deletions
diff --git a/android/translations-converter/src/android/string_value.rs b/android/translations-converter/src/android/string_value.rs index 9207dad6ed..47c12265e7 100644 --- a/android/translations-converter/src/android/string_value.rs +++ b/android/translations-converter/src/android/string_value.rs @@ -1,3 +1,5 @@ +use lazy_static::lazy_static; +use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ fmt::{self, Display, Formatter}, @@ -11,7 +13,10 @@ pub struct StringValue(String); impl StringValue { /// Create a `StringValue` from an unescaped string. /// - /// The string will be properly escaped, and all parameters will have indices added to them. + /// The string will be properly escaped, and all parameters will have indices added to them if + /// they don't have any. Indices are assigned sequentially starting from the previously + /// specified index plus one, or starting from one if there aren't any previously specified + /// indices. pub fn from_unescaped(string: &str) -> Self { let value_with_parameters = htmlize::escape_text(string) .replace(r"\", r"\\") @@ -41,11 +46,37 @@ impl StringValue { /// would update the string so that all parameters have indices: `Things are %1$d, %3$s and /// %4$s`. fn ensure_parameters_are_indexed(original: String) -> String { + lazy_static! { + static ref PARAMETER_INDEX: Regex = Regex::new(r"^(\d+)\$").unwrap(); + } + let mut parts = original.split("%"); let mut output = parts.next().unwrap().to_owned(); + let mut offset = 1; for (index, part) in parts.enumerate() { - output.push_str(&format!("%{}$", index + 1)); + let index = index as isize; + + if let Some(captures) = PARAMETER_INDEX.captures(part) { + // String already has a parameter index + let specified_index: isize = captures + .get(1) + .expect("Regex has at least one capture group") + .as_str() + .parse() + .expect("First capture group should match an integer"); + + // Update offset so that next parameters without index receive sequential values + // starting after the specified index + offset = specified_index - index; + + // Restore '%' removed during the split + output.push('%'); + } else { + // String doesn't have a parameter index, so it is added + output.push_str(&format!("%{}$", index + offset)); + } + output.push_str(part); } |
