use crate::error::{Failure, Result};
use serde::Serialize;
use std::io::Write;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize)]
pub struct Report {
pub path: PathBuf,
pub bytes: u64,
pub checksum: String,
}
pub fn write(path: &Path, bytes: &[u8]) -> Result<Report> {
let folder = enclosing(path);
let mut staged =
tempfile::NamedTempFile::new_in(folder).map_err(|cause| unwritable(path, &cause))?;
staged
.write_all(bytes)
.and_then(|()| staged.as_file().sync_all())
.map_err(|cause| unwritable(path, &cause))?;
staged
.persist(path)
.map_err(|cause| unwritable(path, &cause.error))?;
Ok(Report {
path: path.to_path_buf(),
bytes: bytes.len() as u64,
checksum: super::checksum::of_bytes(bytes),
})
}
pub struct Staged {
destination: PathBuf,
file: tempfile::NamedTempFile,
written: u64,
digest: super::checksum::ByteSignature,
}
impl std::io::Write for Staged {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
let taken = self.file.write(bytes)?;
self.digest.absorb(&bytes[..taken]);
self.written += taken as u64;
Ok(taken)
}
fn flush(&mut self) -> std::io::Result<()> {
self.file.flush()
}
}
impl Staged {
pub fn finish(mut self) -> Result<Report> {
self.file
.flush()
.and_then(|()| self.file.as_file().sync_all())
.map_err(|cause| unwritable(&self.destination, &cause))?;
self.file
.persist(&self.destination)
.map_err(|cause| unwritable(&self.destination, &cause.error))?;
Ok(Report {
bytes: self.written,
checksum: self.digest.finish(),
path: self.destination,
})
}
}
pub fn staged(path: &Path) -> Result<Staged> {
let folder = enclosing(path);
let file = tempfile::NamedTempFile::new_in(folder).map_err(|cause| unwritable(path, &cause))?;
Ok(Staged {
destination: path.to_path_buf(),
file,
written: 0,
digest: super::checksum::ByteSignature::default(),
})
}
fn enclosing(path: &Path) -> &Path {
match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
}
}
fn unwritable(path: &Path, cause: &impl std::fmt::Display) -> Failure {
Failure::config(
"output.destination_unwritable",
format!("the destination `{}` cannot be written", path.display()),
)
.with_detail("detail", path.display().to_string())
.with_hint("point --output at a path inside a writable directory")
.with_cause(cause.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_bytes_arrive_whole_with_their_own_signature() {
let scratch = tempfile::tempdir().expect("scratch directory");
let target = scratch.path().join("result.json");
let report = write(&target, b"{\"rows\":[]}").expect("writes");
assert_eq!(report.bytes, 11);
assert_eq!(std::fs::read(&target).expect("reads"), b"{\"rows\":[]}");
assert!(report.checksum.starts_with("sha256:"));
}
#[test]
fn the_same_bytes_always_report_the_same_signature() {
let scratch = tempfile::tempdir().expect("scratch directory");
let first = write(&scratch.path().join("a"), b"same").expect("writes");
let second = write(&scratch.path().join("b"), b"same").expect("writes");
assert_eq!(first.checksum, second.checksum);
let different = write(&scratch.path().join("c"), b"other").expect("writes");
assert_ne!(first.checksum, different.checksum);
}
#[test]
fn an_existing_destination_is_replaced_whole() {
let scratch = tempfile::tempdir().expect("scratch directory");
let target = scratch.path().join("result.json");
std::fs::write(&target, b"the previous answer").expect("writes");
write(&target, b"new").expect("writes");
assert_eq!(std::fs::read(&target).expect("reads"), b"new");
}
#[test]
fn a_destination_that_cannot_be_reached_leaves_nothing_behind() {
let scratch = tempfile::tempdir().expect("scratch directory");
let missing = scratch.path().join("no-such-folder").join("result.json");
let failure = write(&missing, b"x").expect_err("must refuse");
assert_eq!(failure.code(), "output.destination_unwritable");
assert_eq!(failure.exit_number().code(), 4);
assert!(
std::fs::read_dir(scratch.path())
.expect("reads")
.next()
.is_none(),
"a failed write must leave the directory as it found it"
);
}
#[test]
fn a_bare_name_is_staged_beside_itself() {
assert_eq!(enclosing(Path::new("result.json")), Path::new("."));
assert_eq!(enclosing(Path::new("/tmp/result.json")), Path::new("/tmp"));
}
}