Skip to main content

jubarte_edit/edit/
record.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4//! `edit` and `add` with `--plan PLAN.json`: with operation flags they
5//! record the operations into the plan instead of editing; alone they apply
6//! it, and `--consume` deletes it once applied. The binary, the Python CLI
7//! and the npm CLI all record here, and the shared parser refuses the flags
8//! that do not go with `--plan` ([`plan_flag_conflict`]), so the three print
9//! the same lines.
10
11use std::path::{Path, PathBuf};
12
13use super::flags::{FlagOp, Verb, plan_from_flags, record_into, renumber_notes};
14use super::{EditPlan, ExistingRevisions};
15
16/// Flags that take effect when a plan is applied, so a recording refuses
17/// them.
18const APPLY_ONLY: &[&str] = &[
19    "--consume",
20    "--out-dir",
21    "--output",
22    "--in-place",
23    "--force",
24    "--editing-mode",
25    "--suggesting-mode",
26    "--pdf",
27    "--png",
28    "--dpi",
29    "--revisions",
30    "--revision-palette",
31];
32
33/// Flags that describe recorded operations, so applying a plan refuses
34/// them: the plan names its own.
35const RECORD_ONLY: &[&str] = &["--author", "--datetime", "--existing-revisions"];
36
37/// Why `given` (the flags the command line spells out) cannot go with
38/// `--plan plan`: `recording` is `--plan` with operation flags, otherwise
39/// the plan is applied. `None` when they can.
40pub fn plan_flag_conflict(recording: bool, given: &[&str], plan: &str) -> Option<String> {
41    if recording {
42        let flag = APPLY_ONLY.iter().find(|f| given.contains(f))?;
43        // A bare --plan (D16) is still unresolved here: spell it bare.
44        let apply = if plan.is_empty() {
45            "--plan".to_string()
46        } else {
47            format!("--plan {plan}")
48        };
49        Some(format!(
50            "{flag} takes effect when the plan is applied (jubarte edit FILE {apply}), and is not recorded"
51        ))
52    } else {
53        let flag = RECORD_ONLY.iter().find(|f| given.contains(f))?;
54        if *flag == "--existing-revisions" {
55            return Some(format!(
56                "{flag} belongs to recorded operations; {}",
57                super::KEEP_REVISIONS
58            ));
59        }
60        Some(format!(
61            "{flag} belongs to recorded operations; the plan names its own"
62        ))
63    }
64}
65
66/// Why a recording failed.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub enum RecordError {
69    /// The flags, or their disagreement with the plan: exit 2.
70    Usage(String),
71    /// The plan file held is not a plan: exit 3, as applying it would.
72    Plan(String),
73}
74
75/// A recording, ready to be checked against the source and written.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct Recorded {
78    /// The plan with the new operations, to preview against the source
79    /// and then write.
80    pub plan: EditPlan,
81    /// `op-N: …` notes, numbered within the whole plan.
82    pub notes: Vec<String>,
83    /// How many operations this recording added.
84    pub added: usize,
85    /// How many revision ids this recording added to accept or reject.
86    pub added_revisions: usize,
87}
88
89impl Recorded {
90    /// The plan as written to PLAN.json: pretty JSON with a final newline.
91    pub fn json(&self) -> String {
92        serde_json::to_string_pretty(&self.plan).expect("a plan serializes") + "\n"
93    }
94
95    /// The line a recording prints: what was added, what the plan now holds,
96    /// and the command that applies it. `default_plan`: `--plan` was given
97    /// without a value, so the apply line spells it bare (D16).
98    pub fn summary(&self, file: &str, plan: &str, default_plan: bool, dry_run: bool) -> String {
99        let ids = |side: fn(&super::ResolveRevisions) -> &Option<crate::changes::ChangeFilter>| {
100            self.plan
101                .resolve_revisions
102                .as_ref()
103                .and_then(|r| side(r).as_ref())
104                .and_then(|f| f.ids.as_ref())
105                .map_or(0, Vec::len)
106        };
107        let (accept, reject) = (ids(|r| &r.accept), ids(|r| &r.reject));
108        let total = self.plan.operations.len();
109        let s = |n: usize| if n == 1 { "" } else { "s" };
110        // What this recording added: its operations, its revisions, or both.
111        let operations = format!("{} operation{}", self.added, s(self.added));
112        let revisions = format!(
113            "{} revision{}",
114            self.added_revisions,
115            s(self.added_revisions)
116        );
117        let added = match (self.added, self.added_revisions) {
118            (_, 0) => operations,
119            (0, _) => revisions,
120            _ => format!("{operations} and {revisions}"),
121        };
122        let apply = if default_plan {
123            "--plan".to_string()
124        } else {
125            format!("--plan {plan}")
126        };
127        format!(
128            "{} {added} in {plan}: {total} operation{}, {accept} revision{} to accept, {reject} to reject; apply with: jubarte edit {file} {apply}",
129            if dry_run { "would record" } else { "recorded" },
130            s(total),
131            s(accept),
132        )
133    }
134}
135
136/// Where a recording is written: the file a symbolic link names (the link
137/// stays a link), else `plan` itself. Only the native publish path calls
138/// it; wasm32 writes no files.
139#[cfg(not(target_arch = "wasm32"))]
140pub(crate) fn plan_target(plan: &Path) -> PathBuf {
141    if let Ok(real) = std::fs::canonicalize(plan) {
142        return real;
143    }
144    // A link to a plan not written yet names where it goes.
145    match std::fs::read_link(plan) {
146        Ok(to) => plan.parent().unwrap_or(Path::new("")).join(to),
147        Err(_) => plan.to_path_buf(),
148    }
149}
150
151/// Legacy temporary-name helper, retained for API compatibility. Recordings
152/// no longer open this predictable path; publication creates exclusive staging.
153/// [`commit_plan`] locks a sibling of the plan and refuses when the bytes it
154/// read are gone. A writer that does not call it is not blocked, and a change
155/// that lands before that locked re-read is refused rather than overwritten.
156pub fn partial_path(target: &Path) -> PathBuf {
157    let name = target
158        .file_name()
159        .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
160    target.with_file_name(format!(".{name}.{}.partial", std::process::id()))
161}
162
163/// Write `json` (a [`Recorded::json`]) to PLAN.json at `plan`, atomically:
164/// a precommit error leaves the plan as it was. Returns staging cleanup warnings
165/// after successful installation; publication errors retain their warning payload.
166///
167/// # Errors
168///
169/// The I/O error when the partial file cannot be written beside the plan or
170/// renamed into place (a missing directory, no permission). After a successful
171/// commit, a durability error explicitly reports the committed plan.
172pub fn write_plan(plan: &Path, json: &str) -> std::io::Result<Vec<String>> {
173    #[cfg(not(target_arch = "wasm32"))]
174    {
175        let target = plan_target(plan);
176        crate::publication::publish_paths(&[(target, json.as_bytes())], true)
177            .map(|report| report.warnings)
178            .map_err(|error| std::io::Error::new(error.source.kind(), error))
179    }
180    #[cfg(target_arch = "wasm32")]
181    Err(std::io::Error::new(
182        std::io::ErrorKind::Unsupported,
183        format!(
184            "cannot publish {} ({} bytes): filesystem publication is unavailable in WASM",
185            plan.display(),
186            json.len()
187        ),
188    ))
189}
190
191/// [`commit_plan`]'s refusal: PLAN.json is no longer the bytes the caller
192/// read, so the commit would overwrite a newer plan. It travels inside the
193/// [`std::io::Error`] (kind [`std::io::ErrorKind::AlreadyExists`]) and
194/// callers can downcast to it.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub struct PlanChanged;
197
198impl std::fmt::Display for PlanChanged {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        f.write_str("the plan changed while it was recorded; record the operation again")
201    }
202}
203
204impl std::error::Error for PlanChanged {}
205
206/// Replace PLAN.json with `json` only when its bytes are still `expected`.
207/// `None` means the plan was absent when it was read. A mismatch leaves the
208/// file untouched and returns an error whose message says the plan changed.
209///
210/// Callers of this function take one writer lock on a sibling of the plan, so
211/// two of them cannot overwrite each other. A writer that does not call it is
212/// not blocked. A change that lands before the locked re-read is refused
213/// rather than overwritten.
214///
215/// # Errors
216///
217/// [`std::io::ErrorKind::AlreadyExists`] when `expected` is not the plan's
218/// current bytes. The same I/O errors as [`write_plan`] when the publish
219/// fails. WASM has no filesystem publication.
220pub fn commit_plan(
221    plan: &Path,
222    expected: Option<&str>,
223    json: &str,
224) -> std::io::Result<Vec<String>> {
225    #[cfg(not(target_arch = "wasm32"))]
226    {
227        let target = plan_target(plan);
228        // The lock lives on a sibling inode. Replacing the plan renames a new
229        // inode into place, which would drop a lock held on the plan itself.
230        let _lock = lock_plan(&target)?;
231        let current = match std::fs::read_to_string(&target) {
232            Ok(text) => Some(text),
233            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
234            Err(error) => return Err(error),
235        };
236        if current.as_deref() != expected {
237            return Err(std::io::Error::new(
238                std::io::ErrorKind::AlreadyExists,
239                PlanChanged,
240            ));
241        }
242        write_plan(plan, json)
243    }
244    #[cfg(target_arch = "wasm32")]
245    {
246        let _ = expected;
247        write_plan(plan, json)
248    }
249}
250
251/// Exclusive lock on `.{name}.lock` beside `target`, through std's
252/// [`std::fs::File::lock`] (`flock` on Unix, `LockFileEx` on Windows). The
253/// returned file holds the lock until it is dropped. Callers share one
254/// inode, so a second commit waits instead of publishing over the first.
255/// A lock file another user left, which this one cannot write, is opened
256/// read-only: neither lock call needs write access.
257#[cfg(not(target_arch = "wasm32"))]
258fn lock_plan(target: &Path) -> std::io::Result<std::fs::File> {
259    let name = target
260        .file_name()
261        .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
262    let path = target.with_file_name(format!(".{name}.lock"));
263    let file = match std::fs::OpenOptions::new()
264        .read(true)
265        .write(true)
266        .create(true)
267        .truncate(false)
268        .open(&path)
269    {
270        Ok(file) => file,
271        Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
272            std::fs::File::open(&path)?
273        }
274        Err(error) => return Err(error),
275    };
276    file.lock()?;
277    Ok(file)
278}
279
280/// The operations `ops` recorded into `held` (PLAN.json's text, `None`
281/// before the first recording), pinned to `source`'s SHA-256. `existing`
282/// is `--existing-revisions` (`None` for `auto`). The caller previews the
283/// result against `source` before writing it. Nothing is written here.
284///
285/// # Errors
286///
287/// [`RecordError::Usage`] when the flags describe no operation or an invalid
288/// one, or disagree with the held plan (another source, author, date or
289/// `existing_revisions`); [`RecordError::Plan`] when the held text is not a
290/// plan.
291pub fn record(
292    verb: Verb,
293    ops: &[FlagOp],
294    author: &str,
295    date: Option<&str>,
296    existing: Option<ExistingRevisions>,
297    source: &[u8],
298    held: Option<&str>,
299) -> Result<Recorded, RecordError> {
300    let held = held
301        .map(EditPlan::from_json)
302        .transpose()
303        .map_err(|e| RecordError::Plan(e.to_string()))?;
304    let before = held.as_ref().map_or(0, |p| p.operations.len());
305    // Each id once and in its short spelling, as `record_into` joins them:
306    // `r1+2` is two ids, `r1` and `r2`, so a recording that names an id the
307    // plan already holds adds nothing.
308    let revisions = |plan: Option<&EditPlan>| -> std::collections::HashSet<String> {
309        plan.and_then(|p| p.resolve_revisions.as_ref())
310            .map(|r| {
311                [&r.accept, &r.reject]
312                    .into_iter()
313                    .flatten()
314                    .filter_map(|f| f.normalized().unwrap_or_else(|_| f.clone()).ids)
315                    .flatten()
316                    .collect()
317            })
318            .unwrap_or_default()
319    };
320    let revisions_before = revisions(held.as_ref());
321    let mut built =
322        plan_from_flags(verb, ops, author, date, existing, source).map_err(RecordError::Usage)?;
323    built.plan.source_sha256 = Some(crate::inspect::source_sha256(source));
324    let plan = record_into(held, built.plan).map_err(RecordError::Usage)?;
325    Ok(Recorded {
326        added: plan.operations.len() - before,
327        added_revisions: revisions(Some(&plan)).difference(&revisions_before).count(),
328        notes: renumber_notes(built.notes, before),
329        plan,
330    })
331}
332
333/// What [`record_json`] takes besides the operations: the command line's
334/// options, as the Python and npm CLIs parse them.
335#[derive(Debug, Default, serde::Deserialize)]
336#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
337pub(crate) struct RecordOptions {
338    /// `--author` (default `Jubarte`).
339    pub author: Option<String>,
340    /// `--datetime`.
341    pub date: Option<String>,
342    /// `--existing-revisions`: `auto` (the default), `keep`, `accept`,
343    /// `reject` or `refuse`.
344    pub existing_revisions: Option<String>,
345    /// FILE as the command line names it, for the summary.
346    pub file: String,
347    /// PLAN.json as the command line names it, for the summary.
348    pub plan: String,
349    /// `--plan` was given without a value: the summary prints it bare.
350    pub default_plan: bool,
351    /// `--dry-run`: the summary says "would record".
352    pub dry_run: bool,
353    /// `--rewrite-others-comments`: accepted and ignored.
354    pub rewrite_others_comments: bool,
355    /// `--keep-others`: the recorded plan carries `"others": "keep"`.
356    pub keep_others: bool,
357}
358
359/// [`record`] over JSON, for the Python and npm CLIs: `verb` is `edit` or
360/// `add`, `operations` the parsed command's `operations` array, `held`
361/// PLAN.json's text, `options` a `RecordOptions` object. Returns `{plan,
362/// json, notes, summary}`: `plan` to preview, `json` to write, `notes` and
363/// `summary` to print.
364///
365/// # Errors
366///
367/// [`RecordError::Usage`] for an unknown verb, unparsable operations or
368/// options, a bad date or `--existing-revisions` value, and every
369/// [`record`] failure; [`RecordError::Plan`] when the held text is not a
370/// plan.
371pub fn record_json(
372    verb: &str,
373    operations: &str,
374    source: &[u8],
375    held: Option<&str>,
376    options: &str,
377) -> Result<String, RecordError> {
378    let usage = |e: String| RecordError::Usage(e);
379    let verb = match verb {
380        "edit" => Verb::Edit,
381        "add" => Verb::Add,
382        other => return Err(usage(format!("unknown verb {other:?}: edit or add"))),
383    };
384    let ops: Vec<FlagOp> =
385        serde_json::from_str(operations).map_err(|e| usage(format!("operations: {e}")))?;
386    let options: RecordOptions =
387        serde_json::from_str(options).map_err(|e| usage(format!("options: {e}")))?;
388    // The CLI's --datetime is checked by its parser; the bindings' is here.
389    let date = options
390        .date
391        .as_deref()
392        .map(crate::util::datetime::parse_datetime)
393        .transpose()
394        .map_err(|e| usage(format!("date: {e}")))?;
395    let existing = match options.existing_revisions.as_deref().unwrap_or("auto") {
396        "auto" => None,
397        "keep" => Some(ExistingRevisions::Keep),
398        "accept" => Some(ExistingRevisions::Accept),
399        "reject" => Some(ExistingRevisions::Reject),
400        "refuse" => Some(ExistingRevisions::Refuse),
401        other => {
402            return Err(usage(format!(
403                "existing revisions {other:?}: auto, keep, accept, reject or refuse"
404            )));
405        }
406    };
407    let author = options.author.as_deref().unwrap_or("Jubarte");
408    let mut recorded = record(verb, &ops, author, date.as_deref(), existing, source, held)?;
409    recorded.plan.rewrite_others_comments |= options.rewrite_others_comments;
410    if options.keep_others {
411        recorded.plan.others = super::Others::Keep;
412    }
413    Ok(serde_json::json!({
414        "plan": serde_json::to_string(&recorded.plan).expect("a plan serializes"),
415        "json": recorded.json(),
416        "notes": recorded.notes,
417        "summary": recorded.summary(
418            &options.file,
419            &options.plan,
420            options.default_plan,
421            options.dry_run,
422        ),
423    })
424    .to_string())
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    fn rewrite(at: &str, content: &str) -> FlagOp {
432        FlagOp {
433            at: at.into(),
434            content: Some(content.into()),
435            ..FlagOp::default()
436        }
437    }
438
439    fn once(ops: &[FlagOp], held: Option<&str>) -> Result<Recorded, RecordError> {
440        record(
441            Verb::Edit,
442            ops,
443            "Ann",
444            None,
445            Some(ExistingRevisions::Keep),
446            b"doc",
447            held,
448        )
449    }
450
451    #[test]
452    fn a_recording_pins_the_source_and_counts_on_from_the_held_plan() {
453        let first = once(&[rewrite("p1", "One.")], None).unwrap();
454        assert_eq!(first.added, 1);
455        assert_eq!(
456            first.plan.source_sha256.as_deref(),
457            Some(crate::inspect::source_sha256(b"doc").as_str())
458        );
459        assert_eq!(
460            first.summary("a.docx", "plan.json", false, false),
461            "recorded 1 operation in plan.json: 1 operation, 0 revisions to accept, 0 to reject; \
462             apply with: jubarte edit a.docx --plan plan.json"
463        );
464        let second = once(
465            &[rewrite("p2", "Two."), rewrite("p3", "Three.")],
466            Some(&first.json()),
467        )
468        .unwrap();
469        assert_eq!((second.added, second.plan.operations.len()), (2, 3));
470        assert!(
471            second
472                .summary("a.docx", "plan.json", false, true)
473                .starts_with("would record 2 operations in plan.json: 3 operations,")
474        );
475        assert!(first.json().ends_with("}\n") && !first.json().contains("null"));
476    }
477
478    #[test]
479    fn a_recording_of_revisions_only_says_so() {
480        let accept = FlagOp {
481            at: "r2".into(),
482            accept: true,
483            ..FlagOp::default()
484        };
485        let both = once(&[rewrite("p1", "One."), accept.clone()], None).unwrap();
486        assert!(
487            both.summary("a.docx", "p.json", false, false).starts_with(
488                "recorded 1 operation and 1 revision in p.json: 1 operation, 1 revision to accept,"
489            ),
490            "{}",
491            both.summary("a.docx", "p.json", false, false)
492        );
493        let reject = FlagOp {
494            at: "r3".into(),
495            reject: true,
496            ..FlagOp::default()
497        };
498        let only = once(&[reject], Some(&both.json())).unwrap();
499        assert!(
500            only.summary("a.docx", "p.json", false, false).starts_with(
501                "recorded 1 revision in p.json: 1 operation, 1 revision to accept, 1 to reject"
502            ),
503            "{}",
504            only.summary("a.docx", "p.json", false, false)
505        );
506    }
507
508    /// #433: a held plan's ids count as `record_into` joins them,
509    /// so `r1+2` held is two ids and a duplicate spelling one.
510    #[test]
511    fn recorded_revisions_count_each_long_id_once() {
512        let held = |ids: &[&str]| {
513            let mut plan: serde_json::Value =
514                serde_json::from_str(&once(&[rewrite("p1", "One.")], None).unwrap().json())
515                    .unwrap();
516            plan["resolve_revisions"] = serde_json::json!({"accept": {"ids": ids}});
517            plan.to_string()
518        };
519        let accept = |at: &str| FlagOp {
520            at: at.into(),
521            accept: true,
522            ..FlagOp::default()
523        };
524        let compound = once(&[accept("r3")], Some(&held(&["r1+2"]))).unwrap();
525        assert_eq!(compound.added_revisions, 1);
526        let twice = once(&[accept("r1")], Some(&held(&["r1", "r1"]))).unwrap();
527        assert_eq!(twice.added_revisions, 0);
528    }
529
530    #[test]
531    fn a_held_file_that_is_not_a_plan_is_a_plan_error() {
532        assert!(matches!(
533            once(&[rewrite("p1", "One.")], Some("{}")),
534            Err(RecordError::Plan(_))
535        ));
536        assert!(matches!(
537            once(&[], None),
538            Err(RecordError::Usage(m)) if m.starts_with("no operation")
539        ));
540    }
541
542    #[test]
543    fn flags_are_refused_on_the_side_of_plan_they_do_not_belong_to() {
544        assert_eq!(
545            plan_flag_conflict(true, &["--quiet", "--pdf", "--out-dir"], "p.json").unwrap(),
546            "--out-dir takes effect when the plan is applied (jubarte edit FILE --plan p.json), and is not recorded"
547        );
548        assert_eq!(
549            plan_flag_conflict(true, &["--in-place"], "p.json").unwrap(),
550            "--in-place takes effect when the plan is applied (jubarte edit FILE --plan p.json), and is not recorded"
551        );
552        assert_eq!(
553            plan_flag_conflict(true, &["--author", "--dry-run"], "p.json"),
554            None
555        );
556        assert_eq!(
557            plan_flag_conflict(false, &["--consume", "--datetime"], "p.json").unwrap(),
558            "--datetime belongs to recorded operations; the plan names its own"
559        );
560        assert_eq!(
561            plan_flag_conflict(false, &["--consume", "--out-dir"], "p.json"),
562            None
563        );
564    }
565
566    #[test]
567    fn a_plan_is_written_through_its_link_and_leaves_no_partial() {
568        let dir = tempfile::tempdir().unwrap();
569        let real = dir.path().join("v3.json");
570        std::fs::write(&real, "{}").unwrap();
571        let link = dir.path().join("plan.json");
572        #[cfg(unix)]
573        std::os::unix::fs::symlink(&real, &link).unwrap();
574        #[cfg(not(unix))]
575        std::fs::copy(&real, &link).unwrap();
576        write_plan(&link, "[1]\n").unwrap();
577        assert_eq!(std::fs::read_to_string(&link).unwrap(), "[1]\n");
578        #[cfg(unix)]
579        {
580            assert!(link.symlink_metadata().unwrap().is_symlink());
581            assert_eq!(std::fs::read_to_string(&real).unwrap(), "[1]\n");
582        }
583        let left: Vec<_> = std::fs::read_dir(dir.path())
584            .unwrap()
585            .map(|e| e.unwrap().file_name())
586            .collect();
587        assert_eq!(left.len(), 2, "{left:?}");
588        // A link to a plan not written yet creates the file it names.
589        #[cfg(unix)]
590        {
591            let dangling = dir.path().join("next.json");
592            std::os::unix::fs::symlink("plans-v4.json", &dangling).unwrap();
593            write_plan(&dangling, "[2]\n").unwrap();
594            assert!(dangling.symlink_metadata().unwrap().is_symlink());
595            assert_eq!(
596                std::fs::read_to_string(dir.path().join("plans-v4.json")).unwrap(),
597                "[2]\n"
598            );
599            std::fs::remove_file(&dangling).unwrap();
600            std::fs::remove_file(dir.path().join("plans-v4.json")).unwrap();
601        }
602        // A plan in a directory that is gone fails and leaves nothing.
603        assert!(write_plan(&dir.path().join("gone/plan.json"), "x").is_err());
604        assert!(
605            partial_path(Path::new("a/x.json"))
606                .to_string_lossy()
607                .ends_with(&format!(".x.json.{}.partial", std::process::id()))
608        );
609    }
610
611    #[test]
612    fn record_json_reads_the_options_the_bindings_pass() {
613        let out = record_json(
614            "add",
615            r#"[{"at":"p1","comment":true,"content":"Why?"}]"#,
616            b"doc",
617            None,
618            r#"{"author":"Ann","existingRevisions":"keep","file":"a.docx","plan":"p.json"}"#,
619        )
620        .unwrap();
621        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
622        assert_eq!(v["notes"], serde_json::json!([]));
623        assert!(
624            v["summary"]
625                .as_str()
626                .unwrap()
627                .starts_with("recorded 1 operation in p.json")
628        );
629        let plan = EditPlan::from_json(v["plan"].as_str().unwrap()).unwrap();
630        assert_eq!(plan.author, "Ann");
631        assert_eq!(
632            EditPlan::from_json(v["json"].as_str().unwrap()).unwrap(),
633            plan
634        );
635        for (ops, options) in [
636            (
637                r#"[{"at":"p1","comment":true,"content":"Why?"}]"#,
638                r#"{"date":"yesterday","file":"a","plan":"p"}"#,
639            ),
640            (
641                r#"[{"at":"p1","comment":true,"content":"Why?","style":["bold"]}]"#,
642                r#"{"file":"a","plan":"p"}"#,
643            ),
644        ] {
645            assert!(matches!(
646                record_json("add", ops, b"doc", None, options),
647                Err(RecordError::Usage(_))
648            ));
649        }
650        assert!(matches!(
651            record_json("move", "[]", b"", None, r#"{"file":"a","plan":"p"}"#),
652            Err(RecordError::Usage(m)) if m.contains("edit or add")
653        ));
654        assert!(matches!(
655            record_json("edit", "[]", b"", None, r#"{"file":"a","plan":"p","existingRevisions":"x"}"#),
656            Err(RecordError::Usage(m)) if m.contains("auto, keep")
657        ));
658    }
659
660    /// A direct write is not blocked. A later commit that still names the
661    /// bytes it read refuses and leaves the newer plan in place. A commit
662    /// that names the bytes now on disk replaces them.
663    #[test]
664    fn a_stale_plan_commit_keeps_the_newer_plan() {
665        let dir = tempfile::tempdir().unwrap();
666        let path = dir.path().join("plan.json");
667        std::fs::write(&path, "one\n").unwrap();
668        std::fs::write(&path, "two\n").unwrap();
669        match commit_plan(&path, Some("one\n"), "one-plus\n") {
670            Err(error) => {
671                assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
672                // A typed refusal, not only a message.
673                assert!(
674                    error
675                        .get_ref()
676                        .is_some_and(|inner| inner.downcast_ref::<PlanChanged>().is_some()),
677                    "{error:?}"
678                );
679                assert!(error.to_string().contains("changed"), "{error}");
680            }
681            Ok(_) => panic!(
682                "a stale commit replaced the plan: {}",
683                std::fs::read_to_string(&path).unwrap()
684            ),
685        }
686        assert_eq!(std::fs::read_to_string(&path).unwrap(), "two\n");
687        commit_plan(&path, Some("two\n"), "three\n").unwrap();
688        assert_eq!(std::fs::read_to_string(&path).unwrap(), "three\n");
689    }
690
691    /// The lock file another user left (read-only to this one) still locks:
692    /// an advisory lock needs no write access, so the commit goes ahead.
693    #[cfg(unix)]
694    #[test]
695    fn a_read_only_lock_file_does_not_refuse_the_commit() {
696        use std::os::unix::fs::PermissionsExt;
697        let dir = tempfile::tempdir().unwrap();
698        let path = dir.path().join("plan.json");
699        std::fs::write(&path, "one\n").unwrap();
700        let lock = dir.path().join(".plan.json.lock");
701        std::fs::write(&lock, b"").unwrap();
702        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o444)).unwrap();
703        commit_plan(&path, Some("one\n"), "two\n").unwrap();
704        assert_eq!(std::fs::read_to_string(&path).unwrap(), "two\n");
705    }
706
707    /// The plan lock is exclusive: while one commit holds it, a second
708    /// cannot take it, on every platform the lock compiles for.
709    #[cfg(not(target_arch = "wasm32"))]
710    #[test]
711    fn the_plan_lock_is_exclusive() {
712        let dir = tempfile::tempdir().unwrap();
713        let target = dir.path().join("plan.json");
714        let held = lock_plan(&target).unwrap();
715        let second = std::fs::File::open(dir.path().join(".plan.json.lock")).unwrap();
716        assert!(matches!(
717            second.try_lock(),
718            Err(std::fs::TryLockError::WouldBlock)
719        ));
720        drop(held);
721        second.try_lock().unwrap();
722    }
723}