1use std::path::Path;
2
3pub fn marker_line_span(content: &str, marker: &str) -> Option<(usize, usize)> {
9 let mut offset = 0;
10 for line in content.split_inclusive('\n') {
11 if line.trim() == marker {
12 return Some((offset, offset + line.len()));
13 }
14 offset += line.len();
15 }
16 None
17}
18
19pub fn contains_marker_line(content: &str, marker: &str) -> bool {
23 marker_line_span(content, marker).is_some()
24}
25
26pub fn with_line_endings_of(original: &str, text: String) -> String {
29 if original.contains("\r\n") {
30 text.replace("\r\n", "\n").replace('\n', "\r\n")
31 } else {
32 text
33 }
34}
35
36pub fn upsert(path: &Path, start: &str, end: &str, block: &str, quiet: bool, label: &str) {
37 let existing = std::fs::read_to_string(path).unwrap_or_default();
38
39 if contains_marker_line(&existing, start) {
40 let cleaned = remove_content(&existing, start, end);
41 let mut out = cleaned.trim_end().to_string();
42 if !out.is_empty() {
43 out.push('\n');
44 }
45 out.push('\n');
46 out.push_str(block);
47 out.push('\n');
48 std::fs::write(path, &out).ok();
49 if !quiet {
50 println!(" Updated {label}");
51 }
52 } else {
53 let mut out = existing;
54 if !out.is_empty() && !out.ends_with('\n') {
55 out.push('\n');
56 }
57 if !out.is_empty() {
58 out.push('\n');
59 }
60 out.push_str(block);
61 out.push('\n');
62 std::fs::write(path, &out).ok();
63 if !quiet {
64 eprintln!(" Installed {label}");
65 }
66 }
67}
68
69pub fn remove_from_file(path: &Path, start: &str, end: &str, quiet: bool, label: &str) {
70 let Ok(existing) = std::fs::read_to_string(path) else {
71 return;
72 };
73 if !contains_marker_line(&existing, start) {
74 return;
75 }
76 let cleaned = remove_content(&existing, start, end);
77 std::fs::write(path, cleaned.trim_end().to_owned() + "\n").ok();
78 if !quiet {
79 println!(" Removed {label}");
80 }
81}
82
83pub fn remove_content(content: &str, start: &str, end: &str) -> String {
84 let s = marker_line_span(content, start);
85 let e = s.and_then(|(si, _)| {
86 marker_line_span(&content[si..], end).map(|(es, ee)| (si + es, si + ee))
87 });
88 match (s, e) {
89 (Some((si, _)), Some((_, end_after))) => {
90 let before = content[..si].trim_end_matches('\n');
91 let after = content[end_after..].trim_start_matches('\n');
92 let mut out = before.to_string();
93 if !after.is_empty() {
94 out.push('\n');
95 out.push_str(after);
96 }
97 out
98 }
99 _ => content.to_string(),
100 }
101}
102
103pub fn replace_marked_block(content: &str, start: &str, end: &str, replacement: &str) -> String {
106 let s = marker_line_span(content, start);
107 let e = s.and_then(|(si, _)| {
108 marker_line_span(&content[si..], end).map(|(es, ee)| (si + es, si + ee))
109 });
110 match (s, e) {
111 (Some((si, _)), Some((_, end_after))) => {
112 let before = &content[..si];
113 let after = &content[end_after..];
114 let mut out = String::new();
115 out.push_str(before.trim_end_matches('\n'));
116 out.push('\n');
117 out.push('\n');
118 out.push_str(replacement.trim_end_matches('\n'));
119 out.push('\n');
120 out.push_str(after.trim_start_matches('\n'));
121 out
122 }
123 _ => content.to_string(),
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 #[test]
132 fn remove_content_works() {
133 let content = "before\n# >>> start >>>\nhook content\n# <<< end <<<\nafter\n";
134 let cleaned = remove_content(content, "# >>> start >>>", "# <<< end <<<");
135 assert!(!cleaned.contains("hook content"));
136 assert!(cleaned.contains("before"));
137 assert!(cleaned.contains("after"));
138 }
139
140 #[test]
141 fn remove_content_preserves_when_missing() {
142 let content = "no hook here\n";
143 let cleaned = remove_content(content, "# >>> start >>>", "# <<< end <<<");
144 assert_eq!(cleaned, content);
145 }
146
147 const START: &str = "<!-- lean-ctx -->";
150 const END: &str = "<!-- /lean-ctx -->";
151
152 fn agents_md_with_prose_mention() -> String {
157 format!(
158 "# Context Layer\n\n\
159 The table is auto-injected (see the `{START}` block below) — it is\n\
160 deliberately not duplicated here.\n\n\
161 ## Development Workflow\n\n\
162 1. build\n2. test\n\n\
163 {START}\n## lean-ctx\nold pointer\n{END}\n"
164 )
165 }
166
167 #[test]
168 fn prose_marker_mention_is_not_a_block() {
169 let prose_only = format!("docs: cite `{START}` and `{END}` in text\n");
170 assert!(!contains_marker_line(&prose_only, START));
171 let real = format!("{START}\nbody\n{END}\n");
172 assert!(contains_marker_line(&real, START));
173 }
174
175 #[test]
176 fn replace_marked_block_survives_prose_mention() {
177 let content = agents_md_with_prose_mention();
178 let updated = replace_marked_block(&content, START, END, &format!("{START}\nnew\n{END}"));
179 assert!(
180 updated.contains("## Development Workflow") && updated.contains("2. test"),
181 "user content between prose mention and real block must survive:\n{updated}"
182 );
183 assert!(updated.contains("see the `<!-- lean-ctx -->` block below"));
184 assert!(updated.contains("new"), "block itself must be replaced");
185 assert!(!updated.contains("old pointer"));
186 }
187
188 #[test]
189 fn remove_content_survives_prose_mention() {
190 let content = agents_md_with_prose_mention();
191 let cleaned = remove_content(&content, START, END);
192 assert!(cleaned.contains("## Development Workflow"));
193 assert!(cleaned.contains("see the `<!-- lean-ctx -->` block below"));
194 assert!(!cleaned.contains("old pointer"));
195 }
196
197 #[test]
198 fn end_marker_before_start_is_ignored() {
199 let content = format!("{END}\nuser\n{START}\nbody\n{END}\n");
201 let cleaned = remove_content(&content, START, END);
202 assert!(cleaned.contains("user"));
203 assert!(!cleaned.contains("body"));
204 }
205}