From 011e79e6764440a7860b6c6d430e8c883e5ce525 Mon Sep 17 00:00:00 2001 From: "Alexander I. Chebykin" Date: Sat, 12 Nov 2022 19:08:33 +0300 Subject: [PATCH] Locales are in external files now Locales are in external files now --- Cargo.lock | 42 ++-- Cargo.toml | 4 +- README.md | 5 + .../unix/etc/cai-watchdog/locales/ru-RU.conf | 26 +++ scripts/windows/locales/ru-RU.conf | 26 +++ src/locales.rs | 89 --------- src/main.rs | 184 +++++++++--------- src/mod_fs.rs | 22 +++ src/mod_locales.rs | 168 ++++++++++++++++ 9 files changed, 364 insertions(+), 202 deletions(-) create mode 100644 scripts/unix/etc/cai-watchdog/locales/ru-RU.conf create mode 100644 scripts/windows/locales/ru-RU.conf delete mode 100644 src/locales.rs create mode 100644 src/mod_fs.rs create mode 100644 src/mod_locales.rs diff --git a/Cargo.lock b/Cargo.lock index fd0d26d..a6ac865 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -43,7 +43,7 @@ checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" [[package]] name = "cai-watchdog" -version = "0.7.0" +version = "0.8.0" dependencies = [ "chrono", "exitcode", @@ -58,9 +58,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.73" +version = "1.0.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" +checksum = "76a284da2e6fe2092f2353e51713435363112dfd60030e22add80be333fb928f" [[package]] name = "cfg-if" @@ -70,9 +70,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.22" +version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1" +checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" dependencies = [ "iana-time-zone", "js-sys", @@ -160,9 +160,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b7d4e43b25d3c994662706a1d4fcfc32aaa6afd287502c111b237093bb23f3a" +checksum = "97abf9f0eca9e52b7f81b945524e76710e6cb2366aead23b7d4fbf72e281f888" dependencies = [ "cc", "cxxbridge-flags", @@ -172,9 +172,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84f8829ddc213e2c1368e51a2564c552b65a8cb6a28f31e576270ac81d5e5827" +checksum = "7cc32cc5fea1d894b77d269ddb9f192110069a8a9c1f1d441195fba90553dea3" dependencies = [ "cc", "codespan-reporting", @@ -187,15 +187,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e72537424b474af1460806647c41d4b6d35d09ef7fe031c5c2fa5766047cc56a" +checksum = "8ca220e4794c934dc6b1207c3b42856ad4c302f2df1712e9f8d2eec5afaacf1f" [[package]] name = "cxxbridge-macro" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "309e4fb93eed90e1e14bea0da16b209f81813ba9fc7830c20ed151dd7bc0a4d7" +checksum = "b846f081361125bfc8dc9d3940c84e1fd83ba54bbca7b17cd29483c828be0704" dependencies = [ "proc-macro2", "quote", @@ -383,9 +383,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "hyper" -version = "0.14.20" +version = "0.14.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02c929dc5c39e335a03c405292728118860721b10190d98c2a0f0efd5baafbac" +checksum = "034711faac9d2166cb1baf1a2fb0b60b1f277f8492fd72176c17f3515e1abd3c" dependencies = [ "bytes", "futures-channel", @@ -482,9 +482,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879d54834c8c76457ef4293a689b2a8c59b076067ad77b15efafbb05f92a592b" +checksum = "f88c5561171189e69df9d98bcf18fd5f9558300f7ea7b801eb8a0fd748bd8745" [[package]] name = "itoa" @@ -576,9 +576,9 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.10" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd7e2f3618557f980e0b17e8856252eee3c97fa12c54dff0ca290fb6266ca4a9" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" dependencies = [ "lazy_static", "libc", @@ -622,9 +622,9 @@ dependencies = [ [[package]] name = "num_cpus" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" dependencies = [ "hermit-abi", "libc", diff --git a/Cargo.toml b/Cargo.toml index bb73f74..d4f2ac7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cai-watchdog" -version = "0.7.0" +version = "0.8.0" authors = ["Alexander I. Chebykin "] edition = "2018" @@ -8,7 +8,7 @@ edition = "2018" [dependencies] file-utils = "0.1.5" -chrono = "0.4.22" +chrono = "0.4.23" # Sync #reqwest = { version = "0.11", features = ["blocking"] } # Async diff --git a/README.md b/README.md index f4cc0a2..6f8aa95 100644 --- a/README.md +++ b/README.md @@ -176,3 +176,8 @@ Watchdog can send notifications on user login. Just add to ```/etc/profile.d/ssh and set executable flag on it 1. Modify ```/etc/pam.d/sshd```, add line ```session optional pam_exec.so quiet /etc/pam.d/pam_session.sh``` + +## Localization +You can find locales in ```/etc/cai-watchdog/locales/``` in *nix and in ```locales``` subfolder in Windows. + +locale files must be named like locale_name.conf, for example: Russian locale is ru-RU. diff --git a/scripts/unix/etc/cai-watchdog/locales/ru-RU.conf b/scripts/unix/etc/cai-watchdog/locales/ru-RU.conf new file mode 100644 index 0000000..7dddfdc --- /dev/null +++ b/scripts/unix/etc/cai-watchdog/locales/ru-RU.conf @@ -0,0 +1,26 @@ +[rules] +cant_find_config_file = Не могу найти файл конфигурации +check_failed = Проверка завершилась неудачей +check_is_ok = проверка завершилась успешно +configuration_file = Конфигурационный файл +error = Ошибка +execute = Выполняю +exiting = Завершаю работу... +failed_to_execute_process = Не удалось выполнить процесс +is_not_running = не запущен +is_not_running_now = сейчас не запущен +is_offline = неактивна +is_offline_now = сейчас неактивна +is_online = активна +is_online_now = сейчас активна +is_running = запущен +is_running_now = сейчас запущен +process = Процесс +service = Служба +service_started = Служба запущена +state_changed_to_false = состояние изменилось на истину +state_changed_to_true = состояние изменилось на ложь +this_help_message = Это справочное сообщение +usage = Использование +ver = версия +version_info = Информация о версии diff --git a/scripts/windows/locales/ru-RU.conf b/scripts/windows/locales/ru-RU.conf new file mode 100644 index 0000000..7dddfdc --- /dev/null +++ b/scripts/windows/locales/ru-RU.conf @@ -0,0 +1,26 @@ +[rules] +cant_find_config_file = Не могу найти файл конфигурации +check_failed = Проверка завершилась неудачей +check_is_ok = проверка завершилась успешно +configuration_file = Конфигурационный файл +error = Ошибка +execute = Выполняю +exiting = Завершаю работу... +failed_to_execute_process = Не удалось выполнить процесс +is_not_running = не запущен +is_not_running_now = сейчас не запущен +is_offline = неактивна +is_offline_now = сейчас неактивна +is_online = активна +is_online_now = сейчас активна +is_running = запущен +is_running_now = сейчас запущен +process = Процесс +service = Служба +service_started = Служба запущена +state_changed_to_false = состояние изменилось на истину +state_changed_to_true = состояние изменилось на ложь +this_help_message = Это справочное сообщение +usage = Использование +ver = версия +version_info = Информация о версии diff --git a/src/locales.rs b/src/locales.rs deleted file mode 100644 index 7e09b6b..0000000 --- a/src/locales.rs +++ /dev/null @@ -1,89 +0,0 @@ -pub struct Lang { - pub cant_find_config_file: String, - pub check_failed: String, - pub check_is_ok: String, - pub configuration_file: String, - pub error: String, - pub execute: String, - pub exiting: String, - pub failed_to_execute_process: String, - pub is_not_running: String, - pub is_not_running_now: String, - pub is_offline: String, - pub is_offline_now: String, - pub is_online: String, - pub is_online_now: String, - pub is_running: String, - pub is_running_now: String, - pub process: String, - pub service: String, - pub service_started: String, - pub state_changed_to_false: String, - pub state_changed_to_true: String, - pub this_help_message: String, - pub usage: String, - pub ver: String, - pub version_info: String -} - -pub fn t(lang: String) -> Lang { - let l:Lang = if lang == "ru-RU" { - Lang{ - cant_find_config_file: "Не могу найти файл конфигурации".to_string(), - check_failed: "Проверка завершилась неудачей".to_string(), - check_is_ok: "проверка завершилась успешно".to_string(), - configuration_file: "Конфигурационный файл".to_string(), - error: "Ошибка".to_string(), - execute: "Выполняю".to_string(), - exiting: "Завершаю работу...".to_string(), - failed_to_execute_process: "Не удалось выполнить процесс".to_string(), - is_not_running: "не запущен".to_string(), - is_not_running_now: "сейчас не запущен".to_string(), - is_offline: "неактивна".to_string(), - is_offline_now: "сейчас неактивна".to_string(), - is_online: "активна".to_string(), - is_online_now: "сейчас активна".to_string(), - is_running: "запущен".to_string(), - is_running_now: "сейчас запущен".to_string(), - process: "Процесс".to_string(), - service: "Служба".to_string(), - service_started: "Служба запущена".to_string(), - state_changed_to_false: "состояние изменилось на истину".to_string(), - state_changed_to_true: "состояние изменилось на ложь".to_string(), - this_help_message: "Это справочное сообщение".to_string(), - usage: "Использование".to_string(), - ver: "версия".to_string(), - version_info: "Информация о версии".to_string() - } - } else { - Lang{ - cant_find_config_file: "Can't find configuration file".to_string(), - check_failed: "check failed".to_string(), - check_is_ok: "check is ok".to_string(), - configuration_file: "Configuration file".to_string(), - error: "Error".to_string(), - execute: "Execute".to_string(), - exiting: "Exiting...".to_string(), - failed_to_execute_process: "Can't execute process".to_string(), - is_not_running: "is not running".to_string(), - is_not_running_now: "is not running now".to_string(), - is_offline: "is offline".to_string(), - is_offline_now: "is offline now".to_string(), - is_online: "is online".to_string(), - is_online_now: "is online now".to_string(), - is_running: "is running".to_string(), - is_running_now: "is running now".to_string(), - process: "Process".to_string(), - service: "Service".to_string(), - service_started: "Service started".to_string(), - state_changed_to_false: "state changed to false".to_string(), - state_changed_to_true: "state changed to true".to_string(), - this_help_message: "This help message".to_string(), - usage: "Usage".to_string(), - ver: "ver".to_string(), - version_info: "Version info".to_string() - } - }; - - return l; -} diff --git a/src/main.rs b/src/main.rs index f2732e2..b6c0432 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,9 +8,9 @@ use std::process::Command; use std::thread; use std::time::Duration; use sysinfo::{System, SystemExt}; -use sys_locale::get_locale; -mod locales; +mod mod_locales; +mod mod_fs; /// Rule description structure struct Rule { @@ -134,21 +134,21 @@ fn debug_log(text: String) { /// execute("gedit".to_string()); /// ``` fn execute(command: String) { - let locale = get_locale().unwrap_or_else(|| String::from("en-US")); + let locale = mod_locales::Locale::new(); - debug_log(format!("{} {}", locales::t(locale.clone()).execute, command)); + debug_log(format!("{} {}", locale.t().execute, command)); let output = if cfg!(target_os = "windows") { Command::new("powershell") .args(["-NoLogo", "-NonInteractive", "-Command", &command]) .output() - .expect(&locales::t(locale.clone()).failed_to_execute_process) //.expect("failed to execute process") + .expect(&locale.t().failed_to_execute_process) //.expect("failed to execute process") } else { Command::new("sh") .arg("-c") .arg(&command) .output() - .expect(&locales::t(locale.clone()).failed_to_execute_process) //.expect("failed to execute process") + .expect(&locale.t().failed_to_execute_process) //.expect("failed to execute process") }; let result = output.stdout; @@ -169,18 +169,18 @@ fn execute(command: String) { /// print_help(args.clone()); /// ``` fn print_help(args: Vec) { - let locale = get_locale().unwrap_or_else(|| String::from("en-US")); + let locale = mod_locales::Locale::new(); if cfg!(windows) { if args.len() > 1 && (args[1].to_string() == "/help".to_string() || args[1].to_string() == "/?".to_string()) { const VERSION: &str = env!("CARGO_PKG_VERSION"); - println!("CAI Watchdog {} {}", locales::t(locale.clone()).ver, VERSION); + println!("CAI Watchdog {} {}", locale.t().ver, VERSION); println!(""); println!("Usage: {} [/? | /help | /v | /ver | config_file]", &args[0]); - println!(" /? | /help : {}", locales::t(locale.clone()).this_help_message); - println!(" /v | /ver : {}", locales::t(locale.clone()).version_info); - println!(" config_file : {}", locales::t(locale.clone()).configuration_file); + println!(" /? | /help : {}", locale.t().this_help_message); + println!(" /v | /ver : {}", locale.t().version_info); + println!(" config_file : {}", locale.t().configuration_file); std::process::exit(exitcode::OK); } else if args.len() > 1 @@ -188,7 +188,7 @@ fn print_help(args: Vec) { const VERSION: &str = env!("CARGO_PKG_VERSION"); - println!("CAI Watchdog {} {}", locales::t(locale.clone()).ver, VERSION); + println!("CAI Watchdog {} {}", locale.t().ver, VERSION); std::process::exit(exitcode::OK); } @@ -196,19 +196,19 @@ fn print_help(args: Vec) { if args.len() > 1 && (args[1].to_string() == "--help".to_string() || args[1].to_string() == "-h".to_string()) { const VERSION: &str = env!("CARGO_PKG_VERSION"); - println!("CAI Watchdog {} {}", locales::t(locale.clone()).ver, VERSION); + println!("CAI Watchdog {} {}", locale.t().ver, VERSION); println!(""); - println!("{}: {} [-h | --help | -v | --ver | config_file]", locales::t(locale.clone()).usage, &args[0]); - println!(" -h | --help : {}", locales::t(locale.clone()).this_help_message); - println!(" -v | --ver : {}", locales::t(locale.clone()).version_info); - println!(" config_file : {}", locales::t(locale.clone()).configuration_file); + println!("{}: {} [-h | --help | -v | --ver | config_file]", locale.t().usage, &args[0]); + println!(" -h | --help : {}", locale.t().this_help_message); + println!(" -v | --ver : {}", locale.t().version_info); + println!(" config_file : {}", locale.t().configuration_file); std::process::exit(exitcode::OK); } else if args.len() > 1 && (args[1].to_string() == "--ver".to_string() || args[1].to_string() == "-v".to_string()) { const VERSION: &str = env!("CARGO_PKG_VERSION"); - println!("CAI Watchdog {} {}", locales::t(locale.clone()).ver, VERSION); + println!("CAI Watchdog {} {}", locale.t().ver, VERSION); std::process::exit(exitcode::OK); } @@ -216,29 +216,32 @@ fn print_help(args: Vec) { } fn main() { + let locale = mod_locales::Locale::new(); + let args: Vec = env::args().collect(); - let locale = get_locale().unwrap_or_else(|| String::from("en-US")); - - debug_log(format!("The current locale is {}", locale.clone())); - -// println!("{}", locales::t(locale).usage); print_help(args.clone()); + let mut config_file = mod_fs::get_exe_path(); + + if cfg!(windows) { + config_file = format!("{}\\cai-watchdog.ini", config_file); + } else { + config_file = "/etc/cai-watchdog/cai-watchdog.conf".to_string(); + } + let cfg_file = if args.len() > 1 { &args[1] - } else if cfg!(windows) { - "cai-watchdog.ini" } else { - "/etc/cai-watchdog/cai-watchdog.conf" + &config_file }; if !Path::new(cfg_file).exists() { - println!("\u{26a0} {}! {}.", - locales::t(locale.clone()).error, - locales::t(locale.clone()).cant_find_config_file + println!("\u{26a0} {}! {}.", + locale.t().error, + locale.t().cant_find_config_file ); - println!("{}", locales::t(locale.clone()).exiting); + println!("{}", locale.t().exiting); std::process::exit(exitcode::CONFIG); } @@ -329,7 +332,7 @@ fn main() { "".to_string() }; - debug_log(format!("\u{2139} {}", locales::t(locale.clone()).service_started)); + debug_log(format!("\u{2139} {}", locale.t().service_started)); if on_start_command.to_string() != "" { execute(on_start_command); @@ -347,89 +350,89 @@ fn main() { if check(&tasks_web[i]).await { if tasks_web[i].last_state != true || just_started_web { if tasks_web[i].command.to_string() == "".to_string() { - println!("\u{2705} {} {}", - tasks_web[i].uri, - locales::t(locale.clone()).state_changed_to_true + println!("\u{2705} {} {}", + tasks_web[i].uri, + locale.t().state_changed_to_true ); } else { - debug_log(format!("\u{2705} {} {}", - tasks_web[i].uri, - locales::t(locale.clone()).state_changed_to_true) + debug_log(format!("\u{2705} {} {}", + tasks_web[i].uri, + locale.t().state_changed_to_true) ); let shell_cmd = tasks_web[i].command.to_string() .replace("", &tasks_web[i].email) - .replace("", + .replace("", &format!( - "\"\u{2705} {} {} ({}) {}\"", - locales::t(locale.clone()).service, - tasks_web[i].service, + "\"\u{2705} {} {} ({}) {}\"", + locale.t().service, + tasks_web[i].service, tasks_web[i].uri, - locales::t(locale.clone()).is_online + locale.t().is_online ) ) - .replace("", + .replace("", &format!( - "\"\u{2705} {} {} ({}) {}\"", - locales::t(locale.clone()).service, - tasks_web[i].service, + "\"\u{2705} {} {} ({}) {}\"", + locale.t().service, + tasks_web[i].service, tasks_web[i].uri, - locales::t(locale.clone()).is_online_now + locale.t().is_online_now ) ) .replace("", &tasks_web[i].service) .replace("", &tasks_web[i].uri) .replace("", "online"); - debug_log(format!("{} {}", locales::t(locale.clone()).execute, shell_cmd)); + debug_log(format!("{} {}", locale.t().execute, shell_cmd)); execute(shell_cmd); } } - debug_log(format!("\u{2705} {} {}", tasks_web[i].uri, locales::t(locale.clone()).check_is_ok)); + debug_log(format!("\u{2705} {} {}", tasks_web[i].uri, locale.t().check_is_ok)); tasks_web[i].last_state = true; } else { if tasks_web[i].last_state != false || just_started_web { if tasks_web[i].command.to_string() == "".to_string() { - println!("\u{274c} {} {}", tasks_web[i].uri, locales::t(locale.clone()).state_changed_to_false); + println!("\u{274c} {} {}", tasks_web[i].uri, locale.t().state_changed_to_false); } else { - debug_log(format!("\u{274c} {} {}", tasks_web[i].uri, locales::t(locale.clone()).state_changed_to_false)); + debug_log(format!("\u{274c} {} {}", tasks_web[i].uri, locale.t().state_changed_to_false)); let shell_cmd = tasks_web[i].command.to_string() .replace("", &tasks_web[i].email) .replace("", & format!( - "\"\u{274c} {} {} ({}) {}\"", - locales::t(locale.clone()).service, - tasks_web[i].service, + "\"\u{274c} {} {} ({}) {}\"", + locale.t().service, + tasks_web[i].service, tasks_web[i].uri, - locales::t(locale.clone()).is_offline + locale.t().is_offline ) ) .replace("", & format!( - "\"\u{274c} {} {} ({}) {}\"", - locales::t(locale.clone()).service, - tasks_web[i].service, + "\"\u{274c} {} {} ({}) {}\"", + locale.t().service, + tasks_web[i].service, tasks_web[i].uri, - locales::t(locale.clone()).is_offline_now + locale.t().is_offline_now ) ) .replace("", &tasks_web[i].service) .replace("", &tasks_web[i].uri) .replace("", "offline"); - debug_log(format!("{} {}", locales::t(locale.clone()).execute, shell_cmd)); + debug_log(format!("{} {}", locale.t().execute, shell_cmd)); execute(shell_cmd); } } - debug_log(format!("\u{274c} {} {}", tasks_web[i].uri, locales::t(locale.clone()).check_failed)); + debug_log(format!("\u{274c} {} {}", tasks_web[i].uri, locale.t().check_failed)); tasks_web[i].last_state = false; } @@ -443,7 +446,8 @@ fn main() { }); let mut just_started_prc = true; - let locale_prc = get_locale().unwrap_or_else(|| String::from("en-US")); + + let locale = mod_locales::Locale::new(); loop { for i in 0..tasks_prc.len() { @@ -454,82 +458,82 @@ fn main() { if check(&tasks_prc[i]).await { if tasks_prc[i].last_state != true || just_started_prc { if tasks_prc[i].command.to_string() == "".to_string() { - println!("\u{2705} {} {}", tasks_prc[i].uri, locales::t(locale_prc.clone()).state_changed_to_true); + println!("\u{2705} {} {}", tasks_prc[i].uri, locale.t().state_changed_to_true); } else { - debug_log(format!("\u{2705} {} {}", tasks_prc[i].uri, locales::t(locale_prc.clone()).state_changed_to_true)); + debug_log(format!("\u{2705} {} {}", tasks_prc[i].uri, locale.t().state_changed_to_true)); let shell_cmd = tasks_prc[i].command.to_string() .replace("", &tasks_prc[i].email) - .replace("", + .replace("", &format!( - "\"\u{2705} {} {} ({}) {}\"", - locales::t(locale_prc.clone()).process, - tasks_prc[i].service, + "\"\u{2705} {} {} ({}) {}\"", + locale.t().process, + tasks_prc[i].service, tasks_prc[i].process, - locales::t(locale_prc.clone()).is_running + locale.t().is_running ) ) - .replace("", + .replace("", &format!( - "\"\u{2705} {} {} ({}) {}\"", - locales::t(locale_prc.clone()).process, - tasks_prc[i].service, + "\"\u{2705} {} {} ({}) {}\"", + locale.t().process, + tasks_prc[i].service, tasks_prc[i].process, - locales::t(locale_prc.clone()).is_running_now + locale.t().is_running_now ) ) .replace("", &tasks_prc[i].service) .replace("", &tasks_prc[i].process) .replace("", "running"); - debug_log(format!("{} {}", locales::t(locale_prc.clone()).execute, shell_cmd)); + debug_log(format!("{} {}", locale.t().execute, shell_cmd)); execute(shell_cmd); } } - debug_log(format!("\u{2705} {} {}", tasks_prc[i].process, locales::t(locale_prc.clone()).is_running)); + debug_log(format!("\u{2705} {} {}", tasks_prc[i].process, locale.t().is_running)); tasks_prc[i].last_state = true; } else { if tasks_prc[i].last_state != false || just_started_prc { if tasks_prc[i].command.to_string() == "".to_string() { - println!("\u{274c} {} {}", tasks_prc[i].uri, locales::t(locale_prc.clone()).state_changed_to_false); + println!("\u{274c} {} {}", tasks_prc[i].uri, locale.t().state_changed_to_false); } else { - debug_log(format!("\u{274c} {} {}", tasks_prc[i].uri, locales::t(locale_prc.clone()).state_changed_to_false)); + debug_log(format!("\u{274c} {} {}", tasks_prc[i].uri, locale.t().state_changed_to_false)); let shell_cmd = tasks_prc[i].command.to_string() .replace("", &tasks_prc[i].email) - .replace("", + .replace("", &format!( - "\"\u{274c} {} {} ({}) {}\"", - locales::t(locale_prc.clone()).process, - tasks_prc[i].service, + "\"\u{274c} {} {} ({}) {}\"", + locale.t().process, + tasks_prc[i].service, tasks_prc[i].process, - locales::t(locale_prc.clone()).is_not_running + locale.t().is_not_running ) ) - .replace("", + .replace("", &format!( - "\"\u{274c} {} {} ({}) {}\"", - locales::t(locale_prc.clone()).process, - tasks_prc[i].service, + "\"\u{274c} {} {} ({}) {}\"", + locale.t().process, + tasks_prc[i].service, tasks_prc[i].process, - locales::t(locale_prc.clone()).is_not_running_now + locale.t().is_not_running_now ) ) .replace("", &tasks_prc[i].service) .replace("", &tasks_prc[i].process) .replace("", "stopped"); - debug_log(format!("{} {}", locales::t(locale_prc.clone()).execute, shell_cmd)); + debug_log(format!("{} {}", locale.t().execute, shell_cmd)); execute(shell_cmd); } } - debug_log(format!("\u{274c} {} {}", tasks_prc[i].process, locales::t(locale_prc.clone()).is_not_running)); + debug_log(format!("\u{274c} {} {}", tasks_prc[i].process, locale.t().is_not_running)); tasks_prc[i].last_state = false; diff --git a/src/mod_fs.rs b/src/mod_fs.rs new file mode 100644 index 0000000..8c855be --- /dev/null +++ b/src/mod_fs.rs @@ -0,0 +1,22 @@ +use std::env; +use std::path::PathBuf; + +/// Return executable path +/// +/// Return executable path or . if can't determine it +pub fn get_exe_path() -> String { + let mut dir; + let exe_path: String; + + match env::current_exe() { + Ok(full_name) => { + dir = PathBuf::from(full_name); + dir.pop(); + exe_path = dir.clone().into_os_string().into_string().unwrap(); + }, + Err(_e) => { + exe_path = ".".to_string(); + }, + } + return exe_path; +} diff --git a/src/mod_locales.rs b/src/mod_locales.rs new file mode 100644 index 0000000..ed6e64e --- /dev/null +++ b/src/mod_locales.rs @@ -0,0 +1,168 @@ +use std::borrow::Borrow; +use std::path::Path; + +use crate::mod_fs; +use sys_locale::get_locale; + +pub struct Lang { + pub cant_find_config_file: String, + pub check_failed: String, + pub check_is_ok: String, + pub configuration_file: String, + pub error: String, + pub execute: String, + pub exiting: String, + pub failed_to_execute_process: String, + pub is_not_running: String, + pub is_not_running_now: String, + pub is_offline: String, + pub is_offline_now: String, + pub is_online: String, + pub is_online_now: String, + pub is_running: String, + pub is_running_now: String, + pub process: String, + pub service: String, + pub service_started: String, + pub state_changed_to_false: String, + pub state_changed_to_true: String, + pub this_help_message: String, + pub usage: String, + pub ver: String, + pub version_info: String + +} + +pub struct Locale { + pub locale:Lang, +} + +impl Locale { + pub fn new() -> Self { + let mut l:Lang = Lang{ + cant_find_config_file: "Can't find configuration file".to_string(), + check_failed: "check failed".to_string(), + check_is_ok: "check is ok".to_string(), + configuration_file: "Configuration file".to_string(), + error: "Error".to_string(), + execute: "Execute".to_string(), + exiting: "Exiting...".to_string(), + failed_to_execute_process: "Can't execute process".to_string(), + is_not_running: "is not running".to_string(), + is_not_running_now: "is not running now".to_string(), + is_offline: "is offline".to_string(), + is_offline_now: "is offline now".to_string(), + is_online: "is online".to_string(), + is_online_now: "is online now".to_string(), + is_running: "is running".to_string(), + is_running_now: "is running now".to_string(), + process: "Process".to_string(), + service: "Service".to_string(), + service_started: "Service started".to_string(), + state_changed_to_false: "state changed to false".to_string(), + state_changed_to_true: "state changed to true".to_string(), + this_help_message: "This help message".to_string(), + usage: "Usage".to_string(), + ver: "ver".to_string(), + version_info: "Version info".to_string() + }; + + let locale = get_locale().unwrap_or_else(|| String::from("en-US")); + + let mut locale_file = mod_fs::get_exe_path(); + + locale_file = if cfg!(windows) { + format!("{}\\locales\\{}.conf", locale_file, locale) + } else { + format!("/etc/cai-watchdog/locales/{}.conf", locale) + }; + + if Path::new(&locale_file).exists() { + let cfg = ini!(&locale_file); + + if cfg["rules"].contains_key("cant_find_config_file") { + l.cant_find_config_file = cfg["rules"]["cant_find_config_file"].clone().unwrap(); + } + if cfg["rules"].contains_key("check_failed") { + l.check_failed = cfg["rules"]["check_failed"].clone().unwrap(); + } + if cfg["rules"].contains_key("check_is_ok") { + l.check_is_ok = cfg["rules"]["check_is_ok"].clone().unwrap(); + } + if cfg["rules"].contains_key("configuration_file") { + l.configuration_file = cfg["rules"]["configuration_file"].clone().unwrap(); + } + if cfg["rules"].contains_key("error") { + l.error = cfg["rules"]["error"].clone().unwrap(); + } + if cfg["rules"].contains_key("execute") { + l.execute = cfg["rules"]["execute"].clone().unwrap(); + } + if cfg["rules"].contains_key("exiting") { + l.exiting = cfg["rules"]["exiting"].clone().unwrap(); + } + if cfg["rules"].contains_key("failed_to_execute_process") { + l.failed_to_execute_process = cfg["rules"]["failed_to_execute_process"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_not_running") { + l.is_not_running = cfg["rules"]["is_not_running"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_not_running_now") { + l.is_not_running_now = cfg["rules"]["is_not_running_now"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_offline") { + l.is_offline = cfg["rules"]["is_offline"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_offline_now") { + l.is_offline_now = cfg["rules"]["is_offline_now"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_online") { + l.is_online = cfg["rules"]["is_online"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_online_now") { + l.is_online_now = cfg["rules"]["is_online_now"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_running") { + l.is_running = cfg["rules"]["is_running"].clone().unwrap(); + } + if cfg["rules"].contains_key("is_running_now") { + l.is_running_now = cfg["rules"]["is_running_now"].clone().unwrap(); + } + if cfg["rules"].contains_key("process") { + l.process = cfg["rules"]["process"].clone().unwrap(); + } + if cfg["rules"].contains_key("service") { + l.service = cfg["rules"]["service"].clone().unwrap(); + } + if cfg["rules"].contains_key("service_started") { + l.service_started = cfg["rules"]["service_started"].clone().unwrap(); + } + if cfg["rules"].contains_key("state_changed_to_false") { + l.state_changed_to_false = cfg["rules"]["state_changed_to_false"].clone().unwrap(); + } + if cfg["rules"].contains_key("state_changed_to_true") { + l.state_changed_to_true = cfg["rules"]["state_changed_to_true"].clone().unwrap(); + } + if cfg["rules"].contains_key("this_help_message") { + l.this_help_message = cfg["rules"]["this_help_message"].clone().unwrap(); + } + if cfg["rules"].contains_key("usage") { + l.usage = cfg["rules"]["usage"].clone().unwrap(); + } + if cfg["rules"].contains_key("ver") { + l.ver = cfg["rules"]["ver"].clone().unwrap(); + } + if cfg["rules"].contains_key("version_info") { + l.version_info = cfg["rules"]["version_info"].clone().unwrap(); + } + } + + Self { + locale: l + } + } + + pub fn t(&self) -> &Lang { + return self.locale.borrow().clone(); + } +}