Merge pull request #5 from Venketaramana/riir

[rust] implement list_distros match_condition method in rust
This commit is contained in:
Teoh Han Hui 2024-06-29 16:28:10 +08:00 committed by GitHub
commit 517dde43cc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 66 additions and 0 deletions

View file

@ -100,6 +100,66 @@ impl Distro {
", ",
); );
buf.push_str(
"
impl Distro {
pub fn detect(name: &str) -> Option<Self> {
",
);
for (variant, distro) in &variants {
let distro_pattern = &distro.pattern;
let matches: Vec<&str> = distro_pattern.split('|').map(|s| s.trim()).collect();
let mut condition = Vec::new();
for m in matches {
let stripped = m.trim_matches(|c| c == '*' || c == '\'' || c == '"').to_lowercase();
if stripped.contains('*') || stripped.contains('"') {
println!("TODO: Cannot properly parse: {}", m);
}
// Exact matches
if m.trim_matches('*') == m {
condition.push(format!("name == r#\"{}\"#", stripped));
continue;
}
// Both sides are *
if m.starts_with('*') && m.ends_with('*') {
condition.push(format!("(name.starts_with(r#\"{}\"#) || name.ends_with(r#\"{}\"#))", stripped, stripped));
continue;
}
// Ends with *
if m.ends_with('*') {
condition.push(format!("name.starts_with(r#\"{}\"#)", stripped));
continue;
}
// Starts with *
if m.starts_with('*') {
condition.push(format!("name.ends_with(r#\"{}\"#)", stripped));
continue;
}
}
let condition = condition.join(" || ");
buf.push_str(&format!("
if {condition} {{
return Some(Self::{variant});
}}"
));
};
buf.push_str(&format!("
None
"
));
buf.push_str("
}
}");
fs::write(out_path.join("distros.rs"), buf).expect("couldn't write distros.rs"); fs::write(out_path.join("distros.rs"), buf).expect("couldn't write distros.rs");
} }

View file

@ -9,6 +9,8 @@ use std::{env, fmt};
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use tracing::debug; use tracing::debug;
use crate::distros::Distro;
/// Gets the absolute path of the neofetch command. /// Gets the absolute path of the neofetch command.
pub fn get_command_path() -> Result<PathBuf> { pub fn get_command_path() -> Result<PathBuf> {
if let Ok(workspace_dir) = env::var("CARGO_WORKSPACE_DIR") { if let Ok(workspace_dir) = env::var("CARGO_WORKSPACE_DIR") {
@ -61,6 +63,10 @@ where
}; };
debug!(%distro, "distro name"); debug!(%distro, "distro name");
if let Some(distro) = Distro::detect(&distro) {
return Ok(distro.ascii_art().to_owned());
}
todo!() todo!()
} }