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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//! QPDFLogger routing coverage for qpdf-equivalent CLI output.

use assert_cmd::Command;
use std::path::Path;
use std::process::{Command as ProcessCommand, Output};

#[path = "support/eol.rs"]
mod eol;
use eol::EOL;
#[path = "support/text_newlines.rs"]
mod text_newlines;
use text_newlines::normalize_text_newlines;

const MINIMAL: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/minimal.pdf"
);
const MULTI_STREAM: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/compat/multi-stream-one-page.pdf"
);
const ONE_PAGE: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/compat/one-page.pdf"
);
const WARNING_PDF: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/test_driver/missing_startxref.pdf"
);
const ATTACHMENT_PDF: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/compat/attachment-two-page.pdf"
);
const LARGE_LINEARIZED: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/compat/objstm-lin-outlines-80-200.pdf"
);
const EXPECTED_QPDF_VERSION: &str = "11.9.0";

fn flpdf() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin!("flpdf"))
}

fn qpdf_version_is_expected(stdout: &[u8]) -> bool {
    String::from_utf8_lossy(stdout)
        .lines()
        .next()
        .map(str::trim)
        == Some(&format!("qpdf version {EXPECTED_QPDF_VERSION}"))
}

fn qpdf_available() -> bool {
    let observation = match ProcessCommand::new("qpdf").arg("--version").output() {
        Ok(output) if output.status.success() && qpdf_version_is_expected(&output.stdout) => {
            return true;
        }
        Ok(output) => {
            let first_line = String::from_utf8_lossy(&output.stdout)
                .lines()
                .next()
                .unwrap_or("<empty stdout>")
                .to_owned();
            format!("found {first_line:?} (status {})", output.status)
        }
        Err(error) => format!("unable to run qpdf --version: {error}"),
    };

    if std::env::var_os("CI").is_some() {
        panic!(
            "qpdf {EXPECTED_QPDF_VERSION} is required for cli_logger_routing differential tests on CI; {observation}"
        );
    }
    eprintln!(
        "skipping logger routing differential: qpdf {EXPECTED_QPDF_VERSION} is required; {observation}"
    );
    false
}

fn run_qpdf(args: &[&str]) -> Output {
    ProcessCommand::new("qpdf").args(args).output().unwrap()
}

fn run_flpdf(args: &[&str]) -> Output {
    ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
        .env("FLPDF_PROGNAME", "qpdf")
        .args(args)
        .output()
        .unwrap()
}

#[cfg(unix)]
fn run_merged_check(program: impl AsRef<std::ffi::OsStr>, args: &[&str], input: &Path) -> Output {
    ProcessCommand::new("/bin/sh")
        .args([
            "-c",
            r#"program="$1"; shift; exec "$program" "$@" 2>&1"#,
            "qpdf-check",
        ])
        .arg(program)
        .args(args)
        .arg(input)
        .env("FLPDF_PROGNAME", "qpdf")
        .output()
        .unwrap()
}
fn split_at_marker<'a>(bytes: &'a [u8], marker: &[u8]) -> Option<(&'a [u8], &'a [u8])> {
    let index = bytes
        .windows(marker.len())
        .position(|window| window == marker)?;
    Some((&bytes[..index], &bytes[index + marker.len()..]))
}

fn assert_observables_equal(label: &str, qpdf: &Output, flpdf: &Output, text_output: bool) {
    assert_eq!(flpdf.status.code(), qpdf.status.code(), "{label}: status");
    if cfg!(windows) && text_output {
        assert_eq!(
            normalize_text_newlines(&flpdf.stdout),
            normalize_text_newlines(&qpdf.stdout),
            "{label}: stdout"
        );
        assert_eq!(
            normalize_text_newlines(&flpdf.stderr),
            normalize_text_newlines(&qpdf.stderr),
            "{label}: stderr"
        );
    } else {
        assert_eq!(flpdf.stdout, qpdf.stdout, "{label}: stdout");
        assert_eq!(flpdf.stderr, qpdf.stderr, "{label}: stderr");
    }
}

// Single contract test for the shared `support/text_newlines.rs` helper: a
// lone `\r` must survive so genuine carriage returns inside a text payload
// still compare. Lives here because the logger owns the CRLF text transport
// this helper compensates for.
#[test]
fn text_newline_normalization_only_collapses_crlf_pairs() {
    assert_eq!(
        normalize_text_newlines(b"first\r\nsecond\nthird\rfourth"),
        b"first\nsecond\nthird\rfourth"
    );
}

#[test]
fn qpdf_logger_oracle_version_gate_accepts_only_11_9_0() {
    assert!(qpdf_version_is_expected(
        b"qpdf version 11.9.0\nRun qpdf --copyright for details\n"
    ));
    assert!(!qpdf_version_is_expected(b"qpdf version 12.0.0\n"));
    assert!(!qpdf_version_is_expected(b"qpdf version 11.9.0-custom\n"));
}

#[test]
fn text_logger_uses_qpdf_platform_line_endings() {
    let version = flpdf().args(["--version"]).output().unwrap();
    assert!(version.status.success());
    assert_eq!(
        version.stdout,
        format!("qpdf version 11.9.0{EOL}Run qpdf --copyright to see copyright and license information.{EOL}")
        .into_bytes()
    );

    let check = flpdf()
        .args(["--repair", "--check", WARNING_PDF])
        .output()
        .unwrap();
    assert_eq!(check.status.code(), Some(3));
    assert!(
        String::from_utf8_lossy(&check.stdout).contains(&format!("checking {WARNING_PDF}{EOL}"))
    );
    assert!(String::from_utf8_lossy(&check.stderr)
        .ends_with(&format!("flpdf: operation succeeded with warnings{}", EOL)));
}

#[test]
fn binary_json_uses_stdout_without_stderr() {
    let output = flpdf().args(["--json=2", MINIMAL]).output().unwrap();

    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["version"], serde_json::json!(2));
}

#[test]
fn binary_pdf_dash_writes_stdout_without_creating_a_dash_file() {
    let directory = tempfile::tempdir().unwrap();
    let output = flpdf()
        .current_dir(directory.path())
        .args([MINIMAL, "-"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stderr.is_empty());
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(!Path::new(directory.path()).join("-").exists());
}

#[test]
fn binary_linearized_pdf_dash_uses_the_same_save_route() {
    let output = flpdf()
        .args(["--linearize", ONE_PAGE, "-"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(output.stderr.is_empty());
}

#[test]
fn binary_linearized_pdf_dash_writes_pass1_independently() {
    let directory = tempfile::tempdir().unwrap();
    let pass1 = directory.path().join("pass1.pdf");
    let pass1_arg = format!("--linearize-pass1={}", pass1.display());
    let output = flpdf()
        .args(["--linearize", &pass1_arg, ONE_PAGE, "-"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(output.stderr.is_empty());
    let pass1_bytes = std::fs::read(pass1).unwrap();
    assert!(pass1_bytes.starts_with(b"%PDF-"));
    assert_ne!(pass1_bytes, output.stdout);
    assert!(pass1_bytes
        .windows(b"% hint_offset=".len())
        .any(|window| window == b"% hint_offset="));
}

#[test]
fn qpdf_differential_matches_linearize_pass1_artifact() {
    if !qpdf_available() {
        return;
    }

    let directory = tempfile::tempdir().unwrap();
    for (name, input, object_streams) in [
        ("classic", ONE_PAGE, false),
        ("objstm", LARGE_LINEARIZED, true),
    ] {
        let qpdf_final = directory.path().join(format!("qpdf-{name}-final.pdf"));
        let qpdf_pass1 = directory.path().join(format!("qpdf-{name}-pass1.pdf"));
        let flpdf_final = directory.path().join(format!("flpdf-{name}-final.pdf"));
        let flpdf_pass1 = directory.path().join(format!("flpdf-{name}-pass1.pdf"));
        let qpdf_pass1_arg = format!("--linearize-pass1={}", qpdf_pass1.display());
        let flpdf_pass1_arg = format!("--linearize-pass1={}", flpdf_pass1.display());

        let mut qpdf_args = vec!["--linearize", "--static-id", "--compress-streams=n"];
        if object_streams {
            qpdf_args.push("--object-streams=generate");
        }
        qpdf_args.push(qpdf_pass1_arg.as_str());
        qpdf_args.push(input);
        let qpdf = ProcessCommand::new("qpdf")
            .args(&qpdf_args)
            .arg(&qpdf_final)
            .output()
            .unwrap();

        let mut flpdf_args = vec!["--linearize", "--static-id", "--compress-streams=n"];
        if object_streams {
            flpdf_args.push("--object-streams=generate");
        }
        flpdf_args.push(flpdf_pass1_arg.as_str());
        flpdf_args.push(input);
        let flpdf = ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
            .env("FLPDF_STATIC_ID_QUIET", "1")
            .args(&flpdf_args)
            .arg(&flpdf_final)
            .output()
            .unwrap();

        assert!(qpdf.status.success(), "{name}: qpdf failed: {qpdf:?}");
        assert!(flpdf.status.success(), "{name}: flpdf failed: {flpdf:?}");
        assert_eq!(
            std::fs::read(&qpdf_final).unwrap(),
            std::fs::read(&flpdf_final).unwrap(),
            "{name}: final linearized bytes must remain qpdf-identical"
        );

        let qpdf_pass1_bytes = std::fs::read(&qpdf_pass1).unwrap();
        let flpdf_pass1_bytes = std::fs::read(&flpdf_pass1).unwrap();
        let (qpdf_body, qpdf_comments) = split_at_marker(&qpdf_pass1_bytes, b"% hint_offset=")
            .expect("qpdf pass-1 debug comments are present");
        let (flpdf_body, flpdf_comments) = split_at_marker(&flpdf_pass1_bytes, b"% hint_offset=")
            .expect("flpdf pass-1 debug comments are present");
        assert_eq!(
            flpdf_body, qpdf_body,
            "{name}: pass-1 body must be qpdf-identical"
        );
        assert_eq!(
            flpdf_comments, qpdf_comments,
            "{name}: pass-1 debug comments must retain qpdf values"
        );
    }
}

#[test]
fn binary_linearized_pass1_open_failure_names_path_before_final_stdout() {
    let directory = tempfile::tempdir().unwrap();
    let pass1 = directory.path().join("missing-parent").join("pass1.pdf");
    let pass1_arg = format!("--linearize-pass1={}", pass1.display());
    let output = flpdf()
        .args(["--linearize", &pass1_arg, ONE_PAGE, "-"])
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(2));
    assert!(
        output.stdout.is_empty(),
        "final PDF must not be emitted after pass-1 open failure"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains(&format!("open {}: ", pass1.display())));
    assert!(stderr.contains("No such file") || stderr.contains("cannot find"));
}

#[cfg(unix)]
#[test]
fn qpdf_differential_matches_small_and_large_pass1_dev_full_boundaries() {
    if !Path::new("/dev/full").exists() || !qpdf_available() {
        eprintln!("skipping pass-1 /dev/full differential");
        return;
    }

    let small_args = ["--linearize", "--linearize-pass1=/dev/full", ONE_PAGE, "-"];
    let qpdf_small = run_qpdf(&small_args);
    let flpdf_small = run_flpdf(&small_args);
    assert_eq!(qpdf_small.status.code(), Some(0), "qpdf small status");
    assert_eq!(flpdf_small.status.code(), Some(0), "flpdf small status");
    assert!(qpdf_small.stdout.starts_with(b"%PDF-"));
    assert!(flpdf_small.stdout.starts_with(b"%PDF-"));
    assert!(qpdf_small.stderr.is_empty());
    assert!(flpdf_small.stderr.is_empty());

    let large_args = [
        "--linearize",
        "--linearize-pass1=/dev/full",
        LARGE_LINEARIZED,
        "-",
    ];
    let qpdf_large = run_qpdf(&large_args);
    let flpdf_large = run_flpdf(&large_args);
    assert_eq!(qpdf_large.status.code(), Some(2), "qpdf large status");
    assert_eq!(flpdf_large.status.code(), Some(2), "flpdf large status");
    assert!(qpdf_large.stdout.is_empty());
    assert!(flpdf_large.stdout.is_empty());
    let qpdf_stderr = String::from_utf8_lossy(&qpdf_large.stderr);
    let flpdf_stderr = String::from_utf8_lossy(&flpdf_large.stderr);
    assert!(qpdf_stderr.contains("linearization pass1: Pl_StdioFile::write"));
    assert!(flpdf_stderr.contains("write /dev/full:"));
    assert!(qpdf_stderr.contains("No space left on device"));
    assert!(flpdf_stderr.contains("No space left on device"));
}

#[cfg(unix)]
#[test]
fn qpdf_differential_matches_file_write_error_swallowing() {
    if !Path::new("/dev/full").exists() || !qpdf_available() {
        eprintln!("skipping final file-write /dev/full differential");
        return;
    }

    let plain_args = ["--static-id", ONE_PAGE, "/dev/full"];
    assert_observables_equal(
        "plain file output",
        &run_qpdf(&plain_args),
        &run_flpdf(&plain_args),
        true,
    );

    let page_operation_args = [
        "--progress",
        "--static-id",
        "--rotate=90:1",
        ONE_PAGE,
        "/dev/full",
    ];
    assert_observables_equal(
        "page-operation file output",
        &run_qpdf(&page_operation_args),
        &run_flpdf(&page_operation_args),
        true,
    );

    let page_extraction_args = [
        "--progress",
        "--static-id",
        ONE_PAGE,
        "--pages",
        ".",
        "1",
        "--",
        "/dev/full",
    ];
    assert_observables_equal(
        "page-extraction file output",
        &run_qpdf(&page_extraction_args),
        &run_flpdf(&page_extraction_args),
        true,
    );
}

#[cfg(target_os = "linux")]
#[test]
fn large_file_write_error_does_not_name_the_input_path() {
    if !Path::new("/dev/full").exists() || !qpdf_available() {
        eprintln!("skipping /dev/full output-sink differential");
        return;
    }

    // qpdf names the sink pipeline rather than any file:
    // `QPDFWriter::setOutputFile` wraps the handle in
    // `Pl_StdioFile("qpdf output", file)` (`QPDFWriter.cc:101-110`), and the
    // failure carries that identifier (`Pl_StdioFile.cc:25-37`). Compare the
    // whole observable against the real binary instead of pinning the wording.
    let args = [LARGE_LINEARIZED, "/dev/full"];
    let qpdf = run_qpdf(&args);
    let flpdf = run_flpdf(&args);
    assert_eq!(qpdf.status.code(), Some(2), "qpdf status");
    assert_observables_equal("linearized file output", &qpdf, &flpdf, true);
    assert!(
        !String::from_utf8_lossy(&flpdf.stderr).contains(LARGE_LINEARIZED),
        "the input path must not appear in an output-sink failure"
    );
}

#[test]
fn binary_qdf_dash_uses_the_same_save_route() {
    let output = flpdf().args(["qdf", MINIMAL, "-"]).output().unwrap();

    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(output.stdout.windows(5).any(|window| window == b"%QDF-"));
    assert!(output.stderr.is_empty());
}

#[test]
fn binary_page_extraction_dash_uses_the_save_route_without_creating_a_dash_file() {
    let directory = tempfile::tempdir().unwrap();
    let output = flpdf()
        .current_dir(directory.path())
        .args([ONE_PAGE, "--pages", ".", "1", "--", "-"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(output.stderr.is_empty());
    assert!(!directory.path().join("-").exists());
}

#[test]
fn binary_rotate_dash_uses_the_save_route_without_creating_a_dash_file() {
    let directory = tempfile::tempdir().unwrap();
    let output = flpdf()
        .current_dir(directory.path())
        .args([ONE_PAGE, "-", "--rotate=+90:1"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(output.stderr.is_empty());
    assert!(!directory.path().join("-").exists());
}

#[test]
fn split_pages_dash_is_rejected_before_output_is_created() {
    let directory = tempfile::tempdir().unwrap();
    let output = flpdf()
        .current_dir(directory.path())
        .args([ONE_PAGE, "-", "--split-pages=1"])
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    assert!(String::from_utf8_lossy(&output.stderr)
        .contains("--split-pages may not be used when writing to standard output"));
    assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
}

#[test]
fn verbose_page_extraction_dash_keeps_pdf_and_info_on_separate_routes() {
    let output = flpdf()
        .args(["--verbose", ONE_PAGE, "--pages", ".", "1", "--", "-"])
        .output()
        .unwrap();

    assert!(output.status.success());
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(!output
        .stdout
        .windows(b"flpdf:".len())
        .any(|window| window == b"flpdf:"));
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("flpdf: selecting --keep-open-files=y")
    );
}

#[test]
fn text_rewrite_verbose_uses_info_route_for_file_output() {
    let directory = tempfile::tempdir().unwrap();
    let output_path = directory.path().join("out.pdf");
    let output = flpdf()
        .args(["--verbose", MINIMAL, output_path.to_str().unwrap()])
        .output()
        .unwrap();

    assert!(output.status.success());
    assert_eq!(
        String::from_utf8(output.stdout).unwrap(),
        format!("flpdf: wrote file {}{}", output_path.display(), EOL)
    );
    assert!(output.stderr.is_empty());
}

#[test]
fn text_rewrite_verbose_does_not_announce_standard_output() {
    let output = flpdf().args(["--verbose", MINIMAL, "-"]).output().unwrap();

    assert!(output.status.success());
    assert!(output.stdout.starts_with(b"%PDF-"));
    assert!(output.stderr.is_empty());
}

#[test]
fn text_check_success_stays_on_info_route() {
    let output = flpdf().args(["--check", MINIMAL]).output().unwrap();

    assert!(output.status.success());
    assert!(output.stderr.is_empty());
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.starts_with(&format!("checking {MINIMAL}{EOL}")));
    assert!(stdout.ends_with(&format!("errors that qpdf cannot detect{}", EOL)));
}

#[test]
fn qpdf_differential_matches_routed_output_matrix() {
    if !qpdf_available() {
        eprintln!("qpdf not available; skipping logger routing differential");
        return;
    }

    let cases: &[(&str, &[&str], &[&str], bool)] = &[
        (
            "clean check",
            &["--check", MINIMAL],
            &["--check", MINIMAL],
            true,
        ),
        (
            "warning check",
            &["--check", WARNING_PDF],
            &["--repair", "--check", WARNING_PDF],
            true,
        ),
        (
            "JSON stdout",
            &["--json=2", MINIMAL],
            &["--json=2", MINIMAL],
            false,
        ),
        (
            "raw stream",
            &["--show-object=4", "--raw-stream-data", MULTI_STREAM],
            &["--show-object=4", "--raw-stream-data", MULTI_STREAM],
            false,
        ),
        (
            "filtered stream",
            &["--show-object=4", "--filtered-stream-data", MULTI_STREAM],
            &["--show-object=4", "--filtered-stream-data", MULTI_STREAM],
            false,
        ),
        (
            "attachment",
            &["--show-attachment=attachment.txt", ATTACHMENT_PDF],
            &["--show-attachment=attachment.txt", ATTACHMENT_PDF],
            false,
        ),
    ];

    for (label, qpdf_args, flpdf_args, text_output) in cases {
        assert_observables_equal(
            label,
            &run_qpdf(qpdf_args),
            &run_flpdf(flpdf_args),
            *text_output,
        );
    }
}

#[test]
fn qpdf_differential_matches_missing_input_usage_error() {
    if !qpdf_available() {
        eprintln!("qpdf not available; skipping missing-input usage differential");
        return;
    }

    let cases: &[(&str, &[&str])] = &[
        ("no input", &[]),
        ("--is-encrypted without input", &["--is-encrypted"]),
        (
            "--requires-password without input",
            &["--requires-password"],
        ),
        ("--show-encryption without input", &["--show-encryption"]),
        ("--show-npages without input", &["--show-npages"]),
        ("--show-pages without input", &["--show-pages"]),
        ("--show-xref without input", &["--show-xref"]),
        (
            "--check-linearization without input",
            &["--check-linearization"],
        ),
        (
            "--show-linearization without input",
            &["--show-linearization"],
        ),
        ("--show-object without input", &["--show-object=1"]),
        ("--json without input", &["--json"]),
        (
            "--json-input --check without input",
            &["--json-input", "--check"],
        ),
        (
            "--update-from-json --check without input",
            &["--update-from-json=foo", "--check"],
        ),
        ("--qdf without input", &["--qdf"]),
        ("--list-attachments without input", &["--list-attachments"]),
        (
            "--show-attachment without input",
            &["--show-attachment=foo"],
        ),
        (
            "--remove-attachment without input",
            &["--remove-attachment=foo"],
        ),
        (
            "--check --pages without primary input",
            &["--check", "--pages", "noxref.pdf", "--"],
        ),
        ("rewrite without output", &[MINIMAL]),
        ("--qdf without output", &["--qdf", MINIMAL]),
        (
            "--add-attachment without output",
            &["--add-attachment", MINIMAL, "--", MINIMAL],
        ),
        (
            "--remove-attachment without output",
            &["--remove-attachment=foo", "--", MINIMAL],
        ),
        (
            "--copy-attachments-from without output",
            &["--copy-attachments-from", MINIMAL, "--", MINIMAL],
        ),
    ];
    for (label, args) in cases {
        assert_observables_equal(label, &run_qpdf(args), &run_flpdf(args), true);
    }
}

#[cfg(unix)]
#[test]
fn qpdf_differential_preserves_open_warning_order_before_check_banner() {
    if !qpdf_available() {
        eprintln!("qpdf not available; skipping merged check-order differential");
        return;
    }

    let input = Path::new(WARNING_PDF);
    let qpdf = run_merged_check("qpdf", &["--check"], input);
    let flpdf = run_merged_check(
        assert_cmd::cargo::cargo_bin!("flpdf"),
        &["--repair", "--check"],
        input,
    );

    assert_eq!(qpdf.status.code(), Some(3), "qpdf status");
    assert_eq!(flpdf.status.code(), qpdf.status.code(), "status");
    assert_eq!(flpdf.stdout, qpdf.stdout, "merged stdout/stderr output");
    assert!(
        qpdf.stderr.is_empty(),
        "qpdf shell stderr: {:?}",
        qpdf.stderr
    );
    assert!(
        flpdf.stderr.is_empty(),
        "flpdf shell stderr: {:?}",
        flpdf.stderr
    );

    let qpdf_no_warn = run_merged_check("qpdf", &["--no-warn", "--check"], input);
    let flpdf_no_warn = run_merged_check(
        assert_cmd::cargo::cargo_bin!("flpdf"),
        &["--no-warn", "--repair", "--check"],
        input,
    );
    assert_eq!(qpdf_no_warn.status.code(), Some(3), "qpdf --no-warn status");
    assert_eq!(
        flpdf_no_warn.status.code(),
        qpdf_no_warn.status.code(),
        "--no-warn status"
    );
    assert_eq!(
        flpdf_no_warn.stdout, qpdf_no_warn.stdout,
        "--no-warn merged stdout/stderr output"
    );
    assert!(
        qpdf_no_warn.stderr.is_empty(),
        "qpdf --no-warn shell stderr: {:?}",
        qpdf_no_warn.stderr
    );
    assert!(
        flpdf_no_warn.stderr.is_empty(),
        "flpdf --no-warn shell stderr: {:?}",
        flpdf_no_warn.stderr
    );
}

#[test]
fn qpdf_differential_matches_missing_input_open_error_on_all_input_routes() {
    if !qpdf_available() {
        eprintln!("qpdf not available; skipping logger routing differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary directory");
    let missing = directory.path().join("missing.pdf");
    let rewrite_output = directory.path().join("rewrite-output.pdf");
    let pages_output = directory.path().join("pages-output.pdf");
    let missing = missing.to_str().expect("UTF-8 temporary path");
    let rewrite_output = rewrite_output.to_str().expect("UTF-8 temporary path");
    let pages_output = pages_output.to_str().expect("UTF-8 temporary path");

    let cases = [
        ("plain rewrite", vec![missing, rewrite_output]),
        ("--check", vec!["--check", missing]),
        (
            "--empty --pages",
            vec!["--empty", "--pages", missing, "--", pages_output],
        ),
        (
            "--copy-attachments-from",
            vec![
                "--copy-attachments-from",
                missing,
                "--",
                ONE_PAGE,
                rewrite_output,
            ],
        ),
    ];
    for (label, args) in cases {
        let qpdf = run_qpdf(&args);
        let flpdf = run_flpdf(&args);
        assert_observables_equal(label, &qpdf, &flpdf, true);
    }

    let encrypted = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../tests/fixtures/encrypted/v4-aes-128-r4.pdf"
    );
    let qpdf = run_qpdf(&[
        ONE_PAGE,
        "--pages",
        encrypted,
        "--password=wrong",
        "1",
        "--",
        pages_output,
    ]);
    let flpdf = run_flpdf(&[
        ONE_PAGE,
        "--pages",
        encrypted,
        "--password=wrong",
        "1",
        "--",
        pages_output,
    ]);
    assert_observables_equal("secondary source authentication", &qpdf, &flpdf, true);
}

#[test]
fn qpdf_differential_matches_remaining_file_error_boundaries() {
    if !qpdf_available() {
        eprintln!("qpdf not available; skipping file error-boundary differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary directory");
    let input_directory = directory.path().join("input-directory");
    std::fs::create_dir(&input_directory).expect("create directory input");
    let input_directory = input_directory.to_str().expect("UTF-8 temporary path");
    let output_path = directory.path().join("output.pdf");
    let output = output_path.to_str().expect("UTF-8 temporary path");
    let missing_parent_output_path = directory.path().join("missing-parent").join("output.pdf");
    let missing_parent_output = missing_parent_output_path
        .to_str()
        .expect("UTF-8 temporary path");
    let recovery_input = directory.path().join("bad.pdf");
    std::fs::write(&recovery_input, b"not a PDF\n").expect("write malformed input");
    let recovery_input = recovery_input.to_str().expect("UTF-8 temporary path");

    let missing_parent_json_path = directory.path().join("missing-parent").join("output.json");
    let missing_parent_json = missing_parent_json_path
        .to_str()
        .expect("UTF-8 temporary path");

    let cases = [
        ("directory input", vec![input_directory, output]),
        (
            "missing output parent",
            vec![MINIMAL, missing_parent_output],
        ),
        (
            "missing JSON output parent",
            vec!["--json=2", MINIMAL, "--json-output", missing_parent_json],
        ),
        ("recovery failure", vec![recovery_input, output]),
    ];
    for (label, args) in cases {
        let qpdf = run_qpdf(&args);
        let flpdf = run_flpdf(&args);
        assert_observables_equal(label, &qpdf, &flpdf, true);
    }

    assert!(!output_path.exists(), "failed input must not create output");
    assert!(
        !missing_parent_output_path.exists(),
        "failed output open must not create output"
    );
}

#[cfg(unix)]
#[test]
fn qpdf_differential_matches_permission_denied_output_open() {
    if !qpdf_available() {
        eprintln!("qpdf not available; skipping permission-denied differential");
        return;
    }

    use std::os::unix::fs::PermissionsExt;

    let directory = tempfile::tempdir().expect("temporary directory");
    let readonly = directory.path().join("readonly");
    std::fs::create_dir(&readonly).expect("create read-only output directory");
    std::fs::set_permissions(&readonly, std::fs::Permissions::from_mode(0o555))
        .expect("make output directory read-only");
    let output_path = readonly.join("output.pdf");
    let output = output_path.to_str().expect("UTF-8 temporary path");

    let qpdf = run_qpdf(&[MINIMAL, output]);
    let flpdf = run_flpdf(&[MINIMAL, output]);
    if qpdf.status.code() != Some(2) {
        eprintln!(
            "skipping permission-denied differential: qpdf could write in the read-only directory"
        );
        return;
    }
    assert_eq!(
        flpdf.status.code(),
        Some(2),
        "flpdf must fail when qpdf observes permission denied: {:?}",
        flpdf.stderr
    );
    assert_observables_equal("permission-denied output", &qpdf, &flpdf, true);
    assert!(
        !output_path.exists(),
        "permission failure must not create output"
    );
}

#[cfg(target_os = "linux")]
#[test]
fn cli_accepts_a_non_utf8_input_path_without_panicking() {
    use std::os::unix::ffi::{OsStrExt, OsStringExt};

    let directory = tempfile::tempdir().expect("temporary source directory");
    let input = directory
        .path()
        .join(std::ffi::OsString::from_vec(b"input-\xff.pdf".to_vec()));
    std::fs::copy(MINIMAL, &input).expect("copy fixture to non-UTF-8 path");

    let output = ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
        .env("FLPDF_PROGNAME", "qpdf")
        .arg("--check")
        .arg(&input)
        .output()
        .expect("run flpdf");

    assert_eq!(
        output.status.code(),
        Some(0),
        "non-UTF-8 argv must not panic: {:?}",
        output.stderr
    );
    let input_bytes = input.as_os_str().as_bytes();
    assert!(
        output
            .stdout
            .windows(input_bytes.len())
            .any(|window| window == input_bytes),
        "check output must preserve the raw input path: {:?}",
        output.stdout
    );
    assert!(
        !output
            .stdout
            .windows(3)
            .any(|window| window == b"\xef\xbf\xbd"),
        "check output must not replace the raw input path with U+FFFD: {:?}",
        output.stdout
    );
}

#[cfg(target_os = "linux")]
#[test]
fn cli_reports_a_non_utf8_missing_path_without_panicking() {
    use std::os::unix::ffi::{OsStrExt, OsStringExt};

    let directory = tempfile::tempdir().expect("temporary source directory");
    let input = directory
        .path()
        .join(std::ffi::OsString::from_vec(b"missing-\xff.pdf".to_vec()));

    let output = ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
        .env("FLPDF_PROGNAME", "qpdf")
        .arg("--check")
        .arg(&input)
        .output()
        .expect("run flpdf");

    assert_eq!(
        output.status.code(),
        Some(2),
        "missing input must be a CLI error, not a panic: {:?}",
        output.stderr
    );
    let input_bytes = input.as_os_str().as_bytes();
    assert!(
        output
            .stderr
            .windows(input_bytes.len())
            .any(|window| window == input_bytes),
        "open errors must preserve the raw input path: {:?}",
        output.stderr
    );
    assert!(
        !output
            .stderr
            .windows(3)
            .any(|window| window == b"\xef\xbf\xbd"),
        "open errors must not replace the raw input path with U+FFFD: {:?}",
        output.stderr
    );
}

#[cfg(target_os = "linux")]
#[test]
fn cli_attachment_segment_open_error_matches_qpdf_for_non_utf8_path() {
    use std::ffi::OsString;
    use std::os::unix::ffi::{OsStrExt, OsStringExt};

    if !qpdf_available() {
        eprintln!("qpdf not available; skipping attachment-segment differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary attachment directory");
    let input = directory.path().join("input.pdf");
    let qpdf_output = directory.path().join("qpdf-output.pdf");
    let flpdf_output = directory.path().join("flpdf-output.pdf");
    let attachment = directory
        .path()
        .join(OsString::from_vec(b"attach-\xff.bin".to_vec()));
    std::fs::copy(MINIMAL, &input).expect("copy input fixture");

    let args = |output: &Path| {
        vec![
            input.as_os_str().to_os_string(),
            output.as_os_str().to_os_string(),
            OsString::from("--add-attachment"),
            attachment.as_os_str().to_os_string(),
            OsString::from("--"),
        ]
    };
    let qpdf_args = args(&qpdf_output);
    let qpdf = ProcessCommand::new("qpdf")
        .args(&qpdf_args)
        .output()
        .expect("run qpdf");
    let flpdf_args = args(&flpdf_output);
    let flpdf = ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
        .env("FLPDF_PROGNAME", "qpdf")
        .args(&flpdf_args)
        .output()
        .expect("run flpdf");

    assert_eq!(
        qpdf.status.code(),
        Some(2),
        "qpdf stderr: {:?}",
        qpdf.stderr
    );
    assert_eq!(flpdf.status.code(), qpdf.status.code(), "status");
    assert_eq!(flpdf.stdout, qpdf.stdout, "stdout");
    assert_eq!(flpdf.stderr, qpdf.stderr, "stderr");
    assert!(
        qpdf.stderr
            .windows(attachment.as_os_str().as_bytes().len())
            .any(|window| window == attachment.as_os_str().as_bytes()),
        "qpdf must preserve the raw attachment path: {:?}",
        qpdf.stderr
    );
    assert!(!qpdf
        .stderr
        .windows(3)
        .any(|window| window == b"\xef\xbf\xbd"));
}

#[cfg(target_os = "linux")]
#[test]
fn cli_preserves_a_non_utf8_page_source_path_through_the_qpdf_segment_parser() {
    use std::os::unix::ffi::OsStringExt;

    let directory = tempfile::tempdir().expect("temporary source directory");
    let primary = directory.path().join("primary.pdf");
    let secondary = directory
        .path()
        .join(std::ffi::OsString::from_vec(b"secondary-\xff.pdf".to_vec()));
    let output_path = directory.path().join("output.pdf");
    std::fs::copy(ONE_PAGE, &primary).expect("copy primary fixture");
    std::fs::copy(ONE_PAGE, &secondary).expect("copy secondary fixture");

    let output = ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
        .env("FLPDF_PROGNAME", "qpdf")
        .arg(&primary)
        .arg("--pages")
        .arg(".")
        .arg(&secondary)
        .arg("--")
        .arg(&output_path)
        .output()
        .expect("run flpdf");

    assert_eq!(
        output.status.code(),
        Some(0),
        "non-UTF-8 page-source argv must not panic: {:?}",
        output.stderr
    );
    assert!(
        output_path.is_file(),
        "page operation must create its output"
    );
}

#[cfg(target_os = "linux")]
#[test]
fn cli_preserves_a_non_utf8_overlay_path_through_the_qpdf_segment_parser() {
    use std::os::unix::ffi::OsStringExt;

    let directory = tempfile::tempdir().expect("temporary source directory");
    let primary = directory.path().join("primary.pdf");
    let overlay = directory
        .path()
        .join(std::ffi::OsString::from_vec(b"overlay-\xff.pdf".to_vec()));
    let output_path = directory.path().join("output.pdf");
    std::fs::copy(ONE_PAGE, &primary).expect("copy primary fixture");
    std::fs::copy(ONE_PAGE, &overlay).expect("copy overlay fixture");

    let output = ProcessCommand::new(assert_cmd::cargo::cargo_bin!("flpdf"))
        .env("FLPDF_PROGNAME", "qpdf")
        .arg(&primary)
        .arg("--overlay")
        .arg(&overlay)
        .arg("--")
        .arg(&output_path)
        .output()
        .expect("run flpdf");

    assert_eq!(
        output.status.code(),
        Some(0),
        "non-UTF-8 overlay argv must not panic: {:?}",
        output.stderr
    );
    assert!(
        output_path.is_file(),
        "overlay operation must create its output"
    );
}