docrs-cli 0.3.10

The docrs command: find, replace, review, compare and compose .docx files without disturbing the rest, and convert Markdown or editor HTML to Word with a template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! `docrs` command-line interface.
//!
//! Exit codes: 0 success; 2 invalid usage or argument; 3 safe refusal
//! (nothing changed); 4 resource budget exceeded; 5 I/O failure; 70 internal
//! error (a panic is reported as one, reason `internal_panic`). With
//! `--json`, stdout carries one JSON object with `schema_version: 1`; errors,
//! argument errors included, are JSON on stdout as well.
//!
//! Mutating commands select and edit within one process and publish success
//! only after the output file has been atomically committed.

mod commands;

use std::process::ExitCode;

use clap::{Parser, Subcommand};
use docrs::{Error, ErrorKind};

#[derive(Parser)]
#[command(
    name = "docrs",
    version,
    about = "Preservation-first DOCX inspection and safe editing"
)]
pub struct Cli {
    /// Emit machine-readable JSON (schema_version 1).
    #[arg(long, global = true)]
    json: bool,
    /// Use the trusted-input resource profile instead of the default budgets.
    #[arg(long, global = true)]
    trusted: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
pub enum Command {
    /// Classify a file before opening it (never fails on bad input).
    Diagnose {
        /// File to diagnose.
        file: std::path::PathBuf,
    },
    /// Part-by-part semantic diff of two packages.
    Diff {
        /// First package.
        a: std::path::PathBuf,
        /// Second package.
        b: std::path::PathBuf,
    },
    /// Every block of every story, plus blind-region counts.
    Outline {
        /// Input package.
        input: std::path::PathBuf,
        /// Text layer: current, original or all.
        #[arg(long, default_value = "current")]
        view: String,
    },
    /// Locate text (exact by default) across every story.
    Find {
        /// Input package.
        input: std::path::PathBuf,
        /// Text to find.
        text: String,
        /// Use normalized (case/typography/whitespace-folded) matching.
        #[arg(long)]
        normalized: bool,
        /// Text layer: current, original or all.
        #[arg(long, default_value = "current")]
        view: String,
        /// Restrict to one story (e.g. word/document.xml).
        #[arg(long)]
        story: Option<String>,
    },
    /// Replace one exact occurrence (or all with --all) and save atomically.
    Replace {
        /// Input package.
        input: std::path::PathBuf,
        /// Text to find.
        #[arg(long)]
        find: String,
        /// Replacement text.
        #[arg(long = "with")]
        with_text: String,
        /// Output path (may equal the input).
        #[arg(long)]
        out: std::path::PathBuf,
        /// Replace every match (per-match refusals are reported).
        #[arg(long)]
        all: bool,
        /// Use normalized matching.
        #[arg(long)]
        normalized: bool,
        /// Select the nth match (1-based) instead of requiring uniqueness.
        #[arg(long)]
        nth: Option<usize>,
        /// Restrict to one story.
        #[arg(long)]
        story: Option<String>,
        /// Proceed despite Restrict Editing (the setting is kept).
        #[arg(long)]
        acknowledge_protection: bool,
    },
    /// Unified diff of visible block text between two documents.
    TextDiff {
        /// First document.
        a: std::path::PathBuf,
        /// Second document.
        b: std::path::PathBuf,
        /// Text layer: current, original or all.
        #[arg(long, default_value = "current")]
        view: String,
    },
    /// What accepting every pending revision would change (original vs current).
    Pending {
        /// Input document.
        input: std::path::PathBuf,
    },
    /// Produce a verified tracked-changes redline turning ORIGINAL into REVISED.
    Compare {
        /// Original document.
        original: std::path::PathBuf,
        /// Revised document.
        revised: std::path::PathBuf,
        /// Revision author.
        #[arg(long)]
        author: String,
        /// Revision date (ISO 8601 with zone; default now).
        #[arg(long)]
        date: Option<String>,
        /// Use whole-block granularity instead of word level.
        #[arg(long)]
        block: bool,
        /// Resolve pending input revisions first: accept or reject.
        #[arg(long)]
        materialize: Option<String>,
        /// Proceed despite Restrict Editing on the original (the setting is kept).
        #[arg(long)]
        acknowledge_protection: bool,
        /// Output path for the redline.
        #[arg(long)]
        out: std::path::PathBuf,
    },
    /// Pending tracked changes, in document order.
    Revisions {
        /// Input document.
        input: std::path::PathBuf,
    },
    /// Accept or reject every pending revision (optionally one author's).
    Resolve {
        /// Input document.
        input: std::path::PathBuf,
        /// Accept the revisions.
        #[arg(long, conflicts_with = "reject", required_unless_present = "reject")]
        accept: bool,
        /// Reject the revisions.
        #[arg(long)]
        reject: bool,
        /// Only revisions by this author.
        #[arg(long)]
        author: Option<String>,
        /// Output path (may equal the input).
        #[arg(long)]
        out: std::path::PathBuf,
        /// Proceed despite Restrict Editing (the setting is kept).
        #[arg(long)]
        acknowledge_protection: bool,
    },
    /// Append SOURCE's body (styles, numbering, media, links, bookmarks reconciled).
    Append {
        /// Destination document.
        input: std::path::PathBuf,
        /// Document whose body is appended.
        source: std::path::PathBuf,
        /// Style reconciliation: match_by_name or import_renamed.
        #[arg(long, default_value = "match_by_name")]
        styles: String,
        /// Section start: new_page or continuous.
        #[arg(long, default_value = "new_page")]
        section: String,
        /// Letterhead: destination or source.
        #[arg(long, default_value = "destination")]
        headers: String,
        /// Output path (may equal the input).
        #[arg(long)]
        out: std::path::PathBuf,
        /// Proceed despite Restrict Editing (the setting is kept).
        #[arg(long)]
        acknowledge_protection: bool,
    },
    /// Copy a range of SOURCE's body blocks after the paragraph containing --anchor.
    InsertFrom {
        /// Destination document.
        input: std::path::PathBuf,
        /// Document the blocks come from.
        source: std::path::PathBuf,
        /// Exact text in the source paragraph that starts the range.
        #[arg(long)]
        start: String,
        /// Exact text in the destination paragraph to insert after.
        #[arg(long)]
        anchor: String,
        /// Exact text in the source paragraph that ends the range.
        #[arg(long, conflicts_with = "count")]
        end: Option<String>,
        /// Number of blocks to copy when there is no --end.
        #[arg(long, default_value_t = 1)]
        count: i64,
        /// Leave out the start block.
        #[arg(long)]
        exclude_start: bool,
        /// Leave out the end block (requires --end).
        #[arg(long, requires = "end")]
        exclude_end: bool,
        /// Style reconciliation: match_by_name or import_renamed.
        #[arg(long, default_value = "match_by_name")]
        styles: String,
        /// Output path (may equal the input).
        #[arg(long)]
        out: std::path::PathBuf,
        /// Proceed despite Restrict Editing (the setting is kept).
        #[arg(long)]
        acknowledge_protection: bool,
    },
    /// Convert Markdown, editor HTML or TipTap JSON into a .docx styled by a reference document.
    FromMarkdown {
        /// Markdown, HTML or TipTap JSON (`editor.getJSON()`) file (`-` reads
        /// standard input).
        input: std::path::PathBuf,
        /// Source format: markdown, html or tiptap (default: html for
        /// .html/.htm files, tiptap for .json, else markdown).
        #[arg(long)]
        from: Option<String>,
        /// Reference document supplying styles, lists, page setup, headers
        /// and footers (default: the bundled blank document).
        #[arg(long)]
        reference: Option<std::path::PathBuf>,
        /// Output path.
        #[arg(long)]
        out: std::path::PathBuf,
        /// Replace only the body paragraph reading exactly this text.
        #[arg(long, conflicts_with = "append")]
        placeholder: Option<String>,
        /// Append after the reference document's body instead of replacing it.
        #[arg(long)]
        append: bool,
        /// Map a style role to an existing style, e.g. code_block="My Code" (repeatable).
        #[arg(long = "style", value_name = "ROLE=STYLE")]
        styles: Vec<String>,
        /// Refuse when the reference document lacks a style (default: add it).
        #[arg(long)]
        strict_styles: bool,
        /// Refuse instead of warning when something cannot be converted faithfully.
        #[arg(long)]
        strict: bool,
        /// Directory relative image paths resolve against (default: the Markdown file's).
        #[arg(long)]
        resource_path: Option<std::path::PathBuf>,
        /// Add a table of contents (overrides front matter `toc`).
        #[arg(long, conflicts_with = "no_toc")]
        toc: bool,
        /// Never add a table of contents from front matter.
        #[arg(long)]
        no_toc: bool,
        /// Heading levels in the table of contents (1-9).
        #[arg(long)]
        toc_depth: Option<i64>,
        /// Title above the table of contents (default: the title of the reference document's own contents, else Table of Contents)
        #[arg(long)]
        toc_title: Option<String>,
        /// Add N to every heading level (-1 makes `##` a Heading 1).
        #[arg(long, allow_hyphen_values = true, default_value_t = 0)]
        shift_heading_level: i8,
        /// Typographic quotes, dashes and ellipses.
        #[arg(long)]
        smart: bool,
        /// Do not render the front-matter title block.
        #[arg(long)]
        no_title_block: bool,
        /// Do not copy front matter into the document properties.
        #[arg(long)]
        no_properties: bool,
        /// Do not caption stand-alone images with their alt text (HTML
        /// input never adds captions).
        #[arg(long)]
        no_captions: bool,
        /// Ignore the reference's List Bullet / List Number numbering and
        /// use the converter's own list definitions.
        #[arg(long)]
        converter_lists: bool,
        /// Ask Word to update the table of contents on open (it prompts).
        #[arg(long)]
        toc_page_numbers: bool,
        /// Leave the table of contents without the page numbers this
        /// conversion computes by estimating Word's layout.
        #[arg(long)]
        no_toc_numbers: bool,
        /// Add a centred page number footer when the reference has none.
        #[arg(long)]
        page_numbers: bool,
        /// Keep the reference's first page as a cover: the content starts on
        /// page 2 (default: only when a cover is detected).
        #[arg(long, conflicts_with = "no_cover_page")]
        cover_page: bool,
        /// Start the content on page 1, turning a detected cover's distinct
        /// first page off.
        #[arg(long)]
        no_cover_page: bool,
        /// Proceed despite Restrict Editing on the reference (the setting is kept).
        #[arg(long)]
        acknowledge_protection: bool,
        /// Refuse a reference package with irregularities Word tolerates
        /// (Office `[trash]` members, data in a ZIP directory entry) instead
        /// of setting them aside.
        #[arg(long)]
        strict_package: bool,
    },
    /// Write a starter reference document showing every Markdown style.
    MarkdownReference {
        /// Output path.
        #[arg(long)]
        out: std::path::PathBuf,
    },
    /// Show which style each Markdown role takes from a reference document.
    MarkdownStyles {
        /// Reference document (default: the bundled blank document).
        reference: Option<std::path::PathBuf>,
        /// Map a style role to an existing style (repeatable).
        #[arg(long = "style", value_name = "ROLE=STYLE")]
        styles: Vec<String>,
        /// Refuse a reference package with irregularities Word tolerates.
        #[arg(long)]
        strict_package: bool,
    },
    /// Estimate where Word for Mac breaks pages: each paragraph's page and
    /// position, headings' pages, fonts measured (JSON).
    Layout {
        /// The .docx file.
        file: std::path::PathBuf,
        /// A font file to measure with (repeatable), for fonts the bundled
        /// table lacks; it is read locally and never stored.
        #[arg(long = "font", value_name = "FILE")]
        fonts: Vec<std::path::PathBuf>,
    },
    /// What a conversion will take from a reference document: role styles,
    /// lifted branding, the section kept, headers and footers, cover page,
    /// compatibility mode and problems in plain language (JSON).
    MarkdownInspect {
        /// Reference document.
        reference: std::path::PathBuf,
        /// Map a style role to an existing style (repeatable).
        #[arg(long = "style", value_name = "ROLE=STYLE")]
        styles: Vec<String>,
        /// Inspect as for a conversion with page numbers.
        #[arg(long)]
        page_numbers: bool,
        /// Inspect as for a conversion forcing a cover page.
        #[arg(long, conflicts_with = "no_cover_page")]
        cover_page: bool,
        /// Inspect as for a conversion turning a cover page off.
        #[arg(long)]
        no_cover_page: bool,
        /// Refuse a reference package with irregularities Word tolerates.
        #[arg(long)]
        strict_package: bool,
    },
    /// Open and patch-save without edits (byte-identical when unchanged).
    Roundtrip {
        /// Input package.
        input: std::path::PathBuf,
        /// Output path.
        #[arg(long)]
        out: std::path::PathBuf,
    },
}

pub fn exit_code(err: &Error) -> u8 {
    match err.kind() {
        ErrorKind::Refusal(_) => 3,
        ErrorKind::InvalidArgument => 2,
        ErrorKind::ResourceLimit => 4,
        ErrorKind::Io => 5,
        ErrorKind::Internal => 70,
    }
}

fn main() -> ExitCode {
    // Clap's own errors would be plain text; under `--json` a script reads
    // stdout for the error envelope, so look for the flag before parsing.
    let json = std::env::args_os().any(|arg| arg == "--json");
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => return usage_error(err, json),
    };
    let limits = if cli.trusted {
        docrs::Limits::trusted()
    } else {
        docrs::Limits::default()
    };
    match guarded(|| commands::run(&cli.command, &limits, cli.json)) {
        Ok(code) => ExitCode::from(code),
        Err(err) => {
            if cli.json {
                println!("{}", err.to_json());
            } else {
                eprintln!("docrs: {err}");
            }
            ExitCode::from(exit_code(&err))
        }
    }
}

/// `--help` and `--version` print to stdout and succeed; every other parse
/// failure is an invalid argument (exit 2), as JSON under `--json`.
fn usage_error(err: clap::Error, json: bool) -> ExitCode {
    use clap::error::ErrorKind as Clap;
    if !json || matches!(err.kind(), Clap::DisplayHelp | Clap::DisplayVersion) {
        err.exit();
    }
    let reason = match err.kind() {
        Clap::UnknownArgument => "unknown_argument",
        Clap::InvalidSubcommand => "unknown_command",
        Clap::MissingRequiredArgument => "missing_argument",
        Clap::MissingSubcommand | Clap::DisplayHelpOnMissingArgumentOrSubcommand => {
            "missing_command"
        }
        Clap::InvalidValue | Clap::ValueValidation | Clap::InvalidUtf8 => "invalid_value",
        Clap::ArgumentConflict => "argument_conflict",
        _ => "invalid_usage",
    };
    let message = err.render().to_string();
    let message = message.trim().trim_start_matches("error: ");
    let err = Error::invalid_argument(reason, message);
    println!("{}", err.to_json());
    ExitCode::from(exit_code(&err))
}

/// Location of the last panic, recorded by the hook `guarded` installs.
static PANIC_LOCATION: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

/// Run `command`, turning a panic (a bug) into an internal error (exit 70,
/// reason `internal_panic`) instead of Rust's default report and exit 101.
/// `RUST_BACKTRACE` still prints the default report to stderr.
fn guarded(command: impl FnOnce() -> docrs::Result<u8>) -> docrs::Result<u8> {
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        if let Some(location) = info.location()
            && let Ok(mut slot) = PANIC_LOCATION.lock()
        {
            *slot = Some(location.to_string());
        }
        if std::env::var_os("RUST_BACKTRACE").is_some_and(|value| value != "0") {
            default_hook(info);
        }
    }));
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        #[cfg(debug_assertions)]
        if std::env::var_os("DOCRS_TEST_PANIC").is_some() {
            panic!("panic requested by DOCRS_TEST_PANIC");
        }
        command()
    }))
    .unwrap_or_else(|payload| {
        let what = payload
            .downcast_ref::<&str>()
            .map(|text| text.to_string())
            .or_else(|| payload.downcast_ref::<String>().cloned())
            .unwrap_or_else(|| "panic".to_string());
        let at = PANIC_LOCATION
            .lock()
            .ok()
            .and_then(|mut slot| slot.take())
            .map(|location| format!(" at {location}"))
            .unwrap_or_default();
        Err(Error::internal(
            "internal_panic",
            format!("docrs panicked{at}: {what} (this is a bug; please report it)"),
        ))
    })
}