Rework of locales, moving to use regexp_lite for saner parsing.

This commit is contained in:
kira committed 2026-11-20 17:11:42 +01:00
1 parent d68ee36afa
commit 841090d3d6
4 files changed
+148 -75

No files matched your search

Generated
+7
View File
@@ -1841,6 +1841,7 @@ dependencies = [
"iced_moving_picture",
"log",
"rand 0.10.3",
"regex-lite",
"rust-i18n",
"serde",
"serde_json",
@@ -3113,6 +3114,12 @@ dependencies = [
"regex-syntax",
]
[[package]]
name = "regex-lite"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
[[package]]
name = "regex-syntax"
version = "0.8.11"
+2
View File
@@ -16,6 +16,8 @@ rust-i18n = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
time-format = "1.2"
regex-lite = "0.1"
[dev-dependencies]
rand = "0.10"
+1 -1
View File
@@ -115,7 +115,7 @@ pub fn exec_command(cmd: &str, args: &Vec<&str>) -> Result<(), ExecCommandError>
/// exec given sommand with arguments, returning stdout parsed to UTF-8 string
/// capturing stderr in case or failure
fn exec_command_out(cmd: &str, args: &Vec<&str>) -> Result<String, ExecCommandError> {
pub fn exec_command_out(cmd: &str, args: &Vec<&str>) -> Result<String, ExecCommandError> {
let out = Command::new(cmd).args(args).output()?;
if out.status.success() {
Ok(String::from_utf8(out.stdout)?)
+138 -74
View File
@@ -19,10 +19,12 @@
*/
use crate::{
kira_system::{self, ExecCommandError},
kira_theming,
stage::{KiraConfig, StageAction},
};
use iced::{Alignment, widget};
use regex_lite::Regex;
use rust_i18n::t;
use std::collections::HashMap;
@@ -36,12 +38,17 @@ const LOCALES_GEN_START_LINE: usize = 17;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocaleData {
code: String,
description: String,
charset: String,
description: Option<String>,
}
impl std::fmt::Display for LocaleData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.code, self.description)
if let Some(descr) = &self.description {
write!(f, "{} ({})", self.code, descr)
} else {
write!(f, "{}", self.code)
}
}
}
@@ -49,84 +56,141 @@ impl LocaleData {
pub fn default() -> Self {
Self {
code: "C.UTF-8".into(),
description: "C locale".into(),
charset: "UTF-8".into(),
description: Some("C locale".into()),
}
}
}
/// gets locales list from system "/etc/locale.gen" file
/// Filters out non UTF-8 locales
fn get_locales_codes_list_blocking() -> std::io::Result<Vec<(String, String)>> {
/// Filters result by filter_charset cahrset Some("UTF-8") to get only UTF-8 locales
fn get_locales_blocking(filter_charset: Option<&str>) -> Result<Vec<LocaleData>, ExecCommandError> {
use std::fs::File;
use std::io::{BufReader, Read};
//pt_PT@euro ISO-8859-15
//ru_UA.UTF-8 UTF-8
//#ru_UA KOI8-U
//
// Example ru_UA.UTF-8 UTF-8
// Groups:
// 1: code, like ru_UA.UTF-8
// 3 charser: UTF-8
let key_re = Regex::new(r"^[[:word:]@]+").unwrap();
let loc_re = Regex::new(r"^#?([[:word:].@-]+) ([0-9A-Z-]+)$").unwrap();
let loc_desc = get_loc_descr_blocking()?;
let mut res: Vec<LocaleData> = Vec::new();
let mut file_content = String::new();
{
let locgen_file = File::open(LOCALES_GEN_FILE_NAME)?;
let mut reader = BufReader::new(locgen_file);
reader.read_to_string(&mut file_content)?;
}
let mut res: Vec<(String, String)> = file_content
.split('\n')
.skip(LOCALES_GEN_START_LINE)
.filter_map(|l| {
let trimmed = l.trim_start_matches('#').trim();
if trimmed.len() > 0 {
trimmed.split_once(' ')
} else {
None
for loc_line in file_content.lines() {
if let Some(captured) = loc_re.captures(loc_line.trim_end()) {
let code = captured[1].to_string();
let charset = captured[2].to_string();
// filters charset
if let Some(flt) = filter_charset
&& charset != flt
{
continue;
}
})
.map(|(loc, charset)| (loc.to_string(), charset.to_string()))
.filter(|(_, chrs)| chrs == "UTF-8") // yeld only UTF-8 locales
.collect();
let description = key_re
.find(&code)
.and_then(|m| loc_desc.get(m.as_str()).cloned());
res.push(("C.UTF-8".into(), "UTF-8".into()));
res.push(LocaleData {
code: code,
charset: charset,
description: description,
});
// let subvol_name = &captured[1];
// let date_time = captured[2].to_string();
}
}
//if let Some(captured) = re.captures(&dir_name)
// let mut res: Vec<(String, String)> = file_content
// .split('\n')
// .skip(LOCALES_GEN_START_LINE)
// .filter_map(|l| {
// let trimmed = l.trim_start_matches('#').trim();
// if trimmed.len() > 0 {
// trimmed.split_once(' ')
// } else {
// None
// }
// })
// .map(|(loc, charset)| (loc.to_string(), charset.to_string()))
// .filter(|(_, chrs)| chrs == "UTF-8") // yeld only UTF-8 locales
// .collect();
res.push(LocaleData::default());
Ok(res)
}
/// Gets locales description from "/usr/share/i18n/locales/" directory.
fn get_locales_description_blocking() -> Result<HashMap<String, String>, String> {
use std::process::Command;
fn get_loc_descr_blocking() -> Result<HashMap<String, String>, ExecCommandError> {
// use std::process::Command;
match Command::new("grep")
.args(["-r", "title ", "/usr/share/i18n/locales/"])
.output()
{
Ok(cmd_output) => {
if cmd_output.status.success() {
match String::from_utf8(cmd_output.stdout) {
Ok(raw_str_list) => Ok(raw_str_list
.split("\n")
.filter_map(|s| s.trim().split_once(":title"))
.filter_map(|(code_part, description_part)| {
code_part.rsplit_once("/").and_then(|(_, loc_code)| {
Some((
loc_code.trim().to_string(),
description_part.trim().trim_matches('\"').to_string(),
))
})
})
.collect()),
Err(ex) => Err(format!(
"Exception while converting locales description to UTF8 {}",
ex
)),
}
} else {
Err(format!(
"Error getting locales description list: {}",
String::from_utf8(cmd_output.stderr).unwrap_or("UNKNOWN".into())
))
}
// /usr/share/i18n/locales/uz_UZ:title "Uzbek (latin) locale for Uzbekistan"
// /usr/share/i18n/locales/uz_UZ@cyrillic:title "Uzbek (cyrillic) locale for Uzbekistan"
// 1 group - key code
// 2 group - description
let descr_re = Regex::new(r#"^/usr/share/i18n/locales/(.+):title[[:space:]]+"(.+)"$"#).unwrap();
let mut res: HashMap<String, String> = HashMap::new();
let raw_list =
kira_system::exec_command_out("grep", &vec!["-r", "title ", "/usr/share/i18n/locales/"])?;
for descr_line in raw_list.lines() {
if let Some(captured) = descr_re.captures(descr_line.trim_end()) {
res.insert(captured[1].to_string(), captured[2].to_string());
}
Err(ex) => Err(format!(
"Exception while trying to get locales description {}",
ex
)),
}
// match Command::new("grep")
// .args(["-r", "title ", "/usr/share/i18n/locales/"])
// .output()
// {
// Ok(cmd_output) => {
// if cmd_output.status.success() {
// match String::from_utf8(cmd_output.stdout) {
// Ok(raw_str_list) => Ok(raw_str_list
// .split("\n")
// .filter_map(|s| s.trim().split_once(":title"))
// .filter_map(|(code_part, description_part)| {
// code_part.rsplit_once("/").and_then(|(_, loc_code)| {
// Some((
// loc_code.trim().to_string(),
// description_part.trim().trim_matches('\"').to_string(),
// ))
// })
// })
// .collect()),
// Err(ex) => Err(format!(
// "Exception while converting locales description to UTF8 {}",
// ex
// )),
// }
// } else {
// Err(format!(
// "Error getting locales description list: {}",
// String::from_utf8(cmd_output.stderr).unwrap_or("UNKNOWN".into())
// ))
// }
// }
// Err(ex) => Err(format!(
// "Exception while trying to get locales description {}",
// ex
// )),
// }
Ok(res)
}
#[derive(Debug, Clone)]
@@ -161,25 +225,25 @@ impl LocaleStage {
.as_ref()
.and_then(|rw| Some(rw.loc_code.clone()));
let raw_loc_codes = get_locales_codes_list_blocking().unwrap();
let raw_loc_descr = get_locales_description_blocking().unwrap();
// let raw_loc_codes = get_locales_codes_list_blocking().unwrap();
// let raw_loc_descr = get_locales_description_blocking().unwrap();
let locales: Vec<LocaleData> = raw_loc_codes
.iter()
.filter_map(|(code, _)| {
code.split_once('.')
.and_then(|(key_code, _)| Some((key_code, code)))
})
.filter_map(|(key_code, code)| {
raw_loc_descr
.get(key_code)
.and_then(|descr| Some((code.clone(), descr.clone())))
})
.map(|(code, descr)| LocaleData {
code: code,
description: descr,
})
.collect();
let locales: Vec<LocaleData> = get_locales_blocking(Some("UTF-8")).unwrap();
// .iter()
// .filter_map(|(code, _)| {
// code.split_once('.')
// .and_then(|(key_code, _)| Some((key_code, code)))
// })
// .filter_map(|(key_code, code)| {
// raw_loc_descr
// .get(key_code)
// .and_then(|descr| Some((code.clone(), descr.clone())))
// })
// .map(|(code, descr)| LocaleData {
// code: code,
// description: descr,
// })
// .collect();
// if we get lang code from wellcome stage, try to fing match with system locales
let lang_match = if let Some(lang) = maybe_lang