flpdf-cli 0.10.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
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
480
481
482
483
484
//! End-to-end byte-identity: the `flpdf` CLI binary == qpdf 11.9.0 output.
//!
//! Unlike the library-level parity tests (`flpdf`'s `cmp_linearize_objstm_tests`,
//! which call `write_linearized` directly), these run the actual `flpdf` binary
//! through `rewrite --linearize [...]` and diff the full output bytes against the
//! committed qpdf goldens. This exercises the whole CLI path — argument parsing,
//! `WriterOptions` assembly, the write pipeline, and final framing — so a
//! divergence introduced by the CLI layer (not just the library) is caught.
//!
//! Gated on `qpdf-zlib-compat`: byte identity requires flpdf's DEFLATE to match
//! qpdf's classic-zlib output. `cargo test -p flpdf-cli --features qpdf-zlib-compat`
//! builds the binary with the zlib backend, so `cargo_bin("flpdf")` runs it.
//! Under the default (miniz_oxide) feature these tests are compiled out — the
//! only sanctioned byte deviation per the project's mimicry policy.

#![cfg(feature = "qpdf-zlib-compat")]

use assert_cmd::Command;
use std::path::{Path, PathBuf};
use std::process::Command as StdCommand;

fn fixture(stem: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(format!("{stem}.pdf"))
}

fn golden(stem: &str, kind: &str) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/golden/references")
        .join(stem)
        .join(format!("{kind}.pdf"));
    std::fs::read(&path).unwrap_or_else(|e| panic!("read golden {path:?}: {e}"))
}

/// Run `flpdf rewrite --linearize <extra...> --deterministic-id <fixture> <out>`
/// through the actual binary and return the written bytes.
fn run_cli(stem: &str, extra: &[&str]) -> Vec<u8> {
    let outdir = tempfile::tempdir().unwrap();
    let out = outdir.path().join("out.pdf");
    let input = fixture(stem);

    // Pass the paths through the builder API (`Path`/`PathBuf` are `AsRef<OsStr>`)
    // rather than `to_str().unwrap()`, which would panic on a non-UTF-8 temp path.
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--linearize")
        .args(extra)
        .arg("--deterministic-id")
        .arg(&input)
        .arg(&out)
        .assert()
        .success();

    std::fs::read(&out).unwrap_or_else(|e| panic!("read flpdf output for {stem}: {e}"))
}

/// Run the top-level qpdf-shaped linearization surface with warnings treated
/// as exit-zero, and return the written bytes.
fn run_cli_top_level_linearized(stem: &str, extra: &[&str]) -> Vec<u8> {
    let outdir = tempfile::tempdir().unwrap();
    let out = outdir.path().join("out.pdf");
    let input = fixture(stem);

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["--warning-exit-0", "--linearize"])
        .args(extra)
        .arg("--deterministic-id")
        .arg(&input)
        .arg(&out)
        .assert()
        .success();

    std::fs::read(&out).unwrap_or_else(|e| panic!("read flpdf output for {stem}: {e}"))
}

/// The pinned qpdf release these byte-parity assertions are derived from. A
/// different qpdf on `PATH` is treated as unavailable (and as an error on CI)
/// so its output is never mistaken for the 11.9.0 oracle.
const EXPECTED_QPDF_VERSION: &str = "qpdf version 11.9.0";

fn qpdf_available() -> bool {
    StdCommand::new("qpdf")
        .arg("--version")
        .output()
        .map(|output| {
            output.status.success()
                && String::from_utf8_lossy(&output.stdout)
                    .lines()
                    .next()
                    .is_some_and(|line| line.trim() == EXPECTED_QPDF_VERSION)
        })
        .unwrap_or(false)
}

/// Run the pinned qpdf CLI for a linearized byte-parity assertion.
fn run_qpdf(stem: &str, extra: &[&str]) -> Option<Vec<u8>> {
    if !qpdf_available() {
        if std::env::var_os("CI").is_some() {
            panic!(
                "{EXPECTED_QPDF_VERSION} is required for linearized byte-parity assertions on CI"
            );
        }
        eprintln!("skipping qpdf byte-parity assertion: {EXPECTED_QPDF_VERSION} is not available");
        return None;
    }

    let outdir = tempfile::tempdir().unwrap();
    let out = outdir.path().join("out.pdf");
    let input = fixture(stem);
    let status = StdCommand::new("qpdf")
        .arg("--deterministic-id")
        .arg("--linearize")
        .arg("--warning-exit-0")
        .args(extra)
        .arg(&input)
        .arg(&out)
        .status()
        .expect("spawn qpdf linearized byte-parity oracle");
    assert!(
        status.success(),
        "qpdf linearized byte-parity oracle failed"
    );
    Some(std::fs::read(&out).unwrap_or_else(|e| panic!("read qpdf output for {stem}: {e}")))
}

/// Run `flpdf rewrite --static-id <fixture> <out>` through the
/// actual binary and return the written bytes. Mirrors the library-level
/// `cmp_diff_zero_tests` but goes through the CLI so a divergence in argv
/// parsing, `WriterOptions` assembly, or defaults (e.g. `--newline-before-endstream`)
/// is caught end-to-end.
fn run_cli_full_rewrite_static_id(stem: &str) -> Vec<u8> {
    let outdir = tempfile::tempdir().unwrap();
    let out = outdir.path().join("out.pdf");
    let input = fixture(stem);

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--static-id")
        .arg(&input)
        .arg(&out)
        .assert()
        .success();

    std::fs::read(&out).unwrap_or_else(|e| panic!("read flpdf output for {stem}: {e}"))
}

/// Run `flpdf rewrite --qdf --coalesce-contents --static-id <fixture> <out>`
/// through the actual binary and return the written bytes. The QDF framing
/// makes this a byte-stable end-to-end gate for the page-content coalescer,
/// including the conditional separator between adjacent decoded streams.
fn run_cli_coalesce_qdf_static_id(stem: &str) -> Vec<u8> {
    let outdir = tempfile::tempdir().unwrap();
    let out = outdir.path().join("out.pdf");
    let input = fixture(stem);

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--qdf")
        .arg("--coalesce-contents")
        .arg("--static-id")
        .arg(&input)
        .arg(&out)
        .assert()
        .success();

    std::fs::read(&out).unwrap_or_else(|e| panic!("read flpdf output for {stem}: {e}"))
}

fn assert_byte_identical(stem: &str, kind: &str, extra: &[&str]) {
    let actual = run_cli(stem, extra);
    let expected = golden(stem, kind);
    if actual == expected {
        return;
    }
    let common = actual.len().min(expected.len());
    let off = (0..common)
        .find(|&i| actual[i] != expected[i])
        .unwrap_or(common);
    let lo = off.saturating_sub(24);
    panic!(
        "{stem} ({kind}): CLI output diverged from qpdf golden \
         (flpdf={} bytes, golden={} bytes, first diff at byte {off})\n\
         flpdf : {:?}\ngolden: {:?}",
        actual.len(),
        expected.len(),
        String::from_utf8_lossy(&actual[lo..(off + 24).min(actual.len())]),
        String::from_utf8_lossy(&expected[lo..(off + 24).min(expected.len())]),
    );
}

fn assert_linearize_newline_byte_identical(stem: &str, extra: &[&str]) {
    let Some(expected) = run_qpdf(stem, extra) else {
        return;
    };
    let actual = run_cli(stem, extra);
    if actual == expected {
        return;
    }
    let common = actual.len().min(expected.len());
    let off = (0..common)
        .find(|&i| actual[i] != expected[i])
        .unwrap_or(common);
    let lo = off.saturating_sub(24);
    panic!(
        "{stem} (linearize --newline-before-endstream): CLI output diverged from qpdf 11.9.0 \
         (flpdf={} bytes, qpdf={} bytes, first diff at byte {off})\n\
         flpdf: {:?}\nqpdf: {:?}",
        actual.len(),
        expected.len(),
        String::from_utf8_lossy(&actual[lo..(off + 24).min(actual.len())]),
        String::from_utf8_lossy(&expected[lo..(off + 24).min(expected.len())]),
    );
}

fn assert_linearize_normalize_content_byte_identical(stem: &str) {
    let Some(expected) = run_qpdf(stem, &["--normalize-content=y"]) else {
        return;
    };
    let actual = run_cli_top_level_linearized(stem, &["--normalize-content=y"]);
    if actual == expected {
        return;
    }
    let common = actual.len().min(expected.len());
    let off = (0..common)
        .find(|&i| actual[i] != expected[i])
        .unwrap_or(common);
    let lo = off.saturating_sub(24);
    panic!(
        "{stem} (linearize --normalize-content=y): CLI output diverged from qpdf 11.9.0 \
         (flpdf={} bytes, qpdf={} bytes, first diff at byte {off})\n\
         flpdf: {:?}\nqpdf: {:?}",
        actual.len(),
        expected.len(),
        String::from_utf8_lossy(&actual[lo..(off + 24).min(actual.len())]),
        String::from_utf8_lossy(&expected[lo..(off + 24).min(expected.len())]),
    );
}

#[test]
fn cli_one_page_linearize_newline_before_endstream_matches_qpdf() {
    assert_linearize_newline_byte_identical("one-page", &["--newline-before-endstream"]);
}

#[test]
fn cli_three_page_linearize_objstm_newline_before_endstream_matches_qpdf() {
    assert_linearize_newline_byte_identical(
        "three-page",
        &["--object-streams=generate", "--newline-before-endstream"],
    );
}

// ── Linearized + object-streams=generate (cross-reference stream path) ────────

#[test]
fn cli_two_page_linearize_objstm_byte_identical() {
    assert_byte_identical(
        "two-page",
        "linearize-objstm",
        &["--object-streams=generate"],
    );
}

#[test]
fn cli_three_page_linearize_objstm_byte_identical() {
    assert_byte_identical(
        "three-page",
        "linearize-objstm",
        &["--object-streams=generate"],
    );
}

#[test]
fn cli_shared_stream_linearize_objstm_byte_identical() {
    assert_byte_identical(
        "shared-stream-objstm",
        "linearize-objstm",
        &["--object-streams=generate"],
    );
}

// ── Classic linearized (no object streams) ────────────────────────────────────

#[test]
fn cli_one_page_linearize_byte_identical() {
    assert_byte_identical("one-page", "linearize", &[]);
}

#[test]
fn cli_two_page_linearize_byte_identical() {
    assert_byte_identical("two-page", "linearize", &[]);
}

#[test]
fn cli_three_page_linearize_byte_identical() {
    assert_byte_identical("three-page", "linearize", &[]);
}

fn malformed_live_page_contents_pdf() -> Vec<u8> {
    let objects: [&[u8]; 4] = [
        b"<< /Type /Catalog /Pages 2 0 R >>",
        b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 100 100] >>",
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << >> >>",
        b"[",
    ];
    let mut bytes = b"%PDF-1.3\n".to_vec();
    let mut offsets = [0usize; 5];
    for (index, body) in objects.iter().enumerate() {
        let object_number = index + 1;
        offsets[object_number] = bytes.len();
        bytes.extend_from_slice(format!("{object_number} 0 obj\n").as_bytes());
        bytes.extend_from_slice(body);
        bytes.extend_from_slice(b"\nendobj\n");
    }
    let xref_offset = bytes.len();
    bytes.extend_from_slice(b"xref\n0 5\n0000000000 65535 f \n");
    for offset in offsets.iter().skip(1) {
        bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
    }
    bytes.extend_from_slice(b"trailer\n<< /Root 1 0 R /Size 5 >>\nstartxref\n");
    bytes.extend_from_slice(format!("{xref_offset}\n%%EOF\n").as_bytes());
    bytes
}

/// qpdf keeps warning-to-null recovery for a page-closure object whose xref
/// row is live but whose body fails parsing. The linearization writer then
/// emits the null-resolved object and completes with warnings.
#[test]
fn linearize_malformed_live_page_contents_matches_qpdf_recovery() {
    if !qpdf_available() {
        if std::env::var_os("CI").is_some() {
            panic!("{EXPECTED_QPDF_VERSION} is required for linearization recovery parity");
        }
        eprintln!("skipping malformed-object linearization parity: qpdf 11.9.0 is unavailable");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary directory");
    let input = directory.path().join("malformed-live-content.pdf");
    let qpdf_output = directory.path().join("qpdf-linearized.pdf");
    let flpdf_output = directory.path().join("flpdf-linearized.pdf");
    std::fs::write(&input, malformed_live_page_contents_pdf()).expect("write synthetic input");

    let qpdf = StdCommand::new("qpdf")
        .args(["--linearize", "--static-id"])
        .arg(&input)
        .arg(&qpdf_output)
        .output()
        .expect("run qpdf 11.9.0 linearization");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .env("FLPDF_PROGNAME", "qpdf")
        .args(["--linearize", "--static-id"])
        .arg(&input)
        .arg(&flpdf_output)
        .output()
        .expect("run flpdf linearization");

    assert_eq!(
        qpdf.status.code(),
        Some(3),
        "qpdf must report its parser warnings"
    );
    assert_eq!(
        flpdf.status.code(),
        qpdf.status.code(),
        "warning exit status"
    );
    assert_eq!(flpdf.stdout, qpdf.stdout, "stdout");
    assert_eq!(flpdf.stderr, qpdf.stderr, "ordered parser warnings");

    let qpdf_bytes = std::fs::read(&qpdf_output).expect("qpdf must write despite warnings");
    let flpdf_bytes = std::fs::read(&flpdf_output).expect("flpdf must write despite warnings");
    assert!(
        qpdf_bytes == flpdf_bytes,
        "warning-to-null linearized outputs must match (flpdf {} bytes, qpdf {} bytes)",
        flpdf_bytes.len(),
        qpdf_bytes.len()
    );

    let check = StdCommand::new("qpdf")
        .arg("--check")
        .arg(&qpdf_output)
        .output()
        .expect("check qpdf linearized output");
    assert!(
        check.status.success(),
        "qpdf output must remain readable: {}",
        String::from_utf8_lossy(&check.stderr)
    );
}

#[test]
fn cli_linearize_normalize_content_is_byte_identical_to_qpdf() {
    for stem in [
        "one-page",
        "multi-contents-one-page",
        "shared-stream-objstm",
        "direct-leaf-kid",
    ] {
        assert_linearize_normalize_content_byte_identical(stem);
    }
}

// ── Plain full rewrite + static-id (no linearize) ─────────────────────────────
//
// These cover the plain full-rewrite path, which matches qpdf's framing by
// leaving `--newline-before-endstream` off, exactly as qpdf's own default does.
// The linearize tests above force `Never` internally regardless of the CLI
// default, so only these rows would regress if the CLI default were flipped on.

fn assert_full_rewrite_static_id_byte_identical(stem: &str) {
    let actual = run_cli_full_rewrite_static_id(stem);
    let expected = golden(stem, "static-id");
    if actual == expected {
        return;
    }
    let common = actual.len().min(expected.len());
    let off = (0..common)
        .find(|&i| actual[i] != expected[i])
        .unwrap_or(common);
    let lo = off.saturating_sub(24);
    panic!(
        "{stem} (static-id via full-rewrite): CLI output diverged from qpdf golden \
         (flpdf={} bytes, golden={} bytes, first diff at byte {off})\n\
         flpdf : {:?}\ngolden: {:?}",
        actual.len(),
        expected.len(),
        String::from_utf8_lossy(&actual[lo..(off + 24).min(actual.len())]),
        String::from_utf8_lossy(&expected[lo..(off + 24).min(expected.len())]),
    );
}

#[test]
fn cli_one_page_full_rewrite_static_id_byte_identical() {
    assert_full_rewrite_static_id_byte_identical("one-page");
}

#[test]
fn cli_two_page_full_rewrite_static_id_byte_identical() {
    assert_full_rewrite_static_id_byte_identical("two-page");
}

#[test]
fn cli_three_page_full_rewrite_static_id_byte_identical() {
    assert_full_rewrite_static_id_byte_identical("three-page");
}

// ── QDF coalesce-contents: conditional separator between stream segments ────
//
// multi-contents-one-page.pdf has a non-final content stream whose decoded
// bytes already end in LF. qpdf's pipeContentStreams leaves that LF in place
// and does not add a second one before the next stream.

fn assert_coalesce_qdf_byte_identical(stem: &str) {
    let actual = run_cli_coalesce_qdf_static_id(stem);
    let expected = golden(stem, "coalesce-qdf");
    if actual == expected {
        return;
    }
    let common = actual.len().min(expected.len());
    let off = (0..common)
        .find(|&i| actual[i] != expected[i])
        .unwrap_or(common);
    let lo = off.saturating_sub(24);
    panic!(
        "{stem} (coalesce-qdf): CLI output diverged from qpdf golden \
         (flpdf={} bytes, golden={} bytes, first diff at byte {off})\n\
         flpdf : {:?}\ngolden: {:?}",
        actual.len(),
        expected.len(),
        String::from_utf8_lossy(&actual[lo..(off + 24).min(actual.len())]),
        String::from_utf8_lossy(&expected[lo..(off + 24).min(expected.len())]),
    );
}

#[test]
fn cli_multi_contents_coalesce_qdf_byte_identical() {
    assert_coalesce_qdf_byte_identical("multi-contents-one-page");
}