#[allow(warnings)]
pub mod cli {
use clap::{arg, Arg, ArgAction, Command};
pub fn cli() {
let matches = Command::new("dedup_hosts")
.about("Command line tools for dedup the hosts file\nExample:\nsudo dedup_hosts dedup /etc/hosts\ndedup_hosts.exe dedup C:\\Windows\\System32\\drivers\\etc\\hosts")
.version("1.0.0")
.subcommand_required(true)
.arg_required_else_help(true)
.allow_external_subcommands(true)
.author("Anonymous")
.subcommand(
Command::new("dedup")
.about("sudo dedup_hosts dedup /etc/hosts\ndedup_hosts.exe dedup C:\\Windows\\System32\\drivers\\etc\\hosts")
.arg(arg!([path] "the hosts file path"))
.arg_required_else_help(true),
)
.get_matches();
match matches.subcommand_name() {
Some("dedup") => {
let path = if let Some(dt) = matches.subcommand_matches("dedup") {
let text = dt.get_one::<String>("path").unwrap();
text
} else {
""
};
let hosts = std::fs::read_to_string(path).unwrap();
std::fs::write(path, parse_hosts(hosts)).unwrap();
}
_ => {}
}
}
fn parse_hosts(hosts:String)->String{
let mut new_hosts_vec:Vec<String> = Vec::new();
let hosts_vec = hosts.split("\n").filter(|s|!s.is_empty()).map(|s|s.to_string().trim().to_string()).collect::<Vec<_>>();
hosts_vec.clone().into_iter().for_each(|s|{
if !s.starts_with("#"){
new_hosts_vec.push(s);
}
});
let new_hosts_vec_split = new_hosts_vec.iter().map(|s|{
doe::split_to_vec!(s," ")
}).collect::<Vec<_>>();
let mut new_hosts_vec_split_join = new_hosts_vec_split.into_iter().map(|s|s.join(" ")).collect::<Vec<_>>();
new_hosts_vec_split_join.dedup_by_key(|s|{
s.to_string()
});
new_hosts_vec_split_join.join("\n")
}
}