-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhashline.rs
More file actions
547 lines (518 loc) · 18.6 KB
/
Copy pathhashline.rs
File metadata and controls
547 lines (518 loc) · 18.6 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! OMP-compatible line-anchored edit language used by the existing `edit` tool.
use crate::config::Config;
use crate::tools::{make_unified_diff, Outcome};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{LazyLock, Mutex};
static REGISTERS: LazyLock<Mutex<HashMap<String, String>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
#[derive(Debug)]
enum Locator {
Range(usize, usize),
Before(usize),
After(usize),
End,
}
#[derive(Debug)]
enum Op {
PutBody(Locator, String),
PutRegister(Locator, Option<String>),
Cut(usize, usize, Option<String>),
Remove,
Move(String),
}
#[derive(Debug)]
struct Section {
path: String,
tag: String,
ops: Vec<Op>,
}
#[derive(Debug)]
struct Planned {
source: PathBuf,
path: String,
old: String,
new: String,
remove: bool,
move_to: Option<(PathBuf, String)>,
}
fn parse_range(raw: &str) -> Result<(usize, usize), String> {
let Some((a, b)) = raw.split_once(".=") else {
return Err(format!("bad range `{raw}`; expected N.=M"));
};
let start = a.parse::<usize>().map_err(|_| format!("bad line `{a}`"))?;
let end = b.parse::<usize>().map_err(|_| format!("bad line `{b}`"))?;
if start == 0 || end < start {
return Err(format!(
"bad range `{raw}`; lines are 1-indexed and start must not exceed end"
));
}
Ok((start, end))
}
fn parse_locator(raw: &str, allow_range: bool) -> Result<Locator, String> {
if raw.ends_with('*') {
return Err(format!(
"block locator `{raw}` is not resolvable; use `PUT N.=M:` with an explicit inclusive range"
));
}
if raw == ">$" {
return Ok(Locator::End);
}
if let Some(n) = raw.strip_prefix('<') {
let n = n
.parse::<usize>()
.map_err(|_| format!("bad locator `{raw}`"))?;
return (n > 0)
.then_some(Locator::Before(n))
.ok_or_else(|| format!("bad locator `{raw}`"));
}
if let Some(n) = raw.strip_prefix('>') {
let n = n
.parse::<usize>()
.map_err(|_| format!("bad locator `{raw}`"))?;
return (n > 0)
.then_some(Locator::After(n))
.ok_or_else(|| format!("bad locator `{raw}`"));
}
if allow_range {
let (a, b) = parse_range(raw)?;
return Ok(Locator::Range(a, b));
}
Err(format!("bad gap locator `{raw}`"))
}
fn split_register(raw: &str) -> (&str, Option<String>) {
match raw.rsplit_once(" @") {
Some((loc, name))
if !name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') =>
{
(loc, Some(name.to_string()))
}
_ => (raw, None),
}
}
fn parse(input: &str) -> Result<Vec<Section>, String> {
let normalized = input.replace("\r\n", "\n");
let mut lines = normalized.lines().peekable();
let mut sections = Vec::new();
while let Some(line) = lines.next() {
if line.trim().is_empty() || line == "*** Begin Patch" || line == "*** End Patch" {
continue;
}
if !line.starts_with('[') || !line.ends_with(']') {
return Err(format!("expected `[path#TAG]`, got `{line}`"));
}
let inner = &line[1..line.len() - 1];
let Some((path, tag)) = inner.rsplit_once('#') else {
return Err(format!("bad section header `{line}`"));
};
if path.is_empty() || tag.len() != 4 || !tag.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!(
"bad section header `{line}`; TAG must be 4 hex digits"
));
}
let mut ops = Vec::new();
while let Some(next) = lines.peek().copied() {
if next.starts_with('[') && next.ends_with(']') || next == "*** End Patch" {
break;
}
let line = lines.next().unwrap();
if line.trim().is_empty() {
continue;
}
if let Some(rest) = line.strip_prefix("PUT ") {
if let Some(header) = rest.strip_suffix(':') {
if header.contains(" @") {
return Err("register PUT must be colonless and have no body".into());
}
let locator = parse_locator(header, true)?;
let mut body = String::new();
let mut count = 0;
while let Some(body_line) = lines.peek().copied() {
if !body_line.starts_with('+') {
break;
}
let body_line = lines.next().unwrap();
body.push_str(&body_line[1..]);
body.push('\n');
count += 1;
}
if count == 0 {
return Err(format!(
"`PUT {header}:` requires one or more `+` body rows"
));
}
ops.push(Op::PutBody(locator, body));
} else {
let (loc, reg) = split_register(rest);
let locator = parse_locator(loc, false)?;
ops.push(Op::PutRegister(locator, reg));
}
} else if let Some(rest) = line.strip_prefix("CUT ") {
let (loc, reg) = split_register(rest);
if loc.ends_with('*') {
return Err(format!(
"block locator `{loc}` is not resolvable; use `CUT N.=M` with an explicit inclusive range"
));
}
let (start, end) = parse_range(loc)?;
ops.push(Op::Cut(start, end, reg));
} else if line == "REM" {
ops.push(Op::Remove);
} else if let Some(dest) = line.strip_prefix("MV ") {
let dest = dest.trim();
let dest = if dest.len() >= 2
&& ((dest.starts_with('"') && dest.ends_with('"'))
|| (dest.starts_with('\'') && dest.ends_with('\'')))
{
&dest[1..dest.len() - 1]
} else {
dest
};
if dest.is_empty() {
return Err("MV requires a destination".into());
}
ops.push(Op::Move(dest.to_string()));
} else {
return Err(format!("bad hashline syntax `{line}`"));
}
}
if ops.is_empty() {
return Err(format!("section `{path}` has no operations"));
}
sections.push(Section {
path: path.to_string(),
tag: tag.to_ascii_lowercase(),
ops,
});
}
if sections.is_empty() {
return Err("hashline input requires at least one `[path#TAG]` section".into());
}
Ok(sections)
}
fn resolve(cfg: &Config, input: &str) -> Result<PathBuf, String> {
crate::tools::resolve_ws(cfg, input)
}
fn line_count(content: &str) -> usize {
content.split_inclusive('\n').count()
}
fn offsets(content: &str) -> Vec<usize> {
let mut out = vec![0];
for (i, b) in content.bytes().enumerate() {
if b == b'\n' {
out.push(i + 1);
}
}
if out.last().copied() != Some(content.len()) {
out.push(content.len());
}
out
}
fn range_bytes(content: &str, start: usize, end: usize) -> Result<(usize, usize), String> {
let count = line_count(content);
if start == 0 || end < start || end > count {
return Err(format!(
"line range {start}.={end} is outside displayed file (1..={count})"
));
}
let off = offsets(content);
Ok((off[start - 1], off[end]))
}
fn locator_bytes(content: &str, loc: &Locator) -> Result<(usize, usize), String> {
let count = line_count(content);
match *loc {
Locator::Range(a, b) => range_bytes(content, a, b),
Locator::Before(n) if n <= count => {
let off = offsets(content);
Ok((off[n - 1], off[n - 1]))
}
Locator::After(n) if n <= count => {
let off = offsets(content);
Ok((off[n], off[n]))
}
Locator::End => Ok((content.len(), content.len())),
Locator::Before(n) | Locator::After(n) => Err(format!(
"gap line {n} is outside displayed file (1..={count})"
)),
}
}
fn plan(input: &str, cfg: &Config) -> Result<(Vec<Planned>, HashMap<String, String>), String> {
let sections = parse(input)?;
let mut named = REGISTERS
.lock()
.map_err(|_| "hashline register lock poisoned")?
.clone();
let mut anonymous: Option<String> = None;
let mut planned = Vec::new();
for section in sections {
let source = resolve(cfg, §ion.path)?;
let old = std::fs::read_to_string(&source)
.map_err(|e| format!("hashline: read {:?} failed: {e}", section.path))?;
let have = crate::read_summary::file_tag(&old);
if !have.eq_ignore_ascii_case(§ion.tag) {
return Err(crate::file_snapshot::stale_tag_error(
§ion.path,
&old,
§ion.tag,
true,
)
.unwrap_or_else(|| {
format!(
"stale file tag: read was [{}#{}] but disk is [{}#{}]",
section.path, section.tag, section.path, have
)
}));
}
let mut changes: Vec<(usize, usize, String)> = Vec::new();
let mut remove = false;
let mut move_to = None;
for op in section.ops {
match op {
Op::PutBody(loc, body) => {
let (a, b) = locator_bytes(&old, &loc)?;
changes.push((a, b, body));
}
Op::Cut(start, end, reg) => {
let (a, b) = range_bytes(&old, start, end)?;
let captured = old[a..b].to_string();
if let Some(name) = reg {
named.insert(name, captured);
} else {
anonymous = Some(captured);
}
changes.push((a, b, String::new()));
}
Op::PutRegister(loc, reg) => {
let value = match reg {
Some(name) => named
.get(&name)
.cloned()
.ok_or_else(|| format!("register `@{name}` is empty"))?,
None => anonymous.clone().ok_or_else(|| {
"anonymous register is empty; CUT a range first".to_string()
})?,
};
let (a, b) = locator_bytes(&old, &loc)?;
changes.push((a, b, value));
}
Op::Remove => remove = true,
Op::Move(dest) => move_to = Some((resolve(cfg, &dest)?, dest)),
}
}
if remove && (move_to.is_some() || !changes.is_empty()) {
return Err(format!(
"REM must be the only operation in section `{}`",
section.path
));
}
changes.sort_by_key(|(a, b, _)| (*a, *b));
for pair in changes.windows(2) {
if pair[1].0 < pair[0].1 || (pair[0].0 == pair[1].0 && pair[0].1 != pair[0].0) {
return Err(format!(
"overlapping hashline operations in `{}`",
section.path
));
}
}
let mut new = old.clone();
for (a, b, replacement) in changes.into_iter().rev() {
new.replace_range(a..b, &replacement);
}
planned.push(Planned {
source,
path: section.path,
old,
new,
remove,
move_to,
});
}
Ok((planned, named))
}
fn diff(plans: &[Planned]) -> String {
let mut out = String::new();
for p in plans {
let new = if p.remove { "" } else { &p.new };
out.push_str(&make_unified_diff(&p.old, new, &p.path, 3));
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
}
out
}
pub fn preview(input: &str, cfg: &Config) -> Result<String, String> {
let (plans, _) = plan(input, cfg)?;
Ok(diff(&plans))
}
pub fn execute(input: &str, cfg: &Config) -> Outcome {
let (plans, named) = match plan(input, cfg) {
Ok(v) => v,
Err(e) => return Outcome::err(e),
};
let rendered_diff = diff(&plans);
for p in &plans {
if p.remove {
let outcome = crate::tools::delete_path(&p.path, cfg);
if !outcome.ok {
return outcome;
}
continue;
}
if let Err(e) = crate::tools::atomic_write_file(&p.source, &p.new) {
return Outcome::err(format!("hashline: write {:?} failed: {e}", p.path));
}
let final_path = if let Some((_dest, label)) = &p.move_to {
let outcome = crate::tools::rename_path(&p.path, label, cfg);
if !outcome.ok {
return outcome;
}
label.as_str()
} else {
p.path.as_str()
};
crate::file_snapshot::record(final_path, &p.new);
}
if let Ok(mut registers) = REGISTERS.lock() {
registers.extend(named);
}
let mut out = Outcome::ok(format!("applied hashline edit to {} file(s)", plans.len()));
out.diff = Some(rendered_diff);
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::sync::atomic::{AtomicU64, Ordering};
fn workspace() -> Config {
static N: AtomicU64 = AtomicU64::new(0);
let root = std::env::temp_dir().join(format!(
"catcode_hashline_{}",
N.fetch_add(1, Ordering::SeqCst)
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
Config {
workspace: root,
..Config::default()
}
}
fn tagged(path: &str, content: &str, ops: &str) -> String {
format!("[{path}#{}]\n{ops}", crate::read_summary::file_tag(content))
}
#[test]
fn put_range_and_gap_preserve_keepers() {
let cfg = workspace();
let original = "one\ntwo\nthree\n";
fs::write(cfg.workspace.join("f.txt"), original).unwrap();
let input = tagged("f.txt", original, "PUT 2.=2:\n+TWO\nPUT >2:\n+after\n");
let out = execute(&input, &cfg);
assert!(out.ok, "{}", out.output);
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
"one\nTWO\nafter\nthree\n"
);
}
#[test]
fn edit_dispatch_and_preview_use_hashline_input() {
let cfg = workspace();
let original = "one\ntwo\n";
fs::write(cfg.workspace.join("f.txt"), original).unwrap();
let input = tagged("f.txt", original, "PUT 2.=2:\n+TWO\n");
let preview = super::preview(&input, &cfg).unwrap();
assert!(preview.contains("+TWO"), "{preview}");
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
original
);
let out = crate::tools::execute("edit", &serde_json::json!({"input": input}), &cfg);
assert!(out.ok, "{}", out.output);
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
"one\nTWO\n"
);
}
#[test]
fn cut_and_anonymous_paste() {
let cfg = workspace();
let original = "one\ntwo\nthree\n";
fs::write(cfg.workspace.join("f.txt"), original).unwrap();
let out = execute(&tagged("f.txt", original, "CUT 2.=2\nPUT >3\n"), &cfg);
assert!(out.ok, "{}", out.output);
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
"one\nthree\ntwo\n"
);
}
#[test]
fn stale_tag_and_bad_ranges_fail_without_writing() {
let cfg = workspace();
let original = "one\ntwo\n";
fs::write(cfg.workspace.join("f.txt"), original).unwrap();
let stale = execute("[f.txt#FFFF]\nPUT 2.=2:\n+TWO\n", &cfg);
assert!(!stale.ok);
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
original
);
let bad = execute(&tagged("f.txt", original, "CUT 9.=9\n"), &cfg);
assert!(!bad.ok);
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
original
);
}
#[test]
fn matching_uppercase_tag_puts() {
let cfg = workspace();
let original = "one\ntwo\n";
fs::write(cfg.workspace.join("f.txt"), original).unwrap();
let tag = crate::read_summary::file_tag(original).to_ascii_uppercase();
let out = execute(&format!("[f.txt#{tag}]\nPUT 2.=2:\n+TWO\n"), &cfg);
assert!(out.ok, "{}", out.output);
assert_eq!(
fs::read_to_string(cfg.workspace.join("f.txt")).unwrap(),
"one\nTWO\n"
);
}
#[test]
fn rem_and_move_after_put() {
let cfg = workspace();
let old = "old\n";
fs::write(cfg.workspace.join("remove.txt"), old).unwrap();
let removed = execute(&tagged("remove.txt", old, "REM\n"), &cfg);
assert!(removed.ok, "{}", removed.output);
assert!(!cfg.workspace.join("remove.txt").exists());
fs::write(cfg.workspace.join("from.txt"), old).unwrap();
let moved = execute(
&tagged("from.txt", old, "PUT 1.=1:\n+new\nMV nested/to.txt\n"),
&cfg,
);
assert!(moved.ok, "{}", moved.output);
assert!(!cfg.workspace.join("from.txt").exists());
assert_eq!(
fs::read_to_string(cfg.workspace.join("nested/to.txt")).unwrap(),
"new\n"
);
}
#[test]
fn named_register_persists_across_calls_and_syntax_fails_closed() {
let cfg = workspace();
let a = "keep\ncopy\n";
let b = "target\n";
fs::write(cfg.workspace.join("a.txt"), a).unwrap();
fs::write(cfg.workspace.join("b.txt"), b).unwrap();
assert!(execute(&tagged("a.txt", a, "CUT 2.=2 @saved\n"), &cfg).ok);
assert!(execute(&tagged("b.txt", b, "PUT >$ @saved\n"), &cfg).ok);
assert_eq!(
fs::read_to_string(cfg.workspace.join("b.txt")).unwrap(),
"target\ncopy\n"
);
let block = execute(&tagged("b.txt", "target\ncopy\n", "PUT 1*:\n+x\n"), &cfg);
assert!(!block.ok);
assert!(block.output.contains("PUT N.=M:"), "{}", block.output);
}
}