1pub use crate::edit::flags::FlagOp;
8pub mod edit_actions;
10pub mod edit_template;
12use clap::{CommandFactory, FromArgMatches, Parser};
13use serde::Serialize;
14use std::path::{Path, PathBuf};
15
16pub(crate) use crate::util::datetime::parse_datetime;
17
18#[derive(Parser, Debug, Serialize)]
20#[command(
21 name = "jubarte", version = env!("JUBARTE_BUILD_VERSION"),
22 help_template = "{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{all-args}{after-help}",
23 about = "Read, edit, compare and render Word documents",
24 long_about = None,
25 styles = styles(),
26 term_width = 88,
27 args_conflicts_with_subcommands = true,
28 subcommand_negates_reqs = true,
29 arg_required_else_help = true,
30 subcommand_help_heading = "Tasks",
31 after_help = "Examples:\n jubarte compare old.docx new.docx -o redline.docx\n jubarte contract.docx print the agent view (read)\n jubarte old.docx new.docx redline printed as the agent view (-o writes it)\n jubarte read contract.docx --json\n jubarte diff old.docx new.docx --format github\n jubarte convert contract.docx -o contract.pdf\n\nRun jubarte <task> --help for task options.",
32)]
33pub struct Cli {
34 #[command(subcommand)]
36 pub command: Option<Command>,
37
38 #[arg(
46 short = 'q',
47 long,
48 global = true,
49 overrides_with = "quiet",
50 help_heading = None::<&str>
51 )]
52 pub quiet: bool,
53
54 #[command(flatten)]
57 #[serde(flatten)]
58 pub compare: CompareArgs,
59}
60
61#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
63#[group(id = "read_options", multiple = true)]
64pub struct ReadArgs {
65 #[arg(long, value_enum, value_name = "CHOICE", help_heading = "Read options")]
72 pub track_changes: Option<TrackChanges>,
73 #[arg(
77 long,
78 value_enum,
79 default_value_t = CommentsArg::Inline,
80 value_name = "MODE",
81 help_heading = "Read options"
82 )]
83 pub comments: CommentsArg,
84 #[arg(long, help_heading = "Read options")]
88 pub dates: bool,
89 #[arg(long, help_heading = "Read options")]
93 pub no_page_markers: bool,
94 #[arg(
103 short = 'p',
104 long = "paragraphs",
105 visible_alias = "select",
106 value_name = "SPEC",
107 conflicts_with_all = ["head", "tail"],
108 action = clap::ArgAction::Append,
109 help_heading = "Read options"
110 )]
111 #[serde(serialize_with = "serialize_paragraph_spec")]
112 pub paragraphs: Vec<String>,
113 #[arg(
115 long,
116 value_name = "N",
117 conflicts_with = "tail",
118 help_heading = "Read options"
119 )]
120 pub head: Option<usize>,
121 #[arg(long, value_name = "N", help_heading = "Read options")]
123 pub tail: Option<usize>,
124 #[arg(
126 long,
127 conflicts_with_all = ["paragraphs", "head", "tail"],
128 help_heading = "Read options"
129 )]
130 pub changed: bool,
131 #[arg(
134 long,
135 value_name = "AUTHOR",
136 requires = "changed",
137 value_parser = parse_author,
138 help_heading = "Read options"
139 )]
140 pub by: Option<String>,
141 #[arg(long, help_heading = "Read options")]
149 pub json: bool,
150 #[arg(
163 long,
164 conflicts_with_all = ["json", "head", "tail", "changed", "by"],
165 help_heading = "Read options"
166 )]
167 pub tables: bool,
168 #[arg(long, conflicts_with = "track_changes", help_heading = "Read options")]
177 pub for_edit: bool,
178 #[arg(
181 long,
182 value_name = "ID",
183 requires = "for_edit",
184 help_heading = "Read options"
185 )]
186 pub accept_change: Vec<String>,
187 #[arg(
190 long,
191 value_name = "ID",
192 requires = "for_edit",
193 help_heading = "Read options"
194 )]
195 pub reject_change: Vec<String>,
196 #[arg(
199 long,
200 value_enum,
201 value_name = "MODE",
202 requires = "for_edit",
203 help_heading = "Read options"
204 )]
205 pub existing_revisions: Option<ExistingArg>,
206 #[arg(
209 long,
210 value_enum,
211 value_name = "CHOICE",
212 requires = "for_edit",
213 help_heading = "Read options"
214 )]
215 pub track: Option<TrackArg>,
216 #[arg(
223 long,
224 value_name = "TEXT",
225 conflicts_with = "regex",
226 help_heading = "Read options"
227 )]
228 pub find: Option<String>,
229 #[arg(
232 long,
233 value_name = "PATTERN",
234 conflicts_with = "find",
235 help_heading = "Read options"
236 )]
237 pub regex: Option<String>,
238 #[arg(long, help_heading = "Read options")]
240 pub ignore_case: bool,
241 #[arg(
244 long,
245 value_name = "N",
246 requires = "for_edit",
247 help_heading = "Read options"
248 )]
249 pub context: Option<usize>,
250 #[arg(
252 long,
253 value_name = "N",
254 requires = "for_edit",
255 help_heading = "Read options"
256 )]
257 pub limit: Option<usize>,
258 #[arg(
261 long,
262 value_name = "N",
263 requires = "for_edit",
264 help_heading = "Read options"
265 )]
266 pub max_chars: Option<usize>,
267 #[arg(
270 long,
271 value_name = "TOKEN",
272 requires = "for_edit",
273 help_heading = "Read options"
274 )]
275 pub cursor: Option<String>,
276 #[arg(long, requires = "for_edit", help_heading = "Read options")]
278 pub all: bool,
279}
280
281impl ReadArgs {
282 pub fn paragraph_spec(&self) -> Option<String> {
287 (!self.paragraphs.is_empty()).then(|| self.paragraphs.join(","))
288 }
289
290 pub fn for_edit_request(&self) -> crate::edit::for_edit::ForEditRequest {
296 crate::edit::for_edit::ForEditRequest {
297 select: self.paragraph_spec(),
298 head: self.head,
299 tail: self.tail,
300 find: self.find.clone(),
301 regex: self.regex.clone(),
302 ignore_case: self.ignore_case,
303 changed: self.changed,
304 by: self.by.clone(),
305 context: self.context.unwrap_or(0),
306 limit: self.limit,
307 max_chars: self.max_chars,
308 all: self.all,
309 cursor: self.cursor.clone(),
310 accept: self.accept_change.clone(),
311 reject: self.reject_change.clone(),
312 existing_revisions: self
313 .existing_revisions
314 .and_then(ExistingArg::plan_value)
315 .unwrap_or(crate::edit::ExistingRevisions::Keep),
316 track: self.track.unwrap_or_default() == TrackArg::On,
317 ..Default::default()
318 }
319 }
320}
321
322#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
324#[serde(rename_all = "kebab-case")]
325pub enum CommentsArg {
326 #[default]
328 Inline,
329 None,
331}
332
333#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
335#[serde(rename_all = "kebab-case")]
336pub enum TrackArg {
337 #[default]
339 On,
340 Off,
342}
343
344impl TrackArg {
345 pub fn from_choice(choice: &str) -> Option<Self> {
347 match choice {
348 "on" => Some(Self::On),
349 "off" => Some(Self::Off),
350 _ => None,
351 }
352 }
353}
354
355#[derive(clap::Args, Debug, Serialize)]
357pub struct EditOptions {
358 #[arg(short = 'a', long, value_name = "NAME", default_value = "Jubarte")]
362 pub author: String,
363 #[arg(skip)]
367 #[serde(skip)]
368 pub author_given: bool,
369 #[arg(short = 'd', long = "datetime", value_name = "ISO8601", value_parser = parse_datetime)]
372 pub datetime: Option<String>,
373 #[arg(long, conflicts_with = "editing_mode")]
376 pub suggesting_mode: bool,
377 #[arg(long)]
380 pub editing_mode: bool,
381 #[arg(long, value_enum, value_name = "MODE", default_value_t = ExistingArg::Auto)]
385 pub existing_revisions: ExistingArg,
386 #[arg(long, conflicts_with_all = ["output", "out_dir"])]
389 pub in_place: bool,
390 #[arg(
394 short = 'o',
395 long,
396 value_name = "FILE.docx",
397 conflicts_with = "out_dir"
398 )]
399 pub output: Option<PathBuf>,
400 #[arg(long, value_name = "DIR", num_args = 0..=1)]
404 pub out_dir: Option<Option<PathBuf>>,
405 #[arg(long)]
407 pub force: bool,
408}
409
410#[derive(Clone, Debug, PartialEq, Eq)]
412pub enum EditTarget {
413 Single(PathBuf),
415 Bundle(PathBuf),
417}
418
419impl EditOptions {
420 pub fn target(&self, file: &Path) -> EditTarget {
425 if self.in_place {
426 return EditTarget::Single(file.to_path_buf());
427 }
428 let beside = |name: String| match file.parent().filter(|p| !p.as_os_str().is_empty()) {
429 Some(dir) => dir.join(name),
430 None => PathBuf::from(name),
431 };
432 let stem = file.file_stem().map_or_else(
433 || "document".to_string(),
434 |s| s.to_string_lossy().into_owned(),
435 );
436 match (&self.out_dir, &self.output) {
437 (Some(Some(dir)), _) => EditTarget::Bundle(dir.clone()),
438 (Some(None), _) => EditTarget::Bundle(beside(format!("{stem}.edit"))),
439 (None, Some(output)) => EditTarget::Single(output.clone()),
440 (None, None) if stem.ends_with("_modified") => {
441 EditTarget::Single(beside(format!("{stem}.docx")))
442 }
443 (None, None) => EditTarget::Single(beside(format!("{stem}_modified.docx"))),
444 }
445 }
446}
447
448#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
450#[serde(rename_all = "kebab-case")]
451pub enum ExistingArg {
452 #[default]
454 Auto,
455 Keep,
457 Accept,
459 Reject,
461 Refuse,
463}
464
465impl ExistingArg {
466 pub fn from_choice(choice: &str) -> Option<Self> {
469 match choice {
470 "auto" => Some(Self::Auto),
471 "keep" => Some(Self::Keep),
472 "accept" => Some(Self::Accept),
473 "reject" => Some(Self::Reject),
474 "refuse" => Some(Self::Refuse),
475 _ => None,
476 }
477 }
478
479 pub fn plan_value(self) -> Option<crate::edit::ExistingRevisions> {
481 use crate::edit::ExistingRevisions as E;
482 match self {
483 Self::Auto => None,
484 Self::Keep => Some(E::Keep),
485 Self::Accept => Some(E::Accept),
486 Self::Reject => Some(E::Reject),
487 Self::Refuse => Some(E::Refuse),
488 }
489 }
490}
491
492pub fn flag_operations(matches: &clap::ArgMatches) -> Result<Vec<FlagOp>, String> {
495 if matches.contains_id("anchor") && !matches.contains_id("location") {
496 return Err("--anchor needs -p WHERE (find it with: jubarte read FILE --find TEXT)".into());
497 }
498 let mut tokens: Vec<(usize, &str, Option<String>)> = Vec::new();
499 for name in ["location", "anchor", "content", "reply", "style"] {
500 if let (Some(indices), Some(values)) =
501 (matches.indices_of(name), matches.get_many::<String>(name))
502 {
503 tokens.extend(indices.zip(values).map(|(i, v)| (i, name, Some(v.clone()))));
504 }
505 }
506 if let (Some(indices), Some(values)) = (
507 matches.indices_of("occurrence"),
508 matches.get_many::<usize>("occurrence"),
509 ) {
510 tokens.extend(
511 indices
512 .zip(values)
513 .map(|(i, v)| (i, "occurrence", Some(v.to_string()))),
514 );
515 }
516 for name in [
517 "delete", "resolve", "before", "comment", "accept", "reject", "strike", "restore",
518 "visible",
519 ] {
520 if matches.try_get_many::<bool>(name).ok().flatten().is_none() {
524 continue;
525 }
526 if let Some(indices) = matches.indices_of(name) {
527 tokens.extend(indices.map(|i| (i, name, None)));
528 }
529 }
530 tokens.sort_by_key(|t| t.0);
531 let mut ops: Vec<FlagOp> = Vec::new();
532 for (_, name, value) in tokens {
533 if name == "location" {
534 ops.push(FlagOp {
535 at: value.unwrap_or_default(),
536 ..FlagOp::default()
537 });
538 continue;
539 }
540 let Some(op) = ops.last_mut() else {
541 return Err(format!("--{name} comes before the first -p/--location"));
542 };
543 let twice = |what: &str| Err(format!("-p {}: --{what} given twice", op.at));
544 match name {
545 "anchor" if op.anchor.is_some() => return twice("anchor"),
546 "anchor" => op.anchor = value,
547 "occurrence" if op.occurrence.is_some() => return twice("occurrence"),
548 "occurrence" if op.anchor.is_none() => {
549 return Err(format!(
550 "-p {}: --occurrence must come after --anchor",
551 op.at
552 ));
553 }
554 "occurrence" => {
555 op.occurrence = value.and_then(|v| v.parse().ok());
556 }
557 "content" if op.content.is_some() => return twice("content"),
558 "content" => op.content = value,
559 "reply" if op.reply.is_some() => return twice("reply"),
560 "reply" => op.reply = value,
561 "style" => op.styles.push(value.unwrap_or_default()),
562 "delete" => op.delete = true,
563 "resolve" => op.resolve = true,
564 "before" => op.before = true,
565 "comment" => op.comment = true,
566 "accept" => op.accept = true,
567 "reject" => op.reject = true,
568 "strike" => op.strike = true,
569 "restore" => op.restore = true,
570 "visible" => op.visible = true,
571 _ => {}
572 }
573 }
574 Ok(ops)
575}
576
577fn plan_path() -> impl clap::builder::TypedValueParser<Value = PathBuf> {
583 use clap::builder::TypedValueParser as _;
584 clap::builder::OsStringValueParser::new().try_map(|value| {
585 let text = value.to_string_lossy();
586 if text.ends_with('/') || cfg!(windows) && text.ends_with('\\') {
587 return Err(format!(
588 "{text} ends in a separator, so it names a folder; give the plan's file, such as PLAN.json"
589 ));
590 }
591 Ok(PathBuf::from(value))
592 })
593}
594
595fn hoist_quiet<T: AsRef<std::ffi::OsStr> + Clone>(
600 command: &clap::Command,
601 arguments: &[T],
602) -> Vec<T> {
603 let is_quiet = |a: &T| match a.as_ref().to_str() {
604 Some("--quiet") => true,
605 Some(short) => {
606 short.len() > 1 && short.starts_with('-') && short[1..].bytes().all(|b| b == b'q')
607 }
608 None => false,
609 };
610 let flags = arguments.iter().skip(1).take_while(|a| is_quiet(a)).count();
611 let task = arguments.get(1 + flags).and_then(|a| a.as_ref().to_str());
612 if flags > 0 && task == Some("help") {
613 let mut help = vec![arguments[0].clone()];
615 help.extend_from_slice(&arguments[1 + flags..]);
616 return help;
617 }
618 if flags == 0 || task.is_none_or(|name| command.find_subcommand(name).is_none()) {
619 return arguments.to_vec();
620 }
621 let mut hoisted = Vec::with_capacity(arguments.len());
622 hoisted.push(arguments[0].clone());
623 hoisted.push(arguments[1 + flags].clone());
624 hoisted.extend_from_slice(&arguments[1..1 + flags]);
625 hoisted.extend_from_slice(&arguments[2 + flags..]);
626 hoisted
627}
628
629fn fill_date(date: &mut Option<String>) {
632 if date.is_none() {
633 *date = Some(crate::util::datetime::utc_now_iso8601());
634 }
635}
636
637fn fill_task_date(task: &mut Command) {
639 match task {
640 Command::Compare(compare) => fill_date(&mut compare.datetime),
641 Command::Diff { datetime: date, .. } => fill_date(date),
642 _ => {}
643 }
644}
645
646pub fn slash_path(path: &Path) -> String {
659 let path = unverbatimed(path).unwrap_or_else(|| path.to_path_buf());
660 path.to_string_lossy().replace('\\', "/")
661}
662
663fn unverbatimed(path: &Path) -> Option<PathBuf> {
671 let mut components = path.components();
672 let (mut stripped, keeps_root) = verbatim_head(components.next())?;
673 for component in components {
674 if keeps_root || !matches!(component, std::path::Component::RootDir) {
679 stripped.push(component.as_os_str());
680 }
681 }
682 Some(stripped)
683}
684
685#[cfg(windows)]
690fn verbatim_head(component: Option<std::path::Component>) -> Option<(PathBuf, bool)> {
691 use std::path::{Component, Prefix};
692 match component {
693 Some(Component::Prefix(prefix)) => match prefix.kind() {
694 Prefix::VerbatimDisk(letter) => Some((
695 PathBuf::from(format!("{}:", (letter as char).to_ascii_uppercase())),
696 true,
697 )),
698 Prefix::VerbatimUNC(server, share) => {
699 let mut head = PathBuf::from(r"\\");
700 head.push(server);
701 head.push(share);
702 Some((head, true))
703 }
704 Prefix::Verbatim(rest) => Some((PathBuf::from(rest), false)),
705 _ => None,
706 },
707 _ => None,
708 }
709}
710
711#[cfg(not(windows))]
713fn verbatim_head(_component: Option<std::path::Component>) -> Option<(PathBuf, bool)> {
714 None
715}
716
717fn resolve_plan(task: &mut Command) {
719 let (Command::Edit {
720 file,
721 plan: Some(plan),
722 plan_default,
723 ..
724 }
725 | Command::Add {
726 file,
727 plan: Some(plan),
728 plan_default,
729 ..
730 }) = task
731 else {
732 return;
733 };
734 if !plan.as_os_str().is_empty() {
735 return;
736 }
737 let stem = file.file_stem().map_or_else(
738 || "document".to_string(),
739 |s| s.to_string_lossy().into_owned(),
740 );
741 let name = format!("{stem}_plan.json");
742 *plan = match file.parent().filter(|p| !p.as_os_str().is_empty()) {
743 Some(dir) => dir.join(name),
744 None => PathBuf::from(name),
745 };
746 *plan_default = true;
747}
748
749fn names_word_document(path: &Path) -> bool {
752 path.file_name().is_some_and(|name| {
754 let name = name.to_string_lossy().to_ascii_lowercase();
755 [".docx", ".docm", ".dotx", ".dotm", ".doc"]
756 .iter()
757 .any(|ext| name.ends_with(ext))
758 })
759}
760
761fn swallowed_file(flag: &str, value: &Path) -> String {
764 let instead = if flag == "--plan" { "PLAN.json" } else { "DIR" };
765 format!(
766 "{flag} {} names a Word document; put FILE before {flag}, or write {flag}={instead}",
767 value.display()
768 )
769}
770
771fn usage_error(command: &clap::Command, tokens: &[String], mut error: clap::Error) -> clap::Error {
776 if error.kind() == clap::error::ErrorKind::ArgumentConflict {
777 use clap::error::ContextKind;
778 let conflicts = [ContextKind::InvalidArg, ContextKind::PriorArg]
781 .into_iter()
782 .filter_map(|kind| error.get(kind))
783 .map(ToString::to_string)
784 .collect::<Vec<_>>()
785 .join(" ");
786 let names = |flag: &&str| conflicts.split_whitespace().any(|word| word == *flag);
787 if names(&"--track-changes") && names(&"--for-edit") {
790 return read_usage_error(command, read_view_conflict("--track-changes"));
791 }
792 if names(&"--tables") {
793 error.insert(
794 ContextKind::Usage,
795 clap::error::ContextValue::StyledStr(
796 format!("Usage: {} read [OPTIONS] <FILE>", command.get_name()).into(),
797 ),
798 );
799 }
800 }
801 if error.kind() != clap::error::ErrorKind::MissingRequiredArgument {
802 return error;
803 }
804 let Some(at) = tokens.iter().skip(1).position(|t| !t.starts_with('-')) else {
805 return error;
806 };
807 let name = tokens[at + 1].as_str();
808 let Some(sub) = command
809 .find_subcommand(name)
810 .filter(|_| matches!(name, "edit" | "add"))
811 else {
812 return error;
813 };
814 let options = tokens[at + 2..].iter().take_while(|t| *t != "--");
816 let mut previous: Option<&str> = None;
817 let mut found = None;
818 for token in options {
819 let pair = match token.split_once('=') {
820 Some((flag, value)) if flag.starts_with("--") => Some((flag, value)),
821 _ => previous.map(|flag| (flag, token.as_str())),
822 };
823 if let Some((flag, value)) = pair
824 && matches!(flag, "--plan" | "--out-dir")
825 && !value.starts_with('-')
826 && names_word_document(Path::new(value))
827 {
828 found = Some(swallowed_file(flag, Path::new(value)));
829 break;
830 }
831 previous = Some(token.as_str()).filter(|t| matches!(*t, "--plan" | "--out-dir"));
832 }
833 let Some(message) = found else {
834 return error;
835 };
836 let mut task = sub.clone();
837 task.set_bin_name(format!("{} {name}", command.get_name()));
838 task.error(clap::error::ErrorKind::ArgumentConflict, message)
839}
840
841fn fill_flag_operations(
844 task: &mut Command,
845 matches: &clap::ArgMatches,
846 model: &mut clap::Command,
847) -> Result<(), clap::Error> {
848 let (name, operations, options) = match task {
849 Command::Edit {
850 operations,
851 options,
852 ..
853 } => ("edit", operations, options),
854 Command::Add {
855 operations,
856 options,
857 ..
858 } => ("add", operations, options),
859 _ => return Ok(()),
860 };
861 let Some(sub) = matches.subcommand_matches(name) else {
862 return Ok(());
863 };
864 *operations = flag_operations(sub)
865 .map_err(|m| model.error(clap::error::ErrorKind::ArgumentConflict, m))?;
866 options.author_given =
867 sub.value_source("author") == Some(clap::parser::ValueSource::CommandLine);
868 env_author_fill(&mut options.author, &mut options.author_given)
869 .map_err(|m| model.error(clap::error::ErrorKind::ValueValidation, m))?;
870 Ok(())
871}
872
873fn env_author_fill(author: &mut String, given: &mut bool) -> Result<(), String> {
876 if *given {
877 return Ok(());
878 }
879 let Some(name) = std::env::var("JUBARTE_AUTHOR")
880 .ok()
881 .filter(|name| !name.is_empty())
882 else {
883 return Ok(());
884 };
885 *author = parse_author(&name).map_err(|m| format!("JUBARTE_AUTHOR: {m}"))?;
886 *given = true;
887 Ok(())
888}
889
890pub fn env_timeout() -> Result<Option<std::time::Duration>, String> {
899 let Some(value) = std::env::var_os("JUBARTE_TIMEOUT") else {
902 return Ok(None);
903 };
904 let value = value.into_string().map_err(|raw| {
905 format!(
906 "JUBARTE_TIMEOUT: '{}' is not a number of seconds",
907 raw.to_string_lossy()
908 )
909 })?;
910 if value.is_empty() {
911 return Ok(None);
912 }
913 parse_timeout(&value)
914 .map(Some)
915 .map_err(|m| format!("JUBARTE_TIMEOUT: {m}"))
916}
917
918#[derive(clap::Args, Debug, Serialize)]
920#[group(id = "compare_options", multiple = true)]
921pub struct CompareArgs {
922 #[arg(value_name = "ORIGINAL", required_unless_present = "original")]
924 pub original_pos: Option<PathBuf>,
925
926 #[arg(value_name = "MODIFIED")]
928 pub modified_pos: Option<PathBuf>,
929
930 #[arg(short = 'b', long = "original", value_name = "FILE")]
932 pub original: Option<PathBuf>,
933
934 #[arg(short = 'm', long = "modified", value_name = "FILE")]
936 pub modified: Option<PathBuf>,
937
938 #[arg(short = 'o', long, value_name = "FILE")]
943 pub output: Option<PathBuf>,
944
945 #[arg(short = 'a', long, value_name = "NAME", default_value = "Jubarte")]
947 pub author: String,
948
949 #[arg(short = 'd', long = "datetime", value_name = "ISO8601", value_parser = parse_datetime)]
953 pub datetime: Option<String>,
954
955 #[arg(long)]
957 pub force: bool,
958
959 #[arg(long, value_name = "RATIO", value_parser = parse_threshold)]
961 pub detail_threshold: Option<f64>,
962
963 #[arg(long, value_enum, value_name = "MODE", default_value_t = CompareMode::Word)]
965 pub mode: CompareMode,
966
967 #[arg(long, hide = true)]
969 pub powertools_faithful: bool,
970
971 #[arg(long, hide = true)]
977 pub no_paragraph_merge: bool,
978
979 #[arg(long, value_name = "FILE", help_heading = "Markdown inputs")]
982 pub reference_doc: Option<PathBuf>,
983
984 #[arg(long, help_heading = "Markdown inputs")]
987 pub critic: bool,
988
989 #[arg(long, value_name = "DIR", help_heading = "Markdown inputs")]
995 pub resource_path: Option<PathBuf>,
996
997 #[command(flatten)]
999 #[serde(flatten)]
1000 pub render: RenderArgs,
1001
1002 #[command(flatten)]
1005 #[serde(skip)]
1006 pub read: ReadArgs,
1007
1008 #[arg(skip)]
1012 pub view_given: bool,
1013}
1014
1015pub fn top_level_command() -> clap::Command {
1019 let hidden: std::collections::HashSet<clap::Id> =
1020 <CompareArgs as clap::Args>::augment_args(clap::Command::new("shorthand"))
1021 .get_arguments()
1022 .map(|a| a.get_id().clone())
1023 .collect();
1024 Cli::command().mut_args(move |a| {
1025 if hidden.contains(a.get_id()) {
1026 a.hide(true)
1027 } else {
1028 a
1029 }
1030 })
1031}
1032
1033impl std::ops::Deref for Cli {
1034 type Target = CompareArgs;
1035 fn deref(&self) -> &Self::Target {
1036 &self.compare
1037 }
1038}
1039
1040#[derive(clap::Subcommand, Debug, Serialize)]
1042#[serde(rename_all = "kebab-case", tag = "command", content = "args")]
1043pub enum Command {
1044 #[command(name = "__edit-v2", hide = true, bin_name = "jubarte edit")]
1046 #[serde(rename = "edit")]
1047 TypedEdit(edit_actions::TypedEdit),
1048 #[command(
1050 name = "__edit-template",
1051 hide = true,
1052 bin_name = "jubarte edit template"
1053 )]
1054 #[serde(rename = "edit")]
1055 EditTemplate(edit_template::TemplateDispatch),
1056 #[command(
1058 visible_alias = "redline",
1059 after_help = "Examples:\n jubarte compare old.docx new.docx the redline's agent view\n jubarte compare old.docx new.docx -o redline.docx\n jubarte compare old.docx new.docx -o redline.pdf --changed-pages\n jubarte compare old.md new.md -o changes.md CriticMarkup\n jubarte compare -b old.docx -m new.docx --author Legal -o r.docx"
1060 )]
1061 Compare(CompareArgs),
1062 Changes {
1068 #[arg(value_name = "FILE")]
1070 file: PathBuf,
1071 #[arg(long)]
1074 json: bool,
1075 #[arg(long, value_name = "NAME", action = clap::ArgAction::Append)]
1077 author: Vec<String>,
1078 },
1079 Accept {
1085 #[arg(value_name = "FILE")]
1087 file: PathBuf,
1088 #[arg(long)]
1091 in_place: bool,
1092 #[arg(
1096 short = 'o',
1097 long,
1098 value_name = "FILE",
1099 required_unless_present = "in_place",
1100 conflicts_with = "in_place"
1101 )]
1102 output: Option<PathBuf>,
1103 #[arg(long)]
1105 force: bool,
1106 #[arg(long)]
1108 keep_nested_comment: bool,
1109 #[command(flatten)]
1111 #[serde(flatten)]
1112 selection: Selection,
1113 #[command(flatten)]
1115 #[serde(flatten)]
1116 render: RenderArgs,
1117 },
1118 Reject {
1124 #[arg(value_name = "FILE")]
1126 file: PathBuf,
1127 #[arg(long)]
1130 in_place: bool,
1131 #[arg(
1135 short = 'o',
1136 long,
1137 value_name = "FILE",
1138 required_unless_present = "in_place",
1139 conflicts_with = "in_place"
1140 )]
1141 output: Option<PathBuf>,
1142 #[arg(long)]
1144 force: bool,
1145 #[arg(long)]
1147 keep_nested_comment: bool,
1148 #[command(flatten)]
1150 #[serde(flatten)]
1151 selection: Selection,
1152 #[command(flatten)]
1154 #[serde(flatten)]
1155 render: RenderArgs,
1156 },
1157 #[command(after_help = "Examples:\n \
1159 jubarte convert contract.docx PDF, Word-style layout\n \
1160 jubarte convert draft.md draft.docx, CriticMarkup as tracked changes\n \
1161 jubarte convert draft.md -o draft.pdf the changes painted in a PDF\n \
1162 jubarte convert draft.md --reference-doc house.docx -o draft.docx\n \
1163 jubarte convert draft.md -t md --track-changes accept the text with every change accepted\n \
1164 jubarte convert contract.docx -t md Markdown with <!-- page N of M --> lines\n \
1165 jubarte convert old.doc old.docx (text, headings, lists, tables)\n \
1166 jubarte convert notes.md --no-critic {++ and the other delimiters as text")]
1167 Convert {
1168 #[arg(value_name = "FILE")]
1171 file: PathBuf,
1172 #[arg(short = 'o', long, value_name = "FILE")]
1178 output: Option<PathBuf>,
1179 #[arg(long)]
1181 force: bool,
1182 #[arg(long, hide = true)]
1184 pdf: bool,
1185 #[arg(long, hide = true)]
1187 png: bool,
1188 #[arg(long, value_name = "FILE")]
1190 report: Option<PathBuf>,
1191 #[arg(long)]
1195 compress: bool,
1196 #[arg(long, value_name = "FILE")]
1200 font_report: Option<PathBuf>,
1201 #[command(flatten)]
1203 #[serde(flatten)]
1204 markdown: MarkdownArgs,
1205 #[command(flatten)]
1207 #[serde(flatten)]
1208 render: RenderArgs,
1209 #[arg(long)]
1213 fail_on_substitution: bool,
1214 #[arg(long)]
1221 update_fields: bool,
1222 #[arg(long, value_name = "SECONDS", value_parser = parse_timeout)]
1226 #[serde(serialize_with = "serialize_timeout")]
1227 timeout: Option<std::time::Duration>,
1228 },
1229 #[command(after_help = "Examples:\n \
1231 jubarte diff old.docx new.docx --format github Git/GitHub patch on stdout\n \
1232 jubarte diff old.md new.md the patch on stdout\n \
1233 jubarte diff old.md new.md --format critic CriticMarkup on stdout, as pandiff\n \
1234 jubarte diff old.docx new.docx -o changes.patch the patch in a file\n \
1235 jubarte compare old.md new.md -o changes.docx Word tracked changes (compare writes redlines)\n \
1236 jubarte compare contract.docx edited.md -o redline.pdf\n \
1237 the Markdown's edits painted on the Word document\n\n\
1238 GIT:\n \
1239 git config --global difftool.jubarte.cmd 'jubarte diff \"$LOCAL\" \"$REMOTE\"'\n \
1240 git difftool -t jubarte -y -- '*.md'")]
1241 Diff {
1242 #[arg(value_name = "OLD")]
1244 old: PathBuf,
1245 #[arg(value_name = "NEW")]
1247 new: PathBuf,
1248 #[arg(short = 'o', long, value_name = "FILE", help_heading = "Review")]
1251 output: Option<PathBuf>,
1252 #[arg(long, value_enum, value_name = "FORMAT", default_value_t = PatchFormat::Patch, help_heading = "Review")]
1254 format: PatchFormat,
1255 #[arg(long, value_name = "N", default_value_t = crate::markdown::DEFAULT_COLUMNS, help_heading = "Paragraph patch")]
1257 columns: usize,
1258 #[arg(short = 'U', long, value_name = "LINES", default_value_t = 3, value_parser = parse_context, help_heading = "Review")]
1260 context: usize,
1261 #[arg(long, help_heading = "Review")]
1263 accept_changes: bool,
1264 #[arg(long, help_heading = "Review")]
1266 full_lines: bool,
1267 #[arg(
1271 short = 't',
1272 long = "to",
1273 value_enum,
1274 value_name = "FORMAT",
1275 hide_possible_values = true,
1276 help_heading = "Formats"
1277 )]
1278 to: Option<Format>,
1279 #[arg(
1281 short = 'f',
1282 long = "from",
1283 value_parser = input_format_parser(),
1284 value_name = "FORMAT",
1285 help_heading = "Formats"
1286 )]
1287 from: Option<Format>,
1288 #[arg(long, help_heading = "Review")]
1290 force: bool,
1291 #[arg(
1293 short = 'a',
1294 long,
1295 value_name = "NAME",
1296 default_value = "Jubarte",
1297 help_heading = "Paragraph patch"
1298 )]
1299 author: String,
1300 #[arg(
1303 short = 'd',
1304 long = "datetime",
1305 value_name = "ISO8601",
1306 value_parser = parse_datetime,
1307 help_heading = "Paragraph patch"
1308 )]
1309 datetime: Option<String>,
1310 },
1311 #[command(aliases = ["text", "inspect"])]
1318 Read {
1319 #[arg(value_name = "FILE")]
1321 file: PathBuf,
1322 #[arg(short = 'o', long, value_name = "FILE")]
1325 output: Option<PathBuf>,
1326 #[arg(long)]
1328 force: bool,
1329 #[command(flatten)]
1331 #[serde(flatten)]
1332 args: ReadArgs,
1333 },
1334 #[command(after_help = "Examples:\n \
1340 jubarte edit a.docx -p p12 --anchor \"thirty days\" --content \"forty-five days\" -a NAME\n \
1341 jubarte edit a.docx -p p12 --anchor thirty --content \"thirty (30)\" -a NAME an insertion\n \
1342 jubarte edit a.docx -p p7 --anchor \"at its sole discretion\" --delete -p p9 --delete -a NAME\n \
1343 jubarte edit a.docx -p p3 --content \"The parties agree as follows.\" -a NAME rewrite\n \
1344 jubarte edit a.docx -p p4 --anchor Fees --style bold -p p5 --style Heading2 -a NAME\n \
1345 jubarte edit a.docx -p c5 --content \"Agreed.\" -p c7 --resolve -a NAME\n \
1346 jubarte edit a.docx -p c5 --reply \"Agreed, will fix.\" -a NAME\n \
1347 jubarte edit a.docx -p c5.text --content \"net 30\" -a NAME the text c5 covers\n \
1348 jubarte edit a.docx -p r3 --accept -p header1.r1 --reject\n \
1349 jubarte edit a.docx -p p3 --delete -o b.docx --pdf -a NAME b.docx and b.pdf\n \
1350 jubarte edit a.docx --plan plan.json --out-dir review the bundle in review/\n \
1351 jubarte edit a.docx --plan plan.json -p p3 --content \"New.\" record into plan.json\n \
1352 jubarte edit a.docx --plan plan.json --consume apply plan.json, then delete it\n\n\
1353 WHERE is an id from `jubarte read`: p12, header1, footer2.p1,\n\
1354 t0.row1.cell2, c5 (a comment), c5.text (the text it covers) or r12\n\
1355 (a revision).\n\n\
1356 A plan (--plan plan.json) is a list of operations, applied all or none;\n\
1357 `jubarte capabilities --json` lists every operation kind:\n \
1358 {\"schema_version\": 1, \"source_sha256\": \"<sha256 from jubarte read>\", \"author\": \"Claude\",\n \
1359 \"operations\": [\n \
1360 {\"kind\": \"replace\", \"paragraph\": \"p1\", \"find\": \"his or her\", \"replacement\": \"their\"},\n \
1361 {\"kind\": \"delete_paragraph\", \"paragraph\": \"p2\"}]}\n\n\
1362 Desired-text plans (PlanV2), a separate workflow:\n \
1363 jubarte edit template FILE --select p12,p20-p25 -o edits.json the paragraphs as they read\n \
1364 (edit the desired text in edits.json)\n \
1365 jubarte edit apply FILE --plan edits.json -o OUTPUT.docx tracked changes for the difference\n\n\
1366 Typed actions: jubarte edit replace|rewrite|insert|delete FILE [OPTIONS]\n Inline --save-plan FILE saves without applying; writes require -o or --out-dir.\n Run jubarte edit ACTION --help for its grammar.\nRouting: valid legacy calls, including `edit replace -p p0 --content TEXT`,\n retain v1 semantics. Use ./replace (or ./rewrite, ./insert, ./delete, ./apply)\n to explicitly name a legacy input whose name equals an action.")]
1367 Edit {
1368 #[arg(value_name = "FILE")]
1370 file: PathBuf,
1371 #[arg(long, value_name = "PLAN.json", num_args = 0..=1, default_missing_value = "", value_parser = plan_path(), required_unless_present_any = ["location", "anchor"])]
1377 plan: Option<PathBuf>,
1378 #[arg(skip)]
1380 plan_default: bool,
1381 #[arg(long, requires = "plan")]
1385 consume: bool,
1386 #[arg(short = 'p', long = "location", value_name = "WHERE", action = clap::ArgAction::Append)]
1391 location: Vec<String>,
1392 #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1395 anchor: Vec<String>,
1396 #[arg(long, value_name = "N", action = clap::ArgAction::Append, value_parser = edit_actions::positive)]
1398 occurrence: Vec<usize>,
1399 #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1402 content: Vec<String>,
1403 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1405 delete: Vec<bool>,
1406 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1408 resolve: Vec<bool>,
1409 #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1411 reply: Vec<String>,
1412 #[arg(long, hide = true)]
1416 rewrite_others_comments: bool,
1417 #[arg(long)]
1423 keep_others: bool,
1424 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1427 accept: Vec<bool>,
1428 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1431 reject: Vec<bool>,
1432 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1437 strike: Vec<bool>,
1438 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1443 restore: Vec<bool>,
1444 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1447 visible: Vec<bool>,
1448 #[arg(long, value_name = "SPEC", action = clap::ArgAction::Append)]
1452 style: Vec<String>,
1453 #[command(flatten)]
1455 #[serde(flatten)]
1456 options: EditOptions,
1457 #[arg(long)]
1460 dry_run: bool,
1461 #[arg(long)]
1466 skip_failed: bool,
1467 #[arg(long)]
1471 require_change: bool,
1472 #[arg(long)]
1475 pdf: bool,
1476 #[arg(long)]
1479 png: bool,
1480 #[arg(long, default_value_t = 96.0, value_name = "DPI", value_parser = parse_dpi, help_heading = "Rendering")]
1482 dpi: f32,
1483 #[arg(long, value_enum, default_value_t = Revisions::Conventional, requires_if("custom", "revision_palette"), help_heading = "Revision marks")]
1485 revisions: Revisions,
1486 #[cfg_attr(feature = "render", arg(long, value_name = "SPEC", value_parser = parse_palette, requires = "revisions", help_heading = "Revision marks"))]
1488 #[cfg_attr(
1489 not(feature = "render"),
1490 arg(
1491 long,
1492 value_name = "SPEC",
1493 requires = "revisions",
1494 help_heading = "Revision marks"
1495 )
1496 )]
1497 revision_palette: Option<String>,
1498 #[arg(skip)]
1501 operations: Vec<FlagOp>,
1502 },
1503 #[command(after_help = "Examples:\n \
1508 jubarte add a.docx -p p12 --content \"Time is of the essence.\" -a NAME new paragraph after p12\n \
1509 jubarte add a.docx -p p12 --content Recitals --before --style Heading2 -a NAME\n \
1510 jubarte add a.docx -p p5 --anchor \"monthly fee\" --content \"Net of taxes?\" -a NAME a comment\n \
1511 jubarte add a.docx -p p5 --comment --content \"Whole clause needs a cap.\" -a NAME\n \
1512 jubarte add a.docx -p c5 --content \"Agreed, will fix.\" -a NAME a reply\n \
1513 jubarte add a.docx -p c5 --reply \"Agreed, will fix.\" -a NAME the same reply\n \
1514 jubarte add a.docx --plan plan.json -p p5 --comment --content \"Cap?\" record into plan.json")]
1515 Add {
1516 #[arg(value_name = "FILE")]
1518 file: PathBuf,
1519 #[arg(long, value_name = "PLAN.json", num_args = 0..=1, default_missing_value = "", value_parser = plan_path())]
1524 plan: Option<PathBuf>,
1525 #[arg(skip)]
1527 plan_default: bool,
1528 #[arg(long, requires = "plan")]
1531 consume: bool,
1532 #[arg(short = 'p', long = "location", value_name = "WHERE", action = clap::ArgAction::Append, required_unless_present_any = ["plan", "anchor"])]
1535 location: Vec<String>,
1536 #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1539 anchor: Vec<String>,
1540 #[arg(long, value_name = "N", action = clap::ArgAction::Append, value_parser = edit_actions::positive)]
1542 occurrence: Vec<usize>,
1543 #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1545 content: Vec<String>,
1546 #[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
1548 reply: Vec<String>,
1549 #[arg(long)]
1556 keep_others: bool,
1557 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1559 before: Vec<bool>,
1560 #[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
1563 comment: Vec<bool>,
1564 #[arg(long, value_name = "SPEC", action = clap::ArgAction::Append)]
1567 style: Vec<String>,
1568 #[command(flatten)]
1570 #[serde(flatten)]
1571 options: EditOptions,
1572 #[arg(skip)]
1575 operations: Vec<FlagOp>,
1576 },
1577 Capabilities {
1579 #[arg(long)]
1581 json: bool,
1582 #[arg(long)]
1584 operation: Option<String>,
1585 #[arg(long)]
1587 field: Option<String>,
1588 #[arg(long, conflicts_with_all = ["operation", "field"])]
1590 matrix: bool,
1591 },
1592 #[command(after_help = "Examples:\n \
1594 jubarte self-update --check installed and latest versions\n \
1595 jubarte self-update ask, then install the latest release\n \
1596 jubarte self-update --yes install without asking\n \
1597 jubarte self-update --version 0.9.3 install that release (also older)")]
1598 #[command(display_order = 1000)]
1599 SelfUpdate {
1600 #[arg(long)]
1602 check: bool,
1603 #[arg(long, short = 'y')]
1605 yes: bool,
1606 #[arg(long, value_name = "VERSION")]
1608 version: Option<String>,
1609 },
1610 #[command(after_help = "Examples:\n \
1612 jubarte debug out.docx orphans, fields, bookmarks, package, structure\n \
1613 jubarte debug out.docx --list the package's entries\n \
1614 jubarte debug old.docx new.docx --list entries that differ\n \
1615 jubarte debug old.docx new.docx -c elements -p document.xml\n \
1616 jubarte debug out.docx -c ids revision/docPr ids used twice\n \
1617 jubarte debug out.docx -c textbox -g FILENAME\n \
1618 jubarte debug out.docx -c text paragraphs with ins/del marks\n \
1619 jubarte debug a.docx b.docx -c text paragraphs that differ, per part\n \
1620 jubarte debug a.docx b.docx -c runs the same, with direct formatting\n \
1621 jubarte debug out.docx -c runs -g \"Q: Can\" one paragraph's runs, whole\n \
1622 jubarte debug out.docx -c changes what each pPrChange/tcPrChange/… records\n \
1623 jubarte debug a.docx b.docx -c styledefs style definitions that differ, paired by name\n \
1624 jubarte debug a.docx b.docx -c numbering list levels that differ, by numId\n \
1625 jubarte debug a.docx b.docx -c xml -p document.xml\n \
1626 jubarte debug diff a.docx ours.docx word.docx element by element, three-way")]
1627 #[command(
1628 hide = true,
1629 args_conflicts_with_subcommands = true,
1630 subcommand_negates_reqs = true
1631 )]
1632 Debug {
1633 #[command(subcommand)]
1635 sub: Option<DebugCommand>,
1636 #[arg(value_name = "FILE", num_args = 1..=2, required = true)]
1638 files: Vec<PathBuf>,
1639 #[arg(short = 'l', long)]
1642 list: bool,
1643 #[arg(short = 'c', long = "check", value_enum, value_delimiter = ',')]
1646 checks: Vec<DebugCheck>,
1647 #[arg(short = 'p', long, value_name = "NAME")]
1649 part: Option<String>,
1650 #[arg(short = 'g', long, value_name = "TEXT")]
1652 grep: Option<String>,
1653 #[arg(short = 'n', long, value_name = "N", default_value_t = 5)]
1655 limit: usize,
1656 #[arg(short = 'C', long, value_name = "N", default_value_t = 0)]
1658 context: usize,
1659 #[arg(long)]
1662 full_lines: bool,
1663 },
1664 #[command(
1666 name = "visual-diff",
1667 alias = "diff-render",
1668 after_help = "Examples:\n \
1669 jubarte visual-diff before.docx after.docx changed pages on stdout\n \
1670 jubarte visual-diff before.docx after.docx --out-dir diff PNGs of the changed pages and diff.json\n \
1671 jubarte visual-diff a.docx b.docx --json the diff.json document on stdout\n\n\
1672 With --out-dir, each page that differs is written as a-page-NN.png,\n\
1673 b-page-NN.png and diff-page-NN.png (b's page with the changed pixels\n\
1674 magenta and boxed); diff.json lists every page with its changed_ratio,\n\
1675 bbox and, for a page only one side has, only_in."
1676 )]
1677 VisualDiff {
1678 #[arg(value_name = "A")]
1680 a: PathBuf,
1681 #[arg(value_name = "B")]
1683 b: PathBuf,
1684 #[arg(long, default_value_t = 100.0, value_name = "DPI", value_parser = parse_dpi, help_heading = "Rendering")]
1686 dpi: f32,
1687 #[arg(long, value_name = "DIR")]
1690 out_dir: Option<PathBuf>,
1691 #[arg(long)]
1693 json: bool,
1694 #[arg(long)]
1696 no_overlay: bool,
1697 #[arg(long)]
1699 force: bool,
1700 },
1701 Comments {
1703 #[arg(value_name = "FILE")]
1705 file: PathBuf,
1706 #[arg(long)]
1709 json: bool,
1710 #[arg(long, value_name = "NAME")]
1712 author: Option<String>,
1713 #[arg(long)]
1715 latest: bool,
1716 },
1717 #[command(after_help = "Examples:\n \
1719 jubarte append a.docx b.docx -o ab.docx\n \
1720 jubarte append cover.docx body.docx annex.docx -o all.docx --section-break continuous\n \
1721 jubarte append letter.docx exhibit.docx -o out.docx --keep-sections\n \
1722 jubarte append review_a.docx review_b.docx -o both.docx --carry-comments")]
1723 Append {
1724 #[arg(value_name = "FILE", num_args = 2.., required = true)]
1726 files: Vec<PathBuf>,
1727 #[arg(short = 'o', long, value_name = "FILE")]
1731 output: PathBuf,
1732 #[arg(long, value_enum, default_value_t = SectionBreakArg::NextPage)]
1734 section_break: SectionBreakArg,
1735 #[arg(long)]
1738 keep_sections: bool,
1739 #[arg(long)]
1743 carry_comments: bool,
1744 #[arg(long)]
1746 force: bool,
1747 #[command(flatten)]
1749 #[serde(flatten)]
1750 render: RenderArgs,
1751 },
1752 #[command(alias = "audit")]
1759 #[command(after_help = "Examples:\n \
1760 jubarte validate contract.docx\n \
1761 jubarte validate contract.docx --json\n \
1762 jubarte validate contract.docx --repair fixed.docx\n \
1763 jubarte validate review/redline.docx --original contract.docx --author Claude\n \
1764 jubarte validate review/redline.docx --baseline contract.docx\n \
1765 jubarte validate contract.docx --rules word,a11y,style,structure --strict\n\n\
1766 Rule sets: word (default: Word validity), edits (with --author, and \
1767 --original or --baseline), a11y, style, structure.\n\
1768 Audit codes (code, set, severity):\n \
1769 HEADING_SKIP a11y warning, IMAGE_NO_DESCR a11y error,\n \
1770 TABLE_NO_HEADER_ROW a11y warning, MISSING_LANG a11y warning,\n \
1771 LITERAL_BULLET style warning, EMPTY_SPACER_PARAGRAPH style info,\n \
1772 DIRECT_FORMATTING_OVERRIDES_STYLE style info,\n \
1773 STALE_FIELD_CACHE structure warning, FONT_SUBSTITUTED structure info")]
1774 #[command(group(clap::ArgGroup::new("edits_against").args(["original", "baseline"]).multiple(true)))]
1775 Validate {
1776 #[arg(value_name = "FILE")]
1778 file: PathBuf,
1779 #[arg(long)]
1781 json: bool,
1782 #[arg(long, value_name = "RULES", value_delimiter = ',', value_parser = parse_rule)]
1785 rules: Vec<String>,
1786 #[arg(long)]
1789 strict: bool,
1790 #[arg(long, value_name = "FILE")]
1795 repair: Option<PathBuf>,
1796 #[arg(long, value_name = "FILE", conflicts_with = "repair")]
1802 baseline: Option<PathBuf>,
1803 #[arg(long, value_name = "FILE", requires = "author")]
1806 original: Option<PathBuf>,
1807 #[arg(long, value_name = "NAME", requires = "edits_against")]
1810 author: Option<String>,
1811 #[arg(long)]
1813 force: bool,
1814 },
1815 #[command(after_help = "Examples:\n \
1826 jubarte check revised.docx --expect expectations.json\n \
1827 jubarte check revised.docx --expect expectations.json --json\n\n\
1828 The expectations' source.sha256 must name FILE's own bytes: an\n\
1829 expectation file bound to the pre-edit source refuses as stale on\n\
1830 the edited output. Use the output-bound copy an `edit apply --expect`\n\
1831 receipt carries to re-check a published output.")]
1832 Check {
1833 #[arg(value_name = "FILE")]
1835 file: PathBuf,
1836 #[arg(long, value_name = "FILE")]
1838 expect: Option<PathBuf>,
1839 #[arg(long)]
1841 json: bool,
1842 },
1843 #[command(after_help = "Examples:\n \
1845 jubarte scrub redline.docx -o out.docx everything, alias Author\n \
1846 jubarte scrub redline.docx -o out.docx --author-alias Counsel --rsids\n \
1847 jubarte scrub redline.docx -o out.docx --comments comments only")]
1848 Scrub {
1849 #[arg(value_name = "FILE")]
1851 file: PathBuf,
1852 #[arg(short = 'o', long, value_name = "FILE")]
1856 output: PathBuf,
1857 #[arg(long)]
1859 force: bool,
1860 #[command(flatten)]
1862 #[serde(flatten)]
1863 scrub: ScrubSelection,
1864 #[command(flatten)]
1866 #[serde(flatten)]
1867 render: RenderArgs,
1868 },
1869}
1870
1871#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
1873pub struct ScrubSelection {
1874 #[arg(long, value_name = "NAME")]
1876 pub author_alias: Option<String>,
1877 #[arg(long)]
1879 pub rsids: bool,
1880 #[arg(long)]
1883 pub docprops: bool,
1884 #[arg(long)]
1886 pub comments: bool,
1887}
1888
1889#[derive(clap::Subcommand, Debug, Serialize)]
1890#[serde(rename_all = "kebab-case", tag = "command", content = "args")]
1891pub enum DebugCommand {
1893 #[command(after_help = "Examples:\n \
1902 jubarte debug diff a.docx b.docx\n \
1903 jubarte debug diff a.docx ours_rej.docx word_rej.docx -p styles\n \
1904 jubarte debug diff a.docx ours_rej.docx word_rej.docx --style \"Body Text\" --full\n \
1905 jubarte debug diff a.docx ours.docx --para-text \"Section 4\"")]
1906 Diff {
1907 #[arg(value_name = "FILE", num_args = 2.., required = true)]
1909 files: Vec<PathBuf>,
1910 #[arg(short = 'p', long, value_name = "NAME")]
1913 part: Option<String>,
1914 #[arg(long, value_name = "NAME")]
1916 style: Option<String>,
1917 #[arg(long = "para-text", value_name = "TEXT")]
1919 para_text: Option<String>,
1920 #[arg(long)]
1922 raw: bool,
1923 #[arg(long)]
1925 full: bool,
1926 #[arg(short = 'n', long, value_name = "N", default_value_t = 60)]
1928 limit: usize,
1929 },
1930}
1931
1932#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
1934#[serde(rename_all = "kebab-case")]
1935pub enum DebugCheck {
1936 Orphans,
1939 Fields,
1941 Bookmarks,
1944 Package,
1947 Structure,
1950 Ids,
1953 Styles,
1956 Chains,
1958 Elements,
1960 Textbox,
1962 Text,
1965 Xml,
1968 Runs,
1972 Changes,
1976 Tables,
1982 Styledefs,
1986 Numbering,
1990 Render,
1996}
1997
1998impl From<DebugCheck> for crate::debug::Check {
1999 fn from(c: DebugCheck) -> Self {
2000 use crate::debug::Check;
2001 match c {
2002 DebugCheck::Orphans => Check::Orphans,
2003 DebugCheck::Fields => Check::Fields,
2004 DebugCheck::Bookmarks => Check::Bookmarks,
2005 DebugCheck::Package => Check::Package,
2006 DebugCheck::Structure => Check::Structure,
2007 DebugCheck::Ids => Check::Ids,
2008 DebugCheck::Styles => Check::Styles,
2009 DebugCheck::Chains => Check::Chains,
2010 DebugCheck::Elements => Check::Elements,
2011 DebugCheck::Textbox => Check::Textbox,
2012 DebugCheck::Text => Check::Text,
2013 DebugCheck::Xml => Check::Xml,
2014 DebugCheck::Runs => Check::Runs,
2015 DebugCheck::Changes => Check::Changes,
2016 DebugCheck::Tables => Check::Tables,
2017 DebugCheck::Styledefs => Check::StyleDefs,
2018 DebugCheck::Numbering => Check::Numbering,
2019 #[cfg(feature = "render")]
2020 DebugCheck::Render => Check::Render,
2021 #[cfg(not(feature = "render"))]
2022 DebugCheck::Render => Check::Orphans,
2023 }
2024 }
2025}
2026
2027#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2029#[serde(rename_all = "kebab-case")]
2030pub enum PatchFormat {
2031 Patch,
2034 Critic,
2036 #[value(alias = "unified", alias = "text")]
2038 Github,
2039 Word,
2041 Normal,
2043 Context,
2045 SideBySide,
2047}
2048
2049impl PatchFormat {
2050 pub fn is_text_view(self) -> bool {
2052 !matches!(self, Self::Patch | Self::Critic)
2053 }
2054}
2055
2056#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2058#[serde(rename_all = "kebab-case")]
2059pub enum CompareMode {
2060 Word,
2063 Powertools,
2066}
2067
2068#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2070#[serde(rename_all = "kebab-case")]
2071pub enum Format {
2072 Docx,
2074 #[value(alias = "markdown")]
2077 Md,
2078 Pdf,
2080 Png,
2082 Json,
2085}
2086
2087fn extension(path: &Path) -> Option<String> {
2091 if let Some(extension) = path.extension() {
2092 return extension.to_str().map(str::to_string);
2093 }
2094 let name = path.file_name()?.to_str()?;
2095 name.strip_prefix('.')
2096 .filter(|rest| !rest.is_empty() && !rest.contains('.'))
2097 .map(str::to_string)
2098}
2099
2100impl Format {
2101 pub fn of_path(path: &Path) -> Option<Self> {
2104 Self::of_name(&extension(path)?)
2105 }
2106
2107 pub fn of_name(extension: &str) -> Option<Self> {
2109 match extension.to_ascii_lowercase().as_str() {
2110 "docx" | "docm" | "dotx" | "dotm" => Some(Self::Docx),
2111 "md" | "markdown" | "mdown" | "mkd" | "mkdn" | "txt" => Some(Self::Md),
2112 "pdf" => Some(Self::Pdf),
2113 "png" => Some(Self::Png),
2114 "json" => Some(Self::Json),
2115 _ => None,
2116 }
2117 }
2118
2119 pub fn name(self) -> &'static str {
2121 match self {
2122 Self::Docx => "docx",
2123 Self::Md => "md",
2124 Self::Pdf => "pdf",
2125 Self::Png => "png",
2126 Self::Json => "json",
2127 }
2128 }
2129
2130 pub fn of_input(asked: Option<Self>, path: &Path, bytes: &[u8]) -> Self {
2133 asked
2134 .or_else(|| Format::of_path(path).filter(|f| matches!(f, Self::Docx | Self::Md)))
2135 .unwrap_or(if bytes.starts_with(b"PK\x03\x04") {
2136 Self::Docx
2137 } else {
2138 Self::Md
2139 })
2140 }
2141}
2142
2143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2145pub enum Task {
2146 Compare,
2148 Convert,
2150 Read,
2152 Diff,
2154 Accept,
2156 Reject,
2158 Append,
2160 Scrub,
2162}
2163
2164impl Task {
2165 pub fn name(self) -> &'static str {
2167 match self {
2168 Self::Compare => "compare",
2169 Self::Convert => "convert",
2170 Self::Read => "read",
2171 Self::Diff => "diff",
2172 Self::Accept => "accept",
2173 Self::Reject => "reject",
2174 Self::Append => "append",
2175 Self::Scrub => "scrub",
2176 }
2177 }
2178
2179 pub fn of_name(name: &str) -> Option<Self> {
2181 Some(match name {
2182 "compare" | "redline" => Self::Compare,
2183 "convert" => Self::Convert,
2184 "read" | "text" | "inspect" => Self::Read,
2185 "diff" => Self::Diff,
2186 "accept" => Self::Accept,
2187 "reject" => Self::Reject,
2188 "append" => Self::Append,
2189 "scrub" => Self::Scrub,
2190 _ => return None,
2191 })
2192 }
2193
2194 fn allowed(self) -> Vec<Format> {
2196 crate::capabilities::OUTPUT_FORMATS
2197 .iter()
2198 .find(|(task, _)| *task == self.name())
2199 .map(|(_, names)| {
2200 names
2201 .iter()
2202 .map(|n| Format::of_name(n).expect("OUTPUT_FORMATS names a format"))
2203 .collect()
2204 })
2205 .unwrap_or_default()
2206 }
2207
2208 fn known(self, path: &Path) -> Option<Format> {
2211 let patch = extension(path)
2212 .is_some_and(|e| e.eq_ignore_ascii_case("patch") || e.eq_ignore_ascii_case("diff"));
2213 if self == Self::Diff && patch {
2214 return Some(Format::Md);
2215 }
2216 Format::of_path(path)
2217 }
2218
2219 fn cannot_write(self, format: Format, typed: Option<&str>) -> String {
2222 let ext = format.name();
2223 let named = |stem: &str| typed.map_or_else(|| format!("{stem}.{ext}"), str::to_string);
2224 match (self, format) {
2225 (Self::Diff, Format::Json) => "diff does not write .json yet".to_string(),
2226 (Self::Diff, _) => format!(
2227 "diff writes text (.md, .markdown, .txt, .patch, .diff); `compare OLD NEW -o {}` writes the redline as {ext}",
2228 named("c")
2229 ),
2230 (Self::Read, _) => {
2231 format!(
2232 "read writes .md or .json; `convert FILE -o {}` writes {ext}",
2233 named("v")
2234 )
2235 }
2236 _ => format!("{} does not write .{ext}", self.name()),
2237 }
2238 }
2239}
2240
2241pub fn output_format(
2247 task: Task,
2248 output: Option<&Path>,
2249 to: Option<Format>,
2250) -> Result<Option<Format>, String> {
2251 let said = output.and_then(|path| task.known(path));
2252 let name = output.map(|path| {
2253 path.file_name().map_or_else(
2254 || path.display().to_string(),
2255 |n| n.to_string_lossy().into_owned(),
2256 )
2257 });
2258 if let (Some(name), Some(said), Some(to)) = (&name, said, to)
2259 && said != to
2260 {
2261 return Err(format!(
2262 "-o {name} says {} and --to says {}: drop one",
2263 said.name(),
2264 to.name()
2265 ));
2266 }
2267 let format = match (output, said.or(to)) {
2268 (None, None) => return Ok(None),
2269 (_, Some(format)) => format,
2270 (Some(_), None) => match task {
2271 Task::Convert => return Ok(None),
2272 Task::Read | Task::Diff => Format::Md,
2273 _ => Format::Docx,
2274 },
2275 };
2276 if task.allowed().contains(&format) {
2277 Ok(Some(format))
2278 } else {
2279 let typed = output
2281 .filter(|_| said == Some(format))
2282 .map(|path| path.display().to_string());
2283 Err(task.cannot_write(format, typed.as_deref()))
2284 }
2285}
2286
2287#[must_use]
2292pub fn refused_input(path: &Path, bytes: &[u8], word: bool) -> Option<String> {
2293 let checked = if word {
2294 crate::admission::sniff_package(bytes)
2295 } else {
2296 crate::admission::sniff(bytes)
2297 };
2298 checked.err().map(|refused| {
2299 format!(
2300 "{}: {} is {}",
2301 refused.code(),
2302 path.display(),
2303 refused.message
2304 )
2305 })
2306}
2307
2308#[must_use]
2314pub fn refused_package(path: &Path, bytes: &[u8]) -> Option<String> {
2315 crate::admission::admit(bytes, crate::admission::InputLimits::default())
2316 .err()
2317 .map(|refused| {
2318 format!(
2319 "{}: {} is {}",
2320 refused.code(),
2321 path.display(),
2322 refused.message
2323 )
2324 })
2325}
2326
2327pub fn wrote_line(path: &Path, format: Format, bytes: usize, pages: Option<usize>) -> String {
2330 wrote_line_with(path, format, bytes, pages, None)
2331}
2332
2333#[must_use]
2336pub fn wrote_in_place_line(path: &Path, replaced_sha256: &str, detail: Option<&str>) -> String {
2337 let prefix = replaced_sha256.get(..8).unwrap_or(replaced_sha256);
2338 let extra = detail.map_or_else(String::new, |detail| format!("; {detail}"));
2339 format!(
2340 "wrote {} in place (replaced sha256 {prefix}\u{2026}){extra}",
2341 path.display()
2342 )
2343}
2344
2345pub fn wrote_line_with(
2347 path: &Path,
2348 format: Format,
2349 bytes: usize,
2350 pages: Option<usize>,
2351 detail: Option<&str>,
2352) -> String {
2353 let pages = pages.map_or_else(String::new, |n| format!(", {}", count(n, "page")));
2354 let extra = detail.map_or_else(String::new, |s| format!("; {s}"));
2355 format!(
2356 "wrote {} ({}, {bytes} bytes{pages}{extra})",
2357 path.display(),
2358 format.name()
2359 )
2360}
2361
2362#[must_use]
2367pub fn wrote_markup_detail(changes: usize, comments: usize, author: &str) -> Option<String> {
2368 if changes == 0 && comments == 0 {
2369 return None;
2370 }
2371 let mut detail = String::new();
2372 if changes > 0 {
2373 detail.push_str(&count(changes, "change"));
2374 }
2375 if comments > 0 {
2376 if !detail.is_empty() {
2377 detail.push_str(", ");
2378 }
2379 detail.push_str(&count(comments, "comment"));
2380 }
2381 detail.push_str(&format!(" by \"{author}\""));
2382 Some(detail)
2383}
2384
2385pub fn success_block(before_name: &str, before: &str, after_name: &str, after: &str) -> String {
2387 let body = if before == after {
2388 "no differences\n".to_string()
2389 } else {
2390 similar::TextDiff::from_lines(before, after)
2391 .unified_diff()
2392 .context_radius(3)
2393 .header(
2394 &format!("before {before_name}"),
2395 &format!("after {after_name}"),
2396 )
2397 .to_string()
2398 };
2399 let longest = body
2402 .lines()
2403 .map(|line| {
2404 let indent = line.bytes().take(3).take_while(|b| *b == b' ').count();
2405 line.bytes().skip(indent).take_while(|b| *b == b'~').count()
2406 })
2407 .max()
2408 .unwrap_or(0);
2409 let fence = "~".repeat(4.max(longest + 1));
2410 format!("SUCCESS:\n{fence}diff\n{body}{fence}\n")
2411}
2412
2413#[cfg(test)]
2414mod success_tests {
2415 use super::success_block;
2416
2417 #[test]
2418 fn equal_views() {
2419 assert_eq!(
2420 success_block("in.docx", "same", "out.docx", "same"),
2421 "SUCCESS:\n~~~~diff\nno differences\n~~~~\n"
2422 );
2423 }
2424
2425 #[test]
2426 fn labels_and_known_hunk() {
2427 assert_eq!(
2428 success_block(
2429 "dir/in.docx",
2430 "one\ntwo\nthree\n",
2431 "out.docx",
2432 "one\nnew\nthree\n"
2433 ),
2434 "SUCCESS:\n~~~~diff\n--- before dir/in.docx\n+++ after out.docx\n@@ -1,3 +1,3 @@\n one\n-two\n+new\n three\n~~~~\n"
2435 );
2436 }
2437
2438 #[test]
2439 fn fence_exceeds_leading_tildes_in_diff_body() {
2440 let block = success_block("a", "a\n", "b\n~~~~~", "b\n");
2441 assert!(block.starts_with("SUCCESS:\n~~~~~~diff\n"), "{block}");
2442 assert!(block.ends_with("~~~~~~\n"), "{block}");
2443 assert!(success_block("a", "~~~~~~\n", "b", "x\n").starts_with("SUCCESS:\n~~~~diff\n"));
2445 }
2446
2447 #[test]
2451 fn a_context_line_of_tildes_cannot_close_the_fence() {
2452 let block = success_block("a", "~~~~\nkeep\n", "b", "~~~~\nchanged\n");
2453 assert!(block.contains("\n ~~~~\n"), "{block}");
2454 let fence = block["SUCCESS:\n".len()..]
2455 .bytes()
2456 .take_while(|b| *b == b'~')
2457 .count();
2458 assert!(fence > 4, "{block}");
2459 }
2460
2461 #[test]
2462 fn three_context_lines_and_missing_newline() {
2463 let block = success_block(
2464 "a",
2465 "0\n1\n2\n3\n4\n5\n6\n7",
2466 "b",
2467 "0\n1\n2\n3\n4\n5\n6\nnew",
2468 );
2469 assert!(block.contains("@@ -5,4 +5,4 @@\n 4\n 5\n 6\n-7\n\\ No newline at end of file\n+new\n\\ No newline at end of file\n"), "{block}");
2470 }
2471}
2472
2473pub fn wrote_png_line(pattern: &Path, pages: usize, dpi: f32) -> String {
2476 format!(
2477 "wrote {} (png, {}, {dpi} dpi)",
2478 pattern.display(),
2479 count(pages, "page")
2480 )
2481}
2482
2483fn count(n: usize, word: &str) -> String {
2485 format!("{n} {word}{}", if n == 1 { "" } else { "s" })
2486}
2487
2488#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2490pub struct Retired {
2491 pub old: &'static str,
2493 pub now: &'static str,
2495 pub on: Option<&'static str>,
2498}
2499
2500pub const RETIRED: &[Retired] = &[
2502 Retired {
2503 old: "diff-render",
2504 now: "visual-diff",
2505 on: None,
2506 },
2507 Retired {
2508 old: "text",
2509 now: "read",
2510 on: None,
2511 },
2512 Retired {
2513 old: "inspect",
2514 now: "read",
2515 on: None,
2516 },
2517 Retired {
2518 old: "audit",
2519 now: "validate --rules a11y,style,structure",
2520 on: None,
2521 },
2522 Retired {
2523 old: "--changed-only",
2524 now: "--changed-pages",
2525 on: Some("convert"),
2526 },
2527 Retired {
2528 old: "--changed-only",
2529 now: "--changed-pages",
2530 on: Some("compare"),
2531 },
2532 Retired {
2533 old: "--changed-only",
2534 now: "--changed-pages",
2535 on: Some("accept"),
2536 },
2537 Retired {
2538 old: "--changed-only",
2539 now: "--changed-pages",
2540 on: Some("reject"),
2541 },
2542 Retired {
2543 old: "--changed-only",
2544 now: "--changed-pages",
2545 on: Some("append"),
2546 },
2547 Retired {
2548 old: "--changed-only",
2549 now: "--changed-pages",
2550 on: Some("scrub"),
2551 },
2552 Retired {
2553 old: "--pdf",
2554 now: "--to pdf",
2555 on: Some("convert"),
2556 },
2557 Retired {
2558 old: "--png",
2559 now: "--to png",
2560 on: Some("convert"),
2561 },
2562];
2563
2564pub(crate) const REMOVED_TASKS: &[Retired] = &[Retired {
2568 old: "revisions",
2569 now: "changes",
2570 on: None,
2571}];
2572
2573pub(crate) fn removed_tasks<'a>(
2576 argv: impl IntoIterator<Item = &'a str>,
2577) -> Vec<(&'static str, &'static str)> {
2578 spellings_in(REMOVED_TASKS, argv)
2579}
2580
2581pub(crate) fn removed_task_note(old: &str, now: &str) -> String {
2584 format!("note: {old} is no longer a task, so it reads as a file name; use {now}")
2585}
2586
2587pub const REMOVED: &[Retired] = &[
2591 Retired {
2592 old: "--date",
2593 now: "--datetime",
2594 on: Some("compare"),
2595 },
2596 Retired {
2597 old: "--date",
2598 now: "--datetime",
2599 on: Some("diff"),
2600 },
2601 Retired {
2602 old: "--date",
2603 now: "--datetime",
2604 on: Some("convert"),
2605 },
2606 Retired {
2607 old: "--date",
2608 now: "--datetime",
2609 on: Some("edit"),
2610 },
2611 Retired {
2612 old: "--date",
2613 now: "--datetime",
2614 on: Some("add"),
2615 },
2616];
2617
2618struct Spelled {
2622 name: String,
2623 at: usize,
2624}
2625
2626fn value_taken(arg: Option<&clap::Arg>) -> Option<bool> {
2631 let arg = arg.filter(|a| a.get_action().takes_values())?;
2632 match arg.get_num_args() {
2633 Some(range) if range.max_values() == 0 => None,
2634 Some(range) => Some(range.min_values() == 0),
2635 None => Some(false),
2636 }
2637}
2638
2639fn long_arg<'c>(cmd: &'c clap::Command, name: &str) -> Option<&'c clap::Arg> {
2642 cmd.get_arguments().find(|a| {
2643 a.get_long() == Some(name) || a.get_all_aliases().is_some_and(|v| v.contains(&name))
2644 })
2645}
2646
2647fn short_arg(cmd: &clap::Command, short: char) -> Option<&clap::Arg> {
2649 cmd.get_arguments().find(|a| {
2650 a.get_short() == Some(short)
2651 || a.get_all_short_aliases()
2652 .is_some_and(|v| v.contains(&short))
2653 })
2654}
2655
2656fn spelled_options(cmd: &clap::Command, tokens: &[&str]) -> (Vec<Spelled>, usize) {
2661 let skip_value = |i: &mut usize, optional: bool| {
2664 let value = tokens.get(*i).copied();
2665 if !(optional && value.is_none_or(|v| v.starts_with('-'))) {
2666 *i += 1;
2667 }
2668 };
2669 let mut found = Vec::new();
2670 let mut i = 0;
2671 while let Some(&token) = tokens.get(i) {
2672 i += 1;
2673 if let Some(long) = token.strip_prefix("--") {
2674 let (name, inline) = match long.split_once('=') {
2675 Some((name, value)) => (name, Some(value)),
2676 None => (long, None),
2677 };
2678 if inline.is_none()
2679 && let Some(optional) = value_taken(long_arg(cmd, name))
2680 {
2681 skip_value(&mut i, optional);
2682 }
2683 found.push(Spelled {
2684 name: format!("--{name}"),
2685 at: i - 1,
2686 });
2687 } else if let Some(cluster) = token.strip_prefix('-').filter(|c| !c.is_empty()) {
2688 let at = i - 1;
2689 for (offset, short) in cluster.char_indices() {
2690 let name = format!("-{short}");
2691 let Some(optional) = value_taken(short_arg(cmd, short)) else {
2692 found.push(Spelled { name, at });
2693 continue;
2694 };
2695 if cluster[offset + short.len_utf8()..].is_empty() {
2698 skip_value(&mut i, optional);
2699 }
2700 found.push(Spelled { name, at });
2701 break;
2702 }
2703 } else {
2704 return (found, i - 1);
2705 }
2706 }
2707 (found, i)
2708}
2709
2710pub fn retired_spellings<'a>(
2718 argv: impl IntoIterator<Item = &'a str>,
2719) -> Vec<(&'static str, &'static str)> {
2720 spellings_in(RETIRED, argv)
2721}
2722
2723pub fn removed_spellings<'a>(
2726 argv: impl IntoIterator<Item = &'a str>,
2727) -> Vec<(&'static str, &'static str)> {
2728 spellings_in(REMOVED, argv)
2729}
2730
2731pub fn removed_error(old: &str, now: &str) -> String {
2734 format!("error: {old} is removed; use {now}")
2735}
2736
2737fn spellings_in<'a>(
2738 table: &[Retired],
2739 argv: impl IntoIterator<Item = &'a str>,
2740) -> Vec<(&'static str, &'static str)> {
2741 let argv: Vec<&str> = argv.into_iter().take_while(|t| *t != "--").collect();
2742 let model = Cli::command();
2743 let mut found = Vec::new();
2744 let (before_task, at) = spelled_options(&model, &argv);
2745 let Some(&task) = argv.get(at) else {
2746 return found;
2747 };
2748 if let Some(retired) = table.iter().find(|r| r.on.is_none() && r.old == task) {
2749 found.push((retired.old, retired.now));
2750 }
2751 let (sub, task, from) = match model.find_subcommand(task) {
2754 Some(sub) => (sub, sub.get_name(), at + 1),
2755 None => (&model, "compare", at),
2756 };
2757 let mut spot = |options: Vec<Spelled>| {
2758 for option in options {
2759 for retired in table.iter().filter(|r| r.on == Some(task)) {
2760 if option.name == retired.old {
2761 found.push((retired.old, retired.now));
2762 }
2763 }
2764 }
2765 };
2766 spot(before_task);
2769 let mut rest = &argv[from..];
2771 while !rest.is_empty() {
2772 let (options, next) = spelled_options(sub, rest);
2773 spot(options);
2774 rest = rest.get(next + 1..).unwrap_or_default();
2775 }
2776 let mut seen = std::collections::HashSet::new();
2777 found.retain(|spelling| seen.insert(*spelling));
2778 found
2779}
2780
2781pub use crate::util::shell_word;
2782
2783pub(crate) fn apply_retired(task: &mut Command, retired: &[(&str, &str)]) {
2787 if let Command::Validate { rules, .. } = task
2788 && rules.is_empty()
2789 && retired.iter().any(|(old, _)| *old == "audit")
2790 {
2791 *rules = ["a11y", "style", "structure"].map(String::from).to_vec();
2792 }
2793}
2794
2795pub fn notes(argv: &[String]) -> Vec<String> {
2798 let argv = || argv.iter().map(String::as_str);
2799 let rules_given = argv()
2801 .take_while(|token| *token != "--")
2802 .any(|token| token == "--rules" || token.starts_with("--rules="));
2803 retired_spellings(argv())
2804 .into_iter()
2805 .map(|(old, now)| match old {
2806 "audit" if rules_given => retired_note(old, "validate"),
2807 _ => retired_note(old, now),
2808 })
2809 .chain(
2810 removed_tasks(argv())
2811 .into_iter()
2812 .map(|(old, now)| removed_task_note(old, now)),
2813 )
2814 .collect()
2815}
2816
2817pub fn retired_note(old: &str, now: &str) -> String {
2819 format!("note: {old} is now {now}; {old} is removed in 0.14")
2820}
2821
2822#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
2824#[serde(rename_all = "kebab-case")]
2825pub enum TrackChanges {
2826 All,
2828 #[value(alias = "accepted")]
2830 Accept,
2831 #[value(alias = "rejected")]
2833 Reject,
2834}
2835
2836impl From<TrackChanges> for crate::markdown::TrackChanges {
2837 fn from(choice: TrackChanges) -> Self {
2838 match choice {
2839 TrackChanges::All => Self::All,
2840 TrackChanges::Accept => Self::Accept,
2841 TrackChanges::Reject => Self::Reject,
2842 }
2843 }
2844}
2845
2846#[derive(clap::Args, Clone, Debug, PartialEq, Serialize)]
2849#[command(next_help_heading = "Rendering (-o FILE.pdf or FILE.png)")]
2850pub struct RenderArgs {
2851 #[arg(long, value_enum, default_value_t = Revisions::Conventional, requires_if("custom", "revision_palette"))]
2857 pub revisions: Revisions,
2858 #[cfg_attr(feature = "render", arg(long, value_name = "SPEC", value_parser = parse_palette, requires = "revisions"))]
2863 #[cfg_attr(
2864 not(feature = "render"),
2865 arg(long, value_name = "SPEC", requires = "revisions")
2866 )]
2867 pub revision_palette: Option<String>,
2868 #[arg(long, default_value_t = 96.0, value_name = "DPI", value_parser = parse_dpi)]
2870 pub dpi: f32,
2871 #[arg(long)]
2875 pub move_comments: bool,
2876 #[arg(long, hide = true)]
2880 pub comment_notes: bool,
2881 #[arg(long, alias = "changed-only")]
2886 pub changed_pages: bool,
2887 #[arg(long, value_name = "SPEC", value_parser = validate_pages)]
2891 pub pages: Option<String>,
2892}
2893
2894impl Default for RenderArgs {
2895 fn default() -> Self {
2896 Self {
2897 revisions: Revisions::Conventional,
2898 revision_palette: None,
2899 dpi: 96.0,
2900 move_comments: false,
2901 comment_notes: false,
2902 changed_pages: false,
2903 pages: None,
2904 }
2905 }
2906}
2907
2908impl RenderArgs {
2909 #[cfg(feature = "render")]
2911 pub fn apply(
2912 &self,
2913 options: crate::jubarte_render::convert::PdfOptions,
2914 ) -> crate::jubarte_render::convert::PdfOptions {
2915 crate::jubarte_render::convert::PdfOptions {
2916 comments: if self.move_comments {
2917 crate::jubarte_render::convert::CommentPlacement::End
2918 } else {
2919 crate::jubarte_render::convert::CommentPlacement::Margin
2920 },
2921 comment_notes: self.comment_notes,
2922 changed_only: self.changed_pages,
2923 ..options
2924 }
2925 }
2926}
2927
2928#[derive(clap::Args, Debug, Serialize)]
2930pub struct MarkdownArgs {
2931 #[arg(
2934 short = 'f',
2935 long = "from",
2936 value_parser = input_format_parser(),
2937 value_name = "FORMAT",
2938 help_heading = "Formats"
2939 )]
2940 pub from: Option<Format>,
2941 #[arg(
2944 short = 't',
2945 long = "to",
2946 value_enum,
2947 value_name = "FORMAT",
2948 help_heading = "Formats"
2949 )]
2950 pub to: Option<Format>,
2951 #[arg(long, value_enum, value_name = "CHOICE", default_value_t = TrackChanges::All)]
2955 pub track_changes: TrackChanges,
2956 #[arg(long)]
2958 pub keep_nested_comment: bool,
2959 #[arg(long)]
2962 pub no_critic: bool,
2963 #[arg(long, value_name = "FILE")]
2966 pub reference_doc: Option<PathBuf>,
2967 #[arg(long, value_name = "DIR")]
2972 pub resource_path: Option<PathBuf>,
2973 #[arg(short = 'a', long, value_name = "NAME")]
2977 pub author: Option<String>,
2978 #[arg(
2984 short = 'd',
2985 long = "datetime",
2986 value_name = "ISO8601",
2987 value_parser = parse_datetime
2988 )]
2989 pub datetime: Option<String>,
2990 #[arg(long, value_enum, value_name = "SIZE", default_value_t = Page::Letter)]
2993 pub page: Page,
2994 #[arg(long, value_enum, value_name = "SWITCH")]
2998 pub tracking: Option<Tracking>,
2999 #[arg(long)]
3004 pub scholar: bool,
3005 #[arg(long)]
3008 pub no_page_markers: bool,
3009 #[arg(long)]
3014 pub commonmark: bool,
3015}
3016
3017#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3019#[serde(rename_all = "kebab-case")]
3020pub enum Tracking {
3021 On,
3023 Off,
3025}
3026
3027#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3029#[serde(rename_all = "kebab-case")]
3030pub enum Page {
3031 Letter,
3033 A4,
3035}
3036
3037impl From<Page> for crate::markdown::PageSize {
3038 fn from(choice: Page) -> Self {
3039 match choice {
3040 Page::Letter => Self::Letter,
3041 Page::A4 => Self::A4,
3042 }
3043 }
3044}
3045
3046#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3048#[serde(rename_all = "kebab-case")]
3049pub enum Revisions {
3050 Conventional,
3052 Word,
3054 Custom,
3056}
3057
3058#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
3059pub struct Selection {
3061 #[arg(long = "id", value_name = "ID")]
3064 pub ids: Vec<String>,
3065 #[arg(long = "author", value_name = "NAME")]
3067 pub authors: Vec<String>,
3068 #[arg(long = "kind", value_enum, value_name = "KIND")]
3070 pub kinds: Vec<KindArg>,
3071}
3072
3073#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Serialize)]
3075#[serde(rename_all = "kebab-case")]
3076pub enum KindArg {
3077 Insertion,
3079 Deletion,
3081 Move,
3083 Formatting,
3085 #[value(hide = true)]
3090 Replacement,
3091}
3092
3093fn parse_timeout(value: &str) -> Result<std::time::Duration, String> {
3094 let seconds: f64 = value
3095 .parse()
3096 .map_err(|_| format!("'{value}' is not a number of seconds"))?;
3097 if !(seconds.is_finite() && seconds > 0.0) {
3098 return Err(format!(
3099 "'{value}': the timeout must be a finite number of seconds above 0"
3100 ));
3101 }
3102 std::time::Duration::try_from_secs_f64(seconds).map_err(|e| format!("'{value}': {e}"))
3103}
3104
3105#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
3107#[serde(rename_all = "kebab-case")]
3108pub enum SectionBreakArg {
3109 NextPage,
3111 Continuous,
3114 None,
3116}
3117
3118impl From<SectionBreakArg> for crate::append::SectionBreak {
3119 fn from(arg: SectionBreakArg) -> Self {
3120 match arg {
3121 SectionBreakArg::NextPage => Self::NextPage,
3122 SectionBreakArg::Continuous => Self::Continuous,
3123 SectionBreakArg::None => Self::None,
3124 }
3125 }
3126}
3127
3128fn styles() -> clap::builder::Styles {
3129 use clap::builder::styling::{AnsiColor, Effects};
3130 clap::builder::Styles::styled()
3131 .header(AnsiColor::Cyan.on_default() | Effects::BOLD)
3132 .usage(AnsiColor::Cyan.on_default() | Effects::BOLD)
3133 .literal(AnsiColor::Green.on_default())
3134 .placeholder(AnsiColor::Yellow.on_default())
3135}
3136
3137fn parse_author(value: &str) -> Result<String, String> {
3139 crate::markdown::author(value).map(str::to_string)
3140}
3141
3142fn parse_dpi(value: &str) -> Result<f32, String> {
3143 let dpi: f32 = value.parse().map_err(|_| "DPI must be a number")?;
3144 if dpi.is_finite() && dpi > 0.0 && dpi <= 1200.0 {
3145 Ok(dpi)
3146 } else {
3147 Err("DPI must be finite and above 0, up to 1200".into())
3148 }
3149}
3150
3151fn input_format_parser() -> impl clap::builder::TypedValueParser<Value = Format> {
3152 use clap::builder::TypedValueParser;
3153 clap::builder::PossibleValuesParser::new(["docx", "md", "markdown"]).map(|value| {
3154 if value == "docx" {
3155 Format::Docx
3156 } else {
3157 Format::Md
3158 }
3159 })
3160}
3161
3162fn parse_context(value: &str) -> Result<usize, String> {
3163 value
3164 .parse::<u32>()
3165 .map(|n| n as usize)
3166 .map_err(|_| "context must be an integer between 0 and 4294967295".to_string())
3167}
3168
3169fn parse_threshold(value: &str) -> Result<f64, String> {
3170 let ratio: f64 = value.parse().map_err(|_| "threshold must be a number")?;
3171 if ratio.is_finite() && (0.0..=1.0).contains(&ratio) {
3172 Ok(ratio)
3173 } else {
3174 Err("threshold must be finite and between 0 and 1".into())
3175 }
3176}
3177
3178#[cfg(feature = "render")]
3179fn parse_palette(value: &str) -> Result<String, String> {
3180 crate::jubarte_render::convert::RevisionPalette::parse(value)?;
3181 Ok(value.to_string())
3182}
3183
3184fn parse_rule(value: &str) -> Result<String, String> {
3186 if crate::validate::RULE_SETS.contains(&value) || crate::audit::is_rule(value) {
3187 Ok(value.to_string())
3188 } else {
3189 let codes: Vec<&str> = crate::audit::RULES.iter().map(|rule| rule.0).collect();
3190 Err(format!(
3191 "expected one of {} or an audit code ({})",
3192 crate::validate::RULE_SETS.join(", "),
3193 codes.join(", ")
3194 ))
3195 }
3196}
3197
3198fn validate_pages(value: &str) -> Result<String, String> {
3201 let page = |s: &str| {
3202 let s = s.trim();
3203 if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
3204 return Err(format!("'{s}' is not a page number"));
3205 }
3206 let n = s
3207 .parse::<usize>()
3208 .map_err(|_| format!("'{s}' is not a page number"))?;
3209 if n == 0 {
3210 Err("pages are counted from 1".to_string())
3211 } else {
3212 Ok(n)
3213 }
3214 };
3215 for item in value.split(',') {
3216 let item = item.trim();
3217 if item.is_empty() {
3218 return Err("empty item in page selection".into());
3219 }
3220 if let Some((first, last)) = item.split_once('-') {
3221 if page(first)? > page(last)? {
3222 return Err(format!("'{item}' runs backwards"));
3223 }
3224 } else {
3225 page(item)?;
3226 }
3227 }
3228 Ok(value.to_string())
3229}
3230
3231fn serialize_timeout<S: serde::Serializer>(
3232 timeout: &Option<std::time::Duration>,
3233 serializer: S,
3234) -> Result<S::Ok, S::Error> {
3235 timeout.map(|t| t.as_secs_f64()).serialize(serializer)
3236}
3237
3238fn serialize_paragraph_spec<S: serde::Serializer>(
3243 paragraphs: &[String],
3244 serializer: S,
3245) -> Result<S::Ok, S::Error> {
3246 match paragraphs {
3247 [] => serializer.serialize_none(),
3248 _ => serializer.serialize_str(¶graphs.join(",")),
3249 }
3250}
3251
3252const READ_OPTION_IDS: [&str; 14] = [
3254 "track_changes",
3255 "comments",
3256 "dates",
3257 "no_page_markers",
3258 "paragraphs",
3259 "head",
3260 "tail",
3261 "changed",
3262 "by",
3263 "json",
3264 "tables",
3265 "find",
3266 "regex",
3267 "ignore_case",
3268];
3269
3270fn json_not_yet(matches: &clap::ArgMatches, task: Task) -> Option<String> {
3274 let to = matches.try_get_one::<Format>("to").ok().flatten().copied();
3275 let said = matches
3276 .try_get_one::<PathBuf>("output")
3277 .ok()
3278 .flatten()
3279 .and_then(|path| task.known(path));
3280 (to == Some(Format::Json) || said == Some(Format::Json))
3281 .then(|| format!("{} does not write .json yet", task.name()))
3282}
3283
3284fn compare_output(
3289 output: Option<&Path>,
3290 given: &dyn Fn(&str) -> bool,
3291) -> Result<Option<Format>, String> {
3292 if given("json") {
3293 return Err(
3294 "--json reads one document; `-o FILE.json` writes the redline's snapshot".to_string(),
3295 );
3296 }
3297 if given("tables") {
3298 return Err("--tables reads one document".to_string());
3299 }
3300 let kind = output_format(Task::Compare, output, None)?;
3301 if kind.is_some_and(|kind| kind != Format::Md) && READ_OPTION_IDS.into_iter().any(given) {
3302 return Err(
3303 "read options shape the view: print it (no -o) or write it (-o FILE.md)".to_string(),
3304 );
3305 }
3306 if !matches!(kind, Some(Format::Pdf | Format::Png))
3307 && let Some(flag) = RENDER_ONLY.into_iter().find(|flag| given(flag))
3308 {
3309 return Err(format!(
3310 "--{} applies to PDF or PNG output only",
3311 flag.replace('_', "-")
3312 ));
3313 }
3314 Ok(kind)
3315}
3316
3317fn read_view_conflict(flag: &str) -> String {
3319 format!(
3320 "{flag} shapes the Markdown view, and --for-edit prints the working document JSON, \
3321 which has no view; drop {flag}, or drop --for-edit to read the view"
3322 )
3323}
3324
3325fn read_usage_error(command: &clap::Command, message: String) -> clap::Error {
3329 let mut task = command
3330 .find_subcommand("read")
3331 .unwrap_or(command)
3332 .clone()
3333 .override_usage(format!("{} read [OPTIONS] <FILE>", command.get_name()));
3334 task.set_bin_name(format!("{} read", command.get_name()));
3335 task.error(clap::error::ErrorKind::ArgumentConflict, message)
3336}
3337
3338fn read_output(output: &Path, given: &dyn Fn(&str) -> bool) -> Result<Format, String> {
3342 let kind = output_format(Task::Read, Some(output), None)?.unwrap_or(Format::Md);
3343 if given("tables") && kind == Format::Json {
3344 return Err("--tables writes the grids as text: name the file FILE.md".to_string());
3345 }
3346 if given("for_edit") && kind != Format::Json {
3347 return Err("--for-edit prints JSON: name the file FILE.json or drop -o".to_string());
3348 }
3349 if kind == Format::Json && !given("for_edit") && (given("find") || given("regex")) {
3350 return Err(
3351 "--find/--regex select the Markdown view: name the file FILE.md or use --for-edit"
3352 .into(),
3353 );
3354 }
3355 if given("json") && kind != Format::Json {
3356 return Err("--json writes the snapshot: name the file FILE.json".to_string());
3357 }
3358 Ok(kind)
3361}
3362
3363fn palette_without_custom(args: &clap::ArgMatches) -> bool {
3367 args.try_get_one::<String>("revision_palette")
3368 .ok()
3369 .flatten()
3370 .is_some()
3371 && args.try_get_one::<Revisions>("revisions").ok().flatten() != Some(&Revisions::Custom)
3372}
3373
3374fn validate_matches(
3375 matches: &clap::ArgMatches,
3376 command: &mut clap::Command,
3377) -> Result<(), clap::Error> {
3378 use clap::{error::ErrorKind, parser::ValueSource};
3379 let read_args = match matches.subcommand() {
3380 Some(("read" | "compare", args)) => Some(args),
3381 None => Some(matches),
3382 _ => None,
3383 };
3384 if let Some(args) = read_args {
3385 let find = args.get_one::<String>("find");
3386 let regex = args.get_one::<String>("regex");
3387 if !args.get_flag("for_edit")
3388 && (find.is_some() || regex.is_some())
3389 && (args.get_flag("json") || args.get_flag("tables"))
3390 {
3391 return Err(read_usage_error(
3392 command,
3393 "--find/--regex select the Markdown view; drop --json/--tables or use --for-edit"
3394 .into(),
3395 ));
3396 }
3397 if find.is_none()
3398 && regex.is_none()
3399 && args.get_flag("ignore_case")
3400 && !args.get_flag("for_edit")
3401 {
3402 return Err(read_usage_error(
3403 command,
3404 "--ignore-case needs --find TEXT or --regex PATTERN".into(),
3405 ));
3406 }
3407 }
3408 let Some((name, args)) = matches.subcommand() else {
3409 let given = |id: &str| {
3410 matches.try_contains_id(id).unwrap_or(false)
3411 && matches.value_source(id) == Some(ValueSource::CommandLine)
3412 };
3413 let two = given("modified_pos") || given("modified");
3414 let output = matches.get_one::<PathBuf>("output").map(PathBuf::as_path);
3415 if two {
3416 compare_output(output, &given)
3417 .map_err(|message| command.error(ErrorKind::ArgumentConflict, message))?;
3418 if palette_without_custom(matches) {
3419 return Err(command.error(
3420 ErrorKind::ArgumentConflict,
3421 "--revision-palette needs --revisions custom",
3422 ));
3423 }
3424 } else {
3425 if let Some(output) = output {
3427 read_output(output, &given)
3428 .map_err(|message| read_usage_error(command, message))?;
3429 }
3430 if let Some(flag) = COMPARE_ONLY.into_iter().find(|id| given(id)) {
3433 return Err(command.error(
3434 ErrorKind::ArgumentConflict,
3435 format!(
3436 "--{} is a compare option: name two documents",
3437 flag.replace('_', "-")
3438 ),
3439 ));
3440 }
3441 if let Some(flag) = RENDER_ONLY.into_iter().find(|id| given(id)) {
3442 return Err(command.error(
3443 ErrorKind::ArgumentConflict,
3444 format!(
3445 "--{} draws a PDF or PNG, which read does not write: \
3446 `convert FILE -o FILE.pdf` or `compare A B -o FILE.pdf` does",
3447 flag.replace('_', "-")
3448 ),
3449 ));
3450 }
3451 }
3452 if let Some(task) = matches
3455 .try_get_one::<PathBuf>("original_pos")
3456 .ok()
3457 .flatten()
3458 .and_then(|p| p.to_str())
3459 .and_then(|name| command.find_subcommand(name))
3460 .map(|task| task.get_name().to_string())
3461 {
3462 return Err(command.error(
3463 ErrorKind::ArgumentConflict,
3464 format!(
3465 "options go after the task: `{} {task} … [OPTIONS]`",
3466 command.get_name()
3467 ),
3468 ));
3469 }
3470 let lone = |id: &str| {
3472 matches
3473 .try_get_one::<PathBuf>(id)
3474 .ok()
3475 .flatten()
3476 .filter(|_| matches.value_source(id) == Some(ValueSource::CommandLine))
3477 };
3478 if lone("modified_pos").is_none()
3479 && lone("modified").is_none()
3480 && let Some(file) = lone("original_pos")
3481 && file.extension().is_none()
3482 {
3483 return Err(command.error(
3484 ErrorKind::InvalidSubcommand,
3485 format!(
3486 "'{}' is not a task; to read a file without an extension, use `read FILE`",
3487 file.display()
3488 ),
3489 ));
3490 }
3491 return Ok(());
3492 };
3493 if let Some(message) = Task::of_name(name)
3494 .filter(|task| *task == Task::Diff)
3495 .and_then(|task| json_not_yet(args, task))
3496 {
3497 let mut task = command.find_subcommand(name).expect("parsed task").clone();
3498 task.set_bin_name(format!("{} {name}", command.get_name()));
3499 return Err(task.error(ErrorKind::ValueValidation, message));
3500 }
3501 if name == "validate"
3502 && args
3503 .get_many::<String>("rules")
3504 .is_some_and(|mut rules| rules.any(|rule| rule == "edits"))
3505 && !args.contains_id("author")
3506 {
3507 let mut task = command.find_subcommand(name).expect("parsed task").clone();
3508 task.set_bin_name(format!("{} {name}", command.get_name()));
3509 return Err(task.error(
3510 ErrorKind::MissingRequiredArgument,
3511 "--rules edits needs --author, and --original or --baseline",
3512 ));
3513 }
3514 if name == "compare"
3515 && !["modified", "modified_pos"]
3516 .into_iter()
3517 .any(|id| args.try_contains_id(id).unwrap_or(false))
3518 {
3519 let mut task = command.find_subcommand(name).expect("parsed task").clone();
3520 task.set_bin_name(format!("{} {name}", command.get_name()));
3521 return Err(task.error(
3522 ErrorKind::MissingRequiredArgument,
3523 "compare needs <MODIFIED> (or -m FILE)",
3524 ));
3525 }
3526 if name == "__edit-template" {
3527 return edit_template::validate(args, command);
3528 }
3529 if name == "__edit-v2" {
3530 return edit_actions::validate(args, command);
3531 }
3532 let mut task = command.find_subcommand(name).expect("parsed task").clone();
3533 task.set_bin_name(format!("{} {name}", command.get_name()));
3534 let error =
3535 |task: &mut clap::Command, message: &str| task.error(ErrorKind::ArgumentConflict, message);
3536 let given = |id: &str| {
3537 args.try_contains_id(id).unwrap_or(false)
3538 && args.value_source(id) == Some(ValueSource::CommandLine)
3539 };
3540 if name == "read"
3541 && let Some(output) = args.get_one::<PathBuf>("output")
3542 {
3543 read_output(output, &given).map_err(|message| read_usage_error(command, message))?;
3544 }
3545 if name == "compare" {
3546 compare_output(
3547 args.get_one::<PathBuf>("output").map(PathBuf::as_path),
3548 &given,
3549 )
3550 .map_err(|message| error(&mut task, &message))?;
3551 }
3552 if let Some(writer) = Task::of_name(name).filter(|task| {
3553 matches!(
3554 task,
3555 Task::Accept | Task::Reject | Task::Append | Task::Scrub
3556 )
3557 }) {
3558 let output = args.get_one::<PathBuf>("output").map(PathBuf::as_path);
3559 let kind =
3560 output_format(writer, output, None).map_err(|message| error(&mut task, &message))?;
3561 if !matches!(kind, Some(Format::Pdf | Format::Png))
3562 && let Some(flag) = RENDER_ONLY.into_iter().find(|flag| given(flag))
3563 {
3564 return Err(error(
3565 &mut task,
3566 &format!(
3567 "--{} applies to PDF or PNG output only",
3568 flag.replace('_', "-")
3569 ),
3570 ));
3571 }
3572 }
3573 if matches!(name, "edit" | "add")
3574 && let Some(plan) = args.get_one::<PathBuf>("plan")
3575 {
3576 let given: Vec<String> = args
3579 .ids()
3580 .filter(|id| args.value_source(id.as_str()) == Some(ValueSource::CommandLine))
3581 .map(|id| format!("--{}", id.as_str().replace('_', "-")))
3582 .collect();
3583 let given: Vec<&str> = given.iter().map(String::as_str).collect();
3584 let recording = given.contains(&"--location");
3585 if let Some(message) =
3586 crate::edit::record::plan_flag_conflict(recording, &given, &plan.display().to_string())
3587 {
3588 return Err(error(&mut task, &message));
3589 }
3590 }
3591 if matches!(name, "edit" | "add")
3594 && let Some(dir) = args.try_get_one::<PathBuf>("out_dir").ok().flatten()
3595 && names_word_document(dir)
3596 {
3597 return Err(error(&mut task, &swallowed_file("--out-dir", dir)));
3598 }
3599 if matches!(name, "edit" | "add")
3601 && let Some(plan) = args.get_one::<PathBuf>("plan")
3602 && names_word_document(plan)
3603 {
3604 return Err(error(&mut task, &swallowed_file("--plan", plan)));
3605 }
3606 if matches!(name, "edit" | "add")
3609 && let Some(output) = args.get_one::<PathBuf>("output")
3610 && let Some(kind) = Format::of_path(output).filter(|kind| *kind != Format::Docx)
3611 {
3612 let ext = output.extension().map_or_else(
3614 || kind.name().to_string(),
3615 |e| e.to_string_lossy().to_lowercase(),
3616 );
3617 let how = match kind {
3618 Format::Md | Format::Json => format!("`jubarte read FILE_modified.docx -o v.{ext}`"),
3619 _ => format!("`jubarte convert FILE_modified.docx -o r.{ext}`"),
3620 };
3621 return Err(error(
3622 &mut task,
3623 &format!("{name} writes a .docx; {how} writes .{ext} from it"),
3624 ));
3625 }
3626 if palette_without_custom(args) {
3627 return Err(error(
3628 &mut task,
3629 "--revision-palette needs --revisions custom",
3630 ));
3631 }
3632 if name == "diff" {
3633 output_format(
3635 Task::Diff,
3636 args.get_one::<PathBuf>("output").map(PathBuf::as_path),
3637 args.get_one::<Format>("to").copied(),
3638 )
3639 .map_err(|message| error(&mut task, &message))?;
3640 let format = *args
3641 .get_one::<PatchFormat>("format")
3642 .expect("default format");
3643 let (text_view, theirs) = if format.is_text_view() {
3644 (true, &["columns", "author", "datetime"][..])
3645 } else {
3646 (false, &["context", "accept_changes", "full_lines"][..])
3647 };
3648 let patch_only: &[&str] = if format == PatchFormat::Critic {
3651 &["columns", "author", "datetime"]
3652 } else {
3653 &[]
3654 };
3655 let given = |flag: &&&str| args.value_source(flag) == Some(ValueSource::CommandLine);
3656 if let Some(flag) = patch_only.iter().find(given) {
3657 return Err(error(
3658 &mut task,
3659 &format!("--{flag} applies to the paragraph patch only (--format patch)"),
3660 ));
3661 }
3662 if let Some(flag) = theirs.iter().find(given) {
3663 let flag = flag.replace('_', "-");
3664 return Err(error(
3665 &mut task,
3666 &if text_view {
3667 format!("--{flag} does not apply to this text diff format")
3668 } else {
3669 format!(
3670 "--{flag} requires a text diff format (github, word, normal, context or side-by-side)"
3671 )
3672 },
3673 ));
3674 }
3675 }
3676 if name == "convert" {
3677 if args.get_flag("keep_nested_comment")
3678 && args.get_one::<TrackChanges>("track_changes") == Some(&TrackChanges::All)
3679 {
3680 return Err(error(
3681 &mut task,
3682 "--keep-nested-comment requires --track-changes accept or reject",
3683 ));
3684 }
3685 let alias = match (args.get_flag("pdf"), args.get_flag("png")) {
3687 (true, true) => return Err(error(&mut task, "--pdf and --png name two formats")),
3688 (true, false) => Some(Format::Pdf),
3689 (false, true) => Some(Format::Png),
3690 (false, false) => None,
3691 };
3692 let given = args.get_one::<Format>("to").copied();
3693 if let (Some(to), Some(alias)) = (given, alias)
3694 && to != alias
3695 {
3696 return Err(error(
3697 &mut task,
3698 &format!(
3699 "--to {} and --{} name two formats: drop one",
3700 to.name(),
3701 alias.name()
3702 ),
3703 ));
3704 }
3705 let output = args.get_one::<PathBuf>("output").map(PathBuf::as_path);
3706 let kind = output_format(Task::Convert, output, given.or(alias))
3707 .map_err(|message| error(&mut task, &message))?;
3708 let update_fields = args.get_flag("update_fields");
3709 if update_fields && kind != Some(Format::Docx) {
3710 return Err(error(
3711 &mut task,
3712 "--update-fields writes a .docx: give -o FILE.docx or --to docx",
3713 ));
3714 }
3715 if matches!(kind, Some(Format::Docx | Format::Md | Format::Json)) {
3716 let convert_only = ["compress", "report", "font_report", "fail_on_substitution"];
3717 for flag in RENDER_ONLY.into_iter().chain(convert_only) {
3718 if flag == "report" && update_fields {
3720 continue;
3721 }
3722 if args.value_source(flag) == Some(ValueSource::CommandLine) {
3723 return Err(error(
3724 &mut task,
3725 &format!(
3726 "--{} applies to PDF or PNG output only",
3727 flag.replace('_', "-")
3728 ),
3729 ));
3730 }
3731 }
3732 }
3733 }
3734 Ok(())
3735}
3736
3737const COMPARE_ONLY: [&str; 9] = [
3740 "author",
3741 "datetime",
3742 "detail_threshold",
3743 "mode",
3744 "powertools_faithful",
3745 "no_paragraph_merge",
3746 "reference_doc",
3747 "critic",
3748 "resource_path",
3749];
3750
3751const RENDER_ONLY: [&str; 7] = [
3753 "move_comments",
3754 "comment_notes",
3755 "changed_pages",
3756 "pages",
3757 "dpi",
3758 "revisions",
3759 "revision_palette",
3760];
3761
3762pub fn edit_arguments(
3764 command: &clap::Command,
3765 arguments: &[std::ffi::OsString],
3766) -> Vec<std::ffi::OsString> {
3767 edit_actions::route(&hoist_quiet(command, arguments), command)
3768}
3769
3770pub fn typed_edit_protocol(
3775 arguments: &[std::ffi::OsString],
3776) -> Option<(String, bool, Option<String>)> {
3777 let model = top_level_command();
3778 let routed = edit_arguments(&model, arguments);
3779 if routed.get(1).is_none_or(|a| a != "__edit-v2") {
3780 return None;
3781 }
3782 let typed = model.find_subcommand("__edit-v2")?;
3783 let tokens: Vec<_> = routed
3784 .iter()
3785 .skip(2)
3786 .filter_map(|a| a.to_str())
3787 .take_while(|a| *a != "--")
3788 .collect();
3789 let (_, at) = spelled_options(typed, &tokens);
3790 let action = *tokens.get(at)?;
3791 let command = typed.find_subcommand(action)?;
3792 let mut rest = &tokens[at + 1..];
3793 let mut json = false;
3794 let mut jsonl = false;
3795 let mut file = None;
3796 while !rest.is_empty() {
3797 let (options, next) = spelled_options(command, rest);
3798 for option in options {
3799 json |= option.name == "--json";
3800 jsonl |= option.name == "--jsonl";
3801 }
3802 if file.is_none()
3804 && let Some(operand) = rest.get(next)
3805 {
3806 file = Some(operand.to_string());
3807 }
3808 rest = rest.get(next + 1..).unwrap_or_default();
3809 }
3810 (json || jsonl).then(|| (action.to_string(), jsonl, file))
3811}
3812
3813pub fn next_command(argv: &[String], force: bool) -> Vec<String> {
3818 next_command_to(argv, force, None)
3819}
3820
3821pub fn next_command_to(argv: &[String], force: bool, output: Option<&str>) -> Vec<String> {
3825 let model = top_level_command();
3826 let arguments: Vec<std::ffi::OsString> = std::iter::once("jubarte".into())
3827 .chain(argv.iter().map(Into::into))
3828 .collect();
3829 let routed = edit_arguments(&model, &arguments);
3832 let tokens: Vec<&str> = routed
3833 .iter()
3834 .skip(1)
3835 .filter_map(|a| a.to_str())
3836 .take_while(|a| *a != "--")
3837 .collect();
3838 let mut flags = std::collections::BTreeSet::new();
3839 let mut command = &model;
3840 let mut start = 0;
3841 loop {
3842 let (options, next) = spelled_options(command, &tokens[start..]);
3843 flags.extend(
3844 options
3845 .iter()
3846 .filter(|option| option.name == "--dry-run")
3847 .map(|option| start + option.at),
3848 );
3849 let Some(word) = tokens.get(start + next) else {
3850 break;
3851 };
3852 if let Some(task) = command.find_subcommand(word) {
3853 command = task;
3854 }
3855 start += next + 1;
3856 }
3857 let dropped: std::collections::BTreeSet<usize> = tokens
3859 .iter()
3860 .enumerate()
3861 .filter(|(_, token)| **token == "--dry-run")
3862 .enumerate()
3863 .filter(|(_, (at, _))| flags.contains(at))
3864 .map(|(nth, _)| nth)
3865 .collect();
3866 let tail = |next: &mut Vec<String>| {
3867 if let Some(output) = output {
3868 next.extend(["-o".to_string(), output.to_string()]);
3869 }
3870 if force {
3871 next.push("--force".to_string());
3872 }
3873 };
3874 let mut next = Vec::with_capacity(argv.len() + 3);
3875 let mut spelled = 0;
3876 let mut delimited = false;
3877 for arg in argv {
3878 if !delimited && arg == "--" {
3879 delimited = true;
3880 tail(&mut next);
3881 }
3882 if !delimited && arg == "--dry-run" {
3883 spelled += 1;
3884 if dropped.contains(&(spelled - 1)) {
3885 continue;
3886 }
3887 }
3888 next.push(arg.clone());
3889 }
3890 if !delimited {
3891 tail(&mut next);
3892 }
3893 next
3894}
3895
3896pub fn first_positional(cmd: &clap::Command, tokens: &[&str]) -> Option<String> {
3902 let (_, at) = spelled_options(cmd, tokens);
3903 tokens.get(at).map(ToString::to_string)
3904}
3905
3906impl Cli {
3907 pub fn try_parse_from<I, T>(arguments: I) -> Result<Self, clap::Error>
3909 where
3910 I: IntoIterator<Item = T>,
3911 T: Into<std::ffi::OsString> + Clone,
3912 {
3913 let mut command = top_level_command();
3914 let arguments: Vec<std::ffi::OsString> = arguments.into_iter().map(Into::into).collect();
3915 let arguments = edit_arguments(&command, &arguments);
3916 let matches = command
3917 .try_get_matches_from_mut(arguments.clone())
3918 .map_err(|e| {
3919 let tokens: Vec<String> = arguments
3920 .iter()
3921 .map(|a| a.to_string_lossy().into_owned())
3922 .collect();
3923 usage_error(&command, &tokens, e)
3924 })?;
3925 validate_matches(&matches, &mut command)?;
3926 let mut cli = Self::from_arg_matches(&matches)?;
3927 if let Some(task) = cli.command.as_mut() {
3928 fill_flag_operations(task, &matches, &mut command)?;
3929 resolve_plan(task);
3930 let typed: Vec<String> = arguments
3931 .iter()
3932 .skip(1)
3933 .map(|a| a.to_string_lossy().into_owned())
3934 .collect();
3935 apply_retired(task, &retired_spellings(typed.iter().map(String::as_str)));
3936 fill_task_date(task);
3937 } else {
3938 fill_date(&mut cli.compare.datetime);
3939 }
3940 match (cli.command.as_mut(), matches.subcommand()) {
3941 (Some(Command::Compare(compare)), Some((_, args))) => {
3942 compare.view_given = view_given(args);
3943 }
3944 (Some(Command::TypedEdit(typed)), Some((_, args))) => {
3945 mark_typed_author(typed, args, &mut command)?;
3946 }
3947 (None, _) => cli.compare.view_given = view_given(&matches),
3948 _ => {}
3949 }
3950 Ok(cli)
3951 }
3952}
3953
3954fn mark_typed_author(
3958 typed: &mut edit_actions::TypedEdit,
3959 args: &clap::ArgMatches,
3960 command: &mut clap::Command,
3961) -> Result<(), clap::Error> {
3962 let Some((_, action)) = args.subcommand() else {
3963 return Ok(());
3964 };
3965 let given = action.try_contains_id("author").unwrap_or(false)
3966 && action.value_source("author") == Some(clap::parser::ValueSource::CommandLine);
3967 let Some(inline) = typed.action.inline_mut() else {
3968 return Ok(());
3969 };
3970 inline.author_given = given;
3971 env_author_fill(&mut inline.author, &mut inline.author_given)
3972 .map_err(|m| command.error(clap::error::ErrorKind::ValueValidation, m))?;
3973 Ok(())
3974}
3975
3976fn view_given(matches: &clap::ArgMatches) -> bool {
3978 READ_OPTION_IDS.into_iter().any(|id| {
3979 matches.try_contains_id(id).unwrap_or(false)
3980 && matches.value_source(id) == Some(clap::parser::ValueSource::CommandLine)
3981 })
3982}
3983
3984fn compare_json(compare: &CompareArgs) -> serde_json::Value {
3985 let mut args = serde_json::to_value(compare).expect("UTF-8 CLI arguments");
3986 args["original"] =
3989 serde_json::to_value(compare.original.as_ref().or(compare.original_pos.as_ref()))
3990 .expect("UTF-8 path");
3991 args["modified"] =
3992 serde_json::to_value(compare.modified.as_ref().or(compare.modified_pos.as_ref()))
3993 .expect("UTF-8 path");
3994 let input_format = |path: Option<&PathBuf>| {
3995 path.and_then(|p| Format::of_path(p))
3996 .filter(|f| matches!(f, Format::Docx | Format::Md))
3997 };
3998 args["old_format"] = serde_json::to_value(input_format(
3999 compare.original.as_ref().or(compare.original_pos.as_ref()),
4000 ))
4001 .expect("format");
4002 args["new_format"] = serde_json::to_value(input_format(
4003 compare.modified.as_ref().or(compare.modified_pos.as_ref()),
4004 ))
4005 .expect("format");
4006 let kind = output_format(Task::Compare, compare.output.as_deref(), None)
4008 .ok()
4009 .flatten();
4010 args["output_format"] = serde_json::to_value(kind).expect("format");
4011 if matches!(kind, None | Some(Format::Md)) {
4016 args["view"] = serde_json::to_value(&compare.read).expect("UTF-8 CLI arguments");
4017 }
4018 args
4019}
4020
4021fn view_is_output(args: &serde_json::Value) -> bool {
4025 let markdown = |format: &serde_json::Value| format == "md";
4026 args["output_format"].is_null()
4027 || (args["output_format"] == "md"
4028 && !(markdown(&args["old_format"]) && markdown(&args["new_format"])))
4029}
4030
4031fn view_not_supported(command: &mut clap::Command) -> clap::Error {
4034 command.error(
4035 clap::error::ErrorKind::InvalidSubcommand,
4036 "this adapter prints no agent view; write the redline with -o FILE.docx",
4037 )
4038}
4039
4040fn error_json(error: &clap::Error) -> String {
4041 serde_json::json!({
4042 "exit_code": error.exit_code(),
4043 "stream": if error.use_stderr() { "stderr" } else { "stdout" },
4044 "text": error.to_string(),
4045 })
4046 .to_string()
4047}
4048
4049pub fn wants_json(argv: &[String]) -> bool {
4054 let model = top_level_command();
4057 let arguments: Vec<std::ffi::OsString> = std::iter::once("jubarte".into())
4058 .chain(argv.iter().map(Into::into))
4059 .collect();
4060 let routed = edit_arguments(&model, &arguments);
4061 let tokens: Vec<&str> = routed
4062 .iter()
4063 .skip(1)
4064 .filter_map(|a| a.to_str())
4065 .take_while(|a| *a != "--")
4066 .collect();
4067 let mut command = &model;
4068 let mut rest = &tokens[..];
4069 loop {
4070 let (options, next) = spelled_options(command, rest);
4071 if options.iter().any(|option| option.name == "--json") {
4072 return true;
4073 }
4074 let Some(word) = rest.get(next) else {
4075 return false;
4076 };
4077 if let Some(task) = command.find_subcommand(word) {
4078 command = task;
4079 }
4080 rest = &rest[next + 1..];
4081 }
4082}
4083
4084pub fn json_error(code: &str, message: &str, usage: Option<&str>) -> String {
4087 let mut error = serde_json::json!({ "code": code, "message": message });
4088 if let Some(usage) = usage {
4089 error["usage"] = usage.into();
4090 }
4091 format!("{}\n", serde_json::json!({ "error": error }))
4092}
4093
4094pub fn runtime_json_error(message: &str, exit: u8) -> String {
4099 let lead = message.split_once(": ").map_or("", |(lead, _)| lead);
4100 let coded = lead.len() >= 3
4101 && lead.starts_with(|c: char| c.is_ascii_uppercase())
4102 && lead
4103 .chars()
4104 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
4105 let code = if coded {
4106 lead
4107 } else if exit == 2 {
4108 "USAGE"
4109 } else {
4110 "ERROR"
4111 };
4112 json_error(code, message, None)
4113}
4114
4115pub fn usage_json_error(error: &clap::Error, argv: &[String], program: &str) -> Option<String> {
4122 let (message, usage) = usage_parts(error, argv, program)?;
4123 Some(json_error("USAGE", &message, usage.as_deref()))
4124}
4125
4126pub fn removed_json_error(
4130 error: &clap::Error,
4131 argv: &[String],
4132 program: &str,
4133 message: &str,
4134) -> String {
4135 let usage = usage_parts(error, argv, program).and_then(|(_, usage)| usage);
4136 json_error("USAGE", message, usage.as_deref())
4137}
4138
4139fn usage_parts(
4141 error: &clap::Error,
4142 argv: &[String],
4143 program: &str,
4144) -> Option<(String, Option<String>)> {
4145 if !error.use_stderr() {
4146 return None;
4147 }
4148 #[derive(Clone, Copy)]
4149 enum Part {
4150 Message,
4151 Tip,
4152 Usage,
4153 Other,
4154 }
4155 let text = error.render().to_string();
4156 let (mut message, mut tips, mut usage) = (String::new(), Vec::<String>::new(), Vec::new());
4157 let mut part = Part::Other;
4158 for line in text.lines() {
4161 let trimmed = line.trim();
4162 if let Some(first) = line.strip_prefix("error: ") {
4163 message.push_str(first);
4164 part = Part::Message;
4165 } else if let Some(tip) = trimmed.strip_prefix("tip: ") {
4166 tips.push(tip.to_string());
4167 part = Part::Tip;
4168 } else if let Some(first) = line.strip_prefix("Usage: ") {
4169 usage.push(first.trim());
4170 part = Part::Usage;
4171 } else if trimmed.is_empty() {
4172 part = Part::Other;
4173 } else {
4174 match (part, tips.last_mut()) {
4175 (Part::Message, _) => {
4176 message.push(' ');
4177 message.push_str(trimmed);
4178 }
4179 (Part::Tip, Some(tip)) => {
4180 tip.push(' ');
4181 tip.push_str(trimmed);
4182 }
4183 (Part::Usage, _) => usage.push(trimmed),
4184 _ => {}
4185 }
4186 }
4187 }
4188 for tip in tips {
4189 message.push_str(&format!(" (tip: {tip})"));
4190 }
4191 let usage = task_usage(argv, program).or_else(|| (!usage.is_empty()).then(|| usage.join("\n")));
4192 Some((message, usage))
4193}
4194
4195fn task_usage(argv: &[String], program: &str) -> Option<String> {
4198 let mut model = Cli::command().bin_name(program.to_string());
4199 model.build();
4200 let name = argv
4201 .iter()
4202 .take_while(|a| *a != "--")
4203 .find(|a| !a.starts_with('-'))?;
4204 let usage = model.find_subcommand_mut(name)?.render_usage().to_string();
4205 let usage = usage.strip_prefix("Usage: ")?;
4206 Some(usage.lines().map(str::trim).collect::<Vec<_>>().join("\n"))
4207}
4208
4209fn missing_task(command: &mut clap::Command, program: &str, task: &str) -> clap::Error {
4211 command.error(
4212 clap::error::ErrorKind::InvalidSubcommand,
4213 format!("this {program} has no {task} task; the `jubarte` binary has it"),
4214 )
4215}
4216
4217fn parse_subcommand_json(
4222 command: &mut clap::Command,
4223 matches: &clap::ArgMatches,
4224 arguments: &[String],
4225 accepts: &dyn Fn(&str) -> bool,
4226) -> Result<serde_json::Value, clap::Error> {
4227 let mut task = Command::from_arg_matches(matches)?;
4228 fill_flag_operations(&mut task, matches, command)?;
4229 resolve_plan(&mut task);
4230 apply_retired(
4231 &mut task,
4232 &retired_spellings(arguments.iter().map(String::as_str)),
4233 );
4234 fill_task_date(&mut task);
4235 let mut value = serde_json::to_value(&task).expect("UTF-8 CLI arguments");
4236 if let Command::Compare(compare) = &mut task {
4237 if let Some((_, args)) = matches.subcommand() {
4238 compare.view_given = view_given(args);
4239 }
4240 value["args"] = compare_json(compare);
4241 if view_is_output(&value["args"]) && !accepts("read") {
4242 return Err(view_not_supported(command));
4243 }
4244 }
4245 if let Command::Diff {
4246 old,
4247 new,
4248 output,
4249 to,
4250 from,
4251 ..
4252 } = &task
4253 {
4254 let input_format = |path: &std::path::Path| {
4255 from.or_else(|| {
4256 Format::of_path(path).filter(|f| matches!(f, Format::Docx | Format::Md))
4257 })
4258 };
4259 value["args"]["old_format"] = serde_json::to_value(input_format(old)).expect("format");
4260 value["args"]["new_format"] = serde_json::to_value(input_format(new)).expect("format");
4261 value["args"]["output_format"] = serde_json::to_value(
4262 output_format(Task::Diff, output.as_deref(), *to)
4263 .ok()
4264 .flatten(),
4265 )
4266 .expect("format");
4267 }
4268 if let Command::Convert {
4269 output,
4270 markdown,
4271 pdf,
4272 png,
4273 ..
4274 } = &task
4275 {
4276 let alias = pdf
4277 .then_some(Format::Pdf)
4278 .or_else(|| png.then_some(Format::Png));
4279 value["args"]["output_format"] = serde_json::to_value(
4280 output_format(Task::Convert, output.as_deref(), markdown.to.or(alias))
4281 .ok()
4282 .flatten(),
4283 )
4284 .expect("format");
4285 }
4286 if let Command::Edit {
4287 file,
4288 options,
4289 plan,
4290 operations,
4291 ..
4292 }
4293 | Command::Add {
4294 file,
4295 options,
4296 plan,
4297 operations,
4298 ..
4299 } = &task
4300 {
4301 let recording = plan.is_some() && !operations.is_empty();
4302 let (output, out_dir) = match options.target(file) {
4303 _ if recording => (None, None),
4304 EditTarget::Single(path) => (Some(path), None),
4305 EditTarget::Bundle(dir) => (None, Some(dir)),
4306 };
4307 let slashed = |path: Option<&std::path::PathBuf>| {
4308 path.map(|p| serde_json::Value::String(slash_path(p)))
4309 .unwrap_or(serde_json::Value::Null)
4310 };
4311 value["args"]["plan"] = slashed(plan.as_ref());
4312 value["args"]["output"] = slashed(output.as_ref());
4313 value["args"]["out_dir"] = slashed(out_dir.as_ref());
4314 value["args"]["author_given"] = serde_json::Value::Bool(options.author_given);
4317 }
4318 let written = match &task {
4319 Command::Accept {
4320 file,
4321 output,
4322 in_place,
4323 ..
4324 } => {
4325 if *in_place {
4326 value["args"]["output"] = serde_json::Value::String(slash_path(file));
4327 }
4328 Some((
4329 Task::Accept,
4330 if *in_place {
4331 Some(file.as_path())
4332 } else {
4333 output.as_deref()
4334 },
4335 ))
4336 }
4337 Command::Reject {
4338 file,
4339 output,
4340 in_place,
4341 ..
4342 } => {
4343 if *in_place {
4344 value["args"]["output"] = serde_json::Value::String(slash_path(file));
4345 }
4346 Some((
4347 Task::Reject,
4348 if *in_place {
4349 Some(file.as_path())
4350 } else {
4351 output.as_deref()
4352 },
4353 ))
4354 }
4355 Command::Append { output, .. } => Some((Task::Append, Some(output.as_path()))),
4356 Command::Scrub { output, .. } => Some((Task::Scrub, Some(output.as_path()))),
4357 Command::Read { output, .. } => Some((Task::Read, output.as_deref())),
4358 _ => None,
4359 };
4360 if let Some((writer, output)) = written {
4361 let format = if matches!(
4364 &task,
4365 Command::Accept { in_place: true, .. } | Command::Reject { in_place: true, .. }
4366 ) {
4367 Some(Format::Docx)
4368 } else {
4369 output_format(writer, output, None).ok().flatten()
4370 };
4371 value["args"]["output_format"] = serde_json::to_value(format).expect("format");
4372 }
4373 value["exit_code"] = 0.into();
4374 Ok(value)
4375}
4376
4377fn parse_implicit_compare_json(
4378 command: &mut clap::Command,
4379 matches: &clap::ArgMatches,
4380 model: &clap::Command,
4381 program: &str,
4382 accepts: &dyn Fn(&str) -> bool,
4383) -> Result<serde_json::Value, clap::Error> {
4384 let mut compare = CompareArgs::from_arg_matches(matches)?;
4385 fill_date(&mut compare.datetime);
4386 if let Some(name) = compare
4387 .original_pos
4388 .as_ref()
4389 .and_then(|p| p.to_str())
4390 .and_then(|name| model.find_subcommand(name))
4391 .map(|task| task.get_name().to_string())
4392 .filter(|name| !accepts(name))
4393 {
4394 return Err(missing_task(command, program, &name));
4395 }
4396 if compare.modified.is_none() && compare.modified_pos.is_none() {
4397 if !accepts("read") {
4398 return Err(command.error(
4399 clap::error::ErrorKind::InvalidSubcommand,
4400 "this task is not supported by this adapter",
4401 ));
4402 }
4403 let mut args = serde_json::to_value(&compare.read).expect("UTF-8 CLI arguments");
4404 args["file"] =
4405 serde_json::to_value(compare.original.as_ref().or(compare.original_pos.as_ref()))
4406 .expect("UTF-8 path");
4407 args["output"] = serde_json::to_value(&compare.output).expect("UTF-8 path");
4408 args["force"] = compare.force.into();
4409 args["output_format"] = serde_json::to_value(
4410 output_format(Task::Read, compare.output.as_deref(), None)
4411 .ok()
4412 .flatten(),
4413 )
4414 .expect("format");
4415 return Ok(serde_json::json!({"exit_code": 0, "command": "read", "args": args}));
4416 }
4417 compare.view_given = view_given(matches);
4418 let args = compare_json(&compare);
4419 if view_is_output(&args) && !accepts("read") {
4420 return Err(view_not_supported(command));
4421 }
4422 Ok(serde_json::json!({"exit_code": 0, "command": "compare", "args": args}))
4423}
4424
4425pub fn parse_json(arguments: &[String], program: &str, supported: &[String]) -> String {
4442 let model = top_level_command();
4443 let accepts = |name: &str| supported.is_empty() || supported.iter().any(|s| s == name);
4444 let mut command = clap::Command::new(program.to_string())
4447 .version(env!("JUBARTE_BUILD_VERSION"))
4448 .help_template("{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{all-args}{after-help}")
4449 .about("Read, edit, compare and render Word documents")
4450 .color(clap::ColorChoice::Never)
4451 .styles(styles())
4452 .term_width(88)
4453 .subcommand_help_heading("Tasks")
4454 .arg_required_else_help(true)
4455 .subcommands(
4456 model
4457 .get_subcommands()
4458 .filter(|s| accepts(s.get_name()) || s.get_name() == "__edit-v2" && accepts("edit"))
4459 .cloned(),
4460 );
4461 if accepts("compare") {
4462 command = command
4463 .args(model.get_arguments().cloned())
4464 .groups(model.get_groups().cloned())
4465 .args_conflicts_with_subcommands(true)
4466 .subcommand_negates_reqs(true);
4467 } else {
4468 command = command
4470 .args(model.get_arguments().filter(|a| a.is_global_set()).cloned())
4471 .args_conflicts_with_subcommands(true)
4472 .subcommand_required(true);
4473 }
4474 let examples: Vec<String> = [
4475 ("compare", "compare old.docx new.docx -o redline.docx"),
4476 ("read", "contract.docx"),
4477 ("read", "read contract.docx --json"),
4478 ("diff", "diff old.docx new.docx --format github"),
4479 ("convert", "convert contract.docx -o contract.pdf"),
4480 ]
4481 .into_iter()
4482 .filter(|(name, _)| accepts(name))
4483 .map(|(_, example)| format!(" {program} {example}"))
4484 .collect();
4485 command = command.after_help(format!(
4486 "Examples:\n{}\n\nRun {program} <task> --help for task options.",
4487 examples.join("\n")
4488 ));
4489 let argv = std::iter::once(program.to_string()).chain(arguments.iter().cloned());
4490 let mut quiet = false;
4491 let result = (|| {
4492 if let Some(name) = arguments
4494 .iter()
4495 .take_while(|token| *token != "--")
4496 .find(|token| !token.starts_with('-'))
4497 .and_then(|name| model.find_subcommand(name))
4498 .map(|task| task.get_name().to_string())
4499 .filter(|name| !accepts(name))
4500 {
4501 return Err(missing_task(&mut command, program, &name));
4502 }
4503 let tokens: Vec<String> = hoist_quiet(&command, &argv.collect::<Vec<_>>());
4504 let tokens: Vec<String> = edit_actions::route(
4505 &tokens
4506 .iter()
4507 .map(std::ffi::OsString::from)
4508 .collect::<Vec<_>>(),
4509 &command,
4510 )
4511 .into_iter()
4512 .map(|s| s.to_string_lossy().into_owned())
4513 .collect();
4514 let matches = command
4515 .try_get_matches_from_mut(tokens.clone())
4516 .map_err(|e| usage_error(&command, &tokens, e))?;
4517 validate_matches(&matches, &mut command)?;
4518 quiet = matches.get_flag("quiet");
4519 if matches.subcommand().is_some() {
4520 parse_subcommand_json(&mut command, &matches, arguments, &accepts)
4521 } else {
4522 parse_implicit_compare_json(&mut command, &matches, &model, program, &accepts)
4523 }
4524 })();
4525 match result {
4526 Ok(mut value) => {
4527 value["args"]["quiet"] = quiet.into();
4528 value["notes"] = notes(arguments).into();
4529 value.to_string()
4530 }
4531 Err(error) => match removed_spellings(arguments.iter().map(String::as_str)).first() {
4532 Some((old, now)) => {
4533 let removed = removed_error(old, now);
4534 let mut value = serde_json::json!({
4535 "exit_code": 2,
4536 "stream": "stderr",
4537 "text": format!("{removed}\n"),
4538 });
4539 if wants_json(arguments) {
4541 let message = removed.strip_prefix("error: ").unwrap_or(&removed);
4542 value["json"] = removed_json_error(&error, arguments, program, message).into();
4543 }
4544 value.to_string()
4545 }
4546 None => {
4547 let mut value: serde_json::Value =
4548 serde_json::from_str(&error_json(&error)).unwrap_or_default();
4549 value["notes"] = notes(arguments).into();
4553 if wants_json(arguments)
4554 && let Some(line) = usage_json_error(&error, arguments, program)
4555 {
4556 value["json"] = line.into();
4557 }
4558 value.to_string()
4559 }
4560 },
4561 }
4562}
4563
4564#[cfg(test)]
4565mod slash_path_tests {
4566 use super::{slash_path, unverbatimed};
4567 use std::path::Path;
4568
4569 #[test]
4570 fn slash_path_uses_forward_slashes() {
4571 assert_eq!(slash_path(Path::new(r"dir\sub\name.md")), "dir/sub/name.md");
4572 assert_eq!(slash_path(Path::new("plain")), "plain");
4573 }
4574
4575 #[test]
4578 fn slash_path_canonical_drive_letter_spells_agent_facing() {
4579 let formatted = slash_path(Path::new(r"C:\Users\Alice\out.docx"));
4580 assert_eq!(formatted, "C:/Users/Alice/out.docx");
4581 assert!(!formatted.contains('\\'), "backslashes: {formatted}");
4582 }
4583
4584 #[test]
4585 fn unverbatimed_keeps_every_nonverbatim_path() {
4586 for path in ["plain", r"dir\sub", r"C:\a\b", r"\\server\share\x"] {
4589 assert_eq!(unverbatimed(Path::new(path)), None, "{path}");
4590 }
4591 }
4592
4593 #[cfg(not(windows))]
4594 #[test]
4595 fn a_verbatim_literal_is_an_ordinary_name_off_windows() {
4596 for path in [r"\\?\C:\a\b", r"\\?\UNC\s\sh\x"] {
4597 assert_eq!(unverbatimed(Path::new(path)), None, "{path}");
4598 }
4599 }
4600
4601 #[cfg(windows)]
4602 #[test]
4603 fn unverbatimed_strips_every_verbatim_prefix_kind() {
4604 for (path, stripped) in [
4605 (r"\\?\C:\a\b", "C:/a/b"),
4606 (r"\\?\c:\a", "C:/a"),
4607 (r"\\?\C:", "C:"),
4608 (r"\\?\UNC\server\share\x", "//server/share/x"),
4609 (r"\\?\GLOBALROOT\Device\Foo", "GLOBALROOT/Device/Foo"),
4610 ] {
4611 assert_eq!(slash_path(Path::new(path)), stripped, "{path}");
4612 assert!(!slash_path(Path::new(path)).contains("//?"), "{path}");
4613 }
4614 }
4615
4616 #[cfg(windows)]
4617 #[test]
4618 fn unverbatimed_returns_the_stripped_components() {
4619 assert_eq!(
4620 unverbatimed(Path::new(r"\\?\C:\a\b")).as_deref(),
4621 Some(Path::new(r"C:\a\b"))
4622 );
4623 assert_eq!(
4624 unverbatimed(Path::new(r"\\?\UNC\server\share\x")).as_deref(),
4625 Some(Path::new(r"\\server\share\x"))
4626 );
4627 }
4628}
4629
4630#[cfg(test)]
4631#[cfg_attr(all(coverage_nightly, test), coverage(off))]
4632mod parse_branch_tests {
4633 use super::*;
4634
4635 fn parse(line: &str) -> Result<(), String> {
4636 let mut argv = vec!["jubarte".to_string()];
4637 argv.extend(line.split(' ').map(str::to_string));
4638 Cli::try_parse_from(argv)
4639 .map(drop)
4640 .map_err(|e| e.to_string())
4641 }
4642
4643 const LINES: &[(&str, &str)] = &[
4646 (
4647 "edit x.docx -p p1 --anchor a --anchor b --content c",
4648 "-p p1: --anchor given twice",
4649 ),
4650 (
4651 "edit x.docx -p p1 --content a --content b",
4652 "-p p1: --content given twice",
4653 ),
4654 (
4655 "edit x.docx -p p1 --anchor a --occurrence 2 --occurrence 3 --content c",
4656 "-p p1: --occurrence given twice",
4657 ),
4658 (
4659 "edit x.docx --anchor a -p p1 --content c",
4660 "--anchor comes before the first -p/--location",
4661 ),
4662 (
4663 "edit x.docx -p p1 --occurrence 2 --content c",
4664 "-p p1: --occurrence must come after --anchor",
4665 ),
4666 (
4667 "edit x.docx -p c1 --reply hi --reply again",
4668 "-p c1: --reply given twice",
4669 ),
4670 ("edit x.docx -p c1 --resolve", ""),
4671 (
4672 "edit --plan doc.docx",
4673 "--plan doc.docx names a Word document",
4674 ),
4675 (
4676 "edit --plan=doc.docx",
4677 "--plan doc.docx names a Word document",
4678 ),
4679 (
4680 "edit --out-dir out.docx",
4681 "--out-dir out.docx names a Word document",
4682 ),
4683 ("convert a.docx -o .md", ""),
4684 ("convert a.md --from docx -o b.docx", ""),
4685 (
4686 "convert a.docx --pdf --pages 1,x",
4687 "'x' is not a page number",
4688 ),
4689 ("convert a.docx --pdf --pages 1-3,5", ""),
4690 ("read a.docx --for-edit -o out.md", "--for-edit prints JSON"),
4691 (
4692 "read a.docx --tables -o out.json",
4693 "--tables writes the grids as text",
4694 ),
4695 (
4696 "read a.docx --ignore-case",
4697 "--ignore-case needs --find TEXT or --regex PATTERN",
4698 ),
4699 ("read a.docx --ignore-case --for-edit", ""),
4700 ("compare original", "compare needs <MODIFIED>"),
4701 ("diff a.docx b.docx --format patch --columns 80", ""),
4702 (
4703 "diff a.docx b.docx --context 3",
4704 "--context requires a text diff format",
4705 ),
4706 (
4707 "diff a.docx b.docx --full-lines",
4708 "--full-lines requires a text diff format",
4709 ),
4710 (
4711 "edit insert x.docx --kind paragraph --at p1 --text hi -o y.docx",
4712 "--kind paragraph requires --position",
4713 ),
4714 (
4715 "edit insert x.docx --kind text --at p1 --text hi -o y.docx",
4716 "--kind paragraph requires --position",
4717 ),
4718 (
4719 "edit insert x.docx --kind text --position after --at p1 --text hi -o y.docx",
4720 "--kind paragraph requires --position",
4721 ),
4722 (
4723 "edit insert x.docx --kind paragraph --position after --at p1 --text hi -o y.docx",
4724 "",
4725 ),
4726 (
4727 "edit insert x.docx --kind text --edge end --at p1 --text hi -o y.docx",
4728 "",
4729 ),
4730 ("edit -q replace x.docx --find a --text b -o y.docx", ""),
4731 (
4732 "edit replace x.docx --find a --text b",
4733 "writes require -o FILE",
4734 ),
4735 (
4736 "edit replace x.docx --find a --text b --dry-run --expect-sha256 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
4737 "",
4738 ),
4739 (
4740 "edit replace x.docx --find a --text b --dry-run --expect-sha256 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
4741 "64 lowercase hexadecimal",
4742 ),
4743 (
4744 "edit replace x.docx --find a --text b --dry-run --expect-sha256 abc",
4745 "64 lowercase hexadecimal",
4746 ),
4747 ];
4748
4749 #[test]
4750 fn command_lines_parse_or_say_why_not() {
4751 for (line, refusal) in LINES {
4752 match parse(line) {
4753 Ok(()) => assert!(refusal.is_empty(), "{line} parsed"),
4754 Err(e) => {
4755 assert!(!refusal.is_empty(), "{line}: {e}");
4756 assert!(e.contains(refusal), "{line}: {e}");
4757 }
4758 }
4759 }
4760 }
4761
4762 #[test]
4763 fn json_errors_take_a_leading_upper_case_code() {
4764 let code = |message: &str| -> String {
4765 let v: serde_json::Value =
4766 serde_json::from_str(&runtime_json_error(message, 1)).unwrap();
4767 v["error"]["code"].as_str().unwrap().to_string()
4768 };
4769 assert_eq!(code("STALE_SOURCE: x"), "STALE_SOURCE");
4770 assert_eq!(code("AB_1: x"), "AB_1");
4771 assert_eq!(code("ab: x"), "ERROR");
4772 assert_eq!(code("Abc1: x"), "ERROR");
4773 assert_eq!(code("AB: x"), "ERROR");
4774 assert_eq!(code("nothing"), "ERROR");
4775 }
4776}