Skip to main content

jubarte_cli/cli/
edit_template.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Generator arguments, kept separate from apply's document publication flags.
6use clap::{Args, Subcommand};
7use serde::Serialize;
8use std::path::PathBuf;
9
10/// Internal native routing wrapper; the public spelling is edit template.
11#[derive(Args, Debug, Serialize)]
12pub struct TemplateDispatch {
13    /// Generator action, separate from the legacy edit FILE grammar.
14    #[command(subcommand)]
15    #[serde(flatten)]
16    pub action: TemplateAction,
17}
18
19/// A template is an authoring action, with JSON output rather than DOCX delivery.
20#[derive(Subcommand, Debug, Serialize)]
21#[serde(tag = "action", rename_all = "snake_case")]
22pub enum TemplateAction {
23    /// Generate a source-bound JSON plan without applying edits.
24    #[command(override_usage = "jubarte edit template [OPTIONS] <FILE> (-o PLAN.json|--dry-run)")]
25    Template(TemplateOptions),
26}
27
28/// Generate unchanged desired-text rows; deliberately author edits before apply.
29#[derive(Args, Debug, Serialize)]
30#[command(
31    after_help = "Change a row's text to request a rewrite. Keeping or removing an unchanged row requests no rewrite.\nUse explicit typed operations for insertions, deletions and comments.\n\nExamples:\n  jubarte edit template contract.docx --select p12,p20-p25 -o edits.json\n  jubarte edit template contract.docx --story all -o edits.json\n  jubarte edit apply contract.docx --plan edits.json -o revised.docx --json"
32)]
33pub struct TemplateOptions {
34    /// Original DOCX. Generation never modifies it.
35    pub file: PathBuf,
36    /// Complete PlanV2 JSON; explicit - writes only the raw plan to stdout.
37    #[arg(short, long, value_name = "PLAN.json")]
38    pub output: Option<PathBuf>,
39    /// Printed paragraph/container IDs or closed ranges, frozen on source S.
40    #[arg(long, value_name = "IDS")]
41    pub select: Option<String>,
42    /// body, a printed story ID, or all (default: all).
43    #[arg(long, default_value = "all")]
44    pub story: String,
45    /// Literal search of original-source final logical text.
46    #[arg(long, conflicts_with = "regex")]
47    pub find: Option<String>,
48    /// Explicit regex search of original-source final logical text.
49    #[arg(long)]
50    pub regex: Option<String>,
51    /// Search only; editing remains exact.
52    #[arg(long)]
53    pub ignore_case: bool,
54    /// Blocks intersecting original revisions/comments.
55    #[arg(long)]
56    pub changed: bool,
57    /// Existing-mark author filter; repeat for a union of authors. Requires --changed.
58    #[arg(long, requires = "changed", value_parser = author_filter)]
59    pub by: Vec<String>,
60    /// Read-only original-source neighbours; never additional editing scope.
61    #[arg(long, default_value_t = 0)]
62    pub context: usize,
63    /// Original revision ID to accept in the saved plan; repeatable.
64    #[arg(long)]
65    pub accept_change: Vec<String>,
66    /// Original revision ID to reject in the saved plan; repeatable.
67    #[arg(long)]
68    pub reject_change: Vec<String>,
69    /// Author for later revisions/comments.
70    #[arg(short = 'a', long, default_value = "Jubarte", value_parser = super::parse_author)]
71    pub author: String,
72    /// Frozen timestamp; default current UTC.
73    #[arg(short = 'd', long, value_parser = super::parse_datetime)]
74    pub datetime: Option<String>,
75    /// Track new edits when the plan is applied.
76    #[arg(long, default_value = "on", value_parser = ["on", "off"])]
77    pub track: String,
78    /// Remaining history after the explicitly selected decisions.
79    #[arg(long, default_value = "keep", value_parser = ["keep", "accept", "reject", "refuse"])]
80    pub existing_revisions: String,
81    /// Refuse to accept or reject another author's tracked change, and
82    /// to delete, resolve, reopen or reword their comment. Restore,
83    /// strike, a comment and a reply stay allowed. JUBARTE_KEEP_OTHERS=1
84    /// sets the same guard. Another author is anyone other than
85    /// --author (Jubarte when --author is left out). The generated plan
86    /// carries `"others": "keep"`.
87    #[arg(long)]
88    pub keep_others: bool,
89    /// Require these exact source bytes.
90    #[arg(long, value_name = "HASH", value_parser = super::edit_actions::digest)]
91    pub expect_sha256: Option<String>,
92    /// Report coverage and readiness; write no files. No -o required.
93    #[arg(long)]
94    pub dry_run: bool,
95    /// Explicit receipt path (not another plan); not written during dry-run.
96    #[arg(long, value_name = "FILE")]
97    pub report: Option<PathBuf>,
98    /// Replace only an explicitly named existing output; never an input alias.
99    #[arg(long)]
100    pub force: bool,
101    /// One compact result envelope; conflicts with -o -.
102    #[arg(long, conflicts_with = "jsonl")]
103    pub json: bool,
104    /// Result records ending in a terminal result; never a plan encoding.
105    #[arg(long)]
106    pub jsonl: bool,
107    /// Refresh this plan: write it back whole (every operation, scope,
108    /// decisions, the `others` guard, attribution), with each rewrite of
109    /// the generated rows taking a fresh before_sha256 from the source. The
110    /// plan must be bound to this source.
111    #[arg(long, value_name = "PLAN.json")]
112    pub refresh_plan: Option<PathBuf>,
113}
114
115pub(super) fn validate(
116    args: &clap::ArgMatches,
117    model: &mut clap::Command,
118) -> Result<(), clap::Error> {
119    let (_, args) = args.subcommand().expect("template action required");
120    let error = |message| {
121        model
122            .clone()
123            .error(clap::error::ErrorKind::ArgumentConflict, message)
124    };
125    let output = args.get_one::<PathBuf>("output");
126    let raw = output.is_some_and(|p| p == std::path::Path::new("-"));
127    if output.is_none() && !args.get_flag("dry_run") {
128        return Err(error(
129            "template generation requires -o PLAN.json, explicit -o -, or --dry-run",
130        ));
131    }
132    if raw
133        && ["json", "jsonl", "dry_run"]
134            .iter()
135            .any(|flag| args.get_flag(flag))
136    {
137        return Err(error(
138            "-o - writes only raw PlanV2 JSON; it conflicts with --json, --jsonl and --dry-run",
139        ));
140    }
141    Ok(())
142}
143
144fn author_filter(value: &str) -> Result<String, String> {
145    crate::markdown::author(value).map(str::to_string)
146}