use std::collections::BTreeMap;
use brygge_ir::{
ChangeAtom, ChangedPart, EpistemicStatus, Identity, PathOp, SourceKind, Time, TransformRecord,
};
pub(super) fn to_hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
let _ = write!(out, "{b:02x}");
}
out
}
fn printable_ascii_or_hex(atom_id: &[u8]) -> String {
if !atom_id.is_empty() && atom_id.iter().all(|&b| (0x21..=0x7E).contains(&b)) {
String::from_utf8(atom_id.to_vec()).unwrap_or_else(|_| format!("hex:{}", to_hex(atom_id)))
} else {
format!("hex:{}", to_hex(atom_id))
}
}
pub(super) fn source_id_text(kind: &SourceKind, atom_id: &[u8]) -> String {
match kind {
SourceKind::Git | SourceKind::Hg => {
if atom_id.len() == 20 {
to_hex(atom_id)
} else {
format!("hex:{}", to_hex(atom_id))
}
}
SourceKind::Svn => svn_source_id_text(atom_id),
SourceKind::Cvs => cvs_source_id_text(atom_id),
SourceKind::Other(_) => printable_ascii_or_hex(atom_id),
}
}
fn svn_source_id_text(atom_id: &[u8]) -> String {
if let Ok(bytes) = <[u8; 8]>::try_from(atom_id) {
return format!("r{}", u64::from_be_bytes(bytes));
}
if atom_id.len() > 8 {
let (rev_bytes, root_bytes) = atom_id.split_at(8);
if let Ok(rev) = <[u8; 8]>::try_from(rev_bytes) {
let printable =
!root_bytes.is_empty() && root_bytes.iter().all(|&b| (0x21..=0x7E).contains(&b));
if printable {
if let Ok(root) = std::str::from_utf8(root_bytes) {
return format!("r{} {root}", u64::from_be_bytes(rev));
}
}
}
}
format!("hex:{}", to_hex(atom_id))
}
fn cvs_source_id_text(atom_id: &[u8]) -> String {
let Ok(s) = std::str::from_utf8(atom_id) else {
return format!("hex:{}", to_hex(atom_id));
};
if let Some(name) = s.strip_prefix("branch-point:") {
if name.is_empty() || s.contains('\n') || s.starts_with(' ') || s.ends_with(' ') {
return format!("hex:{}", to_hex(atom_id));
}
return s.to_string();
}
let lines: Vec<&str> = s.split('\n').collect();
let well_formed = lines
.iter()
.all(|l| !l.is_empty() && !l.starts_with(' ') && !l.ends_with(' ') && l.contains('@'));
let Some((first, rest)) = lines.split_first().filter(|_| well_formed) else {
return format!("hex:{}", to_hex(atom_id));
};
let mut out = first.to_string();
for pair in rest {
out.push('\n');
out.push(' ');
out.push_str(pair);
}
out
}
fn from_hex(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) || !s.is_ascii() {
return None;
}
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks_exact(2) {
let a = *pair.first()?;
let b = *pair.get(1)?;
if a.is_ascii_uppercase() || b.is_ascii_uppercase() {
return None;
}
let hi = (a as char).to_digit(16)?;
let lo = (b as char).to_digit(16)?;
out.push((hi * 16 + lo) as u8);
}
Some(out)
}
pub(super) fn parse_source_id(kind: &SourceKind, text: &str) -> Option<Vec<u8>> {
if let Some(hex) = text.strip_prefix("hex:") {
return from_hex(hex);
}
match kind {
SourceKind::Git | SourceKind::Hg => from_hex(text).filter(|b| b.len() == 20),
SourceKind::Svn => {
let rest = text.strip_prefix('r')?;
let (digits, root) = match rest.split_once(' ') {
Some((d, r)) => (d, Some(r)),
None => (rest, None),
};
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let n: u64 = digits.parse().ok()?;
let mut out = n.to_be_bytes().to_vec();
if let Some(root) = root {
if root.is_empty() {
return None;
}
out.extend_from_slice(root.as_bytes());
}
Some(out)
}
SourceKind::Cvs => {
if let Some(name) = text.strip_prefix("branch-point:") {
return if name.is_empty() || name.contains('\n') {
None
} else {
Some(format!("branch-point:{name}").into_bytes())
};
}
let mut out = String::new();
for (i, line) in text.split('\n').enumerate() {
if i == 0 {
out.push_str(line);
} else {
let cont = line.strip_prefix(' ')?;
out.push('\n');
out.push_str(cont);
}
}
if out.is_empty() {
None
} else {
Some(out.into_bytes())
}
}
SourceKind::Other(_) => Some(text.as_bytes().to_vec()),
}
}
pub(super) fn extract_trailer(message: &[u8], key: &str) -> Option<String> {
let lines: Vec<&[u8]> = message.split(|&b| b == b'\n').collect();
let prefix = format!("{key}: ");
let prefix_bytes = prefix.as_bytes();
let idx = lines.iter().position(|l| l.starts_with(prefix_bytes))?;
let first_line = *lines.get(idx)?;
let mut out = std::str::from_utf8(first_line.get(prefix_bytes.len()..)?)
.ok()?
.to_string();
let mut i = idx + 1;
while let Some(line) = lines.get(i) {
if line.starts_with(b" ") {
out.push('\n');
out.push_str(std::str::from_utf8(line).ok()?);
i += 1;
} else {
break;
}
}
Some(out)
}
pub(super) fn truncate_for_refusal(s: &str) -> String {
let mut chars = s.chars();
let head: String = chars.by_ref().take(80).collect();
if chars.next().is_some() {
format!("{head}…")
} else {
head
}
}
pub(super) fn source_kind_label(kind: &SourceKind) -> String {
match kind {
SourceKind::Git => "git".to_string(),
SourceKind::Hg => "hg".to_string(),
SourceKind::Svn => "svn".to_string(),
SourceKind::Cvs => "cvs".to_string(),
SourceKind::Other(label) => label.to_lowercase(),
}
}
#[derive(Debug, Default)]
pub(super) struct Supplied(Vec<String>);
impl Supplied {
pub(super) fn mark(&mut self, field: &str) {
self.0.push(field.to_string());
}
pub(super) fn trailer(&self) -> Option<String> {
if self.0.is_empty() {
None
} else {
Some(format!("Brygge-Supplied: {}", self.0.join(", ")))
}
}
pub(super) fn fold_into(&self, totals: &mut BTreeMap<String, u64>) {
for field in &self.0 {
*totals.entry(field.clone()).or_insert(0) += 1;
}
}
}
#[derive(Debug, Default)]
pub(super) struct Altered(Vec<(String, String)>);
impl Altered {
pub(super) fn mark(&mut self, field: &str, why: &str) {
self.0.push((field.to_string(), why.to_string()));
}
pub(super) fn trailer(&self) -> Option<String> {
if self.0.is_empty() {
None
} else {
let parts: Vec<String> = self
.0
.iter()
.map(|(field, why)| format!("{field} ({why})"))
.collect();
Some(format!("Brygge-Altered: {}", parts.join(", ")))
}
}
pub(super) fn fold_into(&self, totals: &mut BTreeMap<String, u64>) {
for (field, _why) in &self.0 {
*totals.entry(field.clone()).or_insert(0) += 1;
}
}
}
pub(super) fn identity_line(
identity: Option<&Identity>,
supplied: &mut Supplied,
altered: &mut Altered,
field: &'static str,
) -> String {
let Some(identity) = identity else {
supplied.mark(field);
return "unknown <>".to_string();
};
let name = match identity.name.as_utf8() {
Some(s) => sanitize_identity_part(s, &format!("{field}-name"), altered),
None => {
altered.mark(&format!("{field}-name"), "not UTF-8, replaced");
"unknown".to_string()
}
};
let email = match &identity.email {
Some(email) => match email.as_utf8() {
Some(s) => sanitize_identity_part(s, &format!("{field}-email"), altered),
None => {
altered.mark(&format!("{field}-email"), "not UTF-8, replaced");
String::new()
}
},
None => {
supplied.mark(&format!("{field}-email"));
String::new()
}
};
format!("{name} <{email}>")
}
pub(super) fn when(
time: Option<Time>,
supplied: &mut Supplied,
time_field: &'static str,
tz_field: &'static str,
) -> String {
let Some(time) = time else {
supplied.mark(time_field);
supplied.mark(tz_field);
return "0 +0000".to_string();
};
let offset = time.offset_minutes.unwrap_or_else(|| {
supplied.mark(tz_field);
0
});
let sign = if offset < 0 { '-' } else { '+' };
let abs = offset.unsigned_abs();
format!("{} {sign}{:02}{:02}", time.seconds, abs / 60, abs % 60)
}
fn sanitize_identity_part(value: &str, field: &str, altered: &mut Altered) -> String {
let mut reasons: Vec<&'static str> = Vec::new();
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'\n' | '\r' => {
if !reasons.contains(&"newline folded") {
reasons.push("newline folded");
}
out.push(' ');
}
'<' | '>' => {
if !reasons.contains(&"angle bracket removed") {
reasons.push("angle bracket removed");
}
}
'\0' => {
if !reasons.contains(&"NUL removed") {
reasons.push("NUL removed");
}
}
_ => out.push(ch),
}
}
if !reasons.is_empty() {
altered.mark(field, &reasons.join(", "));
}
out
}
pub(super) fn path_token(path: &str) -> String {
if path.starts_with('"') || path.contains('\n') {
let mut out = String::from("\"");
for ch in path.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
_ => out.push(ch),
}
}
out.push('"');
out
} else {
path.to_string()
}
}
fn derived_trailer(scope: &str, status: &EpistemicStatus) -> Option<String> {
let EpistemicStatus::Derived(d) = status else {
return None;
};
let params: Vec<String> = d.params.iter().map(|(k, v)| format!("{k}={v}")).collect();
let params = if params.is_empty() {
String::new()
} else {
format!(" {}", params.join(","))
};
Some(format!(
"Brygge-Derived: {scope} {}{params}",
d.kind.label()
))
}
pub(super) fn status_chain_trailers(
scope: &str,
status: &EpistemicStatus,
transforms: &[TransformRecord],
) -> Vec<String> {
match status {
EpistemicStatus::Transformed {
step,
changed,
prior,
} => {
let parts: Vec<&str> = changed.iter().map(ChangedPart::as_str).collect();
let (name, version) = usize::try_from(*step)
.ok()
.and_then(|i| transforms.get(i))
.map(|t| (t.name.as_str(), t.version.as_str()))
.unwrap_or(("?", "?"));
let mut out = vec![format!(
"Brygge-Transformed: {scope} {step} {name} {version} ({})",
parts.join(",")
)];
out.extend(status_chain_trailers(scope, prior, transforms));
out
}
EpistemicStatus::Derived(_) => derived_trailer(scope, status).into_iter().collect(),
EpistemicStatus::Stated => Vec::new(),
}
}
pub(super) fn status_trailers(atom: &ChangeAtom, transforms: &[TransformRecord]) -> Vec<String> {
let mut out = status_chain_trailers("atom", &atom.status, transforms);
for op in &atom.ops {
let (path, status) = match op {
PathOp::Add { path, status, .. }
| PathOp::Modify { path, status, .. }
| PathOp::Delete { path, status, .. }
| PathOp::Replace { path, status, .. } => (path, status),
};
out.extend(status_chain_trailers(
&format!("op:{path}"),
status,
transforms,
));
}
out
}
#[cfg(test)]
mod tests;