1
Fork 0
bautils/source/cli/run.rs

81 lines
1.7 KiB
Rust
Raw Normal View History

2023-10-31 15:58:35 +00:00
//! The CLI logic.
2023-11-01 16:56:32 +00:00
use {
crate::{
2023-11-05 11:18:45 +00:00
cli::{
ArgumentsSubcommand, Cli, FileSubcommand, MainSubcommand::*, Parser,
},
2023-11-01 16:56:32 +00:00
logging::append_line_to_file,
},
chrono::{SecondsFormat, Utc},
2023-11-06 17:54:33 +00:00
std::{ffi::OsStr, path::Path},
2023-11-01 16:56:32 +00:00
};
2023-10-31 13:51:57 +00:00
2023-10-31 15:58:35 +00:00
/// Parse the CLI arguments and execute them.
2023-10-31 13:51:57 +00:00
pub fn run() {
let cli = Cli::parse();
2023-11-01 16:56:32 +00:00
match cli.command {
2023-11-04 14:11:37 +00:00
Arguments {
command: arguments_subcommand,
} => match arguments_subcommand {
ArgumentsSubcommand::Count { arguments, newline } => {
let mut count = format!("{}", arguments.len());
if newline {
count.push('\n');
}
print!("{}", count);
}
},
2023-11-05 11:18:45 +00:00
File {
command: file_subcommand,
} => match file_subcommand {
FileSubcommand::Exists { file } => {
if !(file.exists() && file.is_file()) {
2023-11-05 11:18:45 +00:00
std::process::exit(1);
}
}
2023-11-06 17:54:33 +00:00
FileSubcommand::Parts {
basename,
directory,
extension,
file,
} => {
if basename {
print!(
"{}",
file.file_stem().and_then(OsStr::to_str).unwrap_or_default()
);
}
if directory {
print!(
"{}",
file.parent().and_then(Path::to_str).unwrap_or_default()
);
}
if extension {
print!(
"{}",
file.extension().and_then(OsStr::to_str).unwrap_or_default()
);
}
}
2023-11-05 11:18:45 +00:00
},
2023-11-04 14:35:54 +00:00
Log { data_to_log, file } => {
2023-11-01 16:56:32 +00:00
let log_line = format!(
"{} {}",
Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
data_to_log.join(" ")
);
println!("{}", log_line);
2023-11-04 14:35:54 +00:00
append_line_to_file(&file, &log_line).unwrap();
2023-11-01 16:56:32 +00:00
}
}
2023-10-31 13:51:57 +00:00
}