1use std::{ffi::OsString, path::PathBuf};
8
9use clap::{Args, Subcommand};
10use serde::Serialize;
11
12#[derive(Args, Debug, Serialize)]
14pub struct TypedEdit {
15 #[command(subcommand)]
17 #[serde(flatten)]
18 pub action: EditAction,
19}
20
21#[derive(Subcommand, Debug, Serialize)]
23#[serde(tag = "action", rename_all = "snake_case")]
24pub enum EditAction {
25 #[command(
27 override_usage = "jubarte edit replace [OPTIONS] <FILE> --find TEXT (--text TEXT|--text-file FILE)"
28 )]
29 Replace {
30 #[command(flatten)]
32 inline: InlineOptions,
33 #[arg(long)]
35 find: String,
36 #[arg(long)]
38 at: Option<String>,
39 #[arg(long, conflicts_with = "at")]
41 story: Option<String>,
42 #[arg(long, value_parser = positive, conflicts_with = "all_matches")]
44 occurrence: Option<usize>,
45 #[arg(long, requires = "expect_count")]
47 all_matches: bool,
48 #[arg(long, requires = "all_matches", value_parser = positive)]
50 expect_count: Option<usize>,
51 #[command(flatten)]
53 payload: TextPayload,
54 },
55 #[command(
57 override_usage = "jubarte edit rewrite [OPTIONS] <FILE> --at ID (--text TEXT|--text-file FILE)"
58 )]
59 Rewrite {
60 #[command(flatten)]
62 inline: InlineOptions,
63 #[arg(long)]
65 at: String,
66 #[command(flatten)]
68 payload: TextPayload,
69 },
70 #[command(
72 override_usage = "jubarte edit insert [OPTIONS] <FILE> --kind text|paragraph --at ID (--text TEXT|--text-file FILE)"
73 )]
74 Insert {
75 #[command(flatten)]
77 inline: InlineOptions,
78 #[arg(long, value_parser = ["text", "paragraph"])]
80 kind: String,
81 #[arg(long)]
83 at: String,
84 #[arg(long, conflicts_with_all = ["after_text", "edge", "position"])]
86 before_text: Option<String>,
87 #[arg(long, conflicts_with_all = ["edge", "position"])]
89 after_text: Option<String>,
90 #[arg(long, value_parser = ["start", "end"], conflicts_with_all = ["position", "occurrence"])]
92 edge: Option<String>,
93 #[arg(long, value_parser = ["before", "after"], conflicts_with = "occurrence")]
95 position: Option<String>,
96 #[arg(long, value_parser = positive)]
98 occurrence: Option<usize>,
99 #[command(flatten)]
101 payload: TextPayload,
102 },
103 #[command(
105 override_usage = "jubarte edit delete [OPTIONS] <FILE> --at ID (--find TEXT|--whole-block)"
106 )]
107 Delete {
108 #[command(flatten)]
110 inline: InlineOptions,
111 #[arg(long)]
113 at: String,
114 #[arg(
116 long,
117 required_unless_present = "whole_block",
118 conflicts_with = "whole_block"
119 )]
120 find: Option<String>,
121 #[arg(long, required_unless_present = "find", conflicts_with = "occurrence")]
123 whole_block: bool,
124 #[arg(long, value_parser = positive, requires = "find")]
126 occurrence: Option<usize>,
127 },
128 #[command(
132 override_usage = "jubarte edit apply [OPTIONS] <FILE> --plan FILE",
133 mut_arg("output", |a| a.help("Primary edited DOCX; required unless bundling, replacing FILE or dry-running"))
134 )]
135 Apply {
136 file: PathBuf,
138 #[arg(long, value_name = "FILE", value_parser = super::plan_path())]
140 plan: PathBuf,
141 #[arg(long)]
143 allow_unbound_plan: bool,
144 #[command(flatten)]
146 delivery: DeliveryOptions,
147 },
148}
149
150#[derive(Args, Debug, Serialize)]
152#[group(skip)]
153pub struct TextPayload {
154 #[arg(
156 long,
157 required_unless_present = "text_file",
158 conflicts_with = "text_file"
159 )]
160 pub text: Option<String>,
161 #[arg(long, value_name = "FILE", required_unless_present = "text")]
163 pub text_file: Option<PathBuf>,
164 #[arg(long)]
166 pub comment: Option<String>,
167}
168
169#[derive(Args, Debug, Serialize)]
171pub struct InlineOptions {
172 pub file: PathBuf,
174 #[arg(short = 'a', long, default_value = "Jubarte", value_parser = super::parse_author)]
177 pub author: String,
178 #[arg(skip)]
182 #[serde(skip)]
183 pub author_given: bool,
184 #[arg(short = 'd', long = "datetime", value_parser = super::parse_datetime)]
186 pub datetime: Option<String>,
187 #[arg(long, default_value = "on", value_parser = ["on", "off"])]
189 pub track: String,
190 #[arg(long, default_value = "keep", value_parser = ["keep", "accept", "reject", "refuse"])]
192 pub existing_revisions: String,
193 #[arg(long)]
195 pub accept_change: Vec<String>,
196 #[arg(long)]
198 pub reject_change: Vec<String>,
199 #[arg(long, value_name = "FILE", value_parser = super::plan_path(), conflicts_with_all = ["output", "out_dir", "report", "emit", "expect", "dry_run", "in_place"])]
201 pub save_plan: Option<PathBuf>,
202 #[command(flatten)]
204 pub delivery: DeliveryOptions,
205}
206
207#[derive(Args, Debug, Serialize)]
209pub struct DeliveryOptions {
210 #[arg(long, conflicts_with_all = ["output", "out_dir", "dry_run"])]
212 pub in_place: bool,
213 #[arg(short = 'o', long, value_name = "FILE", conflicts_with = "out_dir")]
215 pub output: Option<PathBuf>,
216 #[arg(long, value_name = "NEW_DIR")]
218 pub out_dir: Option<PathBuf>,
219 #[arg(long, value_name = "FILE")]
221 pub report: Option<PathBuf>,
222 #[arg(long, value_delimiter = ',', value_parser = ["document", "patch", "report"])]
224 pub emit: Vec<String>,
225 #[arg(long, value_name = "FILE")]
229 pub expect: Option<PathBuf>,
230 #[arg(long, value_name = "HASH", value_parser = digest)]
232 pub expect_sha256: Option<String>,
233 #[arg(long, conflicts_with_all = ["output", "out_dir"])]
235 pub dry_run: bool,
236 #[arg(long)]
238 pub require_change: bool,
239 #[arg(long)]
241 pub force: bool,
242 #[arg(long)]
248 pub keep_others: bool,
249 #[arg(long, conflicts_with = "jsonl")]
251 pub json: bool,
252 #[arg(long)]
254 pub jsonl: bool,
255}
256
257pub(super) fn positive(s: &str) -> Result<usize, String> {
258 s.parse()
259 .ok()
260 .filter(|n| *n > 0)
261 .ok_or_else(|| "must be a positive, 1-based integer".into())
262}
263pub(super) fn digest(s: &str) -> Result<String, String> {
264 if s.len() == 64
265 && s.bytes()
266 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
267 {
268 Ok(s.into())
269 } else {
270 Err("must be 64 lowercase hexadecimal characters".into())
271 }
272}
273
274pub fn route(arguments: &[OsString], model: &clap::Command) -> Vec<OsString> {
278 let mut routed = arguments.to_vec();
279 if arguments.get(1).is_none_or(|a| a != "edit") {
280 return routed;
281 }
282 let action = arguments.iter().skip(2).find(|a| {
283 !a.to_str().is_some_and(|s| {
284 s == "--quiet" || s.starts_with('-') && s.len() > 1 && s[1..].bytes().all(|b| b == b'q')
285 })
286 });
287 if !action.is_some_and(|a| {
288 matches!(
289 a.to_str(),
290 Some("replace" | "rewrite" | "insert" | "delete" | "apply" | "template")
291 )
292 }) {
293 return routed;
294 }
295 if model.clone().try_get_matches_from(arguments).is_ok() {
296 return routed;
297 }
298 if action.is_some_and(|a| a == "template") {
299 routed[1] = "__edit-template".into();
300 return routed;
301 }
302 routed[1] = "__edit-v2".into();
303 routed
304}
305
306pub(super) fn validate(
307 args: &clap::ArgMatches,
308 model: &mut clap::Command,
309) -> Result<(), clap::Error> {
310 let (action, args) = args.subcommand().expect("typed action required");
311 let present = |id| {
312 args.try_contains_id(id).unwrap_or(false)
313 && args.value_source(id) == Some(clap::parser::ValueSource::CommandLine)
314 };
315 let error = |message: &str| {
316 model
317 .clone()
318 .error(clap::error::ErrorKind::ArgumentConflict, message)
319 };
320 if !["output", "out_dir", "dry_run", "save_plan", "in_place"]
321 .into_iter()
322 .any(present)
323 {
324 return Err(error(
325 "writes require -o FILE or --out-dir NEW_DIR or --in-place; use --dry-run or inline --save-plan FILE",
326 ));
327 }
328 if action == "insert" {
329 let paragraph = args
330 .get_one::<String>("kind")
331 .is_some_and(|s| s == "paragraph");
332 if paragraph != present("position")
333 || !paragraph
334 && !["before_text", "after_text", "edge"]
335 .into_iter()
336 .any(present)
337 {
338 return Err(error(
339 "--kind paragraph requires --position before|after; --kind text requires --before-text, --after-text or --edge",
340 ));
341 }
342 }
343 Ok(())
344}
345
346impl EditAction {
347 pub fn name(&self) -> &'static str {
349 match self {
350 Self::Replace { .. } => "replace",
351 Self::Rewrite { .. } => "rewrite",
352 Self::Insert { .. } => "insert",
353 Self::Delete { .. } => "delete",
354 Self::Apply { .. } => "apply",
355 }
356 }
357 pub fn inline(&self) -> Option<&InlineOptions> {
359 match self {
360 Self::Replace { inline, .. }
361 | Self::Rewrite { inline, .. }
362 | Self::Insert { inline, .. }
363 | Self::Delete { inline, .. } => Some(inline),
364 Self::Apply { .. } => None,
365 }
366 }
367 pub fn inline_mut(&mut self) -> Option<&mut InlineOptions> {
369 match self {
370 Self::Replace { inline, .. }
371 | Self::Rewrite { inline, .. }
372 | Self::Insert { inline, .. }
373 | Self::Delete { inline, .. } => Some(inline),
374 Self::Apply { .. } => None,
375 }
376 }
377 pub fn author_was_given(&self) -> bool {
380 self.inline().is_none_or(|inline| inline.author_given)
381 }
382 pub fn payload(&self) -> Option<&TextPayload> {
384 match self {
385 Self::Replace { payload, .. }
386 | Self::Rewrite { payload, .. }
387 | Self::Insert { payload, .. } => Some(payload),
388 _ => None,
389 }
390 }
391 pub fn file(&self) -> &std::path::Path {
393 match self {
394 Self::Apply { file, .. } => file,
395 _ => &self.inline().expect("inline").file,
396 }
397 }
398 pub fn delivery(&self) -> &DeliveryOptions {
400 match self {
401 Self::Apply { delivery, .. } => delivery,
402 _ => &self.inline().expect("inline").delivery,
403 }
404 }
405}