use std::{ffi::OsString, path::PathBuf};
use clap::{Args, Subcommand};
use serde::Serialize;
#[derive(Args, Debug, Serialize)]
pub struct TypedEdit {
#[command(subcommand)]
#[serde(flatten)]
pub action: EditAction,
}
#[derive(Subcommand, Debug, Serialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum EditAction {
#[command(
override_usage = "jubarte edit replace [OPTIONS] <FILE> --find TEXT (--text TEXT|--text-file FILE)"
)]
Replace {
#[command(flatten)]
inline: InlineOptions,
#[arg(long)]
find: String,
#[arg(long)]
at: Option<String>,
#[arg(long, conflicts_with = "at")]
story: Option<String>,
#[arg(long, value_parser = positive, conflicts_with = "all_matches")]
occurrence: Option<usize>,
#[arg(long, requires = "expect_count")]
all_matches: bool,
#[arg(long, requires = "all_matches", value_parser = positive)]
expect_count: Option<usize>,
#[command(flatten)]
payload: TextPayload,
},
#[command(
override_usage = "jubarte edit rewrite [OPTIONS] <FILE> --at ID (--text TEXT|--text-file FILE)"
)]
Rewrite {
#[command(flatten)]
inline: InlineOptions,
#[arg(long)]
at: String,
#[command(flatten)]
payload: TextPayload,
},
#[command(
override_usage = "jubarte edit insert [OPTIONS] <FILE> --kind text|paragraph --at ID (--text TEXT|--text-file FILE)"
)]
Insert {
#[command(flatten)]
inline: InlineOptions,
#[arg(long, value_parser = ["text", "paragraph"])]
kind: String,
#[arg(long)]
at: String,
#[arg(long, conflicts_with_all = ["after_text", "edge", "position"])]
before_text: Option<String>,
#[arg(long, conflicts_with_all = ["edge", "position"])]
after_text: Option<String>,
#[arg(long, value_parser = ["start", "end"], conflicts_with_all = ["position", "occurrence"])]
edge: Option<String>,
#[arg(long, value_parser = ["before", "after"], conflicts_with = "occurrence")]
position: Option<String>,
#[arg(long, value_parser = positive)]
occurrence: Option<usize>,
#[command(flatten)]
payload: TextPayload,
},
#[command(
override_usage = "jubarte edit delete [OPTIONS] <FILE> --at ID (--find TEXT|--whole-block)"
)]
Delete {
#[command(flatten)]
inline: InlineOptions,
#[arg(long)]
at: String,
#[arg(
long,
required_unless_present = "whole_block",
conflicts_with = "whole_block"
)]
find: Option<String>,
#[arg(long, required_unless_present = "find", conflicts_with = "occurrence")]
whole_block: bool,
#[arg(long, value_parser = positive, requires = "find")]
occurrence: Option<usize>,
},
#[command(
override_usage = "jubarte edit apply [OPTIONS] <FILE> --plan FILE",
mut_arg("output", |a| a.help("Primary edited DOCX; required unless bundling, replacing FILE or dry-running"))
)]
Apply {
file: PathBuf,
#[arg(long, value_name = "FILE", value_parser = super::plan_path())]
plan: PathBuf,
#[arg(long)]
allow_unbound_plan: bool,
#[command(flatten)]
delivery: DeliveryOptions,
},
}
#[derive(Args, Debug, Serialize)]
#[group(skip)]
pub struct TextPayload {
#[arg(
long,
required_unless_present = "text_file",
conflicts_with = "text_file"
)]
pub text: Option<String>,
#[arg(long, value_name = "FILE", required_unless_present = "text")]
pub text_file: Option<PathBuf>,
#[arg(long)]
pub comment: Option<String>,
}
#[derive(Args, Debug, Serialize)]
pub struct InlineOptions {
pub file: PathBuf,
#[arg(short = 'a', long, default_value = "Jubarte", value_parser = super::parse_author)]
pub author: String,
#[arg(skip)]
#[serde(skip)]
pub author_given: bool,
#[arg(short = 'd', long = "datetime", value_parser = super::parse_datetime)]
pub datetime: Option<String>,
#[arg(long, default_value = "on", value_parser = ["on", "off"])]
pub track: String,
#[arg(long, default_value = "keep", value_parser = ["keep", "accept", "reject", "refuse"])]
pub existing_revisions: String,
#[arg(long)]
pub accept_change: Vec<String>,
#[arg(long)]
pub reject_change: Vec<String>,
#[arg(long, value_name = "FILE", value_parser = super::plan_path(), conflicts_with_all = ["output", "out_dir", "report", "emit", "expect", "dry_run", "in_place"])]
pub save_plan: Option<PathBuf>,
#[command(flatten)]
pub delivery: DeliveryOptions,
}
#[derive(Args, Debug, Serialize)]
pub struct DeliveryOptions {
#[arg(long, conflicts_with_all = ["output", "out_dir", "dry_run"])]
pub in_place: bool,
#[arg(short = 'o', long, value_name = "FILE", conflicts_with = "out_dir")]
pub output: Option<PathBuf>,
#[arg(long, value_name = "NEW_DIR")]
pub out_dir: Option<PathBuf>,
#[arg(long, value_name = "FILE")]
pub report: Option<PathBuf>,
#[arg(long, value_delimiter = ',', value_parser = ["document", "patch", "report"])]
pub emit: Vec<String>,
#[arg(long, value_name = "FILE")]
pub expect: Option<PathBuf>,
#[arg(long, value_name = "HASH", value_parser = digest)]
pub expect_sha256: Option<String>,
#[arg(long, conflicts_with_all = ["output", "out_dir"])]
pub dry_run: bool,
#[arg(long)]
pub require_change: bool,
#[arg(long)]
pub force: bool,
#[arg(long)]
pub keep_others: bool,
#[arg(long, conflicts_with = "jsonl")]
pub json: bool,
#[arg(long)]
pub jsonl: bool,
}
pub(super) fn positive(s: &str) -> Result<usize, String> {
s.parse()
.ok()
.filter(|n| *n > 0)
.ok_or_else(|| "must be a positive, 1-based integer".into())
}
pub(super) fn digest(s: &str) -> Result<String, String> {
if s.len() == 64
&& s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
Ok(s.into())
} else {
Err("must be 64 lowercase hexadecimal characters".into())
}
}
pub fn route(arguments: &[OsString], model: &clap::Command) -> Vec<OsString> {
let mut routed = arguments.to_vec();
if arguments.get(1).is_none_or(|a| a != "edit") {
return routed;
}
let action = arguments.iter().skip(2).find(|a| {
!a.to_str().is_some_and(|s| {
s == "--quiet" || s.starts_with('-') && s.len() > 1 && s[1..].bytes().all(|b| b == b'q')
})
});
if !action.is_some_and(|a| {
matches!(
a.to_str(),
Some("replace" | "rewrite" | "insert" | "delete" | "apply" | "template")
)
}) {
return routed;
}
if model.clone().try_get_matches_from(arguments).is_ok() {
return routed;
}
if action.is_some_and(|a| a == "template") {
routed[1] = "__edit-template".into();
return routed;
}
routed[1] = "__edit-v2".into();
routed
}
pub(super) fn validate(
args: &clap::ArgMatches,
model: &mut clap::Command,
) -> Result<(), clap::Error> {
let (action, args) = args.subcommand().expect("typed action required");
let present = |id| {
args.try_contains_id(id).unwrap_or(false)
&& args.value_source(id) == Some(clap::parser::ValueSource::CommandLine)
};
let error = |message: &str| {
model
.clone()
.error(clap::error::ErrorKind::ArgumentConflict, message)
};
if !["output", "out_dir", "dry_run", "save_plan", "in_place"]
.into_iter()
.any(present)
{
return Err(error(
"writes require -o FILE or --out-dir NEW_DIR or --in-place; use --dry-run or inline --save-plan FILE",
));
}
if action == "insert" {
let paragraph = args
.get_one::<String>("kind")
.is_some_and(|s| s == "paragraph");
if paragraph != present("position")
|| !paragraph
&& !["before_text", "after_text", "edge"]
.into_iter()
.any(present)
{
return Err(error(
"--kind paragraph requires --position before|after; --kind text requires --before-text, --after-text or --edge",
));
}
}
Ok(())
}
impl EditAction {
pub fn name(&self) -> &'static str {
match self {
Self::Replace { .. } => "replace",
Self::Rewrite { .. } => "rewrite",
Self::Insert { .. } => "insert",
Self::Delete { .. } => "delete",
Self::Apply { .. } => "apply",
}
}
pub fn inline(&self) -> Option<&InlineOptions> {
match self {
Self::Replace { inline, .. }
| Self::Rewrite { inline, .. }
| Self::Insert { inline, .. }
| Self::Delete { inline, .. } => Some(inline),
Self::Apply { .. } => None,
}
}
pub fn inline_mut(&mut self) -> Option<&mut InlineOptions> {
match self {
Self::Replace { inline, .. }
| Self::Rewrite { inline, .. }
| Self::Insert { inline, .. }
| Self::Delete { inline, .. } => Some(inline),
Self::Apply { .. } => None,
}
}
pub fn author_was_given(&self) -> bool {
self.inline().is_none_or(|inline| inline.author_given)
}
pub fn payload(&self) -> Option<&TextPayload> {
match self {
Self::Replace { payload, .. }
| Self::Rewrite { payload, .. }
| Self::Insert { payload, .. } => Some(payload),
_ => None,
}
}
pub fn file(&self) -> &std::path::Path {
match self {
Self::Apply { file, .. } => file,
_ => &self.inline().expect("inline").file,
}
}
pub fn delivery(&self) -> &DeliveryOptions {
match self {
Self::Apply { delivery, .. } => delivery,
_ => &self.inline().expect("inline").delivery,
}
}
}