extern crate minifier;
use std::env;
use std::ffi::OsStr;
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use minifier::{html, js};
fn print_help() {
println!(r##"For now, this minifier supports the following type of files:
* .js
* .html
* .htm"##);
}
pub fn get_all_data(file_path: &str) -> io::Result<String> {
let mut file = File::open(file_path)?;
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
Ok(data)
}
fn call_minifier<F>(file_path: &str, func: F)
where F: Fn(&str) -> String {
match get_all_data(file_path) {
Ok(content) => {
let mut out = PathBuf::from(file_path);
let original_extension = out.extension()
.unwrap_or(OsStr::new(""))
.to_str()
.unwrap_or("")
.to_owned();
out.set_extension(format!("min.{}", original_extension));
if let Ok(mut file) = OpenOptions::new().truncate(true)
.write(true)
.create(true)
.open(out.clone()) {
if let Err(e) = write!(file, "{}", func(&content)) {
writeln!(&mut io::stderr(),
"Impossible to write into {:?}: {}", out, e).unwrap();
} else {
println!("{:?}: done -> generated into {:?}", file_path, out);
}
} else {
writeln!(&mut io::stderr(),
"Impossible to create new file: {:?}", out).unwrap();
}
}
Err(e) => writeln!(&mut io::stderr(), "\"{}\": {}", file_path, e).unwrap(),
}
}
fn main() {
let args: Vec<_> = env::args().skip(1).collect();
if args.is_empty() {
println!("Missing files to work on...\nExample: ./minifier file.js\n");
print_help();
return
}
for arg in &args {
let p = Path::new(arg);
if !p.is_file() {
writeln!(&mut io::stderr(), "\"{}\" isn't a file", arg).unwrap();
continue
}
match p.extension().unwrap_or(OsStr::new("")).to_str().unwrap_or("") {
"js" => call_minifier(arg, js::minify),
"html" | "htm" => call_minifier(arg, html::minify),
x => println!("\"{}\": this format isn't supported", x),
}
}
}