Skip to main content

ask/
markers.rs

1//! Marker-block helpers — Rust port of `packages/cli/src/markers.ts`.
2//!
3//! Injects ASK-owned content into user files without touching the surrounding
4//! user content. Two comment syntaxes:
5//!   - [`MarkerSyntax::Html`] for Markdown (`<!-- ask:start --> … <!-- ask:end -->`)
6//!   - [`MarkerSyntax::Hash`] for ignore/properties files (`# ask:start … # ask:end`)
7//!
8//! Marker delimiters are ASCII, so `str::find` byte offsets always land on char
9//! boundaries even when the wrapped user content is multi-byte UTF-8.
10
11/// Which comment syntax delimits the marker block.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum MarkerSyntax {
14    Html,
15    Hash,
16}
17
18impl MarkerSyntax {
19    fn begin(self) -> &'static str {
20        match self {
21            MarkerSyntax::Html => "<!-- ask:start -->",
22            MarkerSyntax::Hash => "# ask:start",
23        }
24    }
25
26    fn end(self) -> &'static str {
27        match self {
28            MarkerSyntax::Html => "<!-- ask:end -->",
29            MarkerSyntax::Hash => "# ask:end",
30        }
31    }
32}
33
34/// Wrap a payload with begin/end markers. No trailing newline (parity with
35/// `wrap`).
36pub fn wrap(payload: &str, syntax: MarkerSyntax) -> String {
37    format!("{}\n{}\n{}", syntax.begin(), payload, syntax.end())
38}
39
40/// Locate a well-formed marker block: both delimiters present and `end` after
41/// `begin`. Returns the byte offsets `(begin_idx, end_idx)`.
42fn locate(content: &str, syntax: MarkerSyntax) -> Option<(usize, usize)> {
43    let begin_idx = content.find(syntax.begin())?;
44    let end_idx = content.find(syntax.end())?;
45    if end_idx > begin_idx {
46        Some((begin_idx, end_idx))
47    } else {
48        None
49    }
50}
51
52/// Inject or refresh a marker block. If a matching block exists it is replaced
53/// in place; otherwise the block is appended with a blank-line separator.
54/// Deterministic and idempotent (parity with `inject`).
55pub fn inject(content: &str, block: &str, syntax: MarkerSyntax) -> String {
56    let end = syntax.end();
57    if let Some((begin_idx, end_idx)) = locate(content, syntax) {
58        // Replace existing block in place.
59        let mut out = String::with_capacity(content.len());
60        out.push_str(&content[..begin_idx]);
61        out.push_str(block);
62        out.push_str(&content[end_idx + end.len()..]);
63        return out;
64    }
65
66    if content.is_empty() {
67        return format!("{block}\n");
68    }
69    format!("{}\n\n{}\n", content.trim_end(), block)
70}
71
72/// Strip the marker block if present, normalizing the blank lines around the
73/// removed region. Returns the content unchanged if no block is found (parity
74/// with `remove`).
75pub fn remove(content: &str, syntax: MarkerSyntax) -> String {
76    let end = syntax.end();
77    let Some((begin_idx, end_idx)) = locate(content, syntax) else {
78        return content.to_string();
79    };
80    let before = content[..begin_idx].trim_end();
81    let after = content[end_idx + end.len()..].trim_start();
82
83    if before.is_empty() && after.is_empty() {
84        return String::new();
85    }
86    if before.is_empty() {
87        return if after.ends_with('\n') {
88            after.to_string()
89        } else {
90            format!("{after}\n")
91        };
92    }
93    if after.is_empty() {
94        return format!("{before}\n");
95    }
96    let tail = if after.ends_with('\n') {
97        after.to_string()
98    } else {
99        format!("{after}\n")
100    };
101    format!("{before}\n\n{tail}")
102}
103
104/// Whether a well-formed marker block of the given syntax exists.
105pub fn has(content: &str, syntax: MarkerSyntax) -> bool {
106    locate(content, syntax).is_some()
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use MarkerSyntax::{Hash, Html};
113
114    #[test]
115    fn wrap_has_no_trailing_newline() {
116        assert_eq!(
117            wrap("body", Html),
118            "<!-- ask:start -->\nbody\n<!-- ask:end -->"
119        );
120        assert_eq!(wrap("body", Hash), "# ask:start\nbody\n# ask:end");
121    }
122
123    #[test]
124    fn inject_into_empty_appends_single_trailing_newline() {
125        let block = wrap("x", Html);
126        assert_eq!(inject("", &block, Html), format!("{block}\n"));
127    }
128
129    #[test]
130    fn inject_appends_with_blank_line_separator() {
131        let block = wrap("x", Html);
132        let out = inject("# Title\n", &block, Html);
133        assert_eq!(out, format!("# Title\n\n{block}\n"));
134    }
135
136    #[test]
137    fn inject_is_idempotent_and_replaces_in_place() {
138        let first = inject("# Title\n", &wrap("v1", Html), Html);
139        let second = inject(&first, &wrap("v2", Html), Html);
140        // The v1 block is replaced by v2, not duplicated.
141        assert_eq!(second.matches("ask:start").count(), 1);
142        assert!(second.contains("v2"));
143        assert!(!second.contains("v1"));
144        // Re-injecting the same block yields identical output (idempotent).
145        assert_eq!(inject(&second, &wrap("v2", Html), Html), second);
146    }
147
148    #[test]
149    fn has_detects_well_formed_block_only() {
150        let with = inject("doc", &wrap("x", Hash), Hash);
151        assert!(has(&with, Hash));
152        assert!(!has("no markers here", Hash));
153        // end-before-begin is not a well-formed block.
154        assert!(!has("# ask:end\n# ask:start", Hash));
155    }
156
157    #[test]
158    fn remove_block_only_leaves_empty_string() {
159        let only = wrap("x", Html);
160        assert_eq!(remove(&only, Html), "");
161    }
162
163    #[test]
164    fn remove_preserves_surrounding_content() {
165        let content = inject("# Title\n", &wrap("x", Html), Html);
166        assert_eq!(remove(&content, Html), "# Title\n");
167    }
168
169    #[test]
170    fn remove_between_two_user_sections_normalizes_blank_lines() {
171        let block = wrap("x", Hash);
172        let content = format!("before\n\n{block}\n\nafter\n");
173        assert_eq!(remove(&content, Hash), "before\n\nafter\n");
174    }
175
176    #[test]
177    fn remove_absent_block_is_noop() {
178        assert_eq!(remove("untouched\n", Html), "untouched\n");
179    }
180
181    #[test]
182    fn inject_remove_roundtrip_returns_original_trimmed() {
183        let original = "# Title\n";
184        let injected = inject(original, &wrap("x", Html), Html);
185        assert_eq!(remove(&injected, Html), "# Title\n");
186    }
187}