license-tool/src/main.rs

65 lines
1.7 KiB
Rust
Raw Normal View History

2022-10-06 22:34:56 -07:00
use std::env;
use std::fs;
use std::io;
use std::process::exit;
const DATA_PATH: &str = env!("DATA_PATH");
fn main() {
let args: Vec<String> = env::args().collect();
let license_index;
let outfile: &str;
if args.len() < 2 || args[1] == "-h" {
print_help();
return;
} else if args[1] == "-o" {
outfile = get_outfile(&args).unwrap_or_else(|| exit(1));
license_index = 3;
} else {
outfile = "LICENSE";
license_index = 1;
}
if args.len() <= license_index {
print_help();
return;
}
copy_license(&args[license_index], outfile);
}
fn copy_license(license: &str, outfile: &str) {
let license_path = DATA_PATH.to_owned() + "/" + license;
let license_content = fs::read_to_string(license_path).unwrap_or_else(|_| {
eprintln!("error: could not open license for reading: '{}'", license);
exit(1);
});
let _ = fs::write(outfile, license_content).or_else(|_| -> io::Result<()> {
eprintln!("error: could not write license: '{}'", outfile);
exit(1);
});
}
fn get_outfile(args: &Vec<String>) -> Option<&str> {
if args.len() < 3 {
eprintln!("error: -o requires an option");
return None;
}
return Some(&args[2]);
}
fn print_help() {
println!("license-tool [-h] [-o OUTFILE] <license>");
println!("Licenses:");
let dirs = fs::read_dir(DATA_PATH);
if dirs.is_err() {
eprintln!("error: could not open data directory");
exit(1);
}
for file in dirs.unwrap() {
if file.is_err() {
eprintln!("error: error reading data directory");
exit(1);
}
println!(" {}", file.as_ref().unwrap().file_name().to_string_lossy());
}
}