from2to 0.5.0

Fast conversion at the terminal: hex2bin, dec2char, hex2b64, and friends
Documentation
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
//! End-to-end tests: the real binary, run the way a user runs it.

use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

const EXE: &str = env!("CARGO_BIN_EXE_from2to");
const EXE_SUFFIX: &str = std::env::consts::EXE_SUFFIX;

struct Output {
    stdout: String,
    stderr: String,
    code: i32,
}

impl Output {
    /// stdout without the trailing newline the tool adds.
    fn out(&self) -> &str {
        self.stdout.strip_suffix('\n').unwrap_or(&self.stdout)
    }
}

fn run_exe(exe: &Path, args: &[&str], stdin: Option<&str>) -> Output {
    let mut tries = 0;
    // Retried, because of a race Linux has and Windows does not: while one
    // thread is still holding the write fd from `fs::copy`, another thread
    // that forks inherits it, and the binary reads as busy until that child
    // execs. Nothing is wrong with the file — it is ready a moment later.
    let mut child = loop {
        let attempt = Command::new(exe)
            .args(args)
            .stdin(if stdin.is_some() {
                Stdio::piped()
            } else {
                Stdio::null()
            })
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn();
        match attempt {
            Ok(c) => break c,
            Err(e) if e.kind() == io::ErrorKind::ExecutableFileBusy && tries < 100 => {
                tries += 1;
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            Err(e) => panic!("failed to spawn {}: {e:?}", exe.display()),
        }
    };

    if let Some(input) = stdin {
        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(input.as_bytes())
            .unwrap();
    }
    let out = child.wait_with_output().unwrap();
    Output {
        stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
        code: out.status.code().unwrap_or(-1),
    }
}

fn run(args: &[&str]) -> Output {
    run_exe(Path::new(EXE), args, None)
}

fn run_stdin(args: &[&str], input: &str) -> Output {
    run_exe(Path::new(EXE), args, Some(input))
}

fn temp_dir(tag: &str) -> PathBuf {
    let d = std::env::temp_dir().join(format!("f2t-it-{}-{tag}", std::process::id()));
    let _ = fs::remove_dir_all(&d);
    fs::create_dir_all(&d).unwrap();
    d
}

/// Put the binary in `dir` under a shim name, the way `install` would.
///
/// Idempotent: asking for the same name twice hands back what is already
/// there. On Windows the second `copy` would otherwise fail with a sharing
/// violation, because the first shim has just been run.
fn make_shim(dir: &Path, name: &str) -> PathBuf {
    let dst = dir.join(format!("{name}{EXE_SUFFIX}"));
    if dst.exists() {
        return dst;
    }
    if fs::hard_link(EXE, &dst).is_err() {
        fs::copy(EXE, &dst).unwrap();
    }
    dst
}

// ----------------------------------------------------------- arguments

#[test]
fn converts_values_given_as_arguments() {
    assert_eq!(run(&["16", "2", "0f"]).out(), "00001111");
    assert_eq!(run(&["16", "2", "-W", "0f"]).out(), "1111");
    assert_eq!(run(&["36", "10", "zz"]).out(), "1295");
    assert_eq!(run(&["16", "b64", "68656c6c6f"]).out(), "aGVsbG8=");
}

#[test]
fn accepts_word_names_and_combined_names() {
    assert_eq!(run(&["hex", "bin", "ff"]).out(), "11111111");
    assert_eq!(run(&["hex2bin", "ff"]).out(), "11111111");
    assert_eq!(run(&["1628", "ff"]).out(), "377");
}

#[test]
fn multiple_values_produce_multiple_results() {
    assert_eq!(run(&["hex2bin", "41", "42"]).out(), "01000001\n01000010");
}

// ----------------------------------------------------------- stdin

#[test]
fn a_stream_of_decimal_code_points_becomes_text() {
    // What `nc host port | dec2char` sees: decimal code points, one per line.
    let out = run_stdin(&["dec", "char"], "104\n101\n108\n108\n111\n");
    assert_eq!(out.out(), "hello");
    assert_eq!(out.code, 0);
}

#[test]
fn stdin_numbers_convert_line_by_line() {
    assert_eq!(run_stdin(&["dec", "hex"], "255\n16\n").out(), "ff\n10");
}

#[test]
fn char_input_from_a_pipe_drops_the_echo_newline() {
    assert_eq!(run_stdin(&["char", "hex"], "hello\n").out(), "68656c6c6f");
    // Interior newlines are data and must survive.
    assert_eq!(run_stdin(&["char", "hex"], "a\nb\n").out(), "610a62");
}

#[test]
fn trailing_newline_can_be_suppressed() {
    assert_eq!(run(&["dec", "char", "112"]).stdout, "p\n");
    assert_eq!(run(&["dec", "char", "-n", "112"]).stdout, "p");
}

// ------------------------------------------------------ expression math

/// The loop this feature exists to close: read an address off the
/// disassembly, do the math, read the answer in the same base.
#[test]
fn evaluates_address_math_through_the_shims() {
    let dir = temp_dir("expr");
    for (name, args, expected) in [
        ("hex2hex", vec!["4438+1a"], "4452"),
        ("hex2dec", vec!["4438+1a"], "17490"),
        ("hex2hex", vec!["(4500 - 4438)/2"], "64"),
        ("dec2hex", vec!["1000*4"], "fa0"),
        ("hex2bin", vec!["ff & 0f"], "1111"),
        ("hex2hex", vec!["4438 | 8000"], "c438"),
        ("hex2hex", vec!["4438 - 4500"], "-c8"),
        ("hex2hex", vec!["--word", "2", "4438 - 4500"], "ff38"),
        ("hex2hex", vec!["--word", "2", "~0"], "ffff"),
        // Shifts bind looser than +, exactly as in C.
        ("hex2hex", vec!["1<<2+3"], "20"),
        // A comma still separates values, so two expressions are two answers.
        ("hex2hex", vec!["1+1, 2+2"], "2\n4"),
    ] {
        let shim = make_shim(&dir, name);
        let out = run_exe(&shim, &args, None);
        assert_eq!(out.out(), expected, "{name} {args:?}: {}", out.stderr);
        assert_eq!(out.code, 0, "{name} {args:?} exited {}", out.code);
    }
    let _ = fs::remove_dir_all(&dir);
}

/// `main` joins the arguments with a space before converting, so an
/// unquoted expression whose shell split it into three works anyway.
#[test]
fn spaced_operators_survive_the_argv_join() {
    assert_eq!(run(&["hex", "hex", "4438", "+", "1a"]).out(), "4452");
}

/// Everything an operator character newly claims used to be a hard error, so
/// nothing here may have changed. These are the regressions that would matter.
#[test]
fn inputs_without_an_operator_are_untouched() {
    assert_eq!(run(&["hex", "dec", "ff", "10"]).out(), "255\n16");
    assert_eq!(run(&["hex", "dec", "ff,10"]).out(), "255\n16");
    assert_eq!(run(&["hex", "bin", "0f"]).out(), "00001111");
    // `clean_token` strips only the source base's own prefix, so `0b` in hex
    // is the number 0xb — and it must read the same inside an expression.
    assert_eq!(run(&["hex", "dec", "0b"]).out(), "11");
    assert_eq!(run(&["hex", "dec", "0b1+0"]).out(), "177");
    // A char source has no digits, so its text is data, `+` and all.
    assert_eq!(run(&["char", "hex", "1+1"]).out(), "312b31");
    // A lone angle bracket is a shell mistake far more often than a shift.
    assert!(run(&["hex", "dec", "1<2"]).stderr.contains("bad digit"));
    assert!(run(&["hex", "dec", "00:11:22"]).stderr.contains("bad digit"));
}

#[test]
fn strict_turns_expressions_back_into_bad_digits() {
    let out = run(&["hex", "dec", "--strict", "4438+1a"]);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("bad digit"), "{}", out.stderr);
}

/// Hex-shaped identifiers are punctuated with dashes, and every other
/// character in them is a hex digit — so nothing but the dash itself stops a
/// UUID or a MAC address reading as a chain of subtractions. Arithmetic must
/// not turn either into a plausible number at exit 0; both were a clean digit
/// error before it existed, and both stay an error.
#[test]
fn a_dashed_identifier_is_an_error_and_never_a_sum() {
    for id in [
        "550e8400-e29b-41d4-a716-446655440000", // UUID
        "00-11-22-33-44-55",                    // MAC address
        "1a-2b",                                // a dashed byte pair
    ] {
        let out = run(&["hex", "dec", id]);
        assert_eq!(out.code, 1, "hex2dec {id} produced `{}`", out.out());
        assert!(out.stderr.contains("not subtraction"), "{id}: {}", out.stderr);
    }
    // The same shape with `-k`, which is what bulk input reaches for: skipped
    // with a warning, never silently summed.
    let out = run(&["hex", "dec", "-k", "00-11-22"]);
    assert_eq!(out.out(), "");
    assert!(out.stderr.contains("bad digit"), "{}", out.stderr);
}

/// A negative is printable as a number and not as a byte, and the difference
/// has to be an error rather than a magnitude quietly standing in.
#[test]
fn a_negative_result_is_a_sign_or_an_error() {
    assert_eq!(run(&["hex", "dec", "1 - 5"]).out(), "-4");
    assert_eq!(run(&["hex", "hex", "-x", "4438 - 4500"]).out(), "-0xc8");
    for to in ["char", "b64", "esc"] {
        let out = run(&["hex", to, "1 - 5"]);
        assert_eq!(out.code, 1, "hex2{to} accepted a negative");
        assert!(out.stderr.contains("--word"), "hex2{to}: {}", out.stderr);
    }
}

#[test]
fn a_broken_expression_says_what_is_wrong() {
    for (input, want) in [
        ("(4438+1a", "never closed"),
        ("10/0", "division by zero"),
        ("4438+", "ends after an operator"),
        ("1<<ffffff", "bit limit"),
        ("ff 10 aa+1", "nothing between them"),
        ("4438+1a-5", "not subtraction"),
    ] {
        let out = run(&["hex", "hex", input]);
        assert_eq!(out.code, 1, "{input} should fail");
        assert!(out.stderr.contains(want), "{input}: {}", out.stderr);
    }
}

/// A chunk is a line, so an expression per line is what a stream is.
#[test]
fn expressions_stream_a_line_at_a_time() {
    assert_eq!(run_stdin(&["hex", "hex"], "1+1\n2+2\nff&0f\n").out(), "2\n4\nf");
}

/// `-k` promises to skip what fails, never to produce less than before.
#[test]
fn keep_going_still_falls_back_to_a_token_list() {
    let out = run(&["hex", "dec", "-k", "ff 1+1 10"]);
    assert_eq!(out.out(), "255\n16");
    assert_eq!(out.code, 0);
}

/// `--word` makes the same claim to the arithmetic and to the swap.
#[test]
fn a_word_composes_with_byte_order() {
    assert_eq!(run(&["ledec", "hex", "--word", "4", "1+1"]).out(), "2000000");
    assert_eq!(run(&["hex", "lehex", "--word", "2", "4438 - 4500"]).out(), "38ff");
}

/// The four identity pairs are installed now, because they do something.
#[test]
fn positional_identity_commands_exist() {
    let listed = run(&["list"]).stdout;
    // Each line is `name  from -> to`, so compare the first field.
    let named = |want: &str| listed.lines().any(|l| l.split_whitespace().next() == Some(want));
    for name in ["hex2hex", "dec2dec", "bin2bin", "oct2oct"] {
        assert!(named(name), "{name} is not listed");
    }
    assert!(!named("char2char"), "char2char is still a no-op");
    assert!(!named("b642b64"), "b642b64 is still a no-op");

    let dir = temp_dir("identity");
    let shim = make_shim(&dir, "hex2hex");
    // Without an expression it is a formatter, which is worth having too.
    assert_eq!(run_exe(&shim, &["ff"], None).out(), "ff");
    assert_eq!(run_exe(&shim, &["-u", "-g", "2", "deadbeef"], None).out(), "DE AD BE EF");
    let _ = fs::remove_dir_all(&dir);
}

// ----------------------------------------------------------- argv[0]

#[test]
fn argv0_selects_the_conversion() {
    let dir = temp_dir("argv0");
    for (name, args, stdin, expected) in [
        ("hex2bin", vec!["41", "42"], None, "01000001\n01000010"),
        ("1628", vec!["ff"], None, "377"),
        ("b642char", vec!["aGVsbG8="], None, "hello"),
        ("dec2ascii", vec!["104", "105"], None, "hi"),
        ("char2hex", vec!["hello"], None, "68656c6c6f"),
        ("dec2char", vec![], Some("104\n101\n108\n108\n111\n"), "hello"),
    ] {
        let shim = make_shim(&dir, name);
        let out = run_exe(&shim, &args, stdin);
        assert_eq!(out.out(), expected, "{name} produced the wrong output");
        assert_eq!(out.code, 0, "{name} exited {}", out.code);
    }
    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn shim_help_names_the_conversion() {
    let dir = temp_dir("help");
    let shim = make_shim(&dir, "hex2bin");
    let out = run_exe(&shim, &["--help"], None);
    assert!(out.stdout.contains("Convert hex to bin"), "{}", out.stdout);
    let _ = fs::remove_dir_all(&dir);
}

// ----------------------------------------------------------- byte order

#[test]
fn endian_shims_swap_bytes() {
    let dir = temp_dir("endian");
    for (name, args, stdin, expected) in [
        // 0x0d0c0b0a read back to front is 0x0a0b0c0d.
        ("lehex2dec", vec!["0d0c0b0a"], None, "168496141"),
        ("lehex2hex", vec!["0d0c0b0a"], None, "0a0b0c0d"),
        ("hex2lebin", vec!["ff00"], None, "0000000011111111"),
        ("lehex2char", vec!["6f6c6c6568"], None, "hello"),
        ("char2lehex", vec!["hello"], None, "6f6c6c6568"),
        // A single byte has no byte order.
        ("lehex2dec", vec!["ff"], None, "255"),
        // Per token, never across whitespace.
        ("lehex2hex", vec!["0102", "0304"], None, "0201\n0403"),
        // A word size pins the width and swaps each word on its own.
        ("lehex2hex", vec!["--word", "4", "0d0c0b0a78563412"], None, "0a0b0c0d12345678"),
        ("dec2lehex", vec!["--word", "4", "1234"], None, "d2040000"),
        ("lehex2dec", vec![], Some("0d0c0b0a\nff00\n"), "168496141\n255"),
    ] {
        let shim = make_shim(&dir, name);
        let out = run_exe(&shim, &args, stdin);
        assert_eq!(out.out(), expected, "{name} {args:?} produced the wrong output");
        assert_eq!(out.code, 0, "{name} exited {}: {}", out.code, out.stderr);
    }
    let _ = fs::remove_dir_all(&dir);
}

/// The `f2t` spellings must agree with the shim, or people will learn one and
/// be surprised by the other.
#[test]
fn every_spelling_of_a_byte_order_agrees() {
    for args in [
        vec!["lehex2bin", "0d0c0b0a"],
        vec!["lehex", "bin", "0d0c0b0a"],
        vec!["lehex", "2", "0d0c0b0a"],
    ] {
        let out = run(&args);
        assert_eq!(out.code, 0, "{args:?}: {}", out.stderr);
        assert_eq!(out.out(), "00001010000010110000110000001101", "{args:?}");
    }
    // `be` is the default written down, so it changes nothing.
    assert_eq!(run(&["behex2dec", "ff"]).out(), run(&["hex2dec", "ff"]).out());
}

/// A swap over a run of bytes has to see the whole run. Reading it a line at a
/// time would reverse each line on its own, which is a wrong answer.
#[test]
fn a_swapped_byte_run_is_read_whole() {
    let dir = temp_dir("swapstream");
    let shim = make_shim(&dir, "char2lehex");
    let out = run_exe(&shim, &[], Some("hello\nworld\n"));
    // The whole run reversed, newline included — not "olleh\ndlrow".
    assert_eq!(out.out(), "646c726f770a6f6c6c6568", "{}", out.stderr);
    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn a_byte_order_without_a_width_is_refused() {
    // Base 10 carries no byte width of its own.
    let out = run(&["ledec2hex", "258"]);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("--word"), "{}", out.stderr);

    // An odd hex digit count has no byte boundary to swap on.
    let out = run(&["lehex2dec", "fff"]);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("whole number of bytes"), "{}", out.stderr);

    // `-k` downgrades a token-level failure, as it does everywhere else.
    let out = run(&["lehex2dec", "-k", "fff", "0d0c0b0a"]);
    assert_eq!(out.code, 0, "{}", out.stderr);
    assert_eq!(out.out(), "168496141");
}

#[test]
fn shim_help_names_the_byte_order() {
    let dir = temp_dir("lehelp");
    let shim = make_shim(&dir, "lehex2bin");
    let out = run_exe(&shim, &["--help"], None);
    assert!(
        out.stdout.contains("Convert little-endian hex to bin"),
        "{}",
        out.stdout
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Escaped hex through the shim names, including the pwntools-shaped one.
#[test]
fn esc_shims_round_trip_a_payload() {
    let dir = temp_dir("esc");
    for (name, args, expected) in [
        ("char2esc", vec!["hello"], "\\x68\\x65\\x6c\\x6c\\x6f"),
        ("esc2char", vec!["\\x66\\x6c\\x61\\x67"], "flag"),
        ("esc2hex", vec!["GET /\\r\\n"], "474554202f0d0a"),
        // p32(1234): agrees with struct.pack('<I', 1234) byte for byte.
        ("dec2leesc", vec!["--word", "4", "1234"], "\\xd2\\x04\\x00\\x00"),
    ] {
        let shim = make_shim(&dir, name);
        let out = run_exe(&shim, &args, None);
        assert_eq!(out.code, 0, "{name}: {}", out.stderr);
        assert_eq!(out.out(), expected, "{name} {args:?}");
    }

    // And whatbase names it without being told.
    assert_eq!(run(&["detect", "\\x68\\x65\\x6c\\x6c\\x6f"]).out(), "esc     hello");

    let _ = fs::remove_dir_all(&dir);
}

// ----------------------------------------------------------- detection

#[test]
fn detect_answers_before_it_explains() {
    let out = run(&["detect", "bDNhcm5fdGgzX3IwcDM1"]);
    assert_eq!(out.code, 0, "{}", out.stderr);
    // The whole default report: the format, what it says, and the caveat that
    // nothing in the string could separate b64 from b64url.
    assert_eq!(
        out.stdout,
        "b64     l3arn_th3_r0p35
        also reads as b64url (identical here)
",
        "{}",
        out.stdout
    );
    // The reasoning is still there, just behind --why.
    let why = run(&["detect", "--why", "bDNhcm5fdGgzX3IwcDM1"]);
    assert!(why.stdout.contains("all 20 characters"), "{}", why.stdout);
    assert!(why.stdout.contains("b642char bDNhcm5fdGgzX3IwcDM1"), "{}", why.stdout);
}

/// The one case terse output must not stay quiet about: two readings that give
/// different answers and are too close to call.
#[test]
fn detect_names_a_rival_that_is_genuinely_close() {
    let out = run(&["detect", "123456"]);
    assert_eq!(out.stdout, "dec     123456
        also reads as oct (42798)
");

    // ...and stays quiet when the winner is not in doubt.
    assert_eq!(run(&["detect", "68656c6c6f"]).stdout, "hex     hello
");
}

/// A positional base whose bytes are not text still owes you the number.
#[test]
fn detect_shows_the_value_when_it_is_not_text() {
    assert_eq!(run(&["detect", "ff"]).out(), "hex     255");
    assert_eq!(run(&["detect", "deadbeef"]).out(), "hex     3735928559");
    assert_eq!(run(&["detect", "hello world"]).out(), "char    (already text)");
}

#[test]
fn detect_can_decode_in_one_step_or_name_the_format() {
    assert_eq!(
        run(&["detect", "-d", "bDNhcm5fdGgzX3IwcDM1"]).out(),
        "l3arn_th3_r0p35"
    );
    assert_eq!(run(&["detect", "-q", "bDNhcm5fdGgzX3IwcDM1"]).out(), "b64");
    assert_eq!(run(&["detect", "-q", "68656c6c6f"]).out(), "hex");
    assert_eq!(run(&["detect", "-q", "01010101"]).out(), "bin");
    // The named format is one the converter accepts, so the two compose.
    assert_eq!(run(&["b64", "char", "bDNhcm5fdGgzX3IwcDM1"]).out(), "l3arn_th3_r0p35");
}

#[test]
fn detect_reads_stdin_and_reports_runners_up() {
    let out = run_stdin(&["detect"], "aGVsbG8=\n");
    assert_eq!(out.code, 0);
    assert!(out.stdout.starts_with("b64"), "{}", out.stdout);
    assert!(out.stdout.contains("hello"), "{}", out.stdout);

    let all = run(&["detect", "--all", "01010101"]);
    assert!(all.stdout.lines().count() > 4, "{}", all.stdout);
    assert!(all.stdout.contains("oct"), "{}", all.stdout);
}

#[test]
fn whatbase_works_through_its_own_name() {
    let dir = temp_dir("whatbase");
    let shim = make_shim(&dir, "whatbase");

    assert_eq!(run_exe(&shim, &["-q", "bDNhcm5fdGgzX3IwcDM1"], None).out(), "b64");
    assert_eq!(
        run_exe(&shim, &["-d", "bDNhcm5fdGgzX3IwcDM1"], None).out(),
        "l3arn_th3_r0p35"
    );
    let help = run_exe(&shim, &["--help"], None);
    assert!(help.stdout.contains("Work out what format"), "{}", help.stdout);

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn detect_says_when_text_is_already_text() {
    let out = run(&["detect", "-q", "hello world"]);
    assert_eq!(out.out(), "char");
    assert_eq!(out.code, 0);

    let out = run_stdin(&["detect"], "");
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("nothing to identify"), "{}", out.stderr);
}

// ----------------------------------------------------------- errors

#[test]
fn bad_digits_fail_loudly() {
    let out = run(&["hex", "dec", "zz"]);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("not valid base 16"), "{}", out.stderr);
    assert_eq!(out.stdout, "");
}

#[test]
fn keep_going_skips_and_warns() {
    let out = run(&["hex", "dec", "-k", "ff", "zz", "10"]);
    assert_eq!(out.out(), "255\n16");
    assert_eq!(out.code, 0);
    assert!(out.stderr.contains("'zz'"), "{}", out.stderr);
}

#[test]
fn quiet_suppresses_the_warning_but_keeps_the_output() {
    let out = run(&["hex", "dec", "-k", "-q", "ff", "zz"]);
    assert_eq!(out.out(), "255");
    assert_eq!(out.stderr, "");
}

#[test]
fn unknown_format_is_a_usage_error() {
    let out = run(&["nope", "hex", "1"]);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("unknown format"), "{}", out.stderr);
}

// ----------------------------------------------------------- formatting

#[test]
fn formatting_flags_apply() {
    assert_eq!(run(&["hex", "bin", "-g", "4", "ff"]).out(), "1111 1111");
    assert_eq!(run(&["dec", "hex", "-u", "255"]).out(), "FF");
    assert_eq!(run(&["dec", "hex", "-x", "255"]).out(), "0xff");
    assert_eq!(run(&["hex", "bin", "-w", "12", "0f"]).out(), "000000001111");
    assert_eq!(run(&["dec", "hex", "-d", ",", "255", "16"]).out(), "ff,10");
    assert_eq!(run(&["dec", "hex", "-j", "255", "16"]).out(), "ff10");
}

// ----------------------------------------------------------- docs

/// The man page is hand-written, so nothing stops it drifting behind the
/// argument definitions except this. The expectations are read out of `opts`
/// rather than listed here, so a new flag fails the test the day it is added.
#[test]
fn the_man_page_documents_every_flag_and_subcommand() {
    let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("man/from2to.1");
    let roff = fs::read_to_string(&path).expect("man/from2to.1 is missing");
    // roff escapes option dashes as `\-`; compare against plain text.
    let text = roff.replace("\\-", "-");

    fn walk(text: &str, cmd: &clap::Command, missing: &mut Vec<String>, seen: &mut usize) {
        for arg in cmd.get_arguments() {
            if let Some(long) = arg.get_long() {
                *seen += 1;
                let flag = format!("--{long}");
                if !text.contains(&flag) {
                    missing.push(flag);
                }
            }
        }
        for sub in cmd.get_subcommands() {
            *seen += 1;
            if !text.contains(sub.get_name()) {
                missing.push(sub.get_name().to_string());
            }
            walk(text, sub, missing, seen);
        }
    }

    let mut missing = Vec::new();
    let mut seen = 0;
    walk(&text, &from2to::opts::self_command("from2to"), &mut missing, &mut seen);
    walk(&text, &from2to::opts::detect_command("whatbase"), &mut missing, &mut seen);

    assert!(missing.is_empty(), "man page never mentions: {missing:?}");
    // Guard against the test passing because it inspected nothing.
    assert!(seen > 20, "only {seen} items checked; the walk is not working");
}

// ----------------------------------------------------------- install

#[test]
fn list_names_every_command() {
    let out = run(&["list"]);
    assert_eq!(out.code, 0);
    let lines: Vec<&str> = out.stdout.lines().collect();
    assert_eq!(lines.len(), 83);
    assert!(lines.iter().any(|l| l.starts_with("hex2bin ")));
    assert!(lines.iter().any(|l| l.starts_with("whatbase ")));
    // The numeric shorthands are not commands any more, only `f2t` forms.
    assert!(!lines.iter().any(|l| l.starts_with("1628 ")));
}

#[test]
fn dry_run_changes_nothing() {
    let dir = temp_dir("dryrun");
    let exe = dir.join(format!("from2to{EXE_SUFFIX}"));
    fs::copy(EXE, &exe).unwrap();

    let out = run_exe(&exe, &["install", "--dir", dir.to_str().unwrap(), "--dry-run"], None);
    assert_eq!(out.code, 0);
    assert!(out.stdout.contains("would create"));
    // Only the binary itself should be there.
    assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn install_then_uninstall_round_trips() {
    let dir = temp_dir("roundtrip");
    let exe = dir.join(format!("from2to{EXE_SUFFIX}"));
    fs::copy(EXE, &exe).unwrap();
    let dir_s = dir.to_str().unwrap();

    let out = run_exe(&exe, &["install", "--dir", dir_s], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    // 82 shims + whatbase + f2t + the binary.
    assert_eq!(fs::read_dir(&dir).unwrap().count(), 85);

    // A shim really works.
    let shim = dir.join(format!("hex2bin{EXE_SUFFIX}"));
    assert_eq!(run_exe(&shim, &["ff"], None).out(), "11111111");

    // Installing again is a no-op rather than an error.
    let again = run_exe(&exe, &["install", "--dir", dir_s], None);
    assert_eq!(again.code, 0);
    assert!(again.stdout.contains("already present"), "{}", again.stdout);

    let out = run_exe(&exe, &["uninstall", "--dir", dir_s], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);

    let _ = fs::remove_dir_all(&dir);
}

/// The reason Unix defaults to symlinks. `cargo install --force` writes a *new*
/// binary; a symlink follows it, so the shims keep working with no reinstall.
/// A hardlink would still point at the old inode.
#[test]
fn symlink_shims_survive_the_binary_being_replaced() {
    let dir = temp_dir("upgrade");
    let exe = dir.join(format!("from2to{EXE_SUFFIX}"));
    fs::copy(EXE, &exe).unwrap();
    let dir_s = dir.to_str().unwrap();

    let out = run_exe(&exe, &["install", "--dir", dir_s, "--method", "symlink"], None);
    if out.code != 0 {
        // Windows without Developer Mode cannot make symlinks at all.
        eprintln!("skipping: symlinks unavailable here ({})", out.stderr);
        let _ = fs::remove_dir_all(&dir);
        return;
    }

    let shim = dir.join(format!("hex2bin{EXE_SUFFIX}"));
    // Relative, so the whole directory can be moved or renamed as a unit.
    assert_eq!(
        fs::read_link(&shim).unwrap(),
        PathBuf::from(format!("from2to{EXE_SUFFIX}")),
    );
    assert_eq!(run_exe(&shim, &["ff"], None).out(), "11111111");

    // Stand in for `cargo install --force`: same path, different bytes.
    let mut bytes = fs::read(EXE).unwrap();
    bytes.extend_from_slice(b"\n// a later build\n");
    fs::remove_file(&exe).unwrap();
    fs::write(&exe, &bytes).unwrap();
    // `fs::write` creates 0644, but the thing it stands in for writes an
    // executable. Without this the replaced binary cannot be run at all,
    // and the uninstall below fails with a bare "Permission denied".
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
    }

    assert_eq!(
        fs::read(&shim).unwrap(),
        bytes,
        "the shim should now resolve to the new binary, with no reinstall"
    );

    // And uninstall must still recognize symlinks as ours and remove them.
    let out = run_exe(&exe, &["uninstall", "--dir", dir_s], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "only the binary left");

    let _ = fs::remove_dir_all(&dir);
}

/// Rebuilding changes the binary, so every shim stops being byte-identical to
/// it. Reinstalling must refresh them rather than call them foreign.
#[test]
fn reinstall_after_a_rebuild_refreshes_stale_shims() {
    let dir = temp_dir("stale");
    let exe = dir.join(format!("from2to{EXE_SUFFIX}"));
    fs::copy(EXE, &exe).unwrap();
    let dir_s = dir.to_str().unwrap();

    run_exe(&exe, &["install", "--dir", dir_s], None);

    // Stand in for "installed by an earlier build": still one of ours, but no
    // longer the same bytes as the binary doing the installing.
    let shim = dir.join(format!("hex2bin{EXE_SUFFIX}"));
    let mut bytes = fs::read(EXE).unwrap();
    bytes.extend_from_slice(b"\n// an earlier build\n");
    fs::remove_file(&shim).unwrap();
    fs::write(&shim, &bytes).unwrap();

    let out = run_exe(&exe, &["install", "--dir", dir_s], None);
    assert_eq!(out.code, 0, "should not need --force: {}", out.stderr);
    assert!(out.stdout.contains("1 replaced"), "{}", out.stdout);
    assert!(!out.stderr.contains("already taken"), "{}", out.stderr);
    // Refreshed to the current build, and working.
    assert_eq!(fs::read(&shim).unwrap(), fs::read(EXE).unwrap());
    assert_eq!(run_exe(&shim, &["ff"], None).out(), "11111111");

    // Uninstall also has to recognize a stale shim as ours.
    fs::remove_file(&shim).unwrap();
    fs::write(&shim, &bytes).unwrap();
    let out = run_exe(&exe, &["uninstall", "--dir", dir_s], None);
    assert_eq!(out.code, 0);
    assert!(!shim.exists(), "a stale shim should still be removed");

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn uninstall_leaves_files_that_are_not_ours() {
    let dir = temp_dir("foreign");
    let exe = dir.join(format!("from2to{EXE_SUFFIX}"));
    fs::copy(EXE, &exe).unwrap();
    let dir_s = dir.to_str().unwrap();

    run_exe(&exe, &["install", "--dir", dir_s], None);

    // Someone else's tool happens to be called hex2bin.
    let impostor = dir.join(format!("hex2bin{EXE_SUFFIX}"));
    fs::remove_file(&impostor).unwrap();
    fs::write(&impostor, b"a different program entirely").unwrap();

    let out = run_exe(&exe, &["uninstall", "--dir", dir_s], None);
    assert_eq!(out.code, 0);
    assert!(out.stderr.contains("not ours"), "{}", out.stderr);
    assert_eq!(
        fs::read(&impostor).unwrap(),
        b"a different program entirely"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn install_refuses_to_clobber_without_force() {
    let dir = temp_dir("clobber");
    let exe = dir.join(format!("from2to{EXE_SUFFIX}"));
    fs::copy(EXE, &exe).unwrap();
    let dir_s = dir.to_str().unwrap();

    let impostor = dir.join(format!("hex2bin{EXE_SUFFIX}"));
    fs::write(&impostor, b"not ours").unwrap();

    let out = run_exe(&exe, &["install", "--dir", dir_s], None);
    assert_eq!(out.code, 1, "should report the conflict");
    assert!(out.stderr.contains("already taken"), "{}", out.stderr);
    assert_eq!(fs::read(&impostor).unwrap(), b"not ours");

    // --force goes through.
    let out = run_exe(&exe, &["install", "--dir", dir_s, "--force"], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    assert_eq!(run_exe(&impostor, &["ff"], None).out(), "11111111");

    let _ = fs::remove_dir_all(&dir);
}