flpdf-cli 0.6.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
use assert_cmd::Command;
use std::fs;
use std::process::Command as ProcessCommand;

fn qpdf_available() -> bool {
    ProcessCommand::new("qpdf")
        .arg("--version")
        .output()
        .is_ok_and(|output| {
            output.status.success()
                && String::from_utf8_lossy(&output.stdout)
                    .lines()
                    .next()
                    .is_some_and(|line| line.trim() == "qpdf version 11.9.0")
        })
}

#[test]
fn top_level_replace_input_rewrites_unicode_input() {
    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let input = directory.path().join("auto-ü.pdf");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, &input).expect("copy replace-input fixture");
    let original = fs::read(&input).expect("read original input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args([
            "--deterministic-id",
            "--object-streams=generate",
            "--replace-input",
            "./auto-ü.pdf",
        ])
        .assert()
        .success()
        .stdout("")
        .stderr("");

    let replaced = fs::read(&input).expect("read replaced input");
    assert_ne!(
        replaced, original,
        "replace-input must write the transformed PDF"
    );
    assert!(input.is_file(), "replace-input must keep the input path");
    assert!(!directory.path().join("auto-ü.pdf.~qpdf-orig").exists());
    assert!(!directory.path().join("auto-ü.pdf.~qpdf-orig#").exists());
    assert!(!directory.path().join("auto-ü.pdf.~qpdf-temp#").exists());
}

#[test]
fn top_level_pages_replace_input_matches_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping page replace-input differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_directory = directory.path().join("qpdf");
    let flpdf_directory = directory.path().join("flpdf");
    fs::create_dir(&qpdf_directory).expect("create qpdf directory");
    fs::create_dir(&flpdf_directory).expect("create flpdf directory");
    let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let primary = manifest.join("../../tests/fixtures/compat/three-page.pdf");
    let secondary = manifest.join("../../tests/fixtures/compat/two-page.pdf");
    for target in [&qpdf_directory, &flpdf_directory] {
        fs::copy(&primary, target.join("input.pdf")).expect("copy primary input");
        fs::copy(&secondary, target.join("secondary.pdf")).expect("copy secondary input");
    }

    let args = [
        "--static-id",
        "--qdf",
        "input.pdf",
        "--pages",
        ".",
        "1",
        "secondary.pdf",
        "1",
        "--",
        "--replace-input",
    ];
    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(&qpdf_directory)
        .args(args)
        .output()
        .expect("run qpdf page replace-input oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(&flpdf_directory)
        .env("FLPDF_PROGNAME", "qpdf")
        .args(args)
        .output()
        .expect("run flpdf page replace-input");

    assert_eq!(qpdf.status.code(), Some(0));
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
    assert_eq!(
        fs::read(qpdf_directory.join("input.pdf")).unwrap(),
        fs::read(flpdf_directory.join("input.pdf")).unwrap(),
        "page replace-input must replace the primary input with qpdf's result"
    );
}

#[test]
fn top_level_same_input_output_reports_qpdf_replace_input_guidance() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping same-file diagnostic differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary same-file directory");
    let qpdf_directory = directory.path().join("qpdf");
    let flpdf_directory = directory.path().join("flpdf");
    fs::create_dir(&qpdf_directory).expect("create qpdf directory");
    fs::create_dir(&flpdf_directory).expect("create flpdf directory");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, qpdf_directory.join("input.pdf")).expect("copy qpdf input");
    fs::copy(&fixture, flpdf_directory.join("input.pdf")).expect("copy flpdf input");

    let args = ["--static-id", "input.pdf", "input.pdf"];
    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(&qpdf_directory)
        .args(args)
        .output()
        .expect("run qpdf same-file diagnostic oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(&flpdf_directory)
        .env("FLPDF_PROGNAME", "qpdf")
        .args(args)
        .output()
        .expect("run flpdf same-file diagnostic");

    assert_eq!(qpdf.status.code(), Some(2));
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
}

#[test]
fn empty_pages_replace_input_reports_the_empty_conflict_before_missing_output() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping empty-pages diagnostic differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary empty-pages directory");
    let qpdf_directory = directory.path().join("qpdf");
    let flpdf_directory = directory.path().join("flpdf");
    fs::create_dir(&qpdf_directory).expect("create qpdf directory");
    fs::create_dir(&flpdf_directory).expect("create flpdf directory");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, qpdf_directory.join("input.pdf")).expect("copy qpdf input");
    fs::copy(&fixture, flpdf_directory.join("input.pdf")).expect("copy flpdf input");

    let args = [
        "--static-id",
        "--empty",
        "--pages",
        "input.pdf",
        "1",
        "--",
        "--replace-input",
    ];
    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(&qpdf_directory)
        .args(args)
        .output()
        .expect("run qpdf empty-pages diagnostic oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(&flpdf_directory)
        .env("FLPDF_PROGNAME", "qpdf")
        .args(args)
        .output()
        .expect("run flpdf empty-pages diagnostic");

    assert_eq!(qpdf.status.code(), Some(2));
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
}

#[test]
fn top_level_replace_input_removes_attachment_like_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input attachment differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_directory = directory.path().join("qpdf");
    let flpdf_directory = directory.path().join("flpdf");
    fs::create_dir(&qpdf_directory).expect("create qpdf directory");
    fs::create_dir(&flpdf_directory).expect("create flpdf directory");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/attachment-two-page.pdf");
    fs::copy(&fixture, qpdf_directory.join("input.pdf")).expect("copy qpdf input");
    fs::copy(&fixture, flpdf_directory.join("input.pdf")).expect("copy flpdf input");

    let args = [
        "--deterministic-id",
        "--replace-input",
        "--remove-attachment=attachment.txt",
        "input.pdf",
    ];
    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(&qpdf_directory)
        .args(args)
        .output()
        .expect("run qpdf replace-input attachment oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(&flpdf_directory)
        .env("FLPDF_PROGNAME", "qpdf")
        .args(args)
        .output()
        .expect("run flpdf replace-input attachment");

    assert_eq!(qpdf.status.code(), Some(0));
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
    assert!(flpdf_directory.join("input.pdf").is_file());
}

#[test]
fn top_level_replace_input_rejects_json_output_like_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input JSON differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_input = directory.path().join("qpdf-input.pdf");
    let flpdf_input = directory.path().join("flpdf-input.pdf");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, &qpdf_input).expect("copy qpdf input");
    fs::copy(&fixture, &flpdf_input).expect("copy flpdf input");

    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args(["--replace-input", "--json=2", "qpdf-input.pdf"])
        .output()
        .expect("run qpdf replace-input JSON oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["--replace-input", "--json=2", "flpdf-input.pdf"])
        .output()
        .expect("run flpdf replace-input JSON");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
    assert!(flpdf_input.is_file(), "a rejected job must keep its input");
}

#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn top_level_replace_input_matches_qpdf_bytes() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input byte differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_directory = directory.path().join("qpdf");
    let flpdf_directory = directory.path().join("flpdf");
    fs::create_dir(&qpdf_directory).expect("create qpdf directory");
    fs::create_dir(&flpdf_directory).expect("create flpdf directory");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    let qpdf_input = qpdf_directory.join("auto-ü.pdf");
    let flpdf_input = flpdf_directory.join("auto-ü.pdf");
    fs::copy(&fixture, &qpdf_input).expect("copy qpdf input");
    fs::copy(&fixture, &flpdf_input).expect("copy flpdf input");

    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(&qpdf_directory)
        .args([
            "--deterministic-id",
            "--object-streams=generate",
            "--replace-input",
            "./auto-ü.pdf",
        ])
        .output()
        .expect("run qpdf replace-input oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(&flpdf_directory)
        .args([
            "--deterministic-id",
            "--object-streams=generate",
            "--replace-input",
            "./auto-ü.pdf",
        ])
        .output()
        .expect("run flpdf replace-input");

    assert_eq!(flpdf.status.code(), Some(0));
    assert_eq!(qpdf.status.code(), Some(0));
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
    assert_eq!(
        fs::read(&flpdf_input).unwrap(),
        fs::read(&qpdf_input).unwrap()
    );
}

#[test]
fn top_level_replace_input_rejects_split_pages_like_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input split differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_input = directory.path().join("qpdf-input.pdf");
    let flpdf_input = directory.path().join("flpdf-input.pdf");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, &qpdf_input).expect("copy qpdf input");
    fs::copy(&fixture, &flpdf_input).expect("copy flpdf input");

    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args(["--replace-input", "--split-pages=1", "qpdf-input.pdf"])
        .output()
        .expect("run qpdf replace-input split oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["--replace-input", "--split-pages=1", "flpdf-input.pdf"])
        .output()
        .expect("run flpdf replace-input split");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
    assert!(flpdf_input.is_file(), "a rejected job must keep its input");
}

#[test]
fn top_level_replace_input_rejects_an_output_file_like_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input output differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_input = directory.path().join("qpdf-input.pdf");
    let flpdf_input = directory.path().join("flpdf-input.pdf");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, &qpdf_input).expect("copy qpdf input");
    fs::copy(&fixture, &flpdf_input).expect("copy flpdf input");

    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args(["qpdf-input.pdf", "output.pdf", "--replace-input"])
        .output()
        .expect("run qpdf replace-input output oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["flpdf-input.pdf", "output.pdf", "--replace-input"])
        .output()
        .expect("run flpdf replace-input output");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
    assert!(flpdf_input.is_file(), "a rejected job must keep its input");
}

#[test]
fn top_level_replace_input_rejects_empty_input_like_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input empty differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args(["--empty", "--replace-input"])
        .output()
        .expect("run qpdf empty replace-input oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["--empty", "--replace-input"])
        .output()
        .expect("run flpdf empty replace-input");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
}

#[test]
fn top_level_replace_input_rejects_inspection_like_qpdf() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input inspection differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_input = directory.path().join("qpdf-input.pdf");
    let flpdf_input = directory.path().join("flpdf-input.pdf");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, &qpdf_input).expect("copy qpdf input");
    fs::copy(&fixture, &flpdf_input).expect("copy flpdf input");

    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args(["--replace-input", "--check", "qpdf-input.pdf"])
        .output()
        .expect("run qpdf replace-input inspection oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["--replace-input", "--check", "flpdf-input.pdf"])
        .output()
        .expect("run flpdf replace-input inspection");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
    assert!(flpdf_input.is_file(), "a rejected job must keep its input");
}

#[test]
fn top_level_replace_input_is_applied_after_job_json_file() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input job-json differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf_input = directory.path().join("qpdf-input.pdf");
    let flpdf_input = directory.path().join("flpdf-input.pdf");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    fs::copy(&fixture, &qpdf_input).expect("copy qpdf input");
    fs::copy(&fixture, &flpdf_input).expect("copy flpdf input");
    fs::write(
        directory.path().join("job.json"),
        br#"{"deterministicId":"","objectStreams":"generate"}"#,
    )
    .expect("write partial job JSON");

    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args([
            "--job-json-file=job.json",
            "--replace-input",
            "qpdf-input.pdf",
        ])
        .output()
        .expect("run qpdf job-json replace-input oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args([
            "--job-json-file=job.json",
            "--replace-input",
            "flpdf-input.pdf",
        ])
        .output()
        .expect("run flpdf job-json replace-input");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
    assert!(
        flpdf_input.is_file(),
        "replace-input must keep the input path"
    );
}

#[test]
fn top_level_replace_input_empty_output_conflict_matches_qpdf_order() {
    if !qpdf_available() {
        eprintln!("qpdf 11.9.0 is unavailable; skipping replace-input empty-output differential");
        return;
    }

    let directory = tempfile::tempdir().expect("temporary replace-input directory");
    let qpdf = ProcessCommand::new("qpdf")
        .current_dir(directory.path())
        .args(["--empty", "output.pdf", "--replace-input"])
        .output()
        .expect("run qpdf empty-output replace-input oracle");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["--empty", "flpdf-output.pdf", "--replace-input"])
        .output()
        .expect("run flpdf empty-output replace-input");

    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(
        String::from_utf8_lossy(&flpdf.stderr),
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf", "flpdf")
    );
}

/// `--replace-input` takes the output slot, so a second positional path is an
/// argument the command cannot honour. Selecting replacement mode without
/// checking for it would silently discard that path and overwrite the input --
/// the one outcome the user cannot undo. qpdf refuses the combination, and so
/// must the attachment routes.
#[test]
fn attachment_replace_input_with_an_output_path_is_rejected() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");
    let attachment = directory.path().join("attachment.txt");
    fs::write(&attachment, b"payload\n").expect("write attachment");

    let with_attachment = directory.path().join("base.pdf");
    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--static-id"])
        .arg(&fixture)
        .arg("--add-attachment")
        .arg(&attachment)
        .args(["--"])
        .arg(&with_attachment)
        .assert()
        .success();

    for operation in [
        vec!["--remove-attachment=attachment.txt".to_string()],
        vec![
            "--add-attachment".to_string(),
            attachment.to_str().unwrap().to_string(),
            "--".to_string(),
        ],
    ] {
        let input = directory.path().join("in.pdf");
        let output = directory.path().join("out.pdf");
        let _ = fs::remove_file(&output);
        fs::copy(&with_attachment, &input).expect("copy input");
        let before = fs::read(&input).expect("read input");

        Command::cargo_bin("flpdf")
            .expect("flpdf binary")
            .arg("--replace-input")
            .args(&operation)
            .arg(&input)
            .arg(&output)
            .assert()
            .failure()
            .code(2);

        assert_eq!(
            fs::read(&input).expect("read input"),
            before,
            "a rejected command must leave the input untouched for {operation:?}"
        );
        assert!(
            !output.exists(),
            "a rejected command must not create the output for {operation:?}"
        );
    }
}

/// Attachment keys and input paths are arbitrary bytes, not UTF-8. Routing
/// these through a lossy conversion would print U+FFFD where qpdf prints the
/// original byte, which breaks scripts that match on the name.
#[test]
#[cfg(unix)]
fn attachment_diagnostics_preserve_non_utf8_bytes() {
    use std::os::unix::ffi::OsStringExt;

    let directory = tempfile::tempdir().expect("temporary directory");
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/one-page.pdf");

    // A failed open must report the path byte for byte. This path is never
    // created, so it works on every unix filesystem.
    let missing =
        std::path::PathBuf::from(std::ffi::OsString::from_vec(b"missing-\xff.pdf".to_vec()));
    let output = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .env("FLPDF_PROGNAME", "qpdf")
        .args(["--remove-attachment=whatever"])
        .arg(&missing)
        .arg(directory.path().join("unused.pdf"))
        .output()
        .expect("flpdf runs");
    assert!(!output.status.success());
    assert!(
        output
            .stderr
            .windows(16)
            .any(|window| window.starts_with(b"missing-\xff.pdf")),
        "a failed open must report the raw path bytes, got {:?}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The stored attachment key only carries raw bytes when it is derived from
    // the source filename: `--key=` goes through the same lossy argument
    // conversion in qpdf itself, so it cannot produce one. Some filesystems
    // (APFS) reject a name that is not valid UTF-8, so skip this half there
    // rather than asserting on a file that cannot exist.
    let key = std::path::PathBuf::from(std::ffi::OsString::from_vec(b"key-\xff".to_vec()));
    let key_path = directory.path().join(&key);
    if fs::write(&key_path, b"payload\n").is_err() {
        eprintln!("skipping the attachment-key half: this filesystem rejects non-UTF-8 names");
        return;
    }

    let with_attachment = directory.path().join("base.pdf");
    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .args(["--static-id"])
        .arg(&fixture)
        .arg("--add-attachment")
        .arg(&key)
        .args(["--"])
        .arg(&with_attachment)
        .assert()
        .success();

    let mut remove_arg = std::ffi::OsString::from("--remove-attachment=");
    remove_arg.push(std::ffi::OsString::from_vec(b"key-\xff".to_vec()));
    let output = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .current_dir(directory.path())
        .env("FLPDF_PROGNAME", "qpdf")
        .args(["--static-id", "--verbose"])
        .arg(&remove_arg)
        .arg(&with_attachment)
        .arg(directory.path().join("removed.pdf"))
        .output()
        .expect("flpdf runs");
    assert!(
        output.status.success(),
        "verbose removal should succeed: {:?}",
        String::from_utf8_lossy(&output.stderr)
    );
    let combined = [output.stdout.as_slice(), output.stderr.as_slice()].concat();
    assert!(
        combined.windows(6).any(|window| window == b"key-\xff\n"),
        "verbose removal must echo the raw key bytes, got {:?}",
        String::from_utf8_lossy(&combined)
    );
}