From e181ae9b0d4814a7c005c94837426126dde63c6c Mon Sep 17 00:00:00 2001 From: sigoden Date: Tue, 10 Sep 2024 18:35:34 +0800 Subject: refactor: extract built-in roles to embedded files (#853) --- src/utils/command.rs | 15 --------------- src/utils/mod.rs | 2 ++ src/utils/variables.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 15 deletions(-) create mode 100644 src/utils/variables.rs (limited to 'src/utils') diff --git a/src/utils/command.rs b/src/utils/command.rs index caf70c7..8afef14 100644 --- a/src/utils/command.rs +++ b/src/utils/command.rs @@ -5,24 +5,9 @@ use std::{collections::HashMap, env, ffi::OsStr, path::Path, process::Command}; use anyhow::{anyhow, bail, Context, Result}; lazy_static::lazy_static! { - pub static ref OS: String = detect_os(); pub static ref SHELL: Shell = detect_shell(); } -pub fn detect_os() -> String { - let os = env::consts::OS; - if os == "linux" { - if let Ok(contents) = std::fs::read_to_string("/etc/os-release") { - for line in contents.lines() { - if let Some(id) = line.strip_prefix("ID=") { - return format!("{os} ({id})"); - } - } - } - } - os.to_string() -} - pub struct Shell { pub name: String, pub cmd: String, diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 1090c4e..e937e6b 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -8,6 +8,7 @@ mod prompt_input; mod render_prompt; mod request; mod spinner; +mod variables; pub use self::abort_signal::*; pub use self::clipboard::set_text; @@ -19,6 +20,7 @@ pub use self::prompt_input::*; pub use self::render_prompt::render_prompt; pub use self::request::*; pub use self::spinner::*; +pub use self::variables::*; use anyhow::{Context, Result}; use fancy_regex::Regex; diff --git a/src/utils/variables.rs b/src/utils/variables.rs new file mode 100644 index 0000000..91c9912 --- /dev/null +++ b/src/utils/variables.rs @@ -0,0 +1,33 @@ +use super::*; +use fancy_regex::{Captures, Regex}; + +lazy_static::lazy_static! { + pub static ref RE_VARIABLE: Regex = Regex::new(r"\{\{(\w+)\}\}").unwrap(); +} +pub fn interpolate_variables(text: &mut String) { + *text = RE_VARIABLE + .replace_all(text, |caps: &Captures<'_>| { + let key = &caps[1]; + match key { + "__os__" => env::consts::OS.to_string(), + "__os_distro__" => { + let info = os_info::get(); + if env::consts::OS == "linux" { + format!("{info} (linux)") + } else { + info.to_string() + } + } + "__os_family__" => env::consts::FAMILY.to_string(), + "__arch__" => env::consts::ARCH.to_string(), + "__shell__" => SHELL.name.clone(), + "__locale__" => sys_locale::get_locale().unwrap_or_default(), + "__now__" => now(), + "__cwd__" => env::current_dir() + .map(|v| v.display().to_string()) + .unwrap_or_default(), + _ => format!("{{{{{}}}}}", key), + } + }) + .to_string(); +} -- cgit v1.2.3