use flate2::read::GzDecoder; use std::{ fs::File, io::{self, BufWriter, Write}, path::{Path, PathBuf}, time::Instant, }; use tar::Archive; use zstd::zstd_safe::{CCtx, CParameter}; const ZSTD_LEVEL: i32 = 3; pub fn perform(revision: &str, output_dir: &Path) -> anyhow::Result<()> { std::fs::create_dir_all(output_dir)?; std::fs::write(output_dir.join("dict.bin"), crate::DICT)?; std::fs::write(output_dir.join("rev.txt"), revision)?; let tarball_url = format!("https://github.com/rust-lang/crates.io-index/archive/{revision}.tar.gz"); eprintln!("nix2cargo: downloading {tarball_url}"); let resp = crate::agent().get(tarball_url).call()?; let body = resp.into_body().into_reader(); let mut ar = Archive::new(GzDecoder::new(body)); let index_wr = BufWriter::new(File::create(output_dir.join("index.csv"))?); let data_wr = BufWriter::with_capacity(1 << 20, File::create(output_dir.join("data.zst"))?); let mut cctx = CCtx::create(); let zerr = |code| anyhow::Error::msg(zstd::zstd_safe::get_error_name(code)); cctx.set_parameter(CParameter::CompressionLevel(ZSTD_LEVEL)) .map_err(zerr)?; cctx.load_dictionary(super::DICT).map_err(zerr)?; let mut index_wr = index_wr; let mut data_wr = Counter { pos: 0, inner: data_wr, }; let started_at = Instant::now(); let mut count = 0; let mut prev_epoch = 0; let mut prev_path = String::new(); for entry in ar.entries()? { let mut entry = entry?; if !entry.header().entry_type().is_file() { continue; } let path = entry.path()?; let mut comps = path.components(); if comps.next().is_none() { return Err(anyhow::Error::msg("Missing toplevel directory")); } let path = comps .as_path() .to_str() .ok_or_else(|| anyhow::Error::msg("Non-unicode path"))?; if path <= prev_path.as_str() { return Err(anyhow::Error::msg("Unordered archive")); } prev_path.clear(); prev_path.push_str(path); let size = entry.size(); let offset = data_wr.pos; index_wr.write_fmt(format_args!("{path},{offset},{size}\n"))?; count += 1; let epoch = started_at.elapsed().as_secs(); if epoch >= prev_epoch + 5 { eprintln!( "nix2cargo: {}k crates downloaded in {epoch}s, currently at {path}", count / 1_000 ); prev_epoch += 5; } let mut enc = zstd::stream::write::Encoder::with_context(&mut data_wr, &mut cctx); enc.set_pledged_src_size(Some(size))?; io::copy(&mut entry, &mut enc)?; enc.finish()?; } index_wr.flush()?; data_wr.flush()?; Ok(()) } #[derive(clap::Parser)] pub struct Cmd { pub revision: String, pub output_dir: PathBuf, } impl Cmd { pub fn exec(self) -> anyhow::Result<()> { let Self { revision, output_dir, } = self; perform(&revision, &output_dir)?; Ok(()) } } struct Counter { inner: W, pos: u64, } impl Write for Counter { fn write(&mut self, buf: &[u8]) -> io::Result { let n = self.inner.write(buf)?; self.pos += n as u64; Ok(n) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } }