1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use crate::cli::global::GlobalFlags;
use crate::cmd::output::WritePhase;
use crate::cmd::output::execute_via_engine;
use crate::exit;
use crate::ops::md::{dedupe_headings_in, find_section, lint_agents_content};
use crate::plan::Operation;
use anyhow::Context;
use clap::Args;
use serde::Serialize;
#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
patchloom md table-append README.md --heading '## API' --row '| /users | List users |'
patchloom md upsert-bullet AGENTS.md --heading '## Rules' --bullet '- Run make check'
patchloom md replace-section CHANGELOG.md --heading '## Unreleased' --content '- New feature' --apply")]
pub struct MdArgs {
#[command(subcommand)]
pub action: MdAction,
#[command(flatten)]
pub write: crate::cli::global::WriteFlags,
}
#[derive(Debug, clap::Subcommand)]
pub enum MdAction {
/// Replace a heading section.
ReplaceSection {
file: String,
#[arg(long)]
heading: String,
/// Read replacement content from stdin.
// ref:md-mode:stdin
#[arg(long)]
stdin: bool,
/// Replacement content as argument.
#[arg(long)]
content: Option<String>,
},
/// Insert content after a heading.
InsertAfterHeading {
file: String,
#[arg(long)]
heading: String,
// ref:md-mode:stdin
#[arg(long)]
stdin: bool,
#[arg(long)]
content: Option<String>,
},
/// Insert content before a heading.
InsertBeforeHeading {
file: String,
#[arg(long)]
heading: String,
// ref:md-mode:stdin
#[arg(long)]
stdin: bool,
#[arg(long)]
content: Option<String>,
},
/// Add a bullet under a heading if not already present.
UpsertBullet {
file: String,
#[arg(long)]
heading: String,
#[arg(long, allow_hyphen_values = true)]
bullet: String,
},
/// Remove duplicate headings.
DedupeHeadings { file: String },
/// Lint common AGENTS.md problems.
#[command(name = "lint-agents", alias = "lint")]
LintAgents { file: String },
/// Append a row to a markdown table under a heading.
TableAppend {
file: String,
#[arg(long)]
heading: String,
/// The row to append, in markdown table format (e.g., "| col1 | col2 | col3 |").
#[arg(long)]
row: String,
},
/// Move a heading section to a new location (same file or different file).
MoveSection {
/// Source file containing the section to move.
file: String,
/// Heading of the section to move (e.g., "## FAQ").
#[arg(long)]
heading: String,
/// Destination file. Omit for same-file reorder.
#[arg(long)]
to: Option<String>,
/// Insert before this heading at the destination.
#[arg(long, conflicts_with = "after")]
before: Option<String>,
/// Insert after this heading at the destination.
#[arg(long, conflicts_with = "before")]
after: Option<String>,
},
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn read_content(use_stdin: bool, content: &Option<String>) -> anyhow::Result<String> {
if use_stdin {
Ok(std::io::read_to_string(std::io::stdin())?)
} else if let Some(c) = content {
Ok(c.clone())
} else {
anyhow::bail!("one of --stdin or --content must be provided")
}
}
/// JSON output struct for single-file md write operations.
#[derive(Debug, Serialize)]
struct MdOutput {
ok: bool,
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
has_changes: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
diff: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
applied: Option<bool>,
}
/// Execute a single md operation through the engine, mapping "not found"
/// errors to `exit::NO_MATCHES`.
fn execute_md_op(
op: Operation,
global: &GlobalFlags,
file: &str,
check_msg: &str,
apply_msg: &str,
) -> anyhow::Result<u8> {
let cwd = global.resolve_cwd()?;
// Shared empty-path + --contain gate (engine also checks under --contain).
global.check_paths_contained(&cwd, [file])?;
let file_owned = file.to_string();
match execute_via_engine(
op,
global,
|phase, diff| MdOutput {
ok: true,
path: file_owned.clone(),
has_changes: match phase {
WritePhase::Check(changed) => Some(changed),
_ => None,
},
diff,
applied: match phase {
WritePhase::Confirmed(a) => Some(a),
_ => None,
},
},
check_msg,
apply_msg,
) {
Ok(code) => Ok(code),
Err(e) => {
if exit::is_no_match(&e) {
global.emit_error_json(&e.to_string())?;
Ok(exit::NO_MATCHES)
} else {
Err(e)
}
}
}
}
// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------
pub fn run(args: MdArgs, global: &GlobalFlags) -> anyhow::Result<u8> {
crate::verbose!("md: action={:?}", std::mem::discriminant(&args.action));
match args.action {
MdAction::ReplaceSection {
file,
heading,
stdin,
content,
} => {
crate::verbose!("md: replace-section file={}, heading={:?}", file, heading);
let replacement = read_content(stdin, &content)?;
let op = Operation::MdReplaceSection {
path: file.clone(),
heading: heading.clone(),
content: replacement,
};
execute_md_op(
op,
global,
&file,
&format!("would modify {file}"),
&format!("modified {file}"),
)
}
MdAction::InsertAfterHeading {
file,
heading,
stdin,
content,
} => {
crate::verbose!(
"md: insert-after-heading file={}, heading={:?}",
file,
heading
);
let insertion = read_content(stdin, &content)?;
let op = Operation::MdInsertAfterHeading {
path: file.clone(),
heading: heading.clone(),
content: insertion,
};
execute_md_op(
op,
global,
&file,
&format!("would modify {file}"),
&format!("modified {file}"),
)
}
MdAction::InsertBeforeHeading {
file,
heading,
stdin,
content,
} => {
crate::verbose!(
"md: insert-before-heading file={}, heading={:?}",
file,
heading
);
let insertion = read_content(stdin, &content)?;
let op = Operation::MdInsertBeforeHeading {
path: file.clone(),
heading: heading.clone(),
content: insertion,
};
execute_md_op(
op,
global,
&file,
&format!("would modify {file}"),
&format!("modified {file}"),
)
}
MdAction::UpsertBullet {
file,
heading,
bullet,
} => {
crate::verbose!("md: upsert-bullet file={}, heading={:?}", file, heading);
let op = Operation::MdUpsertBullet {
path: file.clone(),
heading: heading.clone(),
bullet,
};
execute_md_op(
op,
global,
&file,
&format!("would modify {file}"),
&format!("modified {file}"),
)
}
MdAction::DedupeHeadings { file } => {
crate::verbose!("md: dedupe-headings file={}", file);
// Pre-read to compute removed headings for side-channel output,
// then route the actual write through the engine.
let cwd = global.resolve_cwd()?;
global.check_paths_contained(&cwd, [&file])?;
let path = cwd.join(&file);
let original =
std::fs::read_to_string(&path).with_context(|| format!("reading {file}"))?;
let (_new, removed) = dedupe_headings_in(&original);
// Emit removed headings as side-channel output.
if !removed.is_empty() && !global.emit_json_items(&removed)? && !global.quiet {
for h in &removed {
eprintln!("md: removed duplicate: {h}");
}
}
// Side-channel headings already emitted; no second JSON schema body.
let op = Operation::MdDedupeHeadings { path: file.clone() };
let (cwd, result) = crate::cmd::output::stage_for_write(
crate::tx::engine::WriteSource::Operations(vec![op]),
global,
)?;
use crate::cmd::write_mode::{FinalizeCallbacks, finalize_report};
finalize_report(
global,
&cwd,
result,
true,
FinalizeCallbacks {
on_check: |_g: &GlobalFlags, _has: bool, _diffs: &[crate::diff::FileDiff]| {
Ok(())
},
on_apply: |_g: &GlobalFlags,
_has: bool,
_diffs: &[crate::diff::FileDiff],
_plain: Option<String>| Ok(()),
on_preview: |g: &GlobalFlags,
_has: bool,
diffs: &[crate::diff::FileDiff],
_plain: Option<String>| {
if !diffs.is_empty() && !g.json && !g.jsonl {
let dr = crate::diff::DiffResult {
diffs: diffs.to_vec(),
};
print!(
"{}",
crate::diff::format_diff_result_colored(&dr, g.should_color())
);
}
Ok(())
},
after_preview_emit: |_: &GlobalFlags| {},
after_preview_apply: |_: &GlobalFlags| {},
},
)
}
MdAction::LintAgents { file } => {
crate::verbose!("md: lint-agents file={}", file);
let cwd = global.resolve_cwd()?;
global.check_paths_contained(&cwd, [&file])?;
let path = cwd.join(&file);
let content =
std::fs::read_to_string(&path).with_context(|| format!("reading {file}"))?;
let issues = lint_agents_content(&content);
if !global.emit_json_items(&issues)? && !global.quiet {
for issue in &issues {
match (issue.line, &issue.heading) {
(Some(ln), Some(h)) => {
println!("{file}:{ln}: {} {h:?}", issue.issue);
}
(Some(ln), None) => {
println!("{file}:{ln}: {}", issue.issue);
}
_ => {
println!("{file}: {}", issue.issue);
}
}
}
}
if issues.is_empty() {
Ok(exit::SUCCESS)
} else {
Ok(exit::CHANGES_DETECTED)
}
}
MdAction::TableAppend { file, heading, row } => {
crate::verbose!("md: table-append file={}, heading={:?}", file, heading);
// Pre-validate: distinguish "heading not found" (NO_MATCHES)
// from "no table under heading" (error), which the engine
// conflates into a single None.
let cwd = global.resolve_cwd()?;
global.check_paths_contained(&cwd, [&file])?;
let path = cwd.join(&file);
let content =
std::fs::read_to_string(&path).with_context(|| format!("reading {file}"))?;
match find_section(&content, &heading) {
None => {
let msg = format!("heading {:?} not found in {file}", heading);
global.emit_error_json(&msg)?;
Ok(exit::NO_MATCHES)
}
Some((body_start, body_end)) => {
// Verify the table exists and the row is valid.
if let Err(e) =
crate::ops::md::table_append_in(&content, body_start, body_end, &row)
{
anyhow::bail!("{e} under heading {:?}", heading);
}
let op = Operation::MdTableAppend {
path: file.clone(),
heading: heading.clone(),
row,
};
let file_owned = file.clone();
execute_via_engine(
op,
global,
|phase, diff| MdOutput {
ok: true,
path: file_owned.clone(),
has_changes: match phase {
WritePhase::Check(changed) => Some(changed),
_ => None,
},
diff,
applied: match phase {
WritePhase::Confirmed(a) => Some(a),
_ => None,
},
},
&format!("would modify {file}"),
&format!("modified {file}"),
)
}
}
}
MdAction::MoveSection {
file,
heading,
to,
before,
after,
} => {
crate::verbose!(
"md: move-section file={}, heading={:?}, to={:?}",
file,
heading,
to
);
// Validate exactly one of --before or --after.
if before.is_none() && after.is_none() {
anyhow::bail!("exactly one of --before or --after must be provided");
}
let dest_file = to.as_deref().unwrap_or(&file);
let (check_msg, apply_msg) = if dest_file != file {
(
format!("would modify {file}\nwould modify {dest_file}"),
format!("modified {file}\nmodified {dest_file}"),
)
} else {
(format!("would modify {file}"), format!("modified {file}"))
};
let op = Operation::MdMoveSection {
path: file.clone(),
heading,
to,
before,
after,
};
execute_md_op(op, global, &file, &check_msg, &apply_msg)
}
}
}
#[path = "md_tests.rs"]
#[cfg(test)]
mod tests;