1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
//! Configuration data that origins from environment variables.
//! Unlike the configuration data in `LIB_CFG` which is sourced only once when
//! Tp-Note is launched, the `SETTINGS` object may be sourced more often in
//! order to follow changes in the related environment variables.
use crate::config::LIB_CFG;
#[cfg(feature = "lang-detection")]
use crate::config::TMPL_FILTER_GET_LANG_ALL;
use crate::error::LibCfgError;
#[cfg(feature = "lang-detection")]
use lingua;
#[cfg(feature = "lang-detection")]
use lingua::IsoCode639_1;
use parking_lot::RwLock;
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::env;
#[cfg(feature = "lang-detection")]
use std::str::FromStr;
#[cfg(target_family = "windows")]
use windows_sys::Win32::Globalization::GetUserDefaultLocaleName;
#[cfg(target_family = "windows")]
use windows_sys::Win32::System::SystemServices::LOCALE_NAME_MAX_LENGTH;
/// The name of the environment variable which can be optionally set to
/// overwrite the `scheme_default` configuration file setting.
pub const ENV_VAR_TPNOTE_SCHEME: &str = "TPNOTE_SCHEME";
/// The name of the environment variable which can be optionally set to
/// overwrite the `filename.extension_default` configuration file setting.
pub const ENV_VAR_TPNOTE_EXTENSION_DEFAULT: &str = "TPNOTE_EXTENSION_DEFAULT";
/// Name of the environment variable, that can be optionally
/// used to overwrite the user's default language setting, which is
/// accessible as `{{ lang }}` template variable and used in various
/// templates.
pub const ENV_VAR_TPNOTE_LANG: &str = "TPNOTE_LANG";
/// Name of the environment variable, that can be optionally
/// used to overwrite the user's `tmpl.filter.get_lang` and `tmpl.filter.map_lang`
/// configuration file setting.
pub const ENV_VAR_TPNOTE_LANG_DETECTION: &str = "TPNOTE_LANG_DETECTION";
/// Name of the environment variable, that can be optionally
/// used to overwrite the user's login name. The result is accessible as
/// `{{ username }}` template variable and used in various templates.
pub const ENV_VAR_TPNOTE_USER: &str = "TPNOTE_USER";
/// Name of the `LOGNAME` environment variable.
const ENV_VAR_LOGNAME: &str = "LOGNAME";
/// Name of the `USERNAME` environment variable.
const ENV_VAR_USERNAME: &str = "USERNAME";
/// Name of the `USER` environment variable.
const ENV_VAR_USER: &str = "USER";
/// Name of the `LANG` environment variable.
#[cfg(not(target_family = "windows"))]
const ENV_VAR_LANG: &str = "LANG";
#[derive(Debug)]
#[allow(dead_code)]
/// Indicates how the `get_lang` filter operates.
pub(crate) enum FilterGetLang {
/// The filter is disabled and returns the empty string.
Disabled,
/// All available (about 76) languages are selected as search candidates.
/// This causes the filter execution to take some time (up to 5 seconds).
AllLanguages,
/// A list of language tags the algorithm considers as potential candidates
/// to determinate the natural language.
#[cfg(feature = "lang-detection")]
SomeLanguages(Vec<IsoCode639_1>),
/// A list of language tags the algorithm considers as potential candidates
/// to determinate the natural language.
#[cfg(not(feature = "lang-detection"))]
SomeLanguages(Vec<String>),
/// The filter configuration could not be read and converted properly.
Error(LibCfgError),
}
/// Struct containing additional user configuration read from or depending
/// on environment variables.
#[derive(Debug)]
#[allow(dead_code)]
pub(crate) struct Settings {
/// This is the index as the schemes are listed in the config file.
pub current_scheme: usize,
/// This has the format of a login name.
pub author: String,
/// [RFC 5646, Tags for the Identification of Languages](http://www.rfc-editor.org/rfc/rfc5646.txt)
pub lang: String,
/// Extension without dot, e.g. `md`
pub extension_default: String,
/// See defintion of type.
pub filter_get_lang: FilterGetLang,
/// The keys and values from
/// `LIB_CFG.schemes[settings.current_scheme].tmpl.filter_btmap_lang` in the `BTreeMap`
/// with the user's default language and region added.
pub filter_map_lang_btmap: Option<BTreeMap<String, String>>,
}
const DEFAULT_SETTINGS: Settings = Settings {
current_scheme: 0,
author: String::new(),
lang: String::new(),
extension_default: String::new(),
filter_get_lang: FilterGetLang::Disabled,
filter_map_lang_btmap: None,
};
impl Default for Settings {
#[cfg(not(any(test, doc)))]
/// Defaults to empty lists and values.
fn default() -> Self {
DEFAULT_SETTINGS
}
#[cfg(any(test, doc))]
/// Defaults to test values.
/// Do not use outside of tests.
fn default() -> Self {
let mut settings = DEFAULT_SETTINGS;
settings.author = String::from("testuser");
settings.lang = String::from("ab-AB");
settings.extension_default = String::from("md");
settings
}
}
/// Global mutable varible of type `Settings`.
#[cfg(not(test))]
pub(crate) static SETTINGS: RwLock<Settings> = RwLock::new(DEFAULT_SETTINGS);
#[cfg(test)]
lazy_static::lazy_static! {
/// Global default for `SETTINGS` in test environments.
pub(crate) static ref SETTINGS: RwLock<Settings> = RwLock::new(DEFAULT_SETTINGS);
}
/// Like `Settings::update`, with `scheme_source = SchemeSource::Force("default")`
/// and `force_lang = None`.
/// This is used in doctests only.
pub fn set_test_default_settings() -> Result<(), LibCfgError> {
let mut settings = SETTINGS.write();
settings.update(SchemeSource::Force("default"), None)
}
/// How should `update_settings` collect the right scheme?
pub(crate) enum SchemeSource<'a> {
/// Ingore `TPNOTE_SCHEME_NEW_DEFAULT`, take this.
Force(&'a str),
/// Take the value `lib_cfg.scheme_sync_default`.
SchemeSyncDefault,
/// Take `TPNOTE_SCHEME_NEW_DEFAULT`, or, if not defined take this.
SchemeNewDefault(&'a str),
}
impl Settings {
/// (Re)read environment variables and store them in the global `SETTINGS`
/// object. Some data originates from `LIB_CFG`.
/// First sets `SETTINGS.current_scheme`:
/// 1. If `force_theme` is `Some(scheme)`, gets the index and stores result, or,
/// 2. if `force_theme` is `Some("")`, stores `lib_cfg.scheme_sync_default`, or,
/// 3. reads the environment variable `TPNOTE_SCHEME_NEW_DEFAULT` or, -if empty-
/// 4. copies `scheme_new_default` into `SETTINGS.curent_scheme`.
/// Then, sets all other fields.
/// `force_lang=Some(_)` disables the `get_lang` filter by setting
/// `filter_get_lang` to `FilterGetLang::Disabled`.
/// When `force_lang` is `Some(l)`, sets `SETTINGS.current_lang` with `l`.
pub(crate) fn update(
&mut self,
scheme_source: SchemeSource,
force_lang: Option<&str>,
) -> Result<(), LibCfgError> {
self.update_current_scheme(scheme_source)?;
self.update_author();
self.update_extension_default();
self.update_lang(force_lang);
self.update_filter_get_lang(force_lang);
self.update_filter_map_lang_btmap();
self.update_env_lang_detection();
log::trace!(
"`SETTINGS` updated (reading config + env. vars.):\n{:#?}",
self
);
if let FilterGetLang::Error(e) = &self.filter_get_lang {
Err(e.clone())
} else {
Ok(())
}
}
/// Sets `SETTINGS.current_scheme`:
fn update_current_scheme(&mut self, scheme_source: SchemeSource) -> Result<(), LibCfgError> {
let lib_cfg = LIB_CFG.read_recursive();
let scheme = match scheme_source {
SchemeSource::Force(s) => Cow::Borrowed(s),
SchemeSource::SchemeSyncDefault => Cow::Borrowed(&*lib_cfg.scheme_sync_default),
SchemeSource::SchemeNewDefault(s) => match env::var(ENV_VAR_TPNOTE_SCHEME) {
Ok(ed_env) if !ed_env.is_empty() => Cow::Owned(ed_env),
Err(_) | Ok(_) => Cow::Borrowed(s),
},
};
self.current_scheme = lib_cfg.scheme_idx(scheme.as_ref())?;
Ok(())
}
/// Set `SETTINGS.author` to content of the first not empty environment
/// variable: `TPNOTE_USER`, `LOGNAME` or `USER`.
fn update_author(&mut self) {
let author = env::var(ENV_VAR_TPNOTE_USER).unwrap_or_else(|_| {
env::var(ENV_VAR_LOGNAME).unwrap_or_else(|_| {
env::var(ENV_VAR_USERNAME)
.unwrap_or_else(|_| env::var(ENV_VAR_USER).unwrap_or_default())
})
});
// Store result.
self.author = author;
}
/// Read the environment variable `TPNOTE_EXTENSION_DEFAULT` or -if empty-
/// the configuration file variable `filename.extension_default` into
/// `SETTINGS.extension_default`.
fn update_extension_default(&mut self) {
// Get the environment variable if it exists.
let ext = match env::var(ENV_VAR_TPNOTE_EXTENSION_DEFAULT) {
Ok(ed_env) if !ed_env.is_empty() => ed_env,
Err(_) | Ok(_) => {
let lib_cfg = LIB_CFG.read_recursive();
lib_cfg.scheme[self.current_scheme]
.filename
.extension_default
.to_string()
}
};
self.extension_default = ext;
}
/// If `lang=None` read the environment variable `TPNOTE_LANG` or
/// -if not defined- `LANG` into `SETTINGS.lang`.
/// If `force_lang=Some(l)`, copy `l` in `settings.lang`.
fn update_lang(&mut self, force_lang: Option<&str>) {
// Overwrite environment setting.
if let Some(l) = force_lang {
if !l.is_empty() {
self.lang = l.to_string();
return;
}
}
// Get the user's language tag.
// [RFC 5646, Tags for the Identification of Languages](http://www.rfc-editor.org/rfc/rfc5646.txt)
let mut lang = String::new();
// Get the environment variable if it exists.
let tpnotelang = env::var(ENV_VAR_TPNOTE_LANG).ok();
// Unix/MacOS version.
#[cfg(not(target_family = "windows"))]
if let Some(tpnotelang) = tpnotelang {
lang = tpnotelang;
} else {
// [Linux: Define Locale and Language Settings -
// ShellHacks](https://www.shellhacks.com/linux-define-locale-language-settings/)
if let Ok(lang_env) = env::var(ENV_VAR_LANG) {
if !lang_env.is_empty() {
// [ISO 639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code.
let mut language = "";
// [ISO 3166](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) country code.
let mut territory = "";
if let Some((l, lang_env)) = lang_env.split_once('_') {
language = l;
if let Some((t, _codeset)) = lang_env.split_once('.') {
territory = t;
}
}
lang = language.to_string();
lang.push('-');
lang.push_str(territory);
}
}
}
// Get the user's language tag.
// Windows version.
#[cfg(target_family = "windows")]
if let Some(tpnotelang) = tpnotelang {
lang = tpnotelang;
} else {
let mut buf = [0u16; LOCALE_NAME_MAX_LENGTH as usize];
let len = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) };
if len > 0 {
lang = String::from_utf16_lossy(&buf[..((len - 1) as usize)]);
}
};
// Store result.
self.lang = lang;
}
/// Read language list from
/// `LIB_CFG.schemes[settings.scheme].tmpl.filter.get_lang`, add the user's
/// default language subtag and store them in `SETTINGS.filter_get_lang`
/// as `FilterGetLang::SomeLanguages(l)` `enum` variant.
/// If `SETTINGS.filter_get_lang` contains a tag `TMPL_FILTER_GET_LANG_ALL`,
/// all languages are selected by setting `FilterGetLang::AllLanguages`.
/// Errors are stored in the `FilterGetLang::Error(e)` variant.
/// If `force_lang` is `Some(_)`, set `FilterGetLang::Disabled`
#[cfg(feature = "lang-detection")]
fn update_filter_get_lang(&mut self, force_lang: Option<&str>) {
if force_lang.is_some() {
self.filter_get_lang = FilterGetLang::Disabled;
return;
}
let lib_cfg = LIB_CFG.read_recursive();
let mut all_languages_selected = false;
// Read and convert ISO codes from config object.
match lib_cfg.scheme[self.current_scheme]
.tmpl
.filter
.get_lang
.iter()
// Skip if this is the pseudo tag for all languages.
.filter(|&l| {
if l == TMPL_FILTER_GET_LANG_ALL {
all_languages_selected = true;
// Skip this string.
false
} else {
// Continue.
true
}
})
.map(|l| {
IsoCode639_1::from_str(l).map_err(|_| {
// The error path.
// Produce list of all available langugages.
let mut all_langs = lingua::Language::all()
.iter()
.map(|l| {
let mut s = l.iso_code_639_1().to_string();
s.push_str(", ");
s
})
.collect::<Vec<String>>();
all_langs.sort();
let mut all_langs = all_langs.into_iter().collect::<String>();
all_langs.truncate(all_langs.len() - ", ".len());
// Insert data into error object.
LibCfgError::ParseLanguageCode {
language_code: l.into(),
all_langs,
}
})
})
.collect::<Result<Vec<IsoCode639_1>, LibCfgError>>()
{
// The happy path.
Ok(mut iso_codes) => {
if all_languages_selected {
// Store result.
self.filter_get_lang = FilterGetLang::AllLanguages;
} else {
// Add the user's language subtag as reported from the OS.
// Silently ignore if anything goes wrong here.
if !self.lang.is_empty() {
if let Some((lang_subtag, _)) = self.lang.split_once('-') {
if let Ok(iso_code) = IsoCode639_1::from_str(lang_subtag) {
if !iso_codes.contains(&iso_code) {
iso_codes.push(iso_code);
}
}
}
}
// Check if there are at least 2 languages in the list.
self.filter_get_lang = match iso_codes.len() {
0 => FilterGetLang::Disabled,
1 => FilterGetLang::Error(LibCfgError::NotEnoughLanguageCodes {
language_code: iso_codes[0].to_string(),
}),
_ => FilterGetLang::SomeLanguages(iso_codes),
}
}
}
// The error path.
Err(e) =>
// Store error.
{
self.filter_get_lang = FilterGetLang::Error(e);
}
}
}
#[cfg(not(feature = "lang-detection"))]
/// Disable filter.
fn update_filter_get_lang(&mut self, _force_lang: Option<&str>) {
self.filter_get_lang = FilterGetLang::Disabled;
}
/// Read keys and values from
/// `LIB_CFG.schemes[self.current_scheme].tmpl.filter_btmap_lang` in the `BTreeMap`.
/// Add the user's default language and region.
fn update_filter_map_lang_btmap(&mut self) {
let mut btm = BTreeMap::new();
let lib_cfg = LIB_CFG.read_recursive();
for l in &lib_cfg.scheme[self.current_scheme].tmpl.filter.map_lang {
if l.len() >= 2 {
btm.insert(l[0].to_string(), l[1].to_string());
};
}
// Insert the user's default language and region in the Map.
if !self.lang.is_empty() {
if let Some((lang_subtag, _)) = self.lang.split_once('-') {
// Do not overwrite existing languages.
if !lang_subtag.is_empty() && !btm.contains_key(lang_subtag) {
btm.insert(lang_subtag.to_string(), self.lang.to_string());
}
};
}
// Store result.
self.filter_map_lang_btmap = Some(btm);
}
/// Reads the environment variable `LANG_DETECTION`. If not empty,
/// parse the content and overwrite the `self.filter_get_lang` and
/// the `self.filter_map_lang` variables.
#[cfg(feature = "lang-detection")]
fn update_env_lang_detection(&mut self) {
if let Ok(env_var) = env::var(ENV_VAR_TPNOTE_LANG_DETECTION) {
if env_var.is_empty() {
// Early return.
self.filter_get_lang = FilterGetLang::Disabled;
self.filter_map_lang_btmap = None;
log::debug!(
"Empty env. var. `{}` disables the `lang-detection` feature.",
ENV_VAR_TPNOTE_LANG_DETECTION
);
return;
}
// Read and convert ISO codes from config object.
let mut hm: BTreeMap<String, String> = BTreeMap::new();
let mut all_languages_selected = false;
match env_var
.split(',')
.map(|t| {
let t = t.trim();
if let Some((lang_subtag, _)) = t.split_once('-') {
// Do not overwrite existing languages.
if !lang_subtag.is_empty() && !hm.contains_key(lang_subtag) {
hm.insert(lang_subtag.to_string(), t.to_string());
};
lang_subtag
} else {
t
}
})
// Check if this is the pseudo tag `TMPL_FILTER_GET_LANG_ALL `.
.filter(|&l| {
if l == TMPL_FILTER_GET_LANG_ALL {
all_languages_selected = true;
// Skip this string.
false
} else {
// Continue.
true
}
})
.map(|l| {
IsoCode639_1::from_str(l.trim()).map_err(|_| {
// The error path.
// Produce list of all available langugages.
let mut all_langs = lingua::Language::all()
.iter()
.map(|l| {
let mut s = l.iso_code_639_1().to_string();
s.push_str(", ");
s
})
.collect::<Vec<String>>();
all_langs.sort();
let mut all_langs = all_langs.into_iter().collect::<String>();
all_langs.truncate(all_langs.len() - ", ".len());
// Insert data into error object.
LibCfgError::ParseLanguageCode {
language_code: l.into(),
all_langs,
}
})
})
.collect::<Result<Vec<IsoCode639_1>, LibCfgError>>()
{
// The happy path.
Ok(mut iso_codes) => {
// Add the user's language subtag as reported from the OS.
// Continue the happy path.
if !self.lang.is_empty() {
if let Some(lang_subtag) = self.lang.split('-').next() {
if let Ok(iso_code) = IsoCode639_1::from_str(lang_subtag) {
if !iso_codes.contains(&iso_code) {
iso_codes.push(iso_code);
}
// Check if there is a remainder (region code).
if lang_subtag != self.lang && !hm.contains_key(lang_subtag) {
hm.insert(lang_subtag.to_string(), self.lang.to_string());
}
}
}
}
// Store result.
if all_languages_selected {
self.filter_get_lang = FilterGetLang::AllLanguages;
} else {
self.filter_get_lang = match iso_codes.len() {
0 => FilterGetLang::Disabled,
1 => FilterGetLang::Error(LibCfgError::NotEnoughLanguageCodes {
language_code: iso_codes[0].to_string(),
}),
_ => FilterGetLang::SomeLanguages(iso_codes),
}
}
self.filter_map_lang_btmap = Some(hm);
}
// The error path.
Err(e) =>
// Store error.
{
self.filter_get_lang = FilterGetLang::Error(e);
}
}
}
}
/// Ignore the environment variable `LANG_DETECTION`.
#[cfg(not(feature = "lang-detection"))]
fn update_env_lang_detection(&mut self) {
if let Ok(env_var) = env::var(ENV_VAR_TPNOTE_LANG_DETECTION) {
if !env_var.is_empty() {
self.filter_get_lang = FilterGetLang::Disabled;
self.filter_map_lang_btmap = None;
log::debug!(
"Ignoring the env. var. `{}`. The `lang-detection` feature \
is not included in this build.",
ENV_VAR_TPNOTE_LANG_DETECTION
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Attention: as these test-functions run in parallel, make sure that
/// each environment variable appears in one function only!
#[test]
fn test_update_author_setting() {
let mut settings = Settings::default();
env::set_var(ENV_VAR_LOGNAME, "testauthor");
settings.update_author();
assert_eq!(settings.author, "testauthor");
}
#[test]
fn test_update_extension_default_setting() {
let mut settings = Settings::default();
env::set_var(ENV_VAR_TPNOTE_EXTENSION_DEFAULT, "markdown");
settings.update_extension_default();
assert_eq!(settings.extension_default, "markdown");
let mut settings = Settings::default();
std::env::remove_var(ENV_VAR_TPNOTE_EXTENSION_DEFAULT);
settings.update_extension_default();
assert_eq!(settings.extension_default, "md");
}
#[test]
#[cfg(not(target_family = "windows"))]
fn test_update_lang_setting() {
// Test 1
let mut settings = Settings::default();
env::remove_var(ENV_VAR_TPNOTE_LANG);
env::set_var(ENV_VAR_LANG, "en_GB.UTF-8");
settings.update_lang(None);
assert_eq!(settings.lang, "en-GB");
// Test empty input.
let mut settings = Settings::default();
env::remove_var(ENV_VAR_TPNOTE_LANG);
env::set_var(ENV_VAR_LANG, "");
settings.update_lang(None);
assert_eq!(settings.lang, "");
// Test precedence of `TPNOTE_LANG`.
let mut settings = Settings::default();
env::set_var(ENV_VAR_TPNOTE_LANG, "it-IT");
env::set_var(ENV_VAR_LANG, "en_GB.UTF-8");
settings.update_lang(None);
assert_eq!(settings.lang, "it-IT");
}
#[test]
fn test_update_filter_get_lang_setting() {
// Test 1.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
settings.update_filter_get_lang(None);
if let FilterGetLang::SomeLanguages(ofgl) = settings.filter_get_lang {
let output_filter_get_lang = ofgl
.iter()
.map(|l| {
let mut l = l.to_string();
l.push(' ');
l
})
.collect::<String>();
assert_eq!(output_filter_get_lang, "en fr de ");
} else {
panic!("Wrong variant: {:?}", settings.filter_get_lang);
}
//
// Test 2.
let mut settings = Settings {
lang: "it-IT".to_string(),
..Default::default()
};
settings.update_filter_get_lang(None);
if let FilterGetLang::SomeLanguages(ofgl) = settings.filter_get_lang {
let output_filter_get_lang = ofgl
.iter()
.map(|l| {
let mut l = l.to_string();
l.push(' ');
l
})
.collect::<String>();
assert_eq!(output_filter_get_lang, "en fr de it ");
} else {
panic!("Wrong variant: {:?}", settings.filter_get_lang);
}
}
#[test]
fn test_update_filter_map_lang_hmap_setting() {
// Test 1.
let mut settings = Settings {
lang: "it-IT".to_string(),
..Default::default()
};
settings.update_filter_map_lang_btmap();
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("et").unwrap(), "et-ET");
assert_eq!(output_filter_map_lang.get("it").unwrap(), "it-IT");
//
// Test short `settings.lang`.
let mut settings = Settings {
lang: "it".to_string(),
..Default::default()
};
settings.update_filter_map_lang_btmap();
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("et").unwrap(), "et-ET");
assert_eq!(output_filter_map_lang.get("it"), None);
}
#[test]
fn test_update_env_lang_detection() {
// Test 1.
// Test short `settings.lang`.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "fr-FR, de-DE, hu");
settings.update_env_lang_detection();
if let FilterGetLang::SomeLanguages(ofgl) = settings.filter_get_lang {
let output_filter_get_lang = ofgl
.iter()
.map(|l| {
let mut l = l.to_string();
l.push(' ');
l
})
.collect::<String>();
assert_eq!(output_filter_get_lang, "fr de hu en ");
} else {
panic!("Wrong variant: {:?}", settings.filter_get_lang);
}
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("fr").unwrap(), "fr-FR");
assert_eq!(output_filter_map_lang.get("en").unwrap(), "en-GB");
//
// Test 2.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "de-DE, de-AT, en-US");
settings.update_env_lang_detection();
if let FilterGetLang::SomeLanguages(ofgl) = settings.filter_get_lang {
let output_filter_get_lang = ofgl
.iter()
.map(|l| {
let mut l = l.to_string();
l.push(' ');
l
})
.collect::<String>();
assert_eq!(output_filter_get_lang, "de de en ");
} else {
panic!("Wrong variant: {:?}", settings.filter_get_lang);
}
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("en").unwrap(), "en-US");
//
// Test 3.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "de-DE, +all, en-US");
settings.update_env_lang_detection();
assert!(matches!(
settings.filter_get_lang,
FilterGetLang::AllLanguages
));
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("en").unwrap(), "en-US");
//
// Test 4.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "de-DE, de-AT, en");
settings.update_env_lang_detection();
if let FilterGetLang::SomeLanguages(ofgl) = settings.filter_get_lang {
let output_filter_get_lang = ofgl
.iter()
.map(|l| {
let mut l = l.to_string();
l.push(' ');
l
})
.collect::<String>();
assert_eq!(output_filter_get_lang, "de de en ");
} else {
panic!("Wrong variant: {:?}", settings.filter_get_lang);
}
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("en").unwrap(), "en-GB");
//
// Test 5.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "de-DE, +all, de-AT, en");
settings.update_env_lang_detection();
assert!(matches!(
settings.filter_get_lang,
FilterGetLang::AllLanguages
));
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("de").unwrap(), "de-DE");
assert_eq!(output_filter_map_lang.get("en").unwrap(), "en-GB");
//
// Test empty env. var.
let mut settings = Settings {
lang: "".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "");
settings.update_env_lang_detection();
assert!(matches!(settings.filter_get_lang, FilterGetLang::Disabled));
assert!(settings.filter_map_lang_btmap.is_none());
//
// Test faulty `settings.lang`.
let mut settings = Settings {
lang: "xy-XY".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "en-GB, fr");
settings.update_env_lang_detection();
if let FilterGetLang::SomeLanguages(ofgl) = settings.filter_get_lang {
let output_filter_get_lang = ofgl
.iter()
.map(|l| {
let mut l = l.to_string();
l.push(' ');
l
})
.collect::<String>();
assert_eq!(output_filter_get_lang, "en fr ");
} else {
panic!("Wrong variant: {:?}", settings.filter_get_lang);
}
let output_filter_map_lang = settings.filter_map_lang_btmap.unwrap();
assert_eq!(output_filter_map_lang.get("en").unwrap(), "en-GB");
//
// Test faulty entry in list.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "de-DE, xy-XY");
settings.update_env_lang_detection();
assert!(matches!(settings.filter_get_lang, FilterGetLang::Error(..)));
assert!(settings.filter_map_lang_btmap.is_none());
//
// Test empty list.
let mut settings = Settings {
lang: "en-GB".to_string(),
..Default::default()
};
env::set_var(ENV_VAR_TPNOTE_LANG_DETECTION, "");
settings.update_env_lang_detection();
assert!(matches!(settings.filter_get_lang, FilterGetLang::Disabled));
assert!(settings.filter_map_lang_btmap.is_none());
}
}