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

103 lines
2.3 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::{
2023-11-08 13:51:04 +00:00
ArgumentsSubcommand, Cli, DirectorySubcommand, FileSubcommand,
2023-11-10 13:33:18 +00:00
MainSubcommand::*, MatchSubcommand, Parser,
2023-11-05 11:18:45 +00:00
},
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-08 13:51:04 +00:00
Directory {
command: directory_subcommand,
} => match directory_subcommand {
DirectorySubcommand::Exists { directory } => {
if !(directory.exists() && directory.is_dir()) {
std::process::exit(1);
}
}
},
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-11-10 13:33:18 +00:00
Match {
command: match_subcommand,
} => match match_subcommand {
MatchSubcommand::Regex { pattern, string } => {
let regex = regex::RegexBuilder::new(&pattern).build().unwrap();
if !regex.is_match(&string) {
std::process::exit(1);
}
}
},
2023-11-01 16:56:32 +00:00
}
2023-10-31 13:51:57 +00:00
}