use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkInfo {
pub index: usize,
pub name: String,
pub size: u64,
pub sha256: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SplitManifest {
pub file: String,
pub total: u64,
pub chunk_size: u64,
pub total_sha256: String,
pub chunks: Vec<ChunkInfo>,
}
#[derive(Debug, Clone, Default)]
pub struct SplitOptions {
pub parts: Option<usize>,
pub size: Option<u64>,
pub out_dir: Option<PathBuf>,
}
pub fn split_file(src: &Path, opts: &SplitOptions) -> Result<(PathBuf, SplitManifest)> {
if opts.parts.is_some() && opts.size.is_some() {
bail!("use either --parts or --size, not both");
}
let meta = std::fs::metadata(src).with_context(|| format!("cannot open {}", src.display()))?;
if !meta.is_file() {
bail!("not a file: {}", src.display());
}
let total = meta.len();
if total == 0 {
bail!("cannot split an empty file: {}", src.display());
}
let chunk_size = match (opts.parts, opts.size) {
(Some(n), None) => {
if n == 0 {
bail!("--parts must be >= 1");
}
total.div_ceil(n as u64).max(1)
}
(None, Some(s)) => {
if s == 0 {
bail!("--size must be > 0");
}
s
}
(None, None) => 10 * 1024 * 1024,
(Some(_), Some(_)) => unreachable!(),
};
let count = total.div_ceil(chunk_size) as usize;
let width = 3.max(count.to_string().len());
let dir = opts.out_dir.clone().unwrap_or_else(|| {
src.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."))
});
std::fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
let base = src
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "file".into());
let mut manifest = SplitManifest {
file: base.clone(),
total,
chunk_size,
total_sha256: String::new(),
chunks: Vec::with_capacity(count),
};
let mut total_hasher = sha2::Sha256::new();
use sha2::Digest;
use std::io::{Read, Write};
let mut f = std::fs::File::open(src)?;
let mut left = total;
for i in 0..count {
let name = format!("{base}.part-{:0width$}", i + 1);
let want = left.min(chunk_size);
let mut hasher = sha2::Sha256::new();
let mut written = 0u64;
let out_path = dir.join(&name);
let mut out = std::fs::File::create(&out_path)
.with_context(|| format!("cannot write {}", out_path.display()))?;
let mut buf = [0u8; 128 * 1024];
while written < want {
let take = (want - written).min(buf.len() as u64) as usize;
let n = f.read(&mut buf[..take])?;
if n == 0 {
break;
}
out.write_all(&buf[..n])?;
hasher.update(&buf[..n]);
total_hasher.update(&buf[..n]);
written += n as u64;
}
if written != want {
bail!(
"short read on {} (file changed during split?)",
src.display()
);
}
manifest.chunks.push(ChunkInfo {
index: i + 1,
name,
size: written,
sha256: hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect(),
});
left -= written;
}
manifest.total_sha256 = total_hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect();
let manifest_path = dir.join(format!("{base}.xget-parts.json"));
let raw = serde_json::to_string_pretty(&manifest)?;
std::fs::write(&manifest_path, raw)?;
Ok((manifest_path, manifest))
}
pub fn join_parts(source: &Path, dest: &Path) -> Result<u64> {
let plan = resolve_plan(source)?;
if let Some(parent) = dest.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
}
let pb = indicatif::ProgressBar::new(plan.total.unwrap_or(0));
pb.set_style(crate::engine::total_style());
pb.set_message("join");
use std::io::Write;
let mut out =
std::fs::File::create(dest).with_context(|| format!("cannot write {}", dest.display()))?;
let mut bytes = 0u64;
for c in &plan.chunks {
let data =
std::fs::read(&c.path).with_context(|| format!("cannot read {}", c.path.display()))?;
if let Some(expect) = c.sha256.as_deref()
&& !hash_eq(&sha256_hex(&data), expect)
{
bail!(
"chunk {} failed sha256 check (file changed?):\n got {}\n expected {expect}",
c.path.display(),
sha256_hex(&data)
);
}
out.write_all(&data)?;
bytes += data.len() as u64;
pb.inc(data.len() as u64);
}
out.flush()?;
pb.finish_and_clear();
if let Some(expect_total) = plan.total
&& bytes != expect_total
{
bail!("size mismatch after join: got {bytes}, expected {expect_total}");
}
Ok(bytes)
}
struct PlannedChunk {
path: PathBuf,
sha256: Option<String>,
}
struct Plan {
chunks: Vec<PlannedChunk>,
total: Option<u64>,
}
fn resolve_plan(source: &Path) -> Result<Plan> {
if source.is_file() && source.extension().is_some_and(|e| e == "json") {
let raw = std::fs::read_to_string(source)
.with_context(|| format!("cannot read {}", source.display()))?;
let m: SplitManifest = serde_json::from_str(&raw)
.context("not an xget parts manifest (need *.xget-parts.json from `xget split`)")?;
if m.chunks.is_empty() {
bail!("manifest has no chunks: {}", source.display());
}
let dir = source.parent().unwrap_or_else(|| Path::new("."));
let chunks = m
.chunks
.iter()
.map(|c| PlannedChunk {
path: dir.join(&c.name),
sha256: Some(c.sha256.clone()),
})
.collect();
return Ok(Plan {
chunks,
total: Some(m.total),
});
}
if source.is_dir() {
let mut manifests: Vec<PathBuf> = std::fs::read_dir(source)?
.flatten()
.map(|e| e.path())
.filter(|p| {
p.extension().is_some_and(|e| e == "json")
&& p.file_name()
.is_some_and(|n| n.to_string_lossy().ends_with(".xget-parts.json"))
})
.collect();
manifests.sort();
if let Some(m) = manifests.into_iter().next() {
return resolve_plan(&m);
}
let chunks = discover_chunks(source, None)?;
return Ok(Plan {
chunks: chunks
.into_iter()
.map(|p| PlannedChunk {
path: p,
sha256: None,
})
.collect(),
total: None,
});
}
if source.is_file() {
let name = source
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
if let Some((prefix, _)) = split_chunk_name(&name) {
let dir = source.parent().unwrap_or_else(|| Path::new("."));
let chunks = discover_chunks(dir, Some(&prefix))?;
return Ok(Plan {
chunks: chunks
.into_iter()
.map(|p| PlannedChunk {
path: p,
sha256: None,
})
.collect(),
total: None,
});
}
}
bail!(
"cannot join {}: need a manifest (*.xget-parts.json), a *.part-NNN chunk, or a directory",
source.display()
);
}
fn split_chunk_name(name: &str) -> Option<(String, usize)> {
let (prefix, num) = name.rsplit_once(".part-")?;
if prefix.is_empty() || num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
Some((prefix.to_string(), num.parse().ok()?))
}
fn discover_chunks(dir: &Path, prefix: Option<&str>) -> Result<Vec<PathBuf>> {
let mut found: Vec<(usize, PathBuf)> = Vec::new();
for e in std::fs::read_dir(dir).with_context(|| format!("cannot read {}", dir.display()))? {
let e = e?;
let name = e.file_name().to_string_lossy().to_string();
let Some((pfx, num)) = split_chunk_name(&name) else {
continue;
};
if prefix.is_some_and(|p| p != pfx) {
continue;
}
found.push((num, e.path()));
}
if found.is_empty() {
bail!("no *.part-NNN chunks in {}", dir.display());
}
found.sort();
for (i, (num, _)) in found.iter().enumerate() {
if *num != i + 1 {
bail!(
"chunk numbering has a gap in {} (missing part-{:03})",
dir.display(),
i + 1
);
}
}
Ok(found.into_iter().map(|(_, p)| p).collect())
}
fn sha256_hex(data: &[u8]) -> String {
use sha2::{Digest, Sha256};
Sha256::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn hash_eq(a: &str, b: &str) -> bool {
a.eq_ignore_ascii_case(b.trim())
}
#[cfg(test)]
mod tests {
use super::*;
fn tmpdir(tag: &str) -> (TempGuard, PathBuf) {
let d = std::env::temp_dir().join(format!("xget-split-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
(TempGuard(d.clone()), d)
}
struct TempGuard(PathBuf);
impl Drop for TempGuard {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn sample(n: usize) -> Vec<u8> {
(0..n).map(|i| (i * 11 % 251) as u8).collect()
}
#[test]
fn split_by_size_and_join_with_manifest() {
let (_g, dir) = tmpdir("roundtrip");
let src = dir.join("data.bin");
let data = sample(5_000_000);
std::fs::write(&src, &data).unwrap();
let (manifest_path, m) = split_file(
&src,
&SplitOptions {
size: Some(2_000_000),
..Default::default()
},
)
.unwrap();
assert_eq!(m.chunks.len(), 3);
assert_eq!(m.total, 5_000_000);
let dest = dir.join("back.bin");
let bytes = join_parts(&manifest_path, &dest).unwrap();
assert_eq!(bytes, 5_000_000);
assert_eq!(std::fs::read(&dest).unwrap(), data);
}
#[test]
fn split_by_parts_count() {
let (_g, dir) = tmpdir("parts");
let src = dir.join("d.bin");
std::fs::write(&src, sample(1000)).unwrap();
let (_, m) = split_file(
&src,
&SplitOptions {
parts: Some(4),
..Default::default()
},
)
.unwrap();
assert_eq!(m.chunks.len(), 4);
assert_eq!(m.chunks.iter().map(|c| c.size).sum::<u64>(), 1000);
let err = split_file(
&src,
&SplitOptions {
parts: Some(2),
size: Some(10),
..Default::default()
},
)
.unwrap_err();
assert!(
err.to_string().contains("either"),
"readable flags error: {err}"
);
}
#[test]
fn tampered_chunk_fails_join() {
let (_g, dir) = tmpdir("tamper");
let src = dir.join("d.bin");
std::fs::write(&src, sample(3000)).unwrap();
let (manifest_path, m) = split_file(
&src,
&SplitOptions {
size: Some(1000),
..Default::default()
},
)
.unwrap();
assert_eq!(m.chunks.len(), 3);
std::fs::write(dir.join(&m.chunks[1].name), vec![0u8; 1000]).unwrap();
let err = join_parts(&manifest_path, &dir.join("back.bin")).unwrap_err();
assert!(
err.to_string().contains("sha256 check"),
"verification catches mismatch: {err}"
);
}
#[test]
fn join_from_first_chunk_without_manifest() {
let (_g, dir) = tmpdir("nochunks");
let src = dir.join("d.bin");
let data = sample(2500);
std::fs::write(&src, &data).unwrap();
let (_, m) = split_file(
&src,
&SplitOptions {
size: Some(1000),
..Default::default()
},
)
.unwrap();
std::fs::remove_file(dir.join(format!("{}.xget-parts.json", "d.bin"))).unwrap();
let first = dir.join(&m.chunks[0].name);
let bytes = join_parts(&first, &dir.join("back.bin")).unwrap();
assert_eq!(bytes, 2500);
assert_eq!(std::fs::read(dir.join("back.bin")).unwrap(), data);
}
#[test]
fn join_rejects_garbage_source() {
let (_g, dir) = tmpdir("garbage");
let f = dir.join("note.txt");
std::fs::write(&f, b"hi").unwrap();
let err = join_parts(&f, &dir.join("back.bin")).unwrap_err();
assert!(
err.to_string().contains("cannot join"),
"readable error: {err}"
);
}
}