use crate::error::{Error, Result};
use crate::port::{Addr, Item, Observed, Output, Ownership, Repr, State, Store};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommentStyle {
Html,
Hash,
}
pub fn sha256_hex(s: &str) -> String {
let mut h = Sha256::new();
h.update(s.as_bytes());
format!("{:x}", h.finalize())
}
fn begin_line(
name: &str,
source: Option<&str>,
digest: Option<&str>,
style: CommentStyle,
) -> String {
let instead = match source {
Some(s) if !s.is_empty() => format!("edit {s} instead"),
_ => "DO NOT EDIT".to_string(),
};
let mut body = format!("==={name}=== generated by cfggraft; {instead}");
if let Some(d) = digest {
body.push_str(&format!("; sha256={d}"));
}
match style {
CommentStyle::Html => format!("<!-- {body} -->"),
CommentStyle::Hash => format!("# {body}"),
}
}
fn end_line(name: &str, style: CommentStyle) -> String {
match style {
CommentStyle::Html => format!("<!-- ==={}=== -->", format_args!("/{name}")),
CommentStyle::Hash => format!("# ===/{name}==="),
}
}
fn comment_text(line: &str, style: CommentStyle) -> Option<&str> {
let t = line.trim();
match style {
CommentStyle::Html => t.strip_prefix("<!--")?.strip_suffix("-->"),
CommentStyle::Hash => t.strip_prefix('#'),
}
.map(str::trim)
}
fn leads_with(text: &str, token: &str) -> bool {
text.strip_prefix(token)
.is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
}
fn is_begin(line: &str, name: &str, style: CommentStyle) -> bool {
comment_text(line, style).is_some_and(|t| leads_with(t, &format!("==={name}===")))
}
fn is_end(line: &str, name: &str, style: CommentStyle) -> bool {
comment_text(line, style).is_some_and(|t| leads_with(t, &format!("===/{name}===")))
}
fn is_valid_name(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
}
fn recorded_digest(line: &str) -> Option<String> {
let rest = line.split("sha256=").nth(1)?;
let hex: String = rest
.chars()
.take_while(char::is_ascii_hexdigit)
.take(64)
.collect();
(hex.len() == 64).then_some(hex)
}
#[derive(Debug, Clone, Copy)]
struct Span {
begin: usize,
end: usize,
}
#[derive(Debug)]
pub struct MarkerSpan {
name: String,
style: CommentStyle,
source: Option<String>,
lines: Vec<String>,
span: Option<Span>,
recorded: Option<String>,
declared: Repr,
trailing_newline: bool,
wrote: bool,
}
impl MarkerSpan {
pub fn new(
target: &str,
name: &str,
body: &str,
style: CommentStyle,
source: Option<&str>,
init: bool,
) -> Result<Self> {
if name.is_empty() {
return Err(Error::invalid("a marker name must not be empty"));
}
if !is_valid_name(name) {
return Err(Error::invalid(format!(
"marker name `{name}` may contain only ASCII letters, digits, `_`, `-` and `.`"
)));
}
let lines: Vec<String> = target.lines().map(str::to_string).collect();
let trailing_newline = target.is_empty() || target.ends_with('\n');
let begins: Vec<usize> = (0..lines.len())
.filter(|&i| is_begin(&lines[i], name, style))
.collect();
if begins.len() > 1 {
let at: Vec<String> = begins.iter().map(|i| (i + 1).to_string()).collect();
return Err(Error::invalid(format!(
"marker `{name}` begins on lines {}; a region is one item, so a file holds it once",
at.join(", ")
)));
}
let span = match begins.first().copied() {
Some(begin) => {
let end = lines
.iter()
.enumerate()
.skip(begin + 1)
.find(|(_, l)| is_end(l, name, style))
.map(|(i, _)| i)
.ok_or_else(|| {
Error::invalid(format!(
"the begin marker `{name}` on line {} has no matching end marker",
begin + 1
))
})?;
Some(Span { begin, end })
}
None if init => None,
None => {
return Err(Error::invalid(format!(
"marker `{name}` not found; pass --init to create the region"
)))
}
};
let recorded = span.and_then(|s| recorded_digest(&lines[s.begin]));
Ok(MarkerSpan {
name: name.to_string(),
style,
source: source.map(str::to_string),
lines,
span,
recorded,
declared: Repr::new(normalise(body)),
trailing_newline,
wrote: false,
})
}
pub fn addr(&self) -> Addr {
Addr::new(self.name.clone())
}
fn body(&self) -> Option<String> {
self.span.map(|s| self.lines[s.begin + 1..s.end].join("\n"))
}
fn should_record(&self) -> bool {
if self.wrote {
return true;
}
self.recorded.is_none() && self.body().as_deref() == Some(self.declared.as_str())
}
fn render(&self) -> String {
let mut s = self.lines.join("\n");
if self.trailing_newline {
s.push('\n');
}
s
}
}
fn normalise(body: &str) -> String {
body.lines().collect::<Vec<_>>().join("\n")
}
impl Store for MarkerSpan {
fn declared(&self) -> Result<Vec<Item>> {
Ok(vec![Item::new(self.addr(), self.declared.clone())])
}
fn owned(&self) -> Vec<Item> {
Vec::new()
}
fn state(&self, _addr: &Addr) -> Result<State> {
let Some(body) = self.body() else {
return Ok(State::new(Observed::Absent, Ownership::Unknown));
};
let observed = Observed::Present(Repr::new(body.clone()));
let actual = sha256_hex(&body);
Ok(match &self.recorded {
None => State::new(observed, Ownership::Unknown)
.with_note("no digest is recorded, so this span cannot be claimed".to_string()),
Some(recorded) if recorded == &actual => State::new(observed, Ownership::Ours),
Some(recorded) => State::new(observed, Ownership::Diverged).with_note(format!(
"recorded sha256={}…, actual sha256={}…",
&recorded[..12],
&actual[..12]
)),
})
}
fn write(&mut self, _addr: &Addr) -> Result<()> {
let body: Vec<String> = self.declared.as_str().lines().map(str::to_string).collect();
match self.span {
Some(s) => {
let mut rest = self.lines.split_off(s.end);
self.lines.truncate(s.begin + 1);
self.lines.extend(body.iter().cloned());
self.lines.append(&mut rest);
self.span = Some(Span {
begin: s.begin,
end: s.begin + 1 + body.len(),
});
}
None => {
if self.lines.last().is_some_and(|l| !l.trim().is_empty()) {
self.lines.push(String::new());
}
let begin = self.lines.len();
self.lines.push(begin_line(
&self.name,
self.source.as_deref(),
None,
self.style,
));
self.lines.extend(body.iter().cloned());
self.lines.push(end_line(&self.name, self.style));
self.span = Some(Span {
begin,
end: begin + 1 + body.len(),
});
}
}
self.wrote = true;
Ok(())
}
fn retract(&mut self, _addr: &Addr) -> Result<()> {
if let Some(s) = self.span {
self.lines.drain(s.begin..=s.end);
self.span = None;
self.wrote = true;
}
Ok(())
}
fn finish(&mut self, _owned: &[Item]) -> Result<Output> {
if let Some(s) = self.span {
if self.should_record() {
let digest = sha256_hex(&self.body().unwrap_or_default());
self.lines[s.begin] = begin_line(
&self.name,
self.source.as_deref(),
Some(&digest),
self.style,
);
}
}
Ok(Output {
document: self.render(),
prior: None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::{run, Options};
use crate::policy::{Decision, Reason};
const HTML: CommentStyle = CommentStyle::Html;
fn apply(
target: &str,
body: &str,
init: bool,
opts: Options,
) -> (String, Decision, Option<String>) {
let mut s = MarkerSpan::new(target, "PROFILE", body, HTML, None, init).expect("marker");
let (report, out) = run(&mut s, opts).expect("run");
let entry = &report.entries[0];
(out.document, entry.decision, entry.note.clone())
}
#[test]
fn init_appends_the_region_and_keeps_the_hand_text() {
let mut s = MarkerSpan::new(
"hand written\n",
"PROFILE",
"gen\n",
HTML,
Some("src/"),
true,
)
.unwrap();
let (report, out) = run(&mut s, Options::default()).unwrap();
assert_eq!(report.entries[0].decision, Decision::Add);
assert!(out.document.starts_with("hand written\n"));
assert!(out.document.contains("<!-- ===PROFILE==="));
assert!(out.document.contains("edit src/ instead"));
assert!(out.document.contains("sha256="));
assert!(out.document.contains("gen"));
assert!(out.document.trim_end().ends_with("<!-- ===/PROFILE=== -->"));
assert!(out.prior.is_none(), "provenance is inline");
}
#[test]
fn adoption_alters_the_document_even_though_no_item_changed() {
let input = "<!-- ===PROFILE=== -->\nmanaged\n<!-- ===/PROFILE=== -->\n";
let mut s = MarkerSpan::new(input, "PROFILE", "managed\n", HTML, None, false).unwrap();
let (report, out) = run(&mut s, Options::default()).unwrap();
assert!(!report.changed(), "no item changed");
assert_ne!(out.document, input, "yet the document did");
assert!(out.document.contains("sha256="));
}
#[test]
fn a_missing_marker_without_init_is_an_error() {
let err = MarkerSpan::new("x\n", "PROFILE", "b\n", HTML, None, false).unwrap_err();
assert!(err.to_string().contains("--init"), "got: {err}");
}
#[test]
fn an_unterminated_region_is_an_error() {
let err =
MarkerSpan::new("<!-- ===P=== -->\nbody\n", "P", "x\n", HTML, None, false).unwrap_err();
assert!(
err.to_string().contains("no matching end marker"),
"got: {err}"
);
}
#[test]
fn a_settled_region_is_left_alone() {
let (first, _, _) = apply("top\n", "one\ntwo\n", true, Options::default());
let (second, decision, _) = apply(&first, "one\ntwo\n", false, Options::default());
assert_eq!(decision, Decision::Skip);
assert_eq!(first, second, "an unchanged run must not rewrite the file");
}
#[test]
fn updates_the_body_and_preserves_both_hand_zones() {
let (seeded, _, _) = apply("above\n", "old\n", true, Options::default());
let seeded = format!("{seeded}below\n");
let (out, decision, _) = apply(&seeded, "new\n", false, Options::default());
assert_eq!(decision, Decision::Update);
assert!(out.starts_with("above\n"));
assert!(out.ends_with("below\n"));
assert!(out.contains("new"));
assert!(!out.contains("old"));
}
#[test]
fn refuses_a_hand_edited_span_and_changes_nothing() {
let (seeded, _, _) = apply("", "generated\n", true, Options::default());
let tampered = seeded.replace("generated", "someone typed this");
let (out, decision, note) = apply(&tampered, "next\n", false, Options::default());
assert_eq!(decision, Decision::Refuse(Reason::HandEdited));
assert_eq!(out, tampered, "the input must come back byte for byte");
assert!(note.unwrap().contains("recorded sha256="));
}
#[test]
fn force_overrides_a_hand_edit() {
let (seeded, _, _) = apply("", "generated\n", true, Options::default());
let tampered = seeded.replace("generated", "someone typed this");
let opts = Options {
force: true,
..Options::default()
};
let (out, decision, _) = apply(&tampered, "next\n", false, opts);
assert_eq!(decision, Decision::Update);
assert!(out.contains("next"));
assert!(!out.contains("someone typed this"));
}
#[test]
fn an_undigested_span_holding_the_declared_body_is_adopted() {
let input = "<!-- ===PROFILE=== -->\nmanaged\n<!-- ===/PROFILE=== -->\n";
let (out, decision, _) = apply(input, "managed\n", false, Options::default());
assert_eq!(decision, Decision::Skip);
assert!(out.contains("sha256="), "adoption records the digest");
assert!(out.contains("managed"));
}
#[test]
fn an_undigested_span_holding_something_else_is_refused() {
let input = "<!-- ===PROFILE=== -->\nhand rolled\n<!-- ===/PROFILE=== -->\n";
let (out, decision, note) = apply(input, "managed\n", false, Options::default());
assert_eq!(decision, Decision::Refuse(Reason::Conflict));
assert_eq!(out, input, "nothing is written without a claim");
assert!(
!out.contains("sha256="),
"a refusal must not stamp a digest"
);
assert!(note.unwrap().contains("no digest"));
}
#[test]
fn adopting_an_undigested_span_needs_force_once() {
let input = "<!-- ===PROFILE=== -->\nhand rolled\n<!-- ===/PROFILE=== -->\n";
let opts = Options {
force: true,
..Options::default()
};
let (out, decision, _) = apply(input, "managed\n", false, opts);
assert_eq!(decision, Decision::Update);
assert!(out.contains("managed"));
assert!(out.contains("sha256="));
let (out2, decision2, _) = apply(&out, "next\n", false, Options::default());
assert_eq!(decision2, Decision::Update);
assert!(out2.contains("next"));
}
#[test]
fn an_end_marker_is_not_mistaken_for_a_begin_marker() {
assert!(is_begin("<!-- ===PROFILE=== x -->", "PROFILE", HTML));
assert!(!is_begin("<!-- ===/PROFILE=== -->", "PROFILE", HTML));
assert!(is_end("<!-- ===/PROFILE=== -->", "PROFILE", HTML));
}
#[test]
fn a_marker_is_a_whole_comment_line_in_the_configured_style() {
let generated = begin_line("P", Some("src/"), Some(&"a".repeat(64)), HTML);
let hash_generated = begin_line("P", None, None, CommentStyle::Hash);
let cases: &[(&str, CommentStyle, bool)] = &[
(generated.as_str(), HTML, true),
("<!-- ===P=== -->", HTML, true),
("<!--===P===-->", HTML, true),
(" <!-- ===P=== -->", HTML, true),
("<!-- ===P=== --> ", HTML, true),
(hash_generated.as_str(), CommentStyle::Hash, true),
("# ===P=== extra words", CommentStyle::Hash, true),
("#===P===", CommentStyle::Hash, true),
("<!-- ===P2=== -->", HTML, false),
("<!-- ===P===x -->", HTML, false),
("read up to `<!-- ===P=== -->` first", HTML, false),
("the marker name ===P=== appears in prose", HTML, false),
("<!-- ===P=== --> is the begin line", HTML, false),
("<!-- ===P===", HTML, false),
("# ===P===", HTML, false),
("<!-- ===P=== -->", CommentStyle::Hash, false),
("## ===P===", CommentStyle::Hash, false),
("#!/bin/sh ===P===", CommentStyle::Hash, false),
];
for (line, style, expected) in cases {
assert_eq!(
is_begin(line, "P", *style),
*expected,
"is_begin({line:?}, {style:?})"
);
assert!(!is_end(line, "P", *style), "is_end({line:?}, {style:?})");
}
assert!(is_end(" <!-- ===/P=== -->", "P", HTML));
assert!(is_end("# ===/P===", "P", CommentStyle::Hash));
assert!(!is_end("see `<!-- ===/P=== -->`", "P", HTML));
}
#[test]
fn a_line_that_mentions_the_marker_is_not_the_marker() {
let input = "intro\n\nread up to the marker line (`<!-- ===PROFILE=== -->`) first,\n\
then stop at `<!-- ===/PROFILE=== -->`.\n\n\
<!-- ===PROFILE=== -->\nbody\n<!-- ===/PROFILE=== -->\n";
let opts = Options {
force: true,
..Options::default()
};
let (out, decision, _) = apply(input, "body\n", false, opts);
assert_eq!(decision, Decision::Skip, "the real region is the one found");
assert!(out.starts_with(
"intro\n\nread up to the marker line (`<!-- ===PROFILE=== -->`) first,\n\
then stop at `<!-- ===/PROFILE=== -->`.\n\n"
));
assert_eq!(out.matches("<!-- ===/PROFILE=== -->").count(), 2);
assert!(out.contains("sha256="), "the real region was adopted");
}
#[test]
fn a_marker_in_the_other_comment_style_is_not_found() {
let input = "the hash form `# ===PROFILE===` in prose\n\n\
<!-- ===PROFILE=== -->\nbody\n<!-- ===/PROFILE=== -->\n";
let (_, decision, _) = apply(input, "body\n", false, Options::default());
assert_eq!(decision, Decision::Skip);
let hash_only = "# ===PROFILE===\nbody\n# ===/PROFILE===\n";
let err = MarkerSpan::new(hash_only, "PROFILE", "body\n", HTML, None, false).unwrap_err();
assert!(err.to_string().contains("not found"), "got: {err}");
}
#[test]
fn a_second_begin_marker_is_refused_with_both_line_numbers() {
let input =
"intro\n\n```\n<!-- ===PROFILE=== -->\nexample\n<!-- ===/PROFILE=== -->\n```\n\n\
<!-- ===PROFILE=== -->\nbody\n<!-- ===/PROFILE=== -->\n";
let err = MarkerSpan::new(input, "PROFILE", "body\n", HTML, None, false).unwrap_err();
let msg = err.to_string();
assert!(msg.contains("lines 4, 9"), "got: {msg}");
assert!(msg.contains("holds it once"), "got: {msg}");
}
#[test]
fn an_indented_marker_is_still_a_marker() {
let input = " <!-- ===PROFILE=== -->\nbody\n <!-- ===/PROFILE=== -->\n";
let (out, decision, _) = apply(input, "body\n", false, Options::default());
assert_eq!(decision, Decision::Skip);
assert!(out.contains("sha256="));
}
#[test]
fn a_marker_name_is_limited_to_safe_characters() {
for bad in ["a b", "a=b", "/x", "x/", "a>b", "P-->"] {
let err = MarkerSpan::new("", bad, "b", HTML, None, true).unwrap_err();
assert!(err.to_string().contains("ASCII letters"), "{bad}: {err}");
}
for good in ["P", "profile-2", "a.b_c"] {
assert!(
MarkerSpan::new("", good, "b", HTML, None, true).is_ok(),
"{good}"
);
}
}
#[test]
fn the_hash_comment_style_is_used_throughout() {
let mut s = MarkerSpan::new("", "P", "b\n", CommentStyle::Hash, None, true).unwrap();
let (_, out) = run(&mut s, Options::default()).unwrap();
assert!(out.document.contains("# ===P==="));
assert!(out.document.contains("# ===/P==="));
assert!(!out.document.contains("<!--"));
}
#[test]
fn a_partial_digest_does_not_establish_ownership() {
assert!(recorded_digest("sha256=abc").is_none());
let full = "a".repeat(64);
assert_eq!(recorded_digest(&format!("x sha256={full} -->")), Some(full));
}
#[test]
fn an_empty_marker_name_is_rejected() {
let err = MarkerSpan::new("", "", "b", HTML, None, true).unwrap_err();
assert!(err.to_string().contains("must not be empty"), "got: {err}");
}
#[test]
fn retracting_removes_the_region_with_its_markers() {
let (seeded, _, _) = apply("above\n", "body\n", true, Options::default());
let mut s = MarkerSpan::new(&seeded, "PROFILE", "body\n", HTML, None, false).unwrap();
s.retract(&s.addr()).unwrap();
let out = s.finish(&[]).unwrap();
assert!(!out.document.contains("PROFILE"));
assert!(out.document.starts_with("above\n"));
}
}