pub use crate::edit::flags::FlagOp;
pub mod edit_actions;
pub mod edit_template;
use clap::{CommandFactory, FromArgMatches, Parser};
use serde::Serialize;
use std::path::{Path, PathBuf};
pub(crate) use crate::util::datetime::parse_datetime;
#[derive(Parser, Debug, Serialize)]
#[command(
name = "jubarte", version = env!("JUBARTE_BUILD_VERSION"),
help_template = "{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{all-args}{after-help}",
about = "Read, edit, compare and render Word documents",
long_about = None,
styles = styles(),
term_width = 88,
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true,
arg_required_else_help = true,
subcommand_help_heading = "Tasks",
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.",
)]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Command>,
#[arg(
short = 'q',
long,
global = true,
overrides_with = "quiet",
help_heading = None::<&str>
)]
pub quiet: bool,
#[command(flatten)]
#[serde(flatten)]
pub compare: CompareArgs,
}
#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
#[group(id = "read_options", multiple = true)]
pub struct ReadArgs {
#[arg(long, value_enum, value_name = "CHOICE", help_heading = "Read options")]
pub track_changes: Option<TrackChanges>,
#[arg(
long,
value_enum,
default_value_t = CommentsArg::Inline,
value_name = "MODE",
help_heading = "Read options"
)]
pub comments: CommentsArg,
#[arg(long, help_heading = "Read options")]
pub dates: bool,
#[arg(long, help_heading = "Read options")]
pub no_page_markers: bool,
#[arg(
short = 'p',
long = "paragraphs",
visible_alias = "select",
value_name = "SPEC",
conflicts_with_all = ["head", "tail"],
action = clap::ArgAction::Append,
help_heading = "Read options"
)]
#[serde(serialize_with = "serialize_paragraph_spec")]
pub paragraphs: Vec<String>,
#[arg(
long,
value_name = "N",
conflicts_with = "tail",
help_heading = "Read options"
)]
pub head: Option<usize>,
#[arg(long, value_name = "N", help_heading = "Read options")]
pub tail: Option<usize>,
#[arg(
long,
conflicts_with_all = ["paragraphs", "head", "tail"],
help_heading = "Read options"
)]
pub changed: bool,
#[arg(
long,
value_name = "AUTHOR",
requires = "changed",
value_parser = parse_author,
help_heading = "Read options"
)]
pub by: Option<String>,
#[arg(long, help_heading = "Read options")]
pub json: bool,
#[arg(
long,
conflicts_with_all = ["json", "head", "tail", "changed", "by"],
help_heading = "Read options"
)]
pub tables: bool,
#[arg(long, conflicts_with = "track_changes", help_heading = "Read options")]
pub for_edit: bool,
#[arg(
long,
value_name = "ID",
requires = "for_edit",
help_heading = "Read options"
)]
pub accept_change: Vec<String>,
#[arg(
long,
value_name = "ID",
requires = "for_edit",
help_heading = "Read options"
)]
pub reject_change: Vec<String>,
#[arg(
long,
value_enum,
value_name = "MODE",
requires = "for_edit",
help_heading = "Read options"
)]
pub existing_revisions: Option<ExistingArg>,
#[arg(
long,
value_enum,
value_name = "CHOICE",
requires = "for_edit",
help_heading = "Read options"
)]
pub track: Option<TrackArg>,
#[arg(
long,
value_name = "TEXT",
conflicts_with = "regex",
help_heading = "Read options"
)]
pub find: Option<String>,
#[arg(
long,
value_name = "PATTERN",
conflicts_with = "find",
help_heading = "Read options"
)]
pub regex: Option<String>,
#[arg(long, help_heading = "Read options")]
pub ignore_case: bool,
#[arg(
long,
value_name = "N",
requires = "for_edit",
help_heading = "Read options"
)]
pub context: Option<usize>,
#[arg(
long,
value_name = "N",
requires = "for_edit",
help_heading = "Read options"
)]
pub limit: Option<usize>,
#[arg(
long,
value_name = "N",
requires = "for_edit",
help_heading = "Read options"
)]
pub max_chars: Option<usize>,
#[arg(
long,
value_name = "TOKEN",
requires = "for_edit",
help_heading = "Read options"
)]
pub cursor: Option<String>,
#[arg(long, requires = "for_edit", help_heading = "Read options")]
pub all: bool,
}
impl ReadArgs {
pub fn paragraph_spec(&self) -> Option<String> {
(!self.paragraphs.is_empty()).then(|| self.paragraphs.join(","))
}
pub fn for_edit_request(&self) -> crate::edit::for_edit::ForEditRequest {
crate::edit::for_edit::ForEditRequest {
select: self.paragraph_spec(),
head: self.head,
tail: self.tail,
find: self.find.clone(),
regex: self.regex.clone(),
ignore_case: self.ignore_case,
changed: self.changed,
by: self.by.clone(),
context: self.context.unwrap_or(0),
limit: self.limit,
max_chars: self.max_chars,
all: self.all,
cursor: self.cursor.clone(),
accept: self.accept_change.clone(),
reject: self.reject_change.clone(),
existing_revisions: self
.existing_revisions
.and_then(ExistingArg::plan_value)
.unwrap_or(crate::edit::ExistingRevisions::Keep),
track: self.track.unwrap_or_default() == TrackArg::On,
..Default::default()
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CommentsArg {
#[default]
Inline,
None,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TrackArg {
#[default]
On,
Off,
}
impl TrackArg {
pub fn from_choice(choice: &str) -> Option<Self> {
match choice {
"on" => Some(Self::On),
"off" => Some(Self::Off),
_ => None,
}
}
}
#[derive(clap::Args, Debug, Serialize)]
pub struct EditOptions {
#[arg(short = 'a', long, value_name = "NAME", default_value = "Jubarte")]
pub author: String,
#[arg(skip)]
#[serde(skip)]
pub author_given: bool,
#[arg(short = 'd', long = "datetime", value_name = "ISO8601", value_parser = parse_datetime)]
pub datetime: Option<String>,
#[arg(long, conflicts_with = "editing_mode")]
pub suggesting_mode: bool,
#[arg(long)]
pub editing_mode: bool,
#[arg(long, value_enum, value_name = "MODE", default_value_t = ExistingArg::Auto)]
pub existing_revisions: ExistingArg,
#[arg(long, conflicts_with_all = ["output", "out_dir"])]
pub in_place: bool,
#[arg(
short = 'o',
long,
value_name = "FILE.docx",
conflicts_with = "out_dir"
)]
pub output: Option<PathBuf>,
#[arg(long, value_name = "DIR", num_args = 0..=1)]
pub out_dir: Option<Option<PathBuf>>,
#[arg(long)]
pub force: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EditTarget {
Single(PathBuf),
Bundle(PathBuf),
}
impl EditOptions {
pub fn target(&self, file: &Path) -> EditTarget {
if self.in_place {
return EditTarget::Single(file.to_path_buf());
}
let beside = |name: String| match file.parent().filter(|p| !p.as_os_str().is_empty()) {
Some(dir) => dir.join(name),
None => PathBuf::from(name),
};
let stem = file.file_stem().map_or_else(
|| "document".to_string(),
|s| s.to_string_lossy().into_owned(),
);
match (&self.out_dir, &self.output) {
(Some(Some(dir)), _) => EditTarget::Bundle(dir.clone()),
(Some(None), _) => EditTarget::Bundle(beside(format!("{stem}.edit"))),
(None, Some(output)) => EditTarget::Single(output.clone()),
(None, None) if stem.ends_with("_modified") => {
EditTarget::Single(beside(format!("{stem}.docx")))
}
(None, None) => EditTarget::Single(beside(format!("{stem}_modified.docx"))),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExistingArg {
#[default]
Auto,
Keep,
Accept,
Reject,
Refuse,
}
impl ExistingArg {
pub fn from_choice(choice: &str) -> Option<Self> {
match choice {
"auto" => Some(Self::Auto),
"keep" => Some(Self::Keep),
"accept" => Some(Self::Accept),
"reject" => Some(Self::Reject),
"refuse" => Some(Self::Refuse),
_ => None,
}
}
pub fn plan_value(self) -> Option<crate::edit::ExistingRevisions> {
use crate::edit::ExistingRevisions as E;
match self {
Self::Auto => None,
Self::Keep => Some(E::Keep),
Self::Accept => Some(E::Accept),
Self::Reject => Some(E::Reject),
Self::Refuse => Some(E::Refuse),
}
}
}
pub fn flag_operations(matches: &clap::ArgMatches) -> Result<Vec<FlagOp>, String> {
if matches.contains_id("anchor") && !matches.contains_id("location") {
return Err("--anchor needs -p WHERE (find it with: jubarte read FILE --find TEXT)".into());
}
let mut tokens: Vec<(usize, &str, Option<String>)> = Vec::new();
for name in ["location", "anchor", "content", "reply", "style"] {
if let (Some(indices), Some(values)) =
(matches.indices_of(name), matches.get_many::<String>(name))
{
tokens.extend(indices.zip(values).map(|(i, v)| (i, name, Some(v.clone()))));
}
}
if let (Some(indices), Some(values)) = (
matches.indices_of("occurrence"),
matches.get_many::<usize>("occurrence"),
) {
tokens.extend(
indices
.zip(values)
.map(|(i, v)| (i, "occurrence", Some(v.to_string()))),
);
}
for name in [
"delete", "resolve", "before", "comment", "accept", "reject", "strike", "restore",
"visible",
] {
if matches.try_get_many::<bool>(name).ok().flatten().is_none() {
continue;
}
if let Some(indices) = matches.indices_of(name) {
tokens.extend(indices.map(|i| (i, name, None)));
}
}
tokens.sort_by_key(|t| t.0);
let mut ops: Vec<FlagOp> = Vec::new();
for (_, name, value) in tokens {
if name == "location" {
ops.push(FlagOp {
at: value.unwrap_or_default(),
..FlagOp::default()
});
continue;
}
let Some(op) = ops.last_mut() else {
return Err(format!("--{name} comes before the first -p/--location"));
};
let twice = |what: &str| Err(format!("-p {}: --{what} given twice", op.at));
match name {
"anchor" if op.anchor.is_some() => return twice("anchor"),
"anchor" => op.anchor = value,
"occurrence" if op.occurrence.is_some() => return twice("occurrence"),
"occurrence" if op.anchor.is_none() => {
return Err(format!(
"-p {}: --occurrence must come after --anchor",
op.at
));
}
"occurrence" => {
op.occurrence = value.and_then(|v| v.parse().ok());
}
"content" if op.content.is_some() => return twice("content"),
"content" => op.content = value,
"reply" if op.reply.is_some() => return twice("reply"),
"reply" => op.reply = value,
"style" => op.styles.push(value.unwrap_or_default()),
"delete" => op.delete = true,
"resolve" => op.resolve = true,
"before" => op.before = true,
"comment" => op.comment = true,
"accept" => op.accept = true,
"reject" => op.reject = true,
"strike" => op.strike = true,
"restore" => op.restore = true,
"visible" => op.visible = true,
_ => {}
}
}
Ok(ops)
}
fn plan_path() -> impl clap::builder::TypedValueParser<Value = PathBuf> {
use clap::builder::TypedValueParser as _;
clap::builder::OsStringValueParser::new().try_map(|value| {
let text = value.to_string_lossy();
if text.ends_with('/') || cfg!(windows) && text.ends_with('\\') {
return Err(format!(
"{text} ends in a separator, so it names a folder; give the plan's file, such as PLAN.json"
));
}
Ok(PathBuf::from(value))
})
}
fn hoist_quiet<T: AsRef<std::ffi::OsStr> + Clone>(
command: &clap::Command,
arguments: &[T],
) -> Vec<T> {
let is_quiet = |a: &T| match a.as_ref().to_str() {
Some("--quiet") => true,
Some(short) => {
short.len() > 1 && short.starts_with('-') && short[1..].bytes().all(|b| b == b'q')
}
None => false,
};
let flags = arguments.iter().skip(1).take_while(|a| is_quiet(a)).count();
let task = arguments.get(1 + flags).and_then(|a| a.as_ref().to_str());
if flags > 0 && task == Some("help") {
let mut help = vec![arguments[0].clone()];
help.extend_from_slice(&arguments[1 + flags..]);
return help;
}
if flags == 0 || task.is_none_or(|name| command.find_subcommand(name).is_none()) {
return arguments.to_vec();
}
let mut hoisted = Vec::with_capacity(arguments.len());
hoisted.push(arguments[0].clone());
hoisted.push(arguments[1 + flags].clone());
hoisted.extend_from_slice(&arguments[1..1 + flags]);
hoisted.extend_from_slice(&arguments[2 + flags..]);
hoisted
}
fn fill_date(date: &mut Option<String>) {
if date.is_none() {
*date = Some(crate::util::datetime::utc_now_iso8601());
}
}
fn fill_task_date(task: &mut Command) {
match task {
Command::Compare(compare) => fill_date(&mut compare.datetime),
Command::Diff { datetime: date, .. } => fill_date(date),
_ => {}
}
}
pub fn slash_path(path: &Path) -> String {
let path = unverbatimed(path).unwrap_or_else(|| path.to_path_buf());
path.to_string_lossy().replace('\\', "/")
}
fn unverbatimed(path: &Path) -> Option<PathBuf> {
let mut components = path.components();
let (mut stripped, keeps_root) = verbatim_head(components.next())?;
for component in components {
if keeps_root || !matches!(component, std::path::Component::RootDir) {
stripped.push(component.as_os_str());
}
}
Some(stripped)
}
#[cfg(windows)]
fn verbatim_head(component: Option<std::path::Component>) -> Option<(PathBuf, bool)> {
use std::path::{Component, Prefix};
match component {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::VerbatimDisk(letter) => Some((
PathBuf::from(format!("{}:", (letter as char).to_ascii_uppercase())),
true,
)),
Prefix::VerbatimUNC(server, share) => {
let mut head = PathBuf::from(r"\\");
head.push(server);
head.push(share);
Some((head, true))
}
Prefix::Verbatim(rest) => Some((PathBuf::from(rest), false)),
_ => None,
},
_ => None,
}
}
#[cfg(not(windows))]
fn verbatim_head(_component: Option<std::path::Component>) -> Option<(PathBuf, bool)> {
None
}
fn resolve_plan(task: &mut Command) {
let (Command::Edit {
file,
plan: Some(plan),
plan_default,
..
}
| Command::Add {
file,
plan: Some(plan),
plan_default,
..
}) = task
else {
return;
};
if !plan.as_os_str().is_empty() {
return;
}
let stem = file.file_stem().map_or_else(
|| "document".to_string(),
|s| s.to_string_lossy().into_owned(),
);
let name = format!("{stem}_plan.json");
*plan = match file.parent().filter(|p| !p.as_os_str().is_empty()) {
Some(dir) => dir.join(name),
None => PathBuf::from(name),
};
*plan_default = true;
}
fn names_word_document(path: &Path) -> bool {
path.file_name().is_some_and(|name| {
let name = name.to_string_lossy().to_ascii_lowercase();
[".docx", ".docm", ".dotx", ".dotm", ".doc"]
.iter()
.any(|ext| name.ends_with(ext))
})
}
fn swallowed_file(flag: &str, value: &Path) -> String {
let instead = if flag == "--plan" { "PLAN.json" } else { "DIR" };
format!(
"{flag} {} names a Word document; put FILE before {flag}, or write {flag}={instead}",
value.display()
)
}
fn usage_error(command: &clap::Command, tokens: &[String], mut error: clap::Error) -> clap::Error {
if error.kind() == clap::error::ErrorKind::ArgumentConflict {
use clap::error::ContextKind;
let conflicts = [ContextKind::InvalidArg, ContextKind::PriorArg]
.into_iter()
.filter_map(|kind| error.get(kind))
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(" ");
let names = |flag: &&str| conflicts.split_whitespace().any(|word| word == *flag);
if names(&"--track-changes") && names(&"--for-edit") {
return read_usage_error(command, read_view_conflict("--track-changes"));
}
if names(&"--tables") {
error.insert(
ContextKind::Usage,
clap::error::ContextValue::StyledStr(
format!("Usage: {} read [OPTIONS] <FILE>", command.get_name()).into(),
),
);
}
}
if error.kind() != clap::error::ErrorKind::MissingRequiredArgument {
return error;
}
let Some(at) = tokens.iter().skip(1).position(|t| !t.starts_with('-')) else {
return error;
};
let name = tokens[at + 1].as_str();
let Some(sub) = command
.find_subcommand(name)
.filter(|_| matches!(name, "edit" | "add"))
else {
return error;
};
let options = tokens[at + 2..].iter().take_while(|t| *t != "--");
let mut previous: Option<&str> = None;
let mut found = None;
for token in options {
let pair = match token.split_once('=') {
Some((flag, value)) if flag.starts_with("--") => Some((flag, value)),
_ => previous.map(|flag| (flag, token.as_str())),
};
if let Some((flag, value)) = pair
&& matches!(flag, "--plan" | "--out-dir")
&& !value.starts_with('-')
&& names_word_document(Path::new(value))
{
found = Some(swallowed_file(flag, Path::new(value)));
break;
}
previous = Some(token.as_str()).filter(|t| matches!(*t, "--plan" | "--out-dir"));
}
let Some(message) = found else {
return error;
};
let mut task = sub.clone();
task.set_bin_name(format!("{} {name}", command.get_name()));
task.error(clap::error::ErrorKind::ArgumentConflict, message)
}
fn fill_flag_operations(
task: &mut Command,
matches: &clap::ArgMatches,
model: &mut clap::Command,
) -> Result<(), clap::Error> {
let (name, operations, options) = match task {
Command::Edit {
operations,
options,
..
} => ("edit", operations, options),
Command::Add {
operations,
options,
..
} => ("add", operations, options),
_ => return Ok(()),
};
let Some(sub) = matches.subcommand_matches(name) else {
return Ok(());
};
*operations = flag_operations(sub)
.map_err(|m| model.error(clap::error::ErrorKind::ArgumentConflict, m))?;
options.author_given =
sub.value_source("author") == Some(clap::parser::ValueSource::CommandLine);
env_author_fill(&mut options.author, &mut options.author_given)
.map_err(|m| model.error(clap::error::ErrorKind::ValueValidation, m))?;
Ok(())
}
fn env_author_fill(author: &mut String, given: &mut bool) -> Result<(), String> {
if *given {
return Ok(());
}
let Some(name) = std::env::var("JUBARTE_AUTHOR")
.ok()
.filter(|name| !name.is_empty())
else {
return Ok(());
};
*author = parse_author(&name).map_err(|m| format!("JUBARTE_AUTHOR: {m}"))?;
*given = true;
Ok(())
}
pub fn env_timeout() -> Result<Option<std::time::Duration>, String> {
let Some(value) = std::env::var_os("JUBARTE_TIMEOUT") else {
return Ok(None);
};
let value = value.into_string().map_err(|raw| {
format!(
"JUBARTE_TIMEOUT: '{}' is not a number of seconds",
raw.to_string_lossy()
)
})?;
if value.is_empty() {
return Ok(None);
}
parse_timeout(&value)
.map(Some)
.map_err(|m| format!("JUBARTE_TIMEOUT: {m}"))
}
#[derive(clap::Args, Debug, Serialize)]
#[group(id = "compare_options", multiple = true)]
pub struct CompareArgs {
#[arg(value_name = "ORIGINAL", required_unless_present = "original")]
pub original_pos: Option<PathBuf>,
#[arg(value_name = "MODIFIED")]
pub modified_pos: Option<PathBuf>,
#[arg(short = 'b', long = "original", value_name = "FILE")]
pub original: Option<PathBuf>,
#[arg(short = 'm', long = "modified", value_name = "FILE")]
pub modified: Option<PathBuf>,
#[arg(short = 'o', long, value_name = "FILE")]
pub output: Option<PathBuf>,
#[arg(short = 'a', long, value_name = "NAME", default_value = "Jubarte")]
pub author: String,
#[arg(short = 'd', long = "datetime", value_name = "ISO8601", value_parser = parse_datetime)]
pub datetime: Option<String>,
#[arg(long)]
pub force: bool,
#[arg(long, value_name = "RATIO", value_parser = parse_threshold)]
pub detail_threshold: Option<f64>,
#[arg(long, value_enum, value_name = "MODE", default_value_t = CompareMode::Word)]
pub mode: CompareMode,
#[arg(long, hide = true)]
pub powertools_faithful: bool,
#[arg(long, hide = true)]
pub no_paragraph_merge: bool,
#[arg(long, value_name = "FILE", help_heading = "Markdown inputs")]
pub reference_doc: Option<PathBuf>,
#[arg(long, help_heading = "Markdown inputs")]
pub critic: bool,
#[arg(long, value_name = "DIR", help_heading = "Markdown inputs")]
pub resource_path: Option<PathBuf>,
#[command(flatten)]
#[serde(flatten)]
pub render: RenderArgs,
#[command(flatten)]
#[serde(skip)]
pub read: ReadArgs,
#[arg(skip)]
pub view_given: bool,
}
pub fn top_level_command() -> clap::Command {
let hidden: std::collections::HashSet<clap::Id> =
<CompareArgs as clap::Args>::augment_args(clap::Command::new("shorthand"))
.get_arguments()
.map(|a| a.get_id().clone())
.collect();
Cli::command().mut_args(move |a| {
if hidden.contains(a.get_id()) {
a.hide(true)
} else {
a
}
})
}
impl std::ops::Deref for Cli {
type Target = CompareArgs;
fn deref(&self) -> &Self::Target {
&self.compare
}
}
#[derive(clap::Subcommand, Debug, Serialize)]
#[serde(rename_all = "kebab-case", tag = "command", content = "args")]
pub enum Command {
#[command(name = "__edit-v2", hide = true, bin_name = "jubarte edit")]
#[serde(rename = "edit")]
TypedEdit(edit_actions::TypedEdit),
#[command(
name = "__edit-template",
hide = true,
bin_name = "jubarte edit template"
)]
#[serde(rename = "edit")]
EditTemplate(edit_template::TemplateDispatch),
#[command(
visible_alias = "redline",
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"
)]
Compare(CompareArgs),
Changes {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long)]
json: bool,
#[arg(long, value_name = "NAME", action = clap::ArgAction::Append)]
author: Vec<String>,
},
Accept {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long)]
in_place: bool,
#[arg(
short = 'o',
long,
value_name = "FILE",
required_unless_present = "in_place",
conflicts_with = "in_place"
)]
output: Option<PathBuf>,
#[arg(long)]
force: bool,
#[arg(long)]
keep_nested_comment: bool,
#[command(flatten)]
#[serde(flatten)]
selection: Selection,
#[command(flatten)]
#[serde(flatten)]
render: RenderArgs,
},
Reject {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long)]
in_place: bool,
#[arg(
short = 'o',
long,
value_name = "FILE",
required_unless_present = "in_place",
conflicts_with = "in_place"
)]
output: Option<PathBuf>,
#[arg(long)]
force: bool,
#[arg(long)]
keep_nested_comment: bool,
#[command(flatten)]
#[serde(flatten)]
selection: Selection,
#[command(flatten)]
#[serde(flatten)]
render: RenderArgs,
},
#[command(after_help = "Examples:\n \
jubarte convert contract.docx PDF, Word-style layout\n \
jubarte convert draft.md draft.docx, CriticMarkup as tracked changes\n \
jubarte convert draft.md -o draft.pdf the changes painted in a PDF\n \
jubarte convert draft.md --reference-doc house.docx -o draft.docx\n \
jubarte convert draft.md -t md --track-changes accept the text with every change accepted\n \
jubarte convert contract.docx -t md Markdown with <!-- page N of M --> lines\n \
jubarte convert old.doc old.docx (text, headings, lists, tables)\n \
jubarte convert notes.md --no-critic {++ and the other delimiters as text")]
Convert {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(short = 'o', long, value_name = "FILE")]
output: Option<PathBuf>,
#[arg(long)]
force: bool,
#[arg(long, hide = true)]
pdf: bool,
#[arg(long, hide = true)]
png: bool,
#[arg(long, value_name = "FILE")]
report: Option<PathBuf>,
#[arg(long)]
compress: bool,
#[arg(long, value_name = "FILE")]
font_report: Option<PathBuf>,
#[command(flatten)]
#[serde(flatten)]
markdown: MarkdownArgs,
#[command(flatten)]
#[serde(flatten)]
render: RenderArgs,
#[arg(long)]
fail_on_substitution: bool,
#[arg(long)]
update_fields: bool,
#[arg(long, value_name = "SECONDS", value_parser = parse_timeout)]
#[serde(serialize_with = "serialize_timeout")]
timeout: Option<std::time::Duration>,
},
#[command(after_help = "Examples:\n \
jubarte diff old.docx new.docx --format github Git/GitHub patch on stdout\n \
jubarte diff old.md new.md the patch on stdout\n \
jubarte diff old.md new.md --format critic CriticMarkup on stdout, as pandiff\n \
jubarte diff old.docx new.docx -o changes.patch the patch in a file\n \
jubarte compare old.md new.md -o changes.docx Word tracked changes (compare writes redlines)\n \
jubarte compare contract.docx edited.md -o redline.pdf\n \
the Markdown's edits painted on the Word document\n\n\
GIT:\n \
git config --global difftool.jubarte.cmd 'jubarte diff \"$LOCAL\" \"$REMOTE\"'\n \
git difftool -t jubarte -y -- '*.md'")]
Diff {
#[arg(value_name = "OLD")]
old: PathBuf,
#[arg(value_name = "NEW")]
new: PathBuf,
#[arg(short = 'o', long, value_name = "FILE", help_heading = "Review")]
output: Option<PathBuf>,
#[arg(long, value_enum, value_name = "FORMAT", default_value_t = PatchFormat::Patch, help_heading = "Review")]
format: PatchFormat,
#[arg(long, value_name = "N", default_value_t = crate::markdown::DEFAULT_COLUMNS, help_heading = "Paragraph patch")]
columns: usize,
#[arg(short = 'U', long, value_name = "LINES", default_value_t = 3, value_parser = parse_context, help_heading = "Review")]
context: usize,
#[arg(long, help_heading = "Review")]
accept_changes: bool,
#[arg(long, help_heading = "Review")]
full_lines: bool,
#[arg(
short = 't',
long = "to",
value_enum,
value_name = "FORMAT",
hide_possible_values = true,
help_heading = "Formats"
)]
to: Option<Format>,
#[arg(
short = 'f',
long = "from",
value_parser = input_format_parser(),
value_name = "FORMAT",
help_heading = "Formats"
)]
from: Option<Format>,
#[arg(long, help_heading = "Review")]
force: bool,
#[arg(
short = 'a',
long,
value_name = "NAME",
default_value = "Jubarte",
help_heading = "Paragraph patch"
)]
author: String,
#[arg(
short = 'd',
long = "datetime",
value_name = "ISO8601",
value_parser = parse_datetime,
help_heading = "Paragraph patch"
)]
datetime: Option<String>,
},
#[command(aliases = ["text", "inspect"])]
Read {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(short = 'o', long, value_name = "FILE")]
output: Option<PathBuf>,
#[arg(long)]
force: bool,
#[command(flatten)]
#[serde(flatten)]
args: ReadArgs,
},
#[command(after_help = "Examples:\n \
jubarte edit a.docx -p p12 --anchor \"thirty days\" --content \"forty-five days\" -a NAME\n \
jubarte edit a.docx -p p12 --anchor thirty --content \"thirty (30)\" -a NAME an insertion\n \
jubarte edit a.docx -p p7 --anchor \"at its sole discretion\" --delete -p p9 --delete -a NAME\n \
jubarte edit a.docx -p p3 --content \"The parties agree as follows.\" -a NAME rewrite\n \
jubarte edit a.docx -p p4 --anchor Fees --style bold -p p5 --style Heading2 -a NAME\n \
jubarte edit a.docx -p c5 --content \"Agreed.\" -p c7 --resolve -a NAME\n \
jubarte edit a.docx -p c5 --reply \"Agreed, will fix.\" -a NAME\n \
jubarte edit a.docx -p c5.text --content \"net 30\" -a NAME the text c5 covers\n \
jubarte edit a.docx -p r3 --accept -p header1.r1 --reject\n \
jubarte edit a.docx -p p3 --delete -o b.docx --pdf -a NAME b.docx and b.pdf\n \
jubarte edit a.docx --plan plan.json --out-dir review the bundle in review/\n \
jubarte edit a.docx --plan plan.json -p p3 --content \"New.\" record into plan.json\n \
jubarte edit a.docx --plan plan.json --consume apply plan.json, then delete it\n\n\
WHERE is an id from `jubarte read`: p12, header1, footer2.p1,\n\
t0.row1.cell2, c5 (a comment), c5.text (the text it covers) or r12\n\
(a revision).\n\n\
A plan (--plan plan.json) is a list of operations, applied all or none;\n\
`jubarte capabilities --json` lists every operation kind:\n \
{\"schema_version\": 1, \"source_sha256\": \"<sha256 from jubarte read>\", \"author\": \"Claude\",\n \
\"operations\": [\n \
{\"kind\": \"replace\", \"paragraph\": \"p1\", \"find\": \"his or her\", \"replacement\": \"their\"},\n \
{\"kind\": \"delete_paragraph\", \"paragraph\": \"p2\"}]}\n\n\
Desired-text plans (PlanV2), a separate workflow:\n \
jubarte edit template FILE --select p12,p20-p25 -o edits.json the paragraphs as they read\n \
(edit the desired text in edits.json)\n \
jubarte edit apply FILE --plan edits.json -o OUTPUT.docx tracked changes for the difference\n\n\
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.")]
Edit {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long, value_name = "PLAN.json", num_args = 0..=1, default_missing_value = "", value_parser = plan_path(), required_unless_present_any = ["location", "anchor"])]
plan: Option<PathBuf>,
#[arg(skip)]
plan_default: bool,
#[arg(long, requires = "plan")]
consume: bool,
#[arg(short = 'p', long = "location", value_name = "WHERE", action = clap::ArgAction::Append)]
location: Vec<String>,
#[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
anchor: Vec<String>,
#[arg(long, value_name = "N", action = clap::ArgAction::Append, value_parser = edit_actions::positive)]
occurrence: Vec<usize>,
#[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
content: Vec<String>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
delete: Vec<bool>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
resolve: Vec<bool>,
#[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
reply: Vec<String>,
#[arg(long, hide = true)]
rewrite_others_comments: bool,
#[arg(long)]
keep_others: bool,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
accept: Vec<bool>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
reject: Vec<bool>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
strike: Vec<bool>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
restore: Vec<bool>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
visible: Vec<bool>,
#[arg(long, value_name = "SPEC", action = clap::ArgAction::Append)]
style: Vec<String>,
#[command(flatten)]
#[serde(flatten)]
options: EditOptions,
#[arg(long)]
dry_run: bool,
#[arg(long)]
skip_failed: bool,
#[arg(long)]
require_change: bool,
#[arg(long)]
pdf: bool,
#[arg(long)]
png: bool,
#[arg(long, default_value_t = 96.0, value_name = "DPI", value_parser = parse_dpi, help_heading = "Rendering")]
dpi: f32,
#[arg(long, value_enum, default_value_t = Revisions::Conventional, requires_if("custom", "revision_palette"), help_heading = "Revision marks")]
revisions: Revisions,
#[cfg_attr(feature = "render", arg(long, value_name = "SPEC", value_parser = parse_palette, requires = "revisions", help_heading = "Revision marks"))]
#[cfg_attr(
not(feature = "render"),
arg(
long,
value_name = "SPEC",
requires = "revisions",
help_heading = "Revision marks"
)
)]
revision_palette: Option<String>,
#[arg(skip)]
operations: Vec<FlagOp>,
},
#[command(after_help = "Examples:\n \
jubarte add a.docx -p p12 --content \"Time is of the essence.\" -a NAME new paragraph after p12\n \
jubarte add a.docx -p p12 --content Recitals --before --style Heading2 -a NAME\n \
jubarte add a.docx -p p5 --anchor \"monthly fee\" --content \"Net of taxes?\" -a NAME a comment\n \
jubarte add a.docx -p p5 --comment --content \"Whole clause needs a cap.\" -a NAME\n \
jubarte add a.docx -p c5 --content \"Agreed, will fix.\" -a NAME a reply\n \
jubarte add a.docx -p c5 --reply \"Agreed, will fix.\" -a NAME the same reply\n \
jubarte add a.docx --plan plan.json -p p5 --comment --content \"Cap?\" record into plan.json")]
Add {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long, value_name = "PLAN.json", num_args = 0..=1, default_missing_value = "", value_parser = plan_path())]
plan: Option<PathBuf>,
#[arg(skip)]
plan_default: bool,
#[arg(long, requires = "plan")]
consume: bool,
#[arg(short = 'p', long = "location", value_name = "WHERE", action = clap::ArgAction::Append, required_unless_present_any = ["plan", "anchor"])]
location: Vec<String>,
#[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
anchor: Vec<String>,
#[arg(long, value_name = "N", action = clap::ArgAction::Append, value_parser = edit_actions::positive)]
occurrence: Vec<usize>,
#[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
content: Vec<String>,
#[arg(long, value_name = "TEXT", action = clap::ArgAction::Append)]
reply: Vec<String>,
#[arg(long)]
keep_others: bool,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
before: Vec<bool>,
#[arg(long, action = clap::ArgAction::Append, num_args = 0, default_missing_value = "true", value_parser = clap::value_parser!(bool))]
comment: Vec<bool>,
#[arg(long, value_name = "SPEC", action = clap::ArgAction::Append)]
style: Vec<String>,
#[command(flatten)]
#[serde(flatten)]
options: EditOptions,
#[arg(skip)]
operations: Vec<FlagOp>,
},
Capabilities {
#[arg(long)]
json: bool,
#[arg(long)]
operation: Option<String>,
#[arg(long)]
field: Option<String>,
#[arg(long, conflicts_with_all = ["operation", "field"])]
matrix: bool,
},
#[command(after_help = "Examples:\n \
jubarte self-update --check installed and latest versions\n \
jubarte self-update ask, then install the latest release\n \
jubarte self-update --yes install without asking\n \
jubarte self-update --version 0.9.3 install that release (also older)")]
#[command(display_order = 1000)]
SelfUpdate {
#[arg(long)]
check: bool,
#[arg(long, short = 'y')]
yes: bool,
#[arg(long, value_name = "VERSION")]
version: Option<String>,
},
#[command(after_help = "Examples:\n \
jubarte debug out.docx orphans, fields, bookmarks, package, structure\n \
jubarte debug out.docx --list the package's entries\n \
jubarte debug old.docx new.docx --list entries that differ\n \
jubarte debug old.docx new.docx -c elements -p document.xml\n \
jubarte debug out.docx -c ids revision/docPr ids used twice\n \
jubarte debug out.docx -c textbox -g FILENAME\n \
jubarte debug out.docx -c text paragraphs with ins/del marks\n \
jubarte debug a.docx b.docx -c text paragraphs that differ, per part\n \
jubarte debug a.docx b.docx -c runs the same, with direct formatting\n \
jubarte debug out.docx -c runs -g \"Q: Can\" one paragraph's runs, whole\n \
jubarte debug out.docx -c changes what each pPrChange/tcPrChange/… records\n \
jubarte debug a.docx b.docx -c styledefs style definitions that differ, paired by name\n \
jubarte debug a.docx b.docx -c numbering list levels that differ, by numId\n \
jubarte debug a.docx b.docx -c xml -p document.xml\n \
jubarte debug diff a.docx ours.docx word.docx element by element, three-way")]
#[command(
hide = true,
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true
)]
Debug {
#[command(subcommand)]
sub: Option<DebugCommand>,
#[arg(value_name = "FILE", num_args = 1..=2, required = true)]
files: Vec<PathBuf>,
#[arg(short = 'l', long)]
list: bool,
#[arg(short = 'c', long = "check", value_enum, value_delimiter = ',')]
checks: Vec<DebugCheck>,
#[arg(short = 'p', long, value_name = "NAME")]
part: Option<String>,
#[arg(short = 'g', long, value_name = "TEXT")]
grep: Option<String>,
#[arg(short = 'n', long, value_name = "N", default_value_t = 5)]
limit: usize,
#[arg(short = 'C', long, value_name = "N", default_value_t = 0)]
context: usize,
#[arg(long)]
full_lines: bool,
},
#[command(
name = "visual-diff",
alias = "diff-render",
after_help = "Examples:\n \
jubarte visual-diff before.docx after.docx changed pages on stdout\n \
jubarte visual-diff before.docx after.docx --out-dir diff PNGs of the changed pages and diff.json\n \
jubarte visual-diff a.docx b.docx --json the diff.json document on stdout\n\n\
With --out-dir, each page that differs is written as a-page-NN.png,\n\
b-page-NN.png and diff-page-NN.png (b's page with the changed pixels\n\
magenta and boxed); diff.json lists every page with its changed_ratio,\n\
bbox and, for a page only one side has, only_in."
)]
VisualDiff {
#[arg(value_name = "A")]
a: PathBuf,
#[arg(value_name = "B")]
b: PathBuf,
#[arg(long, default_value_t = 100.0, value_name = "DPI", value_parser = parse_dpi, help_heading = "Rendering")]
dpi: f32,
#[arg(long, value_name = "DIR")]
out_dir: Option<PathBuf>,
#[arg(long)]
json: bool,
#[arg(long)]
no_overlay: bool,
#[arg(long)]
force: bool,
},
Comments {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long)]
json: bool,
#[arg(long, value_name = "NAME")]
author: Option<String>,
#[arg(long)]
latest: bool,
},
#[command(after_help = "Examples:\n \
jubarte append a.docx b.docx -o ab.docx\n \
jubarte append cover.docx body.docx annex.docx -o all.docx --section-break continuous\n \
jubarte append letter.docx exhibit.docx -o out.docx --keep-sections\n \
jubarte append review_a.docx review_b.docx -o both.docx --carry-comments")]
Append {
#[arg(value_name = "FILE", num_args = 2.., required = true)]
files: Vec<PathBuf>,
#[arg(short = 'o', long, value_name = "FILE")]
output: PathBuf,
#[arg(long, value_enum, default_value_t = SectionBreakArg::NextPage)]
section_break: SectionBreakArg,
#[arg(long)]
keep_sections: bool,
#[arg(long)]
carry_comments: bool,
#[arg(long)]
force: bool,
#[command(flatten)]
#[serde(flatten)]
render: RenderArgs,
},
#[command(alias = "audit")]
#[command(after_help = "Examples:\n \
jubarte validate contract.docx\n \
jubarte validate contract.docx --json\n \
jubarte validate contract.docx --repair fixed.docx\n \
jubarte validate review/redline.docx --original contract.docx --author Claude\n \
jubarte validate review/redline.docx --baseline contract.docx\n \
jubarte validate contract.docx --rules word,a11y,style,structure --strict\n\n\
Rule sets: word (default: Word validity), edits (with --author, and \
--original or --baseline), a11y, style, structure.\n\
Audit codes (code, set, severity):\n \
HEADING_SKIP a11y warning, IMAGE_NO_DESCR a11y error,\n \
TABLE_NO_HEADER_ROW a11y warning, MISSING_LANG a11y warning,\n \
LITERAL_BULLET style warning, EMPTY_SPACER_PARAGRAPH style info,\n \
DIRECT_FORMATTING_OVERRIDES_STYLE style info,\n \
STALE_FIELD_CACHE structure warning, FONT_SUBSTITUTED structure info")]
#[command(group(clap::ArgGroup::new("edits_against").args(["original", "baseline"]).multiple(true)))]
Validate {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long)]
json: bool,
#[arg(long, value_name = "RULES", value_delimiter = ',', value_parser = parse_rule)]
rules: Vec<String>,
#[arg(long)]
strict: bool,
#[arg(long, value_name = "FILE")]
repair: Option<PathBuf>,
#[arg(long, value_name = "FILE", conflicts_with = "repair")]
baseline: Option<PathBuf>,
#[arg(long, value_name = "FILE", requires = "author")]
original: Option<PathBuf>,
#[arg(long, value_name = "NAME", requires = "edits_against")]
author: Option<String>,
#[arg(long)]
force: bool,
},
#[command(after_help = "Examples:\n \
jubarte check revised.docx --expect expectations.json\n \
jubarte check revised.docx --expect expectations.json --json\n\n\
The expectations' source.sha256 must name FILE's own bytes: an\n\
expectation file bound to the pre-edit source refuses as stale on\n\
the edited output. Use the output-bound copy an `edit apply --expect`\n\
receipt carries to re-check a published output.")]
Check {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(long, value_name = "FILE")]
expect: Option<PathBuf>,
#[arg(long)]
json: bool,
},
#[command(after_help = "Examples:\n \
jubarte scrub redline.docx -o out.docx everything, alias Author\n \
jubarte scrub redline.docx -o out.docx --author-alias Counsel --rsids\n \
jubarte scrub redline.docx -o out.docx --comments comments only")]
Scrub {
#[arg(value_name = "FILE")]
file: PathBuf,
#[arg(short = 'o', long, value_name = "FILE")]
output: PathBuf,
#[arg(long)]
force: bool,
#[command(flatten)]
#[serde(flatten)]
scrub: ScrubSelection,
#[command(flatten)]
#[serde(flatten)]
render: RenderArgs,
},
}
#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
pub struct ScrubSelection {
#[arg(long, value_name = "NAME")]
pub author_alias: Option<String>,
#[arg(long)]
pub rsids: bool,
#[arg(long)]
pub docprops: bool,
#[arg(long)]
pub comments: bool,
}
#[derive(clap::Subcommand, Debug, Serialize)]
#[serde(rename_all = "kebab-case", tag = "command", content = "args")]
pub enum DebugCommand {
#[command(after_help = "Examples:\n \
jubarte debug diff a.docx b.docx\n \
jubarte debug diff a.docx ours_rej.docx word_rej.docx -p styles\n \
jubarte debug diff a.docx ours_rej.docx word_rej.docx --style \"Body Text\" --full\n \
jubarte debug diff a.docx ours.docx --para-text \"Section 4\"")]
Diff {
#[arg(value_name = "FILE", num_args = 2.., required = true)]
files: Vec<PathBuf>,
#[arg(short = 'p', long, value_name = "NAME")]
part: Option<String>,
#[arg(long, value_name = "NAME")]
style: Option<String>,
#[arg(long = "para-text", value_name = "TEXT")]
para_text: Option<String>,
#[arg(long)]
raw: bool,
#[arg(long)]
full: bool,
#[arg(short = 'n', long, value_name = "N", default_value_t = 60)]
limit: usize,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DebugCheck {
Orphans,
Fields,
Bookmarks,
Package,
Structure,
Ids,
Styles,
Chains,
Elements,
Textbox,
Text,
Xml,
Runs,
Changes,
Tables,
Styledefs,
Numbering,
Render,
}
impl From<DebugCheck> for crate::debug::Check {
fn from(c: DebugCheck) -> Self {
use crate::debug::Check;
match c {
DebugCheck::Orphans => Check::Orphans,
DebugCheck::Fields => Check::Fields,
DebugCheck::Bookmarks => Check::Bookmarks,
DebugCheck::Package => Check::Package,
DebugCheck::Structure => Check::Structure,
DebugCheck::Ids => Check::Ids,
DebugCheck::Styles => Check::Styles,
DebugCheck::Chains => Check::Chains,
DebugCheck::Elements => Check::Elements,
DebugCheck::Textbox => Check::Textbox,
DebugCheck::Text => Check::Text,
DebugCheck::Xml => Check::Xml,
DebugCheck::Runs => Check::Runs,
DebugCheck::Changes => Check::Changes,
DebugCheck::Tables => Check::Tables,
DebugCheck::Styledefs => Check::StyleDefs,
DebugCheck::Numbering => Check::Numbering,
#[cfg(feature = "render")]
DebugCheck::Render => Check::Render,
#[cfg(not(feature = "render"))]
DebugCheck::Render => Check::Orphans,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PatchFormat {
Patch,
Critic,
#[value(alias = "unified", alias = "text")]
Github,
Word,
Normal,
Context,
SideBySide,
}
impl PatchFormat {
pub fn is_text_view(self) -> bool {
!matches!(self, Self::Patch | Self::Critic)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CompareMode {
Word,
Powertools,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Format {
Docx,
#[value(alias = "markdown")]
Md,
Pdf,
Png,
Json,
}
fn extension(path: &Path) -> Option<String> {
if let Some(extension) = path.extension() {
return extension.to_str().map(str::to_string);
}
let name = path.file_name()?.to_str()?;
name.strip_prefix('.')
.filter(|rest| !rest.is_empty() && !rest.contains('.'))
.map(str::to_string)
}
impl Format {
pub fn of_path(path: &Path) -> Option<Self> {
Self::of_name(&extension(path)?)
}
pub fn of_name(extension: &str) -> Option<Self> {
match extension.to_ascii_lowercase().as_str() {
"docx" | "docm" | "dotx" | "dotm" => Some(Self::Docx),
"md" | "markdown" | "mdown" | "mkd" | "mkdn" | "txt" => Some(Self::Md),
"pdf" => Some(Self::Pdf),
"png" => Some(Self::Png),
"json" => Some(Self::Json),
_ => None,
}
}
pub fn name(self) -> &'static str {
match self {
Self::Docx => "docx",
Self::Md => "md",
Self::Pdf => "pdf",
Self::Png => "png",
Self::Json => "json",
}
}
pub fn of_input(asked: Option<Self>, path: &Path, bytes: &[u8]) -> Self {
asked
.or_else(|| Format::of_path(path).filter(|f| matches!(f, Self::Docx | Self::Md)))
.unwrap_or(if bytes.starts_with(b"PK\x03\x04") {
Self::Docx
} else {
Self::Md
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Task {
Compare,
Convert,
Read,
Diff,
Accept,
Reject,
Append,
Scrub,
}
impl Task {
pub fn name(self) -> &'static str {
match self {
Self::Compare => "compare",
Self::Convert => "convert",
Self::Read => "read",
Self::Diff => "diff",
Self::Accept => "accept",
Self::Reject => "reject",
Self::Append => "append",
Self::Scrub => "scrub",
}
}
pub fn of_name(name: &str) -> Option<Self> {
Some(match name {
"compare" | "redline" => Self::Compare,
"convert" => Self::Convert,
"read" | "text" | "inspect" => Self::Read,
"diff" => Self::Diff,
"accept" => Self::Accept,
"reject" => Self::Reject,
"append" => Self::Append,
"scrub" => Self::Scrub,
_ => return None,
})
}
fn allowed(self) -> Vec<Format> {
crate::capabilities::OUTPUT_FORMATS
.iter()
.find(|(task, _)| *task == self.name())
.map(|(_, names)| {
names
.iter()
.map(|n| Format::of_name(n).expect("OUTPUT_FORMATS names a format"))
.collect()
})
.unwrap_or_default()
}
fn known(self, path: &Path) -> Option<Format> {
let patch = extension(path)
.is_some_and(|e| e.eq_ignore_ascii_case("patch") || e.eq_ignore_ascii_case("diff"));
if self == Self::Diff && patch {
return Some(Format::Md);
}
Format::of_path(path)
}
fn cannot_write(self, format: Format, typed: Option<&str>) -> String {
let ext = format.name();
let named = |stem: &str| typed.map_or_else(|| format!("{stem}.{ext}"), str::to_string);
match (self, format) {
(Self::Diff, Format::Json) => "diff does not write .json yet".to_string(),
(Self::Diff, _) => format!(
"diff writes text (.md, .markdown, .txt, .patch, .diff); `compare OLD NEW -o {}` writes the redline as {ext}",
named("c")
),
(Self::Read, _) => {
format!(
"read writes .md or .json; `convert FILE -o {}` writes {ext}",
named("v")
)
}
_ => format!("{} does not write .{ext}", self.name()),
}
}
}
pub fn output_format(
task: Task,
output: Option<&Path>,
to: Option<Format>,
) -> Result<Option<Format>, String> {
let said = output.and_then(|path| task.known(path));
let name = output.map(|path| {
path.file_name().map_or_else(
|| path.display().to_string(),
|n| n.to_string_lossy().into_owned(),
)
});
if let (Some(name), Some(said), Some(to)) = (&name, said, to)
&& said != to
{
return Err(format!(
"-o {name} says {} and --to says {}: drop one",
said.name(),
to.name()
));
}
let format = match (output, said.or(to)) {
(None, None) => return Ok(None),
(_, Some(format)) => format,
(Some(_), None) => match task {
Task::Convert => return Ok(None),
Task::Read | Task::Diff => Format::Md,
_ => Format::Docx,
},
};
if task.allowed().contains(&format) {
Ok(Some(format))
} else {
let typed = output
.filter(|_| said == Some(format))
.map(|path| path.display().to_string());
Err(task.cannot_write(format, typed.as_deref()))
}
}
#[must_use]
pub fn refused_input(path: &Path, bytes: &[u8], word: bool) -> Option<String> {
let checked = if word {
crate::admission::sniff_package(bytes)
} else {
crate::admission::sniff(bytes)
};
checked.err().map(|refused| {
format!(
"{}: {} is {}",
refused.code(),
path.display(),
refused.message
)
})
}
#[must_use]
pub fn refused_package(path: &Path, bytes: &[u8]) -> Option<String> {
crate::admission::admit(bytes, crate::admission::InputLimits::default())
.err()
.map(|refused| {
format!(
"{}: {} is {}",
refused.code(),
path.display(),
refused.message
)
})
}
pub fn wrote_line(path: &Path, format: Format, bytes: usize, pages: Option<usize>) -> String {
wrote_line_with(path, format, bytes, pages, None)
}
#[must_use]
pub fn wrote_in_place_line(path: &Path, replaced_sha256: &str, detail: Option<&str>) -> String {
let prefix = replaced_sha256.get(..8).unwrap_or(replaced_sha256);
let extra = detail.map_or_else(String::new, |detail| format!("; {detail}"));
format!(
"wrote {} in place (replaced sha256 {prefix}\u{2026}){extra}",
path.display()
)
}
pub fn wrote_line_with(
path: &Path,
format: Format,
bytes: usize,
pages: Option<usize>,
detail: Option<&str>,
) -> String {
let pages = pages.map_or_else(String::new, |n| format!(", {}", count(n, "page")));
let extra = detail.map_or_else(String::new, |s| format!("; {s}"));
format!(
"wrote {} ({}, {bytes} bytes{pages}{extra})",
path.display(),
format.name()
)
}
#[must_use]
pub fn wrote_markup_detail(changes: usize, comments: usize, author: &str) -> Option<String> {
if changes == 0 && comments == 0 {
return None;
}
let mut detail = String::new();
if changes > 0 {
detail.push_str(&count(changes, "change"));
}
if comments > 0 {
if !detail.is_empty() {
detail.push_str(", ");
}
detail.push_str(&count(comments, "comment"));
}
detail.push_str(&format!(" by \"{author}\""));
Some(detail)
}
pub fn success_block(before_name: &str, before: &str, after_name: &str, after: &str) -> String {
let body = if before == after {
"no differences\n".to_string()
} else {
similar::TextDiff::from_lines(before, after)
.unified_diff()
.context_radius(3)
.header(
&format!("before {before_name}"),
&format!("after {after_name}"),
)
.to_string()
};
let longest = body
.lines()
.map(|line| {
let indent = line.bytes().take(3).take_while(|b| *b == b' ').count();
line.bytes().skip(indent).take_while(|b| *b == b'~').count()
})
.max()
.unwrap_or(0);
let fence = "~".repeat(4.max(longest + 1));
format!("SUCCESS:\n{fence}diff\n{body}{fence}\n")
}
#[cfg(test)]
mod success_tests {
use super::success_block;
#[test]
fn equal_views() {
assert_eq!(
success_block("in.docx", "same", "out.docx", "same"),
"SUCCESS:\n~~~~diff\nno differences\n~~~~\n"
);
}
#[test]
fn labels_and_known_hunk() {
assert_eq!(
success_block(
"dir/in.docx",
"one\ntwo\nthree\n",
"out.docx",
"one\nnew\nthree\n"
),
"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"
);
}
#[test]
fn fence_exceeds_leading_tildes_in_diff_body() {
let block = success_block("a", "a\n", "b\n~~~~~", "b\n");
assert!(block.starts_with("SUCCESS:\n~~~~~~diff\n"), "{block}");
assert!(block.ends_with("~~~~~~\n"), "{block}");
assert!(success_block("a", "~~~~~~\n", "b", "x\n").starts_with("SUCCESS:\n~~~~diff\n"));
}
#[test]
fn a_context_line_of_tildes_cannot_close_the_fence() {
let block = success_block("a", "~~~~\nkeep\n", "b", "~~~~\nchanged\n");
assert!(block.contains("\n ~~~~\n"), "{block}");
let fence = block["SUCCESS:\n".len()..]
.bytes()
.take_while(|b| *b == b'~')
.count();
assert!(fence > 4, "{block}");
}
#[test]
fn three_context_lines_and_missing_newline() {
let block = success_block(
"a",
"0\n1\n2\n3\n4\n5\n6\n7",
"b",
"0\n1\n2\n3\n4\n5\n6\nnew",
);
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}");
}
}
pub fn wrote_png_line(pattern: &Path, pages: usize, dpi: f32) -> String {
format!(
"wrote {} (png, {}, {dpi} dpi)",
pattern.display(),
count(pages, "page")
)
}
fn count(n: usize, word: &str) -> String {
format!("{n} {word}{}", if n == 1 { "" } else { "s" })
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Retired {
pub old: &'static str,
pub now: &'static str,
pub on: Option<&'static str>,
}
pub const RETIRED: &[Retired] = &[
Retired {
old: "diff-render",
now: "visual-diff",
on: None,
},
Retired {
old: "text",
now: "read",
on: None,
},
Retired {
old: "inspect",
now: "read",
on: None,
},
Retired {
old: "audit",
now: "validate --rules a11y,style,structure",
on: None,
},
Retired {
old: "--changed-only",
now: "--changed-pages",
on: Some("convert"),
},
Retired {
old: "--changed-only",
now: "--changed-pages",
on: Some("compare"),
},
Retired {
old: "--changed-only",
now: "--changed-pages",
on: Some("accept"),
},
Retired {
old: "--changed-only",
now: "--changed-pages",
on: Some("reject"),
},
Retired {
old: "--changed-only",
now: "--changed-pages",
on: Some("append"),
},
Retired {
old: "--changed-only",
now: "--changed-pages",
on: Some("scrub"),
},
Retired {
old: "--pdf",
now: "--to pdf",
on: Some("convert"),
},
Retired {
old: "--png",
now: "--to png",
on: Some("convert"),
},
];
pub(crate) const REMOVED_TASKS: &[Retired] = &[Retired {
old: "revisions",
now: "changes",
on: None,
}];
pub(crate) fn removed_tasks<'a>(
argv: impl IntoIterator<Item = &'a str>,
) -> Vec<(&'static str, &'static str)> {
spellings_in(REMOVED_TASKS, argv)
}
pub(crate) fn removed_task_note(old: &str, now: &str) -> String {
format!("note: {old} is no longer a task, so it reads as a file name; use {now}")
}
pub const REMOVED: &[Retired] = &[
Retired {
old: "--date",
now: "--datetime",
on: Some("compare"),
},
Retired {
old: "--date",
now: "--datetime",
on: Some("diff"),
},
Retired {
old: "--date",
now: "--datetime",
on: Some("convert"),
},
Retired {
old: "--date",
now: "--datetime",
on: Some("edit"),
},
Retired {
old: "--date",
now: "--datetime",
on: Some("add"),
},
];
struct Spelled {
name: String,
at: usize,
}
fn value_taken(arg: Option<&clap::Arg>) -> Option<bool> {
let arg = arg.filter(|a| a.get_action().takes_values())?;
match arg.get_num_args() {
Some(range) if range.max_values() == 0 => None,
Some(range) => Some(range.min_values() == 0),
None => Some(false),
}
}
fn long_arg<'c>(cmd: &'c clap::Command, name: &str) -> Option<&'c clap::Arg> {
cmd.get_arguments().find(|a| {
a.get_long() == Some(name) || a.get_all_aliases().is_some_and(|v| v.contains(&name))
})
}
fn short_arg(cmd: &clap::Command, short: char) -> Option<&clap::Arg> {
cmd.get_arguments().find(|a| {
a.get_short() == Some(short)
|| a.get_all_short_aliases()
.is_some_and(|v| v.contains(&short))
})
}
fn spelled_options(cmd: &clap::Command, tokens: &[&str]) -> (Vec<Spelled>, usize) {
let skip_value = |i: &mut usize, optional: bool| {
let value = tokens.get(*i).copied();
if !(optional && value.is_none_or(|v| v.starts_with('-'))) {
*i += 1;
}
};
let mut found = Vec::new();
let mut i = 0;
while let Some(&token) = tokens.get(i) {
i += 1;
if let Some(long) = token.strip_prefix("--") {
let (name, inline) = match long.split_once('=') {
Some((name, value)) => (name, Some(value)),
None => (long, None),
};
if inline.is_none()
&& let Some(optional) = value_taken(long_arg(cmd, name))
{
skip_value(&mut i, optional);
}
found.push(Spelled {
name: format!("--{name}"),
at: i - 1,
});
} else if let Some(cluster) = token.strip_prefix('-').filter(|c| !c.is_empty()) {
let at = i - 1;
for (offset, short) in cluster.char_indices() {
let name = format!("-{short}");
let Some(optional) = value_taken(short_arg(cmd, short)) else {
found.push(Spelled { name, at });
continue;
};
if cluster[offset + short.len_utf8()..].is_empty() {
skip_value(&mut i, optional);
}
found.push(Spelled { name, at });
break;
}
} else {
return (found, i - 1);
}
}
(found, i)
}
pub fn retired_spellings<'a>(
argv: impl IntoIterator<Item = &'a str>,
) -> Vec<(&'static str, &'static str)> {
spellings_in(RETIRED, argv)
}
pub fn removed_spellings<'a>(
argv: impl IntoIterator<Item = &'a str>,
) -> Vec<(&'static str, &'static str)> {
spellings_in(REMOVED, argv)
}
pub fn removed_error(old: &str, now: &str) -> String {
format!("error: {old} is removed; use {now}")
}
fn spellings_in<'a>(
table: &[Retired],
argv: impl IntoIterator<Item = &'a str>,
) -> Vec<(&'static str, &'static str)> {
let argv: Vec<&str> = argv.into_iter().take_while(|t| *t != "--").collect();
let model = Cli::command();
let mut found = Vec::new();
let (before_task, at) = spelled_options(&model, &argv);
let Some(&task) = argv.get(at) else {
return found;
};
if let Some(retired) = table.iter().find(|r| r.on.is_none() && r.old == task) {
found.push((retired.old, retired.now));
}
let (sub, task, from) = match model.find_subcommand(task) {
Some(sub) => (sub, sub.get_name(), at + 1),
None => (&model, "compare", at),
};
let mut spot = |options: Vec<Spelled>| {
for option in options {
for retired in table.iter().filter(|r| r.on == Some(task)) {
if option.name == retired.old {
found.push((retired.old, retired.now));
}
}
}
};
spot(before_task);
let mut rest = &argv[from..];
while !rest.is_empty() {
let (options, next) = spelled_options(sub, rest);
spot(options);
rest = rest.get(next + 1..).unwrap_or_default();
}
let mut seen = std::collections::HashSet::new();
found.retain(|spelling| seen.insert(*spelling));
found
}
pub use crate::util::shell_word;
pub(crate) fn apply_retired(task: &mut Command, retired: &[(&str, &str)]) {
if let Command::Validate { rules, .. } = task
&& rules.is_empty()
&& retired.iter().any(|(old, _)| *old == "audit")
{
*rules = ["a11y", "style", "structure"].map(String::from).to_vec();
}
}
pub fn notes(argv: &[String]) -> Vec<String> {
let argv = || argv.iter().map(String::as_str);
let rules_given = argv()
.take_while(|token| *token != "--")
.any(|token| token == "--rules" || token.starts_with("--rules="));
retired_spellings(argv())
.into_iter()
.map(|(old, now)| match old {
"audit" if rules_given => retired_note(old, "validate"),
_ => retired_note(old, now),
})
.chain(
removed_tasks(argv())
.into_iter()
.map(|(old, now)| removed_task_note(old, now)),
)
.collect()
}
pub fn retired_note(old: &str, now: &str) -> String {
format!("note: {old} is now {now}; {old} is removed in 0.14")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TrackChanges {
All,
#[value(alias = "accepted")]
Accept,
#[value(alias = "rejected")]
Reject,
}
impl From<TrackChanges> for crate::markdown::TrackChanges {
fn from(choice: TrackChanges) -> Self {
match choice {
TrackChanges::All => Self::All,
TrackChanges::Accept => Self::Accept,
TrackChanges::Reject => Self::Reject,
}
}
}
#[derive(clap::Args, Clone, Debug, PartialEq, Serialize)]
#[command(next_help_heading = "Rendering (-o FILE.pdf or FILE.png)")]
pub struct RenderArgs {
#[arg(long, value_enum, default_value_t = Revisions::Conventional, requires_if("custom", "revision_palette"))]
pub revisions: Revisions,
#[cfg_attr(feature = "render", arg(long, value_name = "SPEC", value_parser = parse_palette, requires = "revisions"))]
#[cfg_attr(
not(feature = "render"),
arg(long, value_name = "SPEC", requires = "revisions")
)]
pub revision_palette: Option<String>,
#[arg(long, default_value_t = 96.0, value_name = "DPI", value_parser = parse_dpi)]
pub dpi: f32,
#[arg(long)]
pub move_comments: bool,
#[arg(long, hide = true)]
pub comment_notes: bool,
#[arg(long, alias = "changed-only")]
pub changed_pages: bool,
#[arg(long, value_name = "SPEC", value_parser = validate_pages)]
pub pages: Option<String>,
}
impl Default for RenderArgs {
fn default() -> Self {
Self {
revisions: Revisions::Conventional,
revision_palette: None,
dpi: 96.0,
move_comments: false,
comment_notes: false,
changed_pages: false,
pages: None,
}
}
}
impl RenderArgs {
#[cfg(feature = "render")]
pub fn apply(
&self,
options: crate::jubarte_render::convert::PdfOptions,
) -> crate::jubarte_render::convert::PdfOptions {
crate::jubarte_render::convert::PdfOptions {
comments: if self.move_comments {
crate::jubarte_render::convert::CommentPlacement::End
} else {
crate::jubarte_render::convert::CommentPlacement::Margin
},
comment_notes: self.comment_notes,
changed_only: self.changed_pages,
..options
}
}
}
#[derive(clap::Args, Debug, Serialize)]
pub struct MarkdownArgs {
#[arg(
short = 'f',
long = "from",
value_parser = input_format_parser(),
value_name = "FORMAT",
help_heading = "Formats"
)]
pub from: Option<Format>,
#[arg(
short = 't',
long = "to",
value_enum,
value_name = "FORMAT",
help_heading = "Formats"
)]
pub to: Option<Format>,
#[arg(long, value_enum, value_name = "CHOICE", default_value_t = TrackChanges::All)]
pub track_changes: TrackChanges,
#[arg(long)]
pub keep_nested_comment: bool,
#[arg(long)]
pub no_critic: bool,
#[arg(long, value_name = "FILE")]
pub reference_doc: Option<PathBuf>,
#[arg(long, value_name = "DIR")]
pub resource_path: Option<PathBuf>,
#[arg(short = 'a', long, value_name = "NAME")]
pub author: Option<String>,
#[arg(
short = 'd',
long = "datetime",
value_name = "ISO8601",
value_parser = parse_datetime
)]
pub datetime: Option<String>,
#[arg(long, value_enum, value_name = "SIZE", default_value_t = Page::Letter)]
pub page: Page,
#[arg(long, value_enum, value_name = "SWITCH")]
pub tracking: Option<Tracking>,
#[arg(long)]
pub scholar: bool,
#[arg(long)]
pub no_page_markers: bool,
#[arg(long)]
pub commonmark: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Tracking {
On,
Off,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Page {
Letter,
A4,
}
impl From<Page> for crate::markdown::PageSize {
fn from(choice: Page) -> Self {
match choice {
Page::Letter => Self::Letter,
Page::A4 => Self::A4,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Revisions {
Conventional,
Word,
Custom,
}
#[derive(clap::Args, Debug, Default, PartialEq, Serialize)]
pub struct Selection {
#[arg(long = "id", value_name = "ID")]
pub ids: Vec<String>,
#[arg(long = "author", value_name = "NAME")]
pub authors: Vec<String>,
#[arg(long = "kind", value_enum, value_name = "KIND")]
pub kinds: Vec<KindArg>,
}
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum KindArg {
Insertion,
Deletion,
Move,
Formatting,
#[value(hide = true)]
Replacement,
}
fn parse_timeout(value: &str) -> Result<std::time::Duration, String> {
let seconds: f64 = value
.parse()
.map_err(|_| format!("'{value}' is not a number of seconds"))?;
if !(seconds.is_finite() && seconds > 0.0) {
return Err(format!(
"'{value}': the timeout must be a finite number of seconds above 0"
));
}
std::time::Duration::try_from_secs_f64(seconds).map_err(|e| format!("'{value}': {e}"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SectionBreakArg {
NextPage,
Continuous,
None,
}
impl From<SectionBreakArg> for crate::append::SectionBreak {
fn from(arg: SectionBreakArg) -> Self {
match arg {
SectionBreakArg::NextPage => Self::NextPage,
SectionBreakArg::Continuous => Self::Continuous,
SectionBreakArg::None => Self::None,
}
}
}
fn styles() -> clap::builder::Styles {
use clap::builder::styling::{AnsiColor, Effects};
clap::builder::Styles::styled()
.header(AnsiColor::Cyan.on_default() | Effects::BOLD)
.usage(AnsiColor::Cyan.on_default() | Effects::BOLD)
.literal(AnsiColor::Green.on_default())
.placeholder(AnsiColor::Yellow.on_default())
}
fn parse_author(value: &str) -> Result<String, String> {
crate::markdown::author(value).map(str::to_string)
}
fn parse_dpi(value: &str) -> Result<f32, String> {
let dpi: f32 = value.parse().map_err(|_| "DPI must be a number")?;
if dpi.is_finite() && dpi > 0.0 && dpi <= 1200.0 {
Ok(dpi)
} else {
Err("DPI must be finite and above 0, up to 1200".into())
}
}
fn input_format_parser() -> impl clap::builder::TypedValueParser<Value = Format> {
use clap::builder::TypedValueParser;
clap::builder::PossibleValuesParser::new(["docx", "md", "markdown"]).map(|value| {
if value == "docx" {
Format::Docx
} else {
Format::Md
}
})
}
fn parse_context(value: &str) -> Result<usize, String> {
value
.parse::<u32>()
.map(|n| n as usize)
.map_err(|_| "context must be an integer between 0 and 4294967295".to_string())
}
fn parse_threshold(value: &str) -> Result<f64, String> {
let ratio: f64 = value.parse().map_err(|_| "threshold must be a number")?;
if ratio.is_finite() && (0.0..=1.0).contains(&ratio) {
Ok(ratio)
} else {
Err("threshold must be finite and between 0 and 1".into())
}
}
#[cfg(feature = "render")]
fn parse_palette(value: &str) -> Result<String, String> {
crate::jubarte_render::convert::RevisionPalette::parse(value)?;
Ok(value.to_string())
}
fn parse_rule(value: &str) -> Result<String, String> {
if crate::validate::RULE_SETS.contains(&value) || crate::audit::is_rule(value) {
Ok(value.to_string())
} else {
let codes: Vec<&str> = crate::audit::RULES.iter().map(|rule| rule.0).collect();
Err(format!(
"expected one of {} or an audit code ({})",
crate::validate::RULE_SETS.join(", "),
codes.join(", ")
))
}
}
fn validate_pages(value: &str) -> Result<String, String> {
let page = |s: &str| {
let s = s.trim();
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("'{s}' is not a page number"));
}
let n = s
.parse::<usize>()
.map_err(|_| format!("'{s}' is not a page number"))?;
if n == 0 {
Err("pages are counted from 1".to_string())
} else {
Ok(n)
}
};
for item in value.split(',') {
let item = item.trim();
if item.is_empty() {
return Err("empty item in page selection".into());
}
if let Some((first, last)) = item.split_once('-') {
if page(first)? > page(last)? {
return Err(format!("'{item}' runs backwards"));
}
} else {
page(item)?;
}
}
Ok(value.to_string())
}
fn serialize_timeout<S: serde::Serializer>(
timeout: &Option<std::time::Duration>,
serializer: S,
) -> Result<S::Ok, S::Error> {
timeout.map(|t| t.as_secs_f64()).serialize(serializer)
}
fn serialize_paragraph_spec<S: serde::Serializer>(
paragraphs: &[String],
serializer: S,
) -> Result<S::Ok, S::Error> {
match paragraphs {
[] => serializer.serialize_none(),
_ => serializer.serialize_str(¶graphs.join(",")),
}
}
const READ_OPTION_IDS: [&str; 14] = [
"track_changes",
"comments",
"dates",
"no_page_markers",
"paragraphs",
"head",
"tail",
"changed",
"by",
"json",
"tables",
"find",
"regex",
"ignore_case",
];
fn json_not_yet(matches: &clap::ArgMatches, task: Task) -> Option<String> {
let to = matches.try_get_one::<Format>("to").ok().flatten().copied();
let said = matches
.try_get_one::<PathBuf>("output")
.ok()
.flatten()
.and_then(|path| task.known(path));
(to == Some(Format::Json) || said == Some(Format::Json))
.then(|| format!("{} does not write .json yet", task.name()))
}
fn compare_output(
output: Option<&Path>,
given: &dyn Fn(&str) -> bool,
) -> Result<Option<Format>, String> {
if given("json") {
return Err(
"--json reads one document; `-o FILE.json` writes the redline's snapshot".to_string(),
);
}
if given("tables") {
return Err("--tables reads one document".to_string());
}
let kind = output_format(Task::Compare, output, None)?;
if kind.is_some_and(|kind| kind != Format::Md) && READ_OPTION_IDS.into_iter().any(given) {
return Err(
"read options shape the view: print it (no -o) or write it (-o FILE.md)".to_string(),
);
}
if !matches!(kind, Some(Format::Pdf | Format::Png))
&& let Some(flag) = RENDER_ONLY.into_iter().find(|flag| given(flag))
{
return Err(format!(
"--{} applies to PDF or PNG output only",
flag.replace('_', "-")
));
}
Ok(kind)
}
fn read_view_conflict(flag: &str) -> String {
format!(
"{flag} shapes the Markdown view, and --for-edit prints the working document JSON, \
which has no view; drop {flag}, or drop --for-edit to read the view"
)
}
fn read_usage_error(command: &clap::Command, message: String) -> clap::Error {
let mut task = command
.find_subcommand("read")
.unwrap_or(command)
.clone()
.override_usage(format!("{} read [OPTIONS] <FILE>", command.get_name()));
task.set_bin_name(format!("{} read", command.get_name()));
task.error(clap::error::ErrorKind::ArgumentConflict, message)
}
fn read_output(output: &Path, given: &dyn Fn(&str) -> bool) -> Result<Format, String> {
let kind = output_format(Task::Read, Some(output), None)?.unwrap_or(Format::Md);
if given("tables") && kind == Format::Json {
return Err("--tables writes the grids as text: name the file FILE.md".to_string());
}
if given("for_edit") && kind != Format::Json {
return Err("--for-edit prints JSON: name the file FILE.json or drop -o".to_string());
}
if kind == Format::Json && !given("for_edit") && (given("find") || given("regex")) {
return Err(
"--find/--regex select the Markdown view: name the file FILE.md or use --for-edit"
.into(),
);
}
if given("json") && kind != Format::Json {
return Err("--json writes the snapshot: name the file FILE.json".to_string());
}
Ok(kind)
}
fn palette_without_custom(args: &clap::ArgMatches) -> bool {
args.try_get_one::<String>("revision_palette")
.ok()
.flatten()
.is_some()
&& args.try_get_one::<Revisions>("revisions").ok().flatten() != Some(&Revisions::Custom)
}
fn validate_matches(
matches: &clap::ArgMatches,
command: &mut clap::Command,
) -> Result<(), clap::Error> {
use clap::{error::ErrorKind, parser::ValueSource};
let read_args = match matches.subcommand() {
Some(("read" | "compare", args)) => Some(args),
None => Some(matches),
_ => None,
};
if let Some(args) = read_args {
let find = args.get_one::<String>("find");
let regex = args.get_one::<String>("regex");
if !args.get_flag("for_edit")
&& (find.is_some() || regex.is_some())
&& (args.get_flag("json") || args.get_flag("tables"))
{
return Err(read_usage_error(
command,
"--find/--regex select the Markdown view; drop --json/--tables or use --for-edit"
.into(),
));
}
if find.is_none()
&& regex.is_none()
&& args.get_flag("ignore_case")
&& !args.get_flag("for_edit")
{
return Err(read_usage_error(
command,
"--ignore-case needs --find TEXT or --regex PATTERN".into(),
));
}
}
let Some((name, args)) = matches.subcommand() else {
let given = |id: &str| {
matches.try_contains_id(id).unwrap_or(false)
&& matches.value_source(id) == Some(ValueSource::CommandLine)
};
let two = given("modified_pos") || given("modified");
let output = matches.get_one::<PathBuf>("output").map(PathBuf::as_path);
if two {
compare_output(output, &given)
.map_err(|message| command.error(ErrorKind::ArgumentConflict, message))?;
if palette_without_custom(matches) {
return Err(command.error(
ErrorKind::ArgumentConflict,
"--revision-palette needs --revisions custom",
));
}
} else {
if let Some(output) = output {
read_output(output, &given)
.map_err(|message| read_usage_error(command, message))?;
}
if let Some(flag) = COMPARE_ONLY.into_iter().find(|id| given(id)) {
return Err(command.error(
ErrorKind::ArgumentConflict,
format!(
"--{} is a compare option: name two documents",
flag.replace('_', "-")
),
));
}
if let Some(flag) = RENDER_ONLY.into_iter().find(|id| given(id)) {
return Err(command.error(
ErrorKind::ArgumentConflict,
format!(
"--{} draws a PDF or PNG, which read does not write: \
`convert FILE -o FILE.pdf` or `compare A B -o FILE.pdf` does",
flag.replace('_', "-")
),
));
}
}
if let Some(task) = matches
.try_get_one::<PathBuf>("original_pos")
.ok()
.flatten()
.and_then(|p| p.to_str())
.and_then(|name| command.find_subcommand(name))
.map(|task| task.get_name().to_string())
{
return Err(command.error(
ErrorKind::ArgumentConflict,
format!(
"options go after the task: `{} {task} … [OPTIONS]`",
command.get_name()
),
));
}
let lone = |id: &str| {
matches
.try_get_one::<PathBuf>(id)
.ok()
.flatten()
.filter(|_| matches.value_source(id) == Some(ValueSource::CommandLine))
};
if lone("modified_pos").is_none()
&& lone("modified").is_none()
&& let Some(file) = lone("original_pos")
&& file.extension().is_none()
{
return Err(command.error(
ErrorKind::InvalidSubcommand,
format!(
"'{}' is not a task; to read a file without an extension, use `read FILE`",
file.display()
),
));
}
return Ok(());
};
if let Some(message) = Task::of_name(name)
.filter(|task| *task == Task::Diff)
.and_then(|task| json_not_yet(args, task))
{
let mut task = command.find_subcommand(name).expect("parsed task").clone();
task.set_bin_name(format!("{} {name}", command.get_name()));
return Err(task.error(ErrorKind::ValueValidation, message));
}
if name == "validate"
&& args
.get_many::<String>("rules")
.is_some_and(|mut rules| rules.any(|rule| rule == "edits"))
&& !args.contains_id("author")
{
let mut task = command.find_subcommand(name).expect("parsed task").clone();
task.set_bin_name(format!("{} {name}", command.get_name()));
return Err(task.error(
ErrorKind::MissingRequiredArgument,
"--rules edits needs --author, and --original or --baseline",
));
}
if name == "compare"
&& !["modified", "modified_pos"]
.into_iter()
.any(|id| args.try_contains_id(id).unwrap_or(false))
{
let mut task = command.find_subcommand(name).expect("parsed task").clone();
task.set_bin_name(format!("{} {name}", command.get_name()));
return Err(task.error(
ErrorKind::MissingRequiredArgument,
"compare needs <MODIFIED> (or -m FILE)",
));
}
if name == "__edit-template" {
return edit_template::validate(args, command);
}
if name == "__edit-v2" {
return edit_actions::validate(args, command);
}
let mut task = command.find_subcommand(name).expect("parsed task").clone();
task.set_bin_name(format!("{} {name}", command.get_name()));
let error =
|task: &mut clap::Command, message: &str| task.error(ErrorKind::ArgumentConflict, message);
let given = |id: &str| {
args.try_contains_id(id).unwrap_or(false)
&& args.value_source(id) == Some(ValueSource::CommandLine)
};
if name == "read"
&& let Some(output) = args.get_one::<PathBuf>("output")
{
read_output(output, &given).map_err(|message| read_usage_error(command, message))?;
}
if name == "compare" {
compare_output(
args.get_one::<PathBuf>("output").map(PathBuf::as_path),
&given,
)
.map_err(|message| error(&mut task, &message))?;
}
if let Some(writer) = Task::of_name(name).filter(|task| {
matches!(
task,
Task::Accept | Task::Reject | Task::Append | Task::Scrub
)
}) {
let output = args.get_one::<PathBuf>("output").map(PathBuf::as_path);
let kind =
output_format(writer, output, None).map_err(|message| error(&mut task, &message))?;
if !matches!(kind, Some(Format::Pdf | Format::Png))
&& let Some(flag) = RENDER_ONLY.into_iter().find(|flag| given(flag))
{
return Err(error(
&mut task,
&format!(
"--{} applies to PDF or PNG output only",
flag.replace('_', "-")
),
));
}
}
if matches!(name, "edit" | "add")
&& let Some(plan) = args.get_one::<PathBuf>("plan")
{
let given: Vec<String> = args
.ids()
.filter(|id| args.value_source(id.as_str()) == Some(ValueSource::CommandLine))
.map(|id| format!("--{}", id.as_str().replace('_', "-")))
.collect();
let given: Vec<&str> = given.iter().map(String::as_str).collect();
let recording = given.contains(&"--location");
if let Some(message) =
crate::edit::record::plan_flag_conflict(recording, &given, &plan.display().to_string())
{
return Err(error(&mut task, &message));
}
}
if matches!(name, "edit" | "add")
&& let Some(dir) = args.try_get_one::<PathBuf>("out_dir").ok().flatten()
&& names_word_document(dir)
{
return Err(error(&mut task, &swallowed_file("--out-dir", dir)));
}
if matches!(name, "edit" | "add")
&& let Some(plan) = args.get_one::<PathBuf>("plan")
&& names_word_document(plan)
{
return Err(error(&mut task, &swallowed_file("--plan", plan)));
}
if matches!(name, "edit" | "add")
&& let Some(output) = args.get_one::<PathBuf>("output")
&& let Some(kind) = Format::of_path(output).filter(|kind| *kind != Format::Docx)
{
let ext = output.extension().map_or_else(
|| kind.name().to_string(),
|e| e.to_string_lossy().to_lowercase(),
);
let how = match kind {
Format::Md | Format::Json => format!("`jubarte read FILE_modified.docx -o v.{ext}`"),
_ => format!("`jubarte convert FILE_modified.docx -o r.{ext}`"),
};
return Err(error(
&mut task,
&format!("{name} writes a .docx; {how} writes .{ext} from it"),
));
}
if palette_without_custom(args) {
return Err(error(
&mut task,
"--revision-palette needs --revisions custom",
));
}
if name == "diff" {
output_format(
Task::Diff,
args.get_one::<PathBuf>("output").map(PathBuf::as_path),
args.get_one::<Format>("to").copied(),
)
.map_err(|message| error(&mut task, &message))?;
let format = *args
.get_one::<PatchFormat>("format")
.expect("default format");
let (text_view, theirs) = if format.is_text_view() {
(true, &["columns", "author", "datetime"][..])
} else {
(false, &["context", "accept_changes", "full_lines"][..])
};
let patch_only: &[&str] = if format == PatchFormat::Critic {
&["columns", "author", "datetime"]
} else {
&[]
};
let given = |flag: &&&str| args.value_source(flag) == Some(ValueSource::CommandLine);
if let Some(flag) = patch_only.iter().find(given) {
return Err(error(
&mut task,
&format!("--{flag} applies to the paragraph patch only (--format patch)"),
));
}
if let Some(flag) = theirs.iter().find(given) {
let flag = flag.replace('_', "-");
return Err(error(
&mut task,
&if text_view {
format!("--{flag} does not apply to this text diff format")
} else {
format!(
"--{flag} requires a text diff format (github, word, normal, context or side-by-side)"
)
},
));
}
}
if name == "convert" {
if args.get_flag("keep_nested_comment")
&& args.get_one::<TrackChanges>("track_changes") == Some(&TrackChanges::All)
{
return Err(error(
&mut task,
"--keep-nested-comment requires --track-changes accept or reject",
));
}
let alias = match (args.get_flag("pdf"), args.get_flag("png")) {
(true, true) => return Err(error(&mut task, "--pdf and --png name two formats")),
(true, false) => Some(Format::Pdf),
(false, true) => Some(Format::Png),
(false, false) => None,
};
let given = args.get_one::<Format>("to").copied();
if let (Some(to), Some(alias)) = (given, alias)
&& to != alias
{
return Err(error(
&mut task,
&format!(
"--to {} and --{} name two formats: drop one",
to.name(),
alias.name()
),
));
}
let output = args.get_one::<PathBuf>("output").map(PathBuf::as_path);
let kind = output_format(Task::Convert, output, given.or(alias))
.map_err(|message| error(&mut task, &message))?;
let update_fields = args.get_flag("update_fields");
if update_fields && kind != Some(Format::Docx) {
return Err(error(
&mut task,
"--update-fields writes a .docx: give -o FILE.docx or --to docx",
));
}
if matches!(kind, Some(Format::Docx | Format::Md | Format::Json)) {
let convert_only = ["compress", "report", "font_report", "fail_on_substitution"];
for flag in RENDER_ONLY.into_iter().chain(convert_only) {
if flag == "report" && update_fields {
continue;
}
if args.value_source(flag) == Some(ValueSource::CommandLine) {
return Err(error(
&mut task,
&format!(
"--{} applies to PDF or PNG output only",
flag.replace('_', "-")
),
));
}
}
}
}
Ok(())
}
const COMPARE_ONLY: [&str; 9] = [
"author",
"datetime",
"detail_threshold",
"mode",
"powertools_faithful",
"no_paragraph_merge",
"reference_doc",
"critic",
"resource_path",
];
const RENDER_ONLY: [&str; 7] = [
"move_comments",
"comment_notes",
"changed_pages",
"pages",
"dpi",
"revisions",
"revision_palette",
];
pub fn edit_arguments(
command: &clap::Command,
arguments: &[std::ffi::OsString],
) -> Vec<std::ffi::OsString> {
edit_actions::route(&hoist_quiet(command, arguments), command)
}
pub fn typed_edit_protocol(
arguments: &[std::ffi::OsString],
) -> Option<(String, bool, Option<String>)> {
let model = top_level_command();
let routed = edit_arguments(&model, arguments);
if routed.get(1).is_none_or(|a| a != "__edit-v2") {
return None;
}
let typed = model.find_subcommand("__edit-v2")?;
let tokens: Vec<_> = routed
.iter()
.skip(2)
.filter_map(|a| a.to_str())
.take_while(|a| *a != "--")
.collect();
let (_, at) = spelled_options(typed, &tokens);
let action = *tokens.get(at)?;
let command = typed.find_subcommand(action)?;
let mut rest = &tokens[at + 1..];
let mut json = false;
let mut jsonl = false;
let mut file = None;
while !rest.is_empty() {
let (options, next) = spelled_options(command, rest);
for option in options {
json |= option.name == "--json";
jsonl |= option.name == "--jsonl";
}
if file.is_none()
&& let Some(operand) = rest.get(next)
{
file = Some(operand.to_string());
}
rest = rest.get(next + 1..).unwrap_or_default();
}
(json || jsonl).then(|| (action.to_string(), jsonl, file))
}
pub fn next_command(argv: &[String], force: bool) -> Vec<String> {
next_command_to(argv, force, None)
}
pub fn next_command_to(argv: &[String], force: bool, output: Option<&str>) -> Vec<String> {
let model = top_level_command();
let arguments: Vec<std::ffi::OsString> = std::iter::once("jubarte".into())
.chain(argv.iter().map(Into::into))
.collect();
let routed = edit_arguments(&model, &arguments);
let tokens: Vec<&str> = routed
.iter()
.skip(1)
.filter_map(|a| a.to_str())
.take_while(|a| *a != "--")
.collect();
let mut flags = std::collections::BTreeSet::new();
let mut command = &model;
let mut start = 0;
loop {
let (options, next) = spelled_options(command, &tokens[start..]);
flags.extend(
options
.iter()
.filter(|option| option.name == "--dry-run")
.map(|option| start + option.at),
);
let Some(word) = tokens.get(start + next) else {
break;
};
if let Some(task) = command.find_subcommand(word) {
command = task;
}
start += next + 1;
}
let dropped: std::collections::BTreeSet<usize> = tokens
.iter()
.enumerate()
.filter(|(_, token)| **token == "--dry-run")
.enumerate()
.filter(|(_, (at, _))| flags.contains(at))
.map(|(nth, _)| nth)
.collect();
let tail = |next: &mut Vec<String>| {
if let Some(output) = output {
next.extend(["-o".to_string(), output.to_string()]);
}
if force {
next.push("--force".to_string());
}
};
let mut next = Vec::with_capacity(argv.len() + 3);
let mut spelled = 0;
let mut delimited = false;
for arg in argv {
if !delimited && arg == "--" {
delimited = true;
tail(&mut next);
}
if !delimited && arg == "--dry-run" {
spelled += 1;
if dropped.contains(&(spelled - 1)) {
continue;
}
}
next.push(arg.clone());
}
if !delimited {
tail(&mut next);
}
next
}
pub fn first_positional(cmd: &clap::Command, tokens: &[&str]) -> Option<String> {
let (_, at) = spelled_options(cmd, tokens);
tokens.get(at).map(ToString::to_string)
}
impl Cli {
pub fn try_parse_from<I, T>(arguments: I) -> Result<Self, clap::Error>
where
I: IntoIterator<Item = T>,
T: Into<std::ffi::OsString> + Clone,
{
let mut command = top_level_command();
let arguments: Vec<std::ffi::OsString> = arguments.into_iter().map(Into::into).collect();
let arguments = edit_arguments(&command, &arguments);
let matches = command
.try_get_matches_from_mut(arguments.clone())
.map_err(|e| {
let tokens: Vec<String> = arguments
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
usage_error(&command, &tokens, e)
})?;
validate_matches(&matches, &mut command)?;
let mut cli = Self::from_arg_matches(&matches)?;
if let Some(task) = cli.command.as_mut() {
fill_flag_operations(task, &matches, &mut command)?;
resolve_plan(task);
let typed: Vec<String> = arguments
.iter()
.skip(1)
.map(|a| a.to_string_lossy().into_owned())
.collect();
apply_retired(task, &retired_spellings(typed.iter().map(String::as_str)));
fill_task_date(task);
} else {
fill_date(&mut cli.compare.datetime);
}
match (cli.command.as_mut(), matches.subcommand()) {
(Some(Command::Compare(compare)), Some((_, args))) => {
compare.view_given = view_given(args);
}
(Some(Command::TypedEdit(typed)), Some((_, args))) => {
mark_typed_author(typed, args, &mut command)?;
}
(None, _) => cli.compare.view_given = view_given(&matches),
_ => {}
}
Ok(cli)
}
}
fn mark_typed_author(
typed: &mut edit_actions::TypedEdit,
args: &clap::ArgMatches,
command: &mut clap::Command,
) -> Result<(), clap::Error> {
let Some((_, action)) = args.subcommand() else {
return Ok(());
};
let given = action.try_contains_id("author").unwrap_or(false)
&& action.value_source("author") == Some(clap::parser::ValueSource::CommandLine);
let Some(inline) = typed.action.inline_mut() else {
return Ok(());
};
inline.author_given = given;
env_author_fill(&mut inline.author, &mut inline.author_given)
.map_err(|m| command.error(clap::error::ErrorKind::ValueValidation, m))?;
Ok(())
}
fn view_given(matches: &clap::ArgMatches) -> bool {
READ_OPTION_IDS.into_iter().any(|id| {
matches.try_contains_id(id).unwrap_or(false)
&& matches.value_source(id) == Some(clap::parser::ValueSource::CommandLine)
})
}
fn compare_json(compare: &CompareArgs) -> serde_json::Value {
let mut args = serde_json::to_value(compare).expect("UTF-8 CLI arguments");
args["original"] =
serde_json::to_value(compare.original.as_ref().or(compare.original_pos.as_ref()))
.expect("UTF-8 path");
args["modified"] =
serde_json::to_value(compare.modified.as_ref().or(compare.modified_pos.as_ref()))
.expect("UTF-8 path");
let input_format = |path: Option<&PathBuf>| {
path.and_then(|p| Format::of_path(p))
.filter(|f| matches!(f, Format::Docx | Format::Md))
};
args["old_format"] = serde_json::to_value(input_format(
compare.original.as_ref().or(compare.original_pos.as_ref()),
))
.expect("format");
args["new_format"] = serde_json::to_value(input_format(
compare.modified.as_ref().or(compare.modified_pos.as_ref()),
))
.expect("format");
let kind = output_format(Task::Compare, compare.output.as_deref(), None)
.ok()
.flatten();
args["output_format"] = serde_json::to_value(kind).expect("format");
if matches!(kind, None | Some(Format::Md)) {
args["view"] = serde_json::to_value(&compare.read).expect("UTF-8 CLI arguments");
}
args
}
fn view_is_output(args: &serde_json::Value) -> bool {
let markdown = |format: &serde_json::Value| format == "md";
args["output_format"].is_null()
|| (args["output_format"] == "md"
&& !(markdown(&args["old_format"]) && markdown(&args["new_format"])))
}
fn view_not_supported(command: &mut clap::Command) -> clap::Error {
command.error(
clap::error::ErrorKind::InvalidSubcommand,
"this adapter prints no agent view; write the redline with -o FILE.docx",
)
}
fn error_json(error: &clap::Error) -> String {
serde_json::json!({
"exit_code": error.exit_code(),
"stream": if error.use_stderr() { "stderr" } else { "stdout" },
"text": error.to_string(),
})
.to_string()
}
pub fn wants_json(argv: &[String]) -> bool {
let model = top_level_command();
let arguments: Vec<std::ffi::OsString> = std::iter::once("jubarte".into())
.chain(argv.iter().map(Into::into))
.collect();
let routed = edit_arguments(&model, &arguments);
let tokens: Vec<&str> = routed
.iter()
.skip(1)
.filter_map(|a| a.to_str())
.take_while(|a| *a != "--")
.collect();
let mut command = &model;
let mut rest = &tokens[..];
loop {
let (options, next) = spelled_options(command, rest);
if options.iter().any(|option| option.name == "--json") {
return true;
}
let Some(word) = rest.get(next) else {
return false;
};
if let Some(task) = command.find_subcommand(word) {
command = task;
}
rest = &rest[next + 1..];
}
}
pub fn json_error(code: &str, message: &str, usage: Option<&str>) -> String {
let mut error = serde_json::json!({ "code": code, "message": message });
if let Some(usage) = usage {
error["usage"] = usage.into();
}
format!("{}\n", serde_json::json!({ "error": error }))
}
pub fn runtime_json_error(message: &str, exit: u8) -> String {
let lead = message.split_once(": ").map_or("", |(lead, _)| lead);
let coded = lead.len() >= 3
&& lead.starts_with(|c: char| c.is_ascii_uppercase())
&& lead
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
let code = if coded {
lead
} else if exit == 2 {
"USAGE"
} else {
"ERROR"
};
json_error(code, message, None)
}
pub fn usage_json_error(error: &clap::Error, argv: &[String], program: &str) -> Option<String> {
let (message, usage) = usage_parts(error, argv, program)?;
Some(json_error("USAGE", &message, usage.as_deref()))
}
pub fn removed_json_error(
error: &clap::Error,
argv: &[String],
program: &str,
message: &str,
) -> String {
let usage = usage_parts(error, argv, program).and_then(|(_, usage)| usage);
json_error("USAGE", message, usage.as_deref())
}
fn usage_parts(
error: &clap::Error,
argv: &[String],
program: &str,
) -> Option<(String, Option<String>)> {
if !error.use_stderr() {
return None;
}
#[derive(Clone, Copy)]
enum Part {
Message,
Tip,
Usage,
Other,
}
let text = error.render().to_string();
let (mut message, mut tips, mut usage) = (String::new(), Vec::<String>::new(), Vec::new());
let mut part = Part::Other;
for line in text.lines() {
let trimmed = line.trim();
if let Some(first) = line.strip_prefix("error: ") {
message.push_str(first);
part = Part::Message;
} else if let Some(tip) = trimmed.strip_prefix("tip: ") {
tips.push(tip.to_string());
part = Part::Tip;
} else if let Some(first) = line.strip_prefix("Usage: ") {
usage.push(first.trim());
part = Part::Usage;
} else if trimmed.is_empty() {
part = Part::Other;
} else {
match (part, tips.last_mut()) {
(Part::Message, _) => {
message.push(' ');
message.push_str(trimmed);
}
(Part::Tip, Some(tip)) => {
tip.push(' ');
tip.push_str(trimmed);
}
(Part::Usage, _) => usage.push(trimmed),
_ => {}
}
}
}
for tip in tips {
message.push_str(&format!(" (tip: {tip})"));
}
let usage = task_usage(argv, program).or_else(|| (!usage.is_empty()).then(|| usage.join("\n")));
Some((message, usage))
}
fn task_usage(argv: &[String], program: &str) -> Option<String> {
let mut model = Cli::command().bin_name(program.to_string());
model.build();
let name = argv
.iter()
.take_while(|a| *a != "--")
.find(|a| !a.starts_with('-'))?;
let usage = model.find_subcommand_mut(name)?.render_usage().to_string();
let usage = usage.strip_prefix("Usage: ")?;
Some(usage.lines().map(str::trim).collect::<Vec<_>>().join("\n"))
}
fn missing_task(command: &mut clap::Command, program: &str, task: &str) -> clap::Error {
command.error(
clap::error::ErrorKind::InvalidSubcommand,
format!("this {program} has no {task} task; the `jubarte` binary has it"),
)
}
fn parse_subcommand_json(
command: &mut clap::Command,
matches: &clap::ArgMatches,
arguments: &[String],
accepts: &dyn Fn(&str) -> bool,
) -> Result<serde_json::Value, clap::Error> {
let mut task = Command::from_arg_matches(matches)?;
fill_flag_operations(&mut task, matches, command)?;
resolve_plan(&mut task);
apply_retired(
&mut task,
&retired_spellings(arguments.iter().map(String::as_str)),
);
fill_task_date(&mut task);
let mut value = serde_json::to_value(&task).expect("UTF-8 CLI arguments");
if let Command::Compare(compare) = &mut task {
if let Some((_, args)) = matches.subcommand() {
compare.view_given = view_given(args);
}
value["args"] = compare_json(compare);
if view_is_output(&value["args"]) && !accepts("read") {
return Err(view_not_supported(command));
}
}
if let Command::Diff {
old,
new,
output,
to,
from,
..
} = &task
{
let input_format = |path: &std::path::Path| {
from.or_else(|| {
Format::of_path(path).filter(|f| matches!(f, Format::Docx | Format::Md))
})
};
value["args"]["old_format"] = serde_json::to_value(input_format(old)).expect("format");
value["args"]["new_format"] = serde_json::to_value(input_format(new)).expect("format");
value["args"]["output_format"] = serde_json::to_value(
output_format(Task::Diff, output.as_deref(), *to)
.ok()
.flatten(),
)
.expect("format");
}
if let Command::Convert {
output,
markdown,
pdf,
png,
..
} = &task
{
let alias = pdf
.then_some(Format::Pdf)
.or_else(|| png.then_some(Format::Png));
value["args"]["output_format"] = serde_json::to_value(
output_format(Task::Convert, output.as_deref(), markdown.to.or(alias))
.ok()
.flatten(),
)
.expect("format");
}
if let Command::Edit {
file,
options,
plan,
operations,
..
}
| Command::Add {
file,
options,
plan,
operations,
..
} = &task
{
let recording = plan.is_some() && !operations.is_empty();
let (output, out_dir) = match options.target(file) {
_ if recording => (None, None),
EditTarget::Single(path) => (Some(path), None),
EditTarget::Bundle(dir) => (None, Some(dir)),
};
let slashed = |path: Option<&std::path::PathBuf>| {
path.map(|p| serde_json::Value::String(slash_path(p)))
.unwrap_or(serde_json::Value::Null)
};
value["args"]["plan"] = slashed(plan.as_ref());
value["args"]["output"] = slashed(output.as_ref());
value["args"]["out_dir"] = slashed(out_dir.as_ref());
value["args"]["author_given"] = serde_json::Value::Bool(options.author_given);
}
let written = match &task {
Command::Accept {
file,
output,
in_place,
..
} => {
if *in_place {
value["args"]["output"] = serde_json::Value::String(slash_path(file));
}
Some((
Task::Accept,
if *in_place {
Some(file.as_path())
} else {
output.as_deref()
},
))
}
Command::Reject {
file,
output,
in_place,
..
} => {
if *in_place {
value["args"]["output"] = serde_json::Value::String(slash_path(file));
}
Some((
Task::Reject,
if *in_place {
Some(file.as_path())
} else {
output.as_deref()
},
))
}
Command::Append { output, .. } => Some((Task::Append, Some(output.as_path()))),
Command::Scrub { output, .. } => Some((Task::Scrub, Some(output.as_path()))),
Command::Read { output, .. } => Some((Task::Read, output.as_deref())),
_ => None,
};
if let Some((writer, output)) = written {
let format = if matches!(
&task,
Command::Accept { in_place: true, .. } | Command::Reject { in_place: true, .. }
) {
Some(Format::Docx)
} else {
output_format(writer, output, None).ok().flatten()
};
value["args"]["output_format"] = serde_json::to_value(format).expect("format");
}
value["exit_code"] = 0.into();
Ok(value)
}
fn parse_implicit_compare_json(
command: &mut clap::Command,
matches: &clap::ArgMatches,
model: &clap::Command,
program: &str,
accepts: &dyn Fn(&str) -> bool,
) -> Result<serde_json::Value, clap::Error> {
let mut compare = CompareArgs::from_arg_matches(matches)?;
fill_date(&mut compare.datetime);
if let Some(name) = compare
.original_pos
.as_ref()
.and_then(|p| p.to_str())
.and_then(|name| model.find_subcommand(name))
.map(|task| task.get_name().to_string())
.filter(|name| !accepts(name))
{
return Err(missing_task(command, program, &name));
}
if compare.modified.is_none() && compare.modified_pos.is_none() {
if !accepts("read") {
return Err(command.error(
clap::error::ErrorKind::InvalidSubcommand,
"this task is not supported by this adapter",
));
}
let mut args = serde_json::to_value(&compare.read).expect("UTF-8 CLI arguments");
args["file"] =
serde_json::to_value(compare.original.as_ref().or(compare.original_pos.as_ref()))
.expect("UTF-8 path");
args["output"] = serde_json::to_value(&compare.output).expect("UTF-8 path");
args["force"] = compare.force.into();
args["output_format"] = serde_json::to_value(
output_format(Task::Read, compare.output.as_deref(), None)
.ok()
.flatten(),
)
.expect("format");
return Ok(serde_json::json!({"exit_code": 0, "command": "read", "args": args}));
}
compare.view_given = view_given(matches);
let args = compare_json(&compare);
if view_is_output(&args) && !accepts("read") {
return Err(view_not_supported(command));
}
Ok(serde_json::json!({"exit_code": 0, "command": "compare", "args": args}))
}
pub fn parse_json(arguments: &[String], program: &str, supported: &[String]) -> String {
let model = top_level_command();
let accepts = |name: &str| supported.is_empty() || supported.iter().any(|s| s == name);
let mut command = clap::Command::new(program.to_string())
.version(env!("JUBARTE_BUILD_VERSION"))
.help_template("{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{all-args}{after-help}")
.about("Read, edit, compare and render Word documents")
.color(clap::ColorChoice::Never)
.styles(styles())
.term_width(88)
.subcommand_help_heading("Tasks")
.arg_required_else_help(true)
.subcommands(
model
.get_subcommands()
.filter(|s| accepts(s.get_name()) || s.get_name() == "__edit-v2" && accepts("edit"))
.cloned(),
);
if accepts("compare") {
command = command
.args(model.get_arguments().cloned())
.groups(model.get_groups().cloned())
.args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true);
} else {
command = command
.args(model.get_arguments().filter(|a| a.is_global_set()).cloned())
.args_conflicts_with_subcommands(true)
.subcommand_required(true);
}
let examples: Vec<String> = [
("compare", "compare old.docx new.docx -o redline.docx"),
("read", "contract.docx"),
("read", "read contract.docx --json"),
("diff", "diff old.docx new.docx --format github"),
("convert", "convert contract.docx -o contract.pdf"),
]
.into_iter()
.filter(|(name, _)| accepts(name))
.map(|(_, example)| format!(" {program} {example}"))
.collect();
command = command.after_help(format!(
"Examples:\n{}\n\nRun {program} <task> --help for task options.",
examples.join("\n")
));
let argv = std::iter::once(program.to_string()).chain(arguments.iter().cloned());
let mut quiet = false;
let result = (|| {
if let Some(name) = arguments
.iter()
.take_while(|token| *token != "--")
.find(|token| !token.starts_with('-'))
.and_then(|name| model.find_subcommand(name))
.map(|task| task.get_name().to_string())
.filter(|name| !accepts(name))
{
return Err(missing_task(&mut command, program, &name));
}
let tokens: Vec<String> = hoist_quiet(&command, &argv.collect::<Vec<_>>());
let tokens: Vec<String> = edit_actions::route(
&tokens
.iter()
.map(std::ffi::OsString::from)
.collect::<Vec<_>>(),
&command,
)
.into_iter()
.map(|s| s.to_string_lossy().into_owned())
.collect();
let matches = command
.try_get_matches_from_mut(tokens.clone())
.map_err(|e| usage_error(&command, &tokens, e))?;
validate_matches(&matches, &mut command)?;
quiet = matches.get_flag("quiet");
if matches.subcommand().is_some() {
parse_subcommand_json(&mut command, &matches, arguments, &accepts)
} else {
parse_implicit_compare_json(&mut command, &matches, &model, program, &accepts)
}
})();
match result {
Ok(mut value) => {
value["args"]["quiet"] = quiet.into();
value["notes"] = notes(arguments).into();
value.to_string()
}
Err(error) => match removed_spellings(arguments.iter().map(String::as_str)).first() {
Some((old, now)) => {
let removed = removed_error(old, now);
let mut value = serde_json::json!({
"exit_code": 2,
"stream": "stderr",
"text": format!("{removed}\n"),
});
if wants_json(arguments) {
let message = removed.strip_prefix("error: ").unwrap_or(&removed);
value["json"] = removed_json_error(&error, arguments, program, message).into();
}
value.to_string()
}
None => {
let mut value: serde_json::Value =
serde_json::from_str(&error_json(&error)).unwrap_or_default();
value["notes"] = notes(arguments).into();
if wants_json(arguments)
&& let Some(line) = usage_json_error(&error, arguments, program)
{
value["json"] = line.into();
}
value.to_string()
}
},
}
}
#[cfg(test)]
mod slash_path_tests {
use super::{slash_path, unverbatimed};
use std::path::Path;
#[test]
fn slash_path_uses_forward_slashes() {
assert_eq!(slash_path(Path::new(r"dir\sub\name.md")), "dir/sub/name.md");
assert_eq!(slash_path(Path::new("plain")), "plain");
}
#[test]
fn slash_path_canonical_drive_letter_spells_agent_facing() {
let formatted = slash_path(Path::new(r"C:\Users\Alice\out.docx"));
assert_eq!(formatted, "C:/Users/Alice/out.docx");
assert!(!formatted.contains('\\'), "backslashes: {formatted}");
}
#[test]
fn unverbatimed_keeps_every_nonverbatim_path() {
for path in ["plain", r"dir\sub", r"C:\a\b", r"\\server\share\x"] {
assert_eq!(unverbatimed(Path::new(path)), None, "{path}");
}
}
#[cfg(not(windows))]
#[test]
fn a_verbatim_literal_is_an_ordinary_name_off_windows() {
for path in [r"\\?\C:\a\b", r"\\?\UNC\s\sh\x"] {
assert_eq!(unverbatimed(Path::new(path)), None, "{path}");
}
}
#[cfg(windows)]
#[test]
fn unverbatimed_strips_every_verbatim_prefix_kind() {
for (path, stripped) in [
(r"\\?\C:\a\b", "C:/a/b"),
(r"\\?\c:\a", "C:/a"),
(r"\\?\C:", "C:"),
(r"\\?\UNC\server\share\x", "//server/share/x"),
(r"\\?\GLOBALROOT\Device\Foo", "GLOBALROOT/Device/Foo"),
] {
assert_eq!(slash_path(Path::new(path)), stripped, "{path}");
assert!(!slash_path(Path::new(path)).contains("//?"), "{path}");
}
}
#[cfg(windows)]
#[test]
fn unverbatimed_returns_the_stripped_components() {
assert_eq!(
unverbatimed(Path::new(r"\\?\C:\a\b")).as_deref(),
Some(Path::new(r"C:\a\b"))
);
assert_eq!(
unverbatimed(Path::new(r"\\?\UNC\server\share\x")).as_deref(),
Some(Path::new(r"\\server\share\x"))
);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod parse_branch_tests {
use super::*;
fn parse(line: &str) -> Result<(), String> {
let mut argv = vec!["jubarte".to_string()];
argv.extend(line.split(' ').map(str::to_string));
Cli::try_parse_from(argv)
.map(drop)
.map_err(|e| e.to_string())
}
const LINES: &[(&str, &str)] = &[
(
"edit x.docx -p p1 --anchor a --anchor b --content c",
"-p p1: --anchor given twice",
),
(
"edit x.docx -p p1 --content a --content b",
"-p p1: --content given twice",
),
(
"edit x.docx -p p1 --anchor a --occurrence 2 --occurrence 3 --content c",
"-p p1: --occurrence given twice",
),
(
"edit x.docx --anchor a -p p1 --content c",
"--anchor comes before the first -p/--location",
),
(
"edit x.docx -p p1 --occurrence 2 --content c",
"-p p1: --occurrence must come after --anchor",
),
(
"edit x.docx -p c1 --reply hi --reply again",
"-p c1: --reply given twice",
),
("edit x.docx -p c1 --resolve", ""),
(
"edit --plan doc.docx",
"--plan doc.docx names a Word document",
),
(
"edit --plan=doc.docx",
"--plan doc.docx names a Word document",
),
(
"edit --out-dir out.docx",
"--out-dir out.docx names a Word document",
),
("convert a.docx -o .md", ""),
("convert a.md --from docx -o b.docx", ""),
(
"convert a.docx --pdf --pages 1,x",
"'x' is not a page number",
),
("convert a.docx --pdf --pages 1-3,5", ""),
("read a.docx --for-edit -o out.md", "--for-edit prints JSON"),
(
"read a.docx --tables -o out.json",
"--tables writes the grids as text",
),
(
"read a.docx --ignore-case",
"--ignore-case needs --find TEXT or --regex PATTERN",
),
("read a.docx --ignore-case --for-edit", ""),
("compare original", "compare needs <MODIFIED>"),
("diff a.docx b.docx --format patch --columns 80", ""),
(
"diff a.docx b.docx --context 3",
"--context requires a text diff format",
),
(
"diff a.docx b.docx --full-lines",
"--full-lines requires a text diff format",
),
(
"edit insert x.docx --kind paragraph --at p1 --text hi -o y.docx",
"--kind paragraph requires --position",
),
(
"edit insert x.docx --kind text --at p1 --text hi -o y.docx",
"--kind paragraph requires --position",
),
(
"edit insert x.docx --kind text --position after --at p1 --text hi -o y.docx",
"--kind paragraph requires --position",
),
(
"edit insert x.docx --kind paragraph --position after --at p1 --text hi -o y.docx",
"",
),
(
"edit insert x.docx --kind text --edge end --at p1 --text hi -o y.docx",
"",
),
("edit -q replace x.docx --find a --text b -o y.docx", ""),
(
"edit replace x.docx --find a --text b",
"writes require -o FILE",
),
(
"edit replace x.docx --find a --text b --dry-run --expect-sha256 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"",
),
(
"edit replace x.docx --find a --text b --dry-run --expect-sha256 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"64 lowercase hexadecimal",
),
(
"edit replace x.docx --find a --text b --dry-run --expect-sha256 abc",
"64 lowercase hexadecimal",
),
];
#[test]
fn command_lines_parse_or_say_why_not() {
for (line, refusal) in LINES {
match parse(line) {
Ok(()) => assert!(refusal.is_empty(), "{line} parsed"),
Err(e) => {
assert!(!refusal.is_empty(), "{line}: {e}");
assert!(e.contains(refusal), "{line}: {e}");
}
}
}
}
#[test]
fn json_errors_take_a_leading_upper_case_code() {
let code = |message: &str| -> String {
let v: serde_json::Value =
serde_json::from_str(&runtime_json_error(message, 1)).unwrap();
v["error"]["code"].as_str().unwrap().to_string()
};
assert_eq!(code("STALE_SOURCE: x"), "STALE_SOURCE");
assert_eq!(code("AB_1: x"), "AB_1");
assert_eq!(code("ab: x"), "ERROR");
assert_eq!(code("Abc1: x"), "ERROR");
assert_eq!(code("AB: x"), "ERROR");
assert_eq!(code("nothing"), "ERROR");
}
}