use std::collections::BTreeMap;
use crate::identity::sha256_hex;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdoptionEntry {
pub anchor: String,
pub certifies: String,
pub evidence: String,
pub verifier: String,
pub at: String,
pub files: Vec<String>,
pub fingerprint: String,
pub reason: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdoptionError {
pub line: usize,
pub message: String,
}
pub fn parse_adoption(ledger: &str) -> Result<Vec<AdoptionEntry>, AdoptionError> {
let mut entries = Vec::new();
for (index, line) in ledger.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let fields = line.split('|').collect::<Vec<_>>();
if fields.len() != 8 {
return Err(AdoptionError {
line: index + 1,
message: format!("must contain 8 fields, found {}", fields.len()),
});
}
if fields.iter().any(|field| field.trim().is_empty()) {
return Err(AdoptionError {
line: index + 1,
message: "contains an empty field".to_owned(),
});
}
let files = fields[5]
.split(',')
.map(str::trim)
.filter(|file| !file.is_empty())
.map(str::to_owned)
.collect::<Vec<_>>();
if files.is_empty() {
return Err(AdoptionError {
line: index + 1,
message: "names no file, so the decision rests on nothing".to_owned(),
});
}
entries.push(AdoptionEntry {
anchor: fields[0].to_owned(),
certifies: fields[1].to_owned(),
evidence: fields[2].to_owned(),
verifier: fields[3].to_owned(),
at: fields[4].to_owned(),
files,
fingerprint: fields[6].to_owned(),
reason: fields[7].to_owned(),
});
}
Ok(entries)
}
pub fn parse_adoption_prints(ledger: &str) -> Result<Vec<AdoptionPrints>, AdoptionError> {
let mut prints = Vec::new();
for (index, line) in ledger.lines().enumerate() {
let line = line.trim();
let Some(rest) = line.strip_prefix("# prints ") else {
continue;
};
let parts = rest.split('|').map(str::trim).collect::<Vec<_>>();
if parts.len() != 3 || parts[0].is_empty() || parts[1].is_empty() {
return Err(AdoptionError {
line: index + 1,
message:
"a `# prints` line must read `# prints <anchor> | <at> | <path>=<print>,…`"
.to_owned(),
});
}
let mut files = Vec::new();
for pair in parts[2]
.split(',')
.map(str::trim)
.filter(|pair| !pair.is_empty())
{
let Some((path, print)) = pair.rsplit_once('=') else {
return Err(AdoptionError {
line: index + 1,
message: format!("`{pair}` is not `<path>=<print>`"),
});
};
files.push((path.trim().to_owned(), print.trim().to_owned()));
}
prints.push(AdoptionPrints {
anchor: parts[0].to_owned(),
at: parts[1].to_owned(),
files,
});
}
Ok(prints)
}
pub fn render_adoption_prints(anchor: &str, at: &str, files: &[(String, String)]) -> String {
let pairs = files
.iter()
.map(|(path, print)| format!("{path}={print}"))
.collect::<Vec<_>>()
.join(",");
format!("# prints {anchor} | {at} | {pairs}\n")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdoptionObject {
pub anchor: String,
pub at: String,
pub stable: String,
}
pub fn parse_adoption_objects(ledger: &str) -> Result<Vec<AdoptionObject>, AdoptionError> {
let mut objects = Vec::new();
for (index, line) in ledger.lines().enumerate() {
let line = line.trim();
let Some(rest) = line.strip_prefix("# object ") else {
continue;
};
let parts = rest.split('|').map(str::trim).collect::<Vec<_>>();
if parts.len() != 3 || parts.iter().any(|part| part.is_empty()) {
return Err(AdoptionError {
line: index + 1,
message: "a `# object` line must read `# object <anchor> | <at> | <stable>`"
.to_owned(),
});
}
if parts[2].len() != 32 || !parts[2].bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(AdoptionError {
line: index + 1,
message: format!(
"`{}` is not a 32-hex object identity; write the identity the ledger uses",
parts[2]
),
});
}
objects.push(AdoptionObject {
anchor: parts[0].to_owned(),
at: parts[1].to_owned(),
stable: parts[2].to_ascii_lowercase(),
});
}
Ok(objects)
}
pub fn render_adoption_object(anchor: &str, at: &str, stable: &str) -> String {
format!("# object {anchor} | {at} | {stable}\n")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdoptionPrints {
pub anchor: String,
pub at: String,
pub files: Vec<(String, String)>,
}
pub fn adoption_fingerprint(files: &[(String, String)]) -> String {
let mut ordered = files.to_vec();
ordered.sort();
let mut input = Vec::new();
for (path, contents) in ordered {
input.extend_from_slice(path.as_bytes());
input.push(0);
input.extend_from_slice(contents.len().to_string().as_bytes());
input.push(0);
input.extend_from_slice(contents.as_bytes());
input.push(0);
}
sha256_hex(&input)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AdoptionVerdict {
Provisional,
Lapsed {
file: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdoptionState {
pub verdict: AdoptionVerdict,
pub current: String,
}
pub fn state_of(entry: &AdoptionEntry, current: &[(String, String)]) -> AdoptionState {
let held: BTreeMap<&str, &str> = current
.iter()
.map(|(path, contents)| (path.as_str(), contents.as_str()))
.collect();
let named = entry
.files
.iter()
.map(|file| {
let contents = held.get(file.as_str()).copied().unwrap_or_default();
(file.clone(), contents.to_owned())
})
.collect::<Vec<_>>();
let missing = entry
.files
.iter()
.find(|file| !held.contains_key(file.as_str()));
let current = adoption_fingerprint(&named);
let verdict = if let Some(file) = missing {
AdoptionVerdict::Lapsed { file: file.clone() }
} else if current == entry.fingerprint {
AdoptionVerdict::Provisional
} else {
AdoptionVerdict::Lapsed {
file: entry.files[0].clone(),
}
};
AdoptionState { verdict, current }
}
pub fn verdict_of(entry: &AdoptionEntry, current: &[(String, String)]) -> AdoptionVerdict {
state_of(entry, current).verdict
}
#[cfg(test)]
#[path = "adoption_tests.rs"]
mod adoption_tests;