use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::{Methods, Noticed, Prov, ProvError, Record, day};
use crate::cache::{Cache, QueryRecord};
use crate::exec::RunReport;
use crate::graph::{Graph, NodeId};
use crate::hash::ContentHash;
use crate::remote::request::Method;
use crate::store::{BlobStore, ObjectKey};
use crate::types::DataKind;
const MANIFEST_HASH: &str = "blake3";
pub struct Request<'a> {
pub graph: &'a Graph,
pub roots: &'a [NodeId],
pub report: &'a RunReport,
pub prov: &'a Prov,
pub methods: &'a Methods,
pub include: &'a [PathBuf],
pub queries: Option<&'a Cache>,
pub thin: bool,
}
#[derive(Clone, Debug, Default)]
pub struct Summary {
pub root: PathBuf,
pub files: Vec<String>,
pub steps: usize,
pub gaps: usize,
}
#[derive(Debug)]
pub enum BundleError {
Io {
path: PathBuf,
source: io::Error,
},
Prov(ProvError),
Malformed {
path: PathBuf,
detail: String,
},
}
impl fmt::Display for BundleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Prov(error) => write!(f, "{error}"),
Self::Malformed { path, detail } => write!(f, "{}: {detail}", path.display()),
}
}
}
impl std::error::Error for BundleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Prov(error) => Some(error),
Self::Malformed { .. } => None,
}
}
}
impl From<ProvError> for BundleError {
fn from(error: ProvError) -> Self {
Self::Prov(error)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Match {
Identical,
Reproduced,
Differs,
Missing,
}
impl fmt::Display for Match {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Identical => "identical",
Self::Reproduced => "reproduced",
Self::Differs => "differs",
Self::Missing => "missing",
})
}
}
#[derive(Clone, Debug)]
pub struct Check {
pub step: String,
pub scope: Option<String>,
pub expected: ContentHash,
pub found: Option<ContentHash>,
pub same_key: bool,
pub verdict: Match,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
Same,
Changed,
Absent,
}
impl fmt::Display for Presence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Same => "same",
Self::Changed => "changed",
Self::Absent => "absent",
})
}
}
#[derive(Clone, Debug)]
pub struct InputCheck {
pub step: String,
pub param: String,
pub path: PathBuf,
pub presence: Presence,
}
#[derive(Clone, Debug, Default)]
pub struct Verification {
pub checks: Vec<Check>,
pub inputs: Vec<InputCheck>,
pub noticed: Vec<Noticed>,
}
impl Verification {
#[must_use]
pub fn reproduced(&self) -> bool {
!self.checks.is_empty()
&& self
.checks
.iter()
.all(|check| matches!(check.verdict, Match::Identical | Match::Reproduced))
}
#[must_use]
pub fn verdict(&self) -> Match {
self.checks
.iter()
.map(|check| check.verdict)
.max()
.unwrap_or(Match::Missing)
}
#[must_use]
pub fn summary(&self) -> String {
let count = |wanted: Match| {
self.checks
.iter()
.filter(|check| check.verdict == wanted)
.count()
};
let mut parts = Vec::new();
for verdict in [
Match::Identical,
Match::Reproduced,
Match::Differs,
Match::Missing,
] {
let found = count(verdict);
if found > 0 {
parts.push(format!("{found} {verdict}"));
}
}
let places = self.checks.len();
let noun = if places == 1 { "result" } else { "results" };
if parts.is_empty() {
return "this bundle records no results.".to_owned();
}
format!("{places} {noun}: {}.", parts.join(", "))
}
#[must_use]
pub fn text(&self) -> String {
let mut lines = Vec::new();
for check in &self.checks {
let named = match &check.scope {
Some(scope) => format!("`{}` ({scope})", check.step),
None => format!("`{}`", check.step),
};
lines.push(format!("{:<16} {named}", check.verdict.to_string()));
match check.verdict {
Match::Identical => lines.push(format!(
" the same key, the same result {}",
short(check.expected)
)),
Match::Reproduced => {
lines.push(format!(
" the result is the same {}",
short(check.expected)
));
lines.push(" the key is not: something in the environment moved".to_owned());
}
Match::Differs => lines.push(format!(
" expected {} and got {}",
short(check.expected),
check.found.map_or_else(|| "nothing".to_owned(), short),
)),
Match::Missing => {
lines.push(" this pipeline did not produce it".to_owned());
}
}
}
let moved: Vec<&InputCheck> = self
.inputs
.iter()
.filter(|input| input.presence != Presence::Same)
.collect();
if !moved.is_empty() {
lines.push(String::new());
lines.push(format!(
"{} of {} inputs are not the ones this bundle was built from:",
moved.len(),
self.inputs.len()
));
for input in moved {
lines.push(format!(
" {:<10} `{}` of `{}`: {}",
input.presence.to_string(),
input.param,
input.step,
input.path.display()
));
}
lines
.push("A changed input explains a changed output, so read these first.".to_owned());
}
if !self.noticed.is_empty() {
lines.push(String::new());
let mut places: Vec<(&str, Option<&str>)> = self
.noticed
.iter()
.map(|item| (item.step.as_str(), item.scope.as_deref()))
.collect();
places.dedup();
lines.push(format!(
"{} of {} results name a file where a sample identifier belongs:",
places.len(),
self.checks.len()
));
for item in &self.noticed {
let named = match &item.scope {
Some(scope) => format!("`{}` ({scope})", item.step),
None => format!("`{}`", item.step),
};
lines.push(format!(" {named}: {}", item.note));
}
lines.push(
"Such a hash depends on the file it was named after, so a `differs` here may \
be that and nothing else."
.to_owned(),
);
let mut given: Vec<&str> = Vec::new();
for item in &self.noticed {
if !given.contains(&item.note.code()) {
given.push(item.note.code());
lines.push(format!(" {}", item.note.advice()));
}
}
}
if !lines.is_empty() {
lines.push(String::new());
}
lines.push(self.summary());
lines.join("\n")
}
}
pub fn write(into: &Path, request: &Request<'_>) -> Result<Summary, BundleError> {
create_dir(into)?;
let scopes = request.graph.scopes(request.roots);
let mut rows = Vec::new();
for result in &request.report.results {
let record = request.prov.lookup(result.key)?;
rows.push((
result,
scopes.get(&result.node).map(|scope| scope.value.clone()),
record,
));
}
let gaps = rows.iter().filter(|(_, _, held)| held.is_none()).count();
let mut methods = String::from("# Methods\n\n");
methods.push_str(&request.methods.text());
methods.push('\n');
put(into, "METHODS.md", &methods)?;
put(into, "README.md", &readme(request.methods, request.thin))?;
let mut results = Table::new(&["step", "scope", "key", "bytes", "canonical"]);
for (result, scope, _) in &rows {
results.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&result.key.to_hex(),
&result.hash.to_hex(),
&result.canonical.to_hex(),
]);
}
put(into, "results.tsv", &results.finish())?;
let mut commands = Table::new(&["step", "scope", "key", "command"]);
for (result, scope, record) in &rows {
let command = record
.as_ref()
.and_then(|record| record.command.clone())
.unwrap_or_default();
commands.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&result.key.to_hex(),
&command,
]);
}
put(into, "commands.tsv", &commands.finish())?;
let mut inputs = Table::new(&[
"step",
"scope",
"param",
"kind",
"path",
"bytes",
"canonical",
]);
for (result, scope, record) in &rows {
let Some(record) = record else { continue };
for input in &record.inputs {
inputs.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&input.param,
input.kind.name(),
&input.path.to_string_lossy(),
&input.bytes.to_hex(),
&input.canonical.to_hex(),
]);
}
}
put(into, "inputs.tsv", &inputs.finish())?;
let mut notes = Table::new(&["step", "scope", "key", "code", "value"]);
for (result, scope, record) in &rows {
let Some(record) = record else { continue };
for note in &record.output_notes {
notes.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&result.key.to_hex(),
note.code(),
¬e.value(),
]);
}
}
put(into, "notes.tsv", ¬es.finish())?;
let mut references = Table::new(&[
"param",
"path",
"build",
"accession",
"contigs",
"length",
"checksum",
"fingerprint",
]);
for reference in request.methods.references() {
references.row(&[
&reference.param,
&reference.path.to_string_lossy(),
reference.build.as_deref().unwrap_or(""),
reference.accession.as_deref().unwrap_or(""),
&reference.contigs.to_string(),
&reference.length.to_string(),
reference.checksum.as_deref().unwrap_or(""),
&reference.fingerprint,
]);
}
put(into, "references.tsv", &references.finish())?;
if !request.methods.claims.is_empty() {
let mut claims = Table::new(&["claim", "verdict", "step", "scope", "key", "canonical"]);
for check in &request.methods.claims {
match check.bound.as_slice() {
[] => claims.row(&[
&check.claim.text,
check.verdict.name(),
&check.claim.step,
check.claim.scope.as_deref().unwrap_or(""),
"",
"",
]),
bound => {
for row in bound {
claims.row(&[
&check.claim.text,
check.verdict.name(),
&check.claim.step,
row.scope.as_deref().unwrap_or(""),
&row.key.to_hex(),
&row.canonical.to_hex(),
]);
}
}
}
}
put(into, "claims.tsv", &claims.finish())?;
}
let mut remotes = Table::new(&["locator", "verdict", "fetched", "digest", "bytes"]);
for remote in request.methods.remotes() {
remotes.row(&[
&remote.locator,
&remote.verdict.to_string(),
&day(remote.fetched_at),
&remote.digest.to_hex(),
&remote.bytes.to_hex(),
]);
}
put(into, "remotes.tsv", &remotes.finish())?;
if let Some(cache) = request.queries {
let held = cache.all_query_records().map_err(|error| BundleError::Io {
path: into.to_path_buf(),
source: io::Error::other(error.to_string()),
})?;
if !held.is_empty() {
if !request.thin {
create_dir(&into.join("records"))?;
}
let mut records = Table::new(&[
"request", "revision", "recorded", "locator", "kind", "method", "url", "status",
"body", "digest",
]);
for record in &held {
records.row(&[
&record.request.to_hex(),
&record.revision.to_string(),
&day(record.recorded_at),
&record.locator,
record.kind.name(),
record.method.name(),
&record.url,
&record.status.to_string(),
&record.body.to_string(),
&record.digest.to_hex(),
]);
let body =
cache
.objects()
.checked_get(&record.body)
.map_err(|error| BundleError::Io {
path: into.to_path_buf(),
source: io::Error::other(error.to_string()),
})?;
if request.thin {
continue;
}
let Some(body) = body else { continue };
let name = format!("records/{}", record.body);
fs::write(into.join(&name), &body).map_err(|error| BundleError::Io {
path: into.join(&name),
source: error,
})?;
}
put(into, "records.tsv", &records.finish())?;
}
}
if request.thin {
let mut store = Table::new(&["name", "value"]);
store.row(&["thin", "yes"]);
store.row(&[
"store",
request
.queries
.and_then(|cache| cache.objects().remote_url())
.unwrap_or("(none configured on the machine that wrote this)"),
]);
put(into, "store.tsv", &store.finish())?;
}
let mut environment = Table::new(&["name", "value"]);
for engine in &request.methods.engines {
environment.row(&["ligase", engine]);
}
for platform in &request.methods.platforms {
environment.row(&["platform", platform]);
}
for (tool, version) in request.methods.tools() {
environment.row(&[&tool, &version]);
}
put(into, "environment.tsv", &environment.finish())?;
create_dir(&into.join("steps"))?;
let mut sources: BTreeMap<String, String> = BTreeMap::new();
for (_, _, record) in &rows {
let Some(record) = record else { continue };
sources.insert(step_file(record, &sources), record.code.clone());
}
for (name, code) in &sources {
put(into, &format!("steps/{name}"), code)?;
}
if !request.include.is_empty() {
create_dir(&into.join("pipeline"))?;
for source in request.include {
let Some(name) = source.file_name() else {
continue;
};
let destination = into.join("pipeline").join(name);
fs::copy(source, &destination).map_err(|error| BundleError::Io {
path: source.clone(),
source: error,
})?;
}
}
let files = manifest(into)?;
Ok(Summary {
root: into.to_path_buf(),
files,
steps: rows.len() - gaps,
gaps,
})
}
pub fn verify(
bundle: &Path,
graph: &Graph,
roots: &[NodeId],
report: &RunReport,
) -> Result<Verification, BundleError> {
let scopes = graph.scopes(roots);
let here: Vec<(String, Option<String>, &crate::exec::StepResult)> = report
.results
.iter()
.map(|result| {
(
result.step.clone(),
scopes.get(&result.node).map(|scope| scope.value.clone()),
result,
)
})
.collect();
let mut verification = Verification::default();
for result in &report.results {
for note in result
.notes
.iter()
.filter(|note| note.explains_a_difference())
{
verification.noticed.push(Noticed {
step: result.step.clone(),
scope: scopes.get(&result.node).map(|scope| scope.value.clone()),
scope_kind: scopes.get(&result.node).map(|scope| scope.kind),
note: note.clone(),
});
}
}
for row in read_table(bundle, "results.tsv", 5)? {
let (step, scope, key, _bytes, canonical) = (&row[0], &row[1], &row[2], &row[3], &row[4]);
let scope = (!scope.is_empty()).then(|| scope.clone());
let expected = parse_hash(bundle, "results.tsv", canonical)?;
let found = here
.iter()
.find(|(name, at, _)| name == step && at == &scope);
let check = match found {
None => Check {
step: step.clone(),
scope,
expected,
found: None,
same_key: false,
verdict: Match::Missing,
},
Some((_, _, result)) => {
let same_key = result.key.to_hex() == *key;
let verdict = if result.canonical == expected {
if same_key {
Match::Identical
} else {
Match::Reproduced
}
} else {
Match::Differs
};
Check {
step: step.clone(),
scope,
expected,
found: Some(result.canonical),
same_key,
verdict,
}
}
};
verification.checks.push(check);
}
for row in read_table(bundle, "inputs.tsv", 7)? {
let (step, param, path, bytes) = (&row[0], &row[2], &row[4], &row[5]);
let path = PathBuf::from(path);
let recorded = parse_hash(bundle, "inputs.tsv", bytes)?;
let presence = if path.is_file() {
match ContentHash::of_file(&path) {
Ok(hash) if hash == recorded => Presence::Same,
Ok(_) => Presence::Changed,
Err(_) => Presence::Absent,
}
} else {
Presence::Absent
};
verification.inputs.push(InputCheck {
step: step.clone(),
param: param.clone(),
path,
presence,
});
}
Ok(verification)
}
pub fn seed(bundle: &Path, cache: &Cache) -> Result<usize, BundleError> {
if !bundle.join("records.tsv").is_file() {
return Ok(0);
}
let thin = bundle.join("store.tsv").is_file();
let mut absent: Vec<String> = Vec::new();
let mut added = 0;
for row in read_table(bundle, "records.tsv", 10)? {
let (request, revision, locator, kind, method, url, status, body, digest) = (
&row[0], &row[1], &row[3], &row[4], &row[5], &row[6], &row[7], &row[8], &row[9],
);
let request = parse_hash(bundle, "records.tsv", request)?;
let Some(key) = parse_key(body) else { continue };
let bytes = match fs::read(bundle.join("records").join(body)) {
Ok(bytes) => bytes,
Err(_) if thin => match cache.objects().checked_get(&key) {
Ok(Some(bytes)) => bytes,
Ok(None) => {
absent.push(key.to_string());
continue;
}
Err(error) => {
absent.push(format!("{key} ({error})"));
continue;
}
},
Err(_) => continue,
};
let record = QueryRecord {
request,
revision: revision.parse().unwrap_or(0),
recorded_at: crate::prov::now(),
locator: locator.clone(),
kind: match DataKind::ALL
.iter()
.copied()
.find(|known| known.name() == kind)
{
Some(kind) => kind,
None => continue,
},
method: match Method::parse(method) {
Some(method) => method,
None => continue,
},
url: url.clone(),
status: status.parse().unwrap_or(200),
body: key.clone(),
digest: parse_hash(bundle, "records.tsv", digest)?,
notes: Vec::new(),
};
cache
.objects()
.put(&key, &bytes)
.map_err(|error| BundleError::Io {
path: bundle.to_path_buf(),
source: io::Error::other(error.to_string()),
})?;
let held = cache
.query_records(request)
.map_err(|error| BundleError::Io {
path: bundle.to_path_buf(),
source: io::Error::other(error.to_string()),
})?;
if held.iter().any(|existing| existing.body == key) {
continue;
}
cache
.record_query(&record)
.map_err(|error| BundleError::Io {
path: bundle.to_path_buf(),
source: io::Error::other(error.to_string()),
})?;
added += 1;
}
if !absent.is_empty() {
let store = store_named_by(bundle).unwrap_or_else(|| "(unnamed)".to_owned());
return Err(BundleError::Malformed {
path: bundle.join("store.tsv"),
detail: format!(
"this is a thin bundle: it names the store {store} and \
carries no response bodies of its own. {} could not be \
read from there, so the run would replay some queries and \
not others, which is the one thing a replay must not do. \
Point LIGASE_STORE at a store holding them, or ask for a \
bundle written without --thin. Missing: {}",
plural(absent.len(), "body"),
absent.join(", ")
),
});
}
Ok(added)
}
fn store_named_by(bundle: &Path) -> Option<String> {
let text = fs::read_to_string(bundle.join("store.tsv")).ok()?;
text.lines()
.filter_map(|line| line.split_once('\t'))
.find(|(name, _)| *name == "store")
.map(|(_, value)| value.to_owned())
}
fn plural(count: usize, word: &str) -> String {
if count == 1 {
format!("{count} {word}")
} else {
format!("{count} {}", word.trim_end_matches('y').to_owned() + "ies")
}
}
fn parse_key(text: &str) -> Option<ObjectKey> {
if text.len() < 64 {
return None;
}
let (hash, suffix) = text.split_at(64);
Some(ObjectKey::new(ContentHash::parse(hash)?, suffix))
}
fn readme(methods: &Methods, thin: bool) -> String {
let mut out = String::from(
"# Reproducibility bundle\n\n\
Written by Ligase. Everything here describes how a set of results was\n\
produced, and is enough to check whether another machine produces the\n\
same ones.\n\n\
## What is here\n\n\
| File | What it holds |\n\
| --- | --- |\n\
| `METHODS.md` | The methods paragraph, with tool versions and references. |\n\
| `results.tsv` | Every step's output, by content hash. **This is the claim.** |\n\
| `commands.tsv` | The command that produced each one, as it ran. |\n\
| `inputs.tsv` | Every input file, by content hash. |\n\
| `notes.tsv` | What canonicalising an output noticed. Usually empty. |\n\
| `references.tsv` | Every reference, by accession and checksum. |\n\
| `remotes.tsv` | Every remote input, by locator and digest. |\n\
| `records.tsv` | Every recorded query, with its response body in `records/`. |\n\
| `environment.tsv` | The engine, the platform and every tool's version. |\n\
| `steps/` | The source of every step. |\n\
| `pipeline/` | The pipeline file itself, where one was given. |\n\
| `store.tsv` | Where the bodies are, in a thin bundle. |\n\
| `MANIFEST` | Every file above, hashed, so damage is visible. |\n\n\
## What is not here\n\n\
Most of the data. Sequencing runs are gigabytes and a bundle is\n\
meant to be readable, so inputs are *named* rather than carried:\n\
every one by content hash, every reference by accession and\n\
checksum, and every pinned remote by locator. Fetch them by those\n\
identifiers; nothing else will satisfy the check.\n\n\
The one exception is the one that has to be: a recorded query's\n\
response, which no one could fetch again, and which is therefore\n\
carried. See `records/` below.\n\n\
A remote in `remotes.tsv` is *pinned*, which means the source\n\
promises the same bytes forever: `ligase run` on the pipeline in\n\
`pipeline/` obtains it and checks it against the digest recorded\n\
here before any step runs.\n\n\
A *recorded query* is the other case, and its data **is** here. A\n\
live source promises nothing about what it will answer next, so\n\
the response bodies themselves are in `records/`, named by their\n\
own hashes and listed in `records.tsv`. Verifying this bundle\n\
replays from them: no network, and no API key.\n\n\
## How to check it\n\n\
With the data in place and the pipeline to hand:\n\n\
```\n\
ligase methods --verify <this directory>\n\
```\n\n\
It runs the pipeline and compares every output's canonical hash with\n\
the one recorded here. Three answers are good news and one is not:\n\
`identical` (nothing moved), `reproduced` (a tool version or a\n\
platform moved and the result did not), `differs` (it did), and\n\
`missing` (this pipeline no longer produces that step).\n\n\
A `differs` is worth reading alongside the input lines: an input\n\
reported as `changed` or `absent` explains an output that moved.\n\n",
);
if thin {
out.push_str(
"## This is a thin bundle\n\n\
It carries the manifest and the hashes and **not** the object\n\
bodies, so it is small and it is not self-contained. Checking\n\
it needs access to the store named in `store.tsv`, with\n\
whatever credentials that store wants.\n\n\
That includes the recorded query responses. A fat bundle --\n\
`ligase methods --bundle` without `--thin` -- carries them, and\n\
a reviewer replays it with no network and no API key. **This\n\
one does not make that promise.** It is for a collaborator who\n\
can already reach the lab's store; for a reviewer, a referee or\n\
an archive, write a fat one.\n\n\
Without store access, `ligase methods --verify` on this\n\
directory fails before any step runs and names what is\n\
missing. It will not replay half a pipeline.\n\n",
);
}
let notices = methods.notices();
if !notices.is_empty() {
out.push_str("## What was noticed\n\n");
out.push_str(¬ices.join("\n\n"));
out.push_str("\n\n");
}
out.push_str("## What produced it\n\n");
out.push_str(&format!(
"Ligase {} on {}.\n",
methods.engines.join(", "),
methods.platforms.join(", ")
));
out
}
fn step_file(record: &Record, used: &BTreeMap<String, String>) -> String {
let base = record
.step
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
character
} else {
'_'
}
})
.collect::<String>();
let first = format!("{base}.py");
if used.get(&first).is_none_or(|held| held == &record.code) {
return first;
}
for attempt in 2.. {
let next = format!("{base}.{attempt}.py");
if used.get(&next).is_none_or(|held| held == &record.code) {
return next;
}
}
first
}
fn manifest(root: &Path) -> Result<Vec<String>, BundleError> {
let mut files = Vec::new();
collect(root, root, &mut files)?;
files.sort();
let mut out = format!("# {MANIFEST_HASH}\n");
for name in &files {
let hash = ContentHash::of_file(&root.join(name)).map_err(|error| BundleError::Io {
path: root.join(name),
source: error,
})?;
out.push_str(&format!("{} {name}\n", hash.to_hex()));
}
put(root, "MANIFEST", &out)?;
Ok(files)
}
fn collect(root: &Path, at: &Path, into: &mut Vec<String>) -> Result<(), BundleError> {
let entries = fs::read_dir(at).map_err(|error| BundleError::Io {
path: at.to_path_buf(),
source: error,
})?;
for entry in entries {
let entry = entry.map_err(|error| BundleError::Io {
path: at.to_path_buf(),
source: error,
})?;
let path = entry.path();
if path.is_dir() {
collect(root, &path, into)?;
} else if let Ok(relative) = path.strip_prefix(root) {
into.push(relative.to_string_lossy().replace('\\', "/"));
}
}
Ok(())
}
struct Table {
text: String,
}
impl Table {
fn new(columns: &[&str]) -> Self {
Self {
text: format!("{}\n", columns.join("\t")),
}
}
fn row(&mut self, fields: &[&str]) {
let escaped: Vec<String> = fields.iter().map(|field| escape(field)).collect();
self.text.push_str(&escaped.join("\t"));
self.text.push('\n');
}
fn finish(self) -> String {
self.text
}
}
fn escape(field: &str) -> String {
let mut out = String::with_capacity(field.len());
for character in field.chars() {
match character {
'\\' => out.push_str("\\\\"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
other => out.push(other),
}
}
out
}
fn unescape(field: &str) -> String {
let mut out = String::with_capacity(field.len());
let mut characters = field.chars();
while let Some(character) = characters.next() {
if character != '\\' {
out.push(character);
continue;
}
match characters.next() {
Some('\\') => out.push('\\'),
Some('t') => out.push('\t'),
Some('n') => out.push('\n'),
Some('r') => out.push('\r'),
Some(other) => out.push(other),
None => out.push('\\'),
}
}
out
}
fn read_table(bundle: &Path, name: &str, columns: usize) -> Result<Vec<Vec<String>>, BundleError> {
let path = bundle.join(name);
let text = fs::read_to_string(&path).map_err(|error| BundleError::Io {
path: path.clone(),
source: error,
})?;
let mut lines = text.lines();
let header = lines.next().ok_or_else(|| BundleError::Malformed {
path: path.clone(),
detail: "the file is empty; it should begin with a header row".to_owned(),
})?;
if header.split('\t').count() != columns {
return Err(BundleError::Malformed {
path: path.clone(),
detail: format!(
"the header has {} columns and should have {columns}",
header.split('\t').count()
),
});
}
let mut rows = Vec::new();
for (number, line) in lines.enumerate() {
if line.trim().is_empty() {
continue;
}
let fields: Vec<String> = line.split('\t').map(unescape).collect();
if fields.len() != columns {
return Err(BundleError::Malformed {
path: path.clone(),
detail: format!(
"row {} has {} columns and should have {columns}",
number + 2,
fields.len()
),
});
}
rows.push(fields);
}
Ok(rows)
}
fn parse_hash(bundle: &Path, name: &str, text: &str) -> Result<ContentHash, BundleError> {
ContentHash::parse(text).ok_or_else(|| BundleError::Malformed {
path: bundle.join(name),
detail: format!("`{text}` is not a content hash"),
})
}
fn put(root: &Path, name: &str, contents: &str) -> Result<(), BundleError> {
let path = root.join(name);
fs::write(&path, contents).map_err(|error| BundleError::Io {
path,
source: error,
})
}
fn create_dir(path: &Path) -> Result<(), BundleError> {
fs::create_dir_all(path).map_err(|error| BundleError::Io {
path: path.to_path_buf(),
source: error,
})
}
fn short(hash: ContentHash) -> String {
hash.to_hex().chars().take(12).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_field_survives_a_tab_and_a_newline() {
let awkward = "a\tb\nc\\d";
assert_eq!(escape(awkward), "a\\tb\\nc\\\\d");
assert_eq!(unescape(&escape(awkward)), awkward);
assert!(
!escape(awkward).contains('\t'),
"an escaped field cannot shift a column"
);
}
#[test]
fn an_ordinary_field_is_left_alone() {
assert_eq!(escape("minimap2 2.31-r1287"), "minimap2 2.31-r1287");
}
}