use std::ffi::OsStr; use libflate::gzip::Encoder; use walkdir::WalkDir; fn main() -> Result<(), std::io::Error> { use std::env; let out_dir = std::path::PathBuf::from(env::var("OUT_DIR").unwrap()); println!("cargo:rerun-if-changed=javascript/"); if let Ok(exit) = std::process::Command::new("tsc") .arg("--outDir") .arg(&out_dir) .current_dir("javascript") .spawn()? .wait() { if !exit.success() { std::process::exit(exit.code().unwrap_or(1)) } } println!("cargo:rerun-if-changed=assets/"); let assets_path = std::path::Path::new("assets"); let mut assets = WalkDir::new(&assets_path) .into_iter(); while let Some(Ok(entry)) = assets.next() { if entry.file_type().is_dir() { if let Err(err) = std::fs::create_dir(&out_dir.join(entry.path())) { if err.kind() != std::io::ErrorKind::AlreadyExists { return Err(err) } } } else { std::fs::copy(entry.path(), &out_dir.join(entry.path().strip_prefix(assets_path).unwrap()))?; } } let walker = WalkDir::new(&out_dir) .into_iter() .map(Result::unwrap) .filter(|e| { e.file_type().is_file() && e.path().extension().unwrap() != "gz" }); for entry in walker { let normal_path = entry.path(); let gzip_path = normal_path.with_extension({ let mut extension = normal_path .extension() .unwrap() .to_owned(); extension.push(OsStr::new(".gz")); extension }); eprintln!( "{} -> {}", normal_path.strip_prefix(&out_dir).unwrap().display(), gzip_path.strip_prefix(&out_dir).unwrap().display() ); { let mut out_file = std::fs::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&gzip_path)?; let mut in_file = std::fs::File::open(&normal_path)?; let mut encoder = Encoder::new(&mut out_file)?; std::io::copy(&mut in_file, &mut encoder)?; encoder.finish().into_result()?; } let normal_len: f64 = std::fs::metadata(&normal_path).unwrap().len() as f64; let gzipped_len: f64 = std::fs::metadata(&gzip_path).unwrap().len() as f64; let ratio = gzipped_len / normal_len; eprintln!("Ratio: {}", ratio); if ratio <= 0.9 { std::fs::remove_file(&normal_path)? } else { println!( "cargo:warning={} compression ratio is {} (> 0.9), leaving as is", entry.path().display(), ratio ); std::fs::remove_file(&gzip_path)? } } Ok(()) }