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
//! Creating and removing the per-conversion command shims.
//!
//! Every shim is the same binary under a different name; the name is what
//! selects the conversion. Both linking methods share one copy on disk, so the
//! choice between them is about what survives an upgrade:
//!
//! - **Unix leads with symlinks.** `cargo install --force` writes a *new*
//!   binary. A symlink follows it; a hardlink is left pointing at the old
//!   inode, which is why every shim used to go stale on every upgrade.
//! - **Windows leads with hardlinks**, because creating a symlink there needs
//!   Developer Mode or an elevated prompt.
//!
//! An outright copy is the last resort on both. `--method` overrides the order.

use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use crate::names;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
    Hardlink,
    Symlink,
    Copy,
}

impl Method {
    pub fn label(self) -> &'static str {
        match self {
            Method::Hardlink => "hardlink",
            Method::Symlink => "symlink",
            Method::Copy => "copy",
        }
    }

    /// Every spelling `--method` accepts, and the order they are listed in help.
    pub const ALL: [Method; 3] = [Method::Hardlink, Method::Symlink, Method::Copy];

    pub fn parse(s: &str) -> Option<Method> {
        Method::ALL.into_iter().find(|m| m.label() == s)
    }
}

/// The order to try when the caller has not insisted on one. See the module
/// docs for why the two platforms disagree.
#[cfg(windows)]
const DEFAULT_ORDER: [Method; 3] = [Method::Hardlink, Method::Symlink, Method::Copy];
#[cfg(not(windows))]
const DEFAULT_ORDER: [Method; 3] = [Method::Symlink, Method::Hardlink, Method::Copy];

const EXE_SUFFIX: &str = std::env::consts::EXE_SUFFIX;

/// Where the shims go, and what they are linked from.
pub struct Target {
    pub exe: PathBuf,
    pub dir: PathBuf,
    exe_bytes: OnceLock<Option<Vec<u8>>>,
}

/// Can we actually create files here?
///
/// Probed by trying, rather than by reading permission bits: the bits lie on
/// network filesystems, and on Windows they barely mean anything at all.
fn writable(dir: &Path) -> bool {
    let probe = dir.join(".from2to-write-probe");
    match fs::File::create(&probe) {
        Ok(_) => {
            let _ = fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

/// Where the shims go when the binary's own directory is not ours to write to.
///
/// This is the case for every system package: from `/usr/bin/from2to`, a normal
/// user running `from2to install` would otherwise just get a permission error.
/// `cargo install` is unaffected, because `~/.cargo/bin` is already writable.
fn user_bin_dir(fallback: PathBuf) -> PathBuf {
    let candidate = if cfg!(windows) {
        std::env::var_os("LOCALAPPDATA").map(|p| Path::new(&p).join("Programs").join("from2to"))
    } else {
        std::env::var_os("XDG_BIN_HOME")
            .map(PathBuf::from)
            .or_else(|| {
                std::env::var_os("HOME").map(|h| Path::new(&h).join(".local").join("bin"))
            })
    };
    match candidate {
        // Created eagerly: `~/.local/bin` often does not exist yet, and a
        // directory that cannot be made is no use as a fallback.
        Some(d) if fs::create_dir_all(&d).is_ok() && writable(&d) => d,
        // Nothing better to offer; let the real create fail with a real error.
        _ => fallback,
    }
}

impl Target {
    pub fn resolve(dir: Option<&str>) -> io::Result<Target> {
        let exe = std::env::current_exe()?;
        let exe = fs::canonicalize(&exe).unwrap_or(exe);
        let dir = match dir {
            Some(d) => PathBuf::from(d),
            None => {
                let beside = exe
                    .parent()
                    .ok_or_else(|| io::Error::other("cannot determine the binary's directory"))?
                    .to_path_buf();
                if writable(&beside) { beside } else { user_bin_dir(beside) }
            }
        };
        Ok(Target {
            exe,
            dir,
            exe_bytes: OnceLock::new(),
        })
    }

    fn path_for(&self, name: &str) -> PathBuf {
        self.dir.join(format!("{name}{EXE_SUFFIX}"))
    }

    fn exe_bytes(&self) -> Option<&Vec<u8>> {
        self.exe_bytes.get_or_init(|| fs::read(&self.exe).ok()).as_ref()
    }

    /// Is this path the binary that is currently running?
    ///
    /// A symlink shim *resolves* to that binary, so canonicalizing alone would
    /// call every one of them "self" — and `uninstall`, which skips anything
    /// that is self, would then remove nothing at all. Only the real file
    /// counts; a link that merely points at it does not.
    fn is_self(&self, path: &Path) -> bool {
        if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
            return false;
        }
        fs::canonicalize(path).is_ok_and(|p| p == self.exe)
    }

    /// A symlink naming the same file as our binary — ours, even if it dangles.
    fn points_at_us(&self, path: &Path) -> bool {
        fs::read_link(path).is_ok_and(|t| t.file_name() == self.exe.file_name())
    }

    /// Work out what a file occupying one of our names actually is.
    ///
    /// Byte-identity alone is not enough: `cargo install` writes a brand new
    /// binary, which instantly makes every existing shim a non-match even
    /// though we put it there. So a shim from any build is recognized by the
    /// marker below, and byte-identity only distinguishes "already current"
    /// from "ours but stale".
    fn classify(&self, path: &Path) -> Kind {
        let Ok(bytes) = fs::read(path) else {
            // Unreadable, which for a valid symlink cannot happen — `read`
            // follows it. So this is a shim left dangling by a binary that
            // moved away, and it is still ours to replace.
            return if self.points_at_us(path) {
                Kind::Stale
            } else {
                Kind::Foreign
            };
        };
        if self.exe_bytes().is_some_and(|ours| &bytes == ours) {
            return Kind::Current;
        }
        if contains(&bytes, SHIM_MARKER) {
            return Kind::Stale;
        }
        Kind::Foreign
    }
}

/// What a file sitting on one of our command names turned out to be.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    /// Byte-identical to the binary we are installing from.
    Current,
    /// A from2to build, but not this one — safe to replace or remove.
    Stale,
    /// Someone else's file. Never touched without `--force`.
    Foreign,
}

/// Compiled into every build so that any version can recognize its own shims.
///
/// It is referenced by `contains` below, which keeps the literal in the
/// binary's data section where a scan of the file will find it.
const SHIM_MARKER: &[u8] = b"from2to/shim-marker/9f3ac41d-0e2b-4c77-8a15-6db0e3f9c2a1";

/// Substring search, scanning on the first byte so a megabyte-sized executable
/// does not turn into a quadratic walk.
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() || haystack.len() < needle.len() {
        return false;
    }
    let first = needle[0];
    let last = haystack.len() - needle.len();
    let mut i = 0;
    while i <= last {
        if haystack[i] == first && &haystack[i..i + needle.len()] == needle {
            return true;
        }
        i += 1;
    }
    false
}

/// Names to create: every conversion, the detector, plus the short self-name.
fn all_names() -> Vec<String> {
    let mut names: Vec<String> = names::shim_names().into_iter().map(|(n, _, _)| n).collect();
    names.push(names::DETECT_NAME.to_string());
    names.push(names::SHORT_NAME.to_string());
    names
}

// ------------------------------------------------------------ linking

#[cfg(windows)]
fn try_symlink(src: &Path, dst: &Path) -> io::Result<()> {
    std::os::windows::fs::symlink_file(src, dst)
}

#[cfg(unix)]
fn try_symlink(src: &Path, dst: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(src, dst)
}

/// Do two paths name the same directory?
fn same_dir(a: &Path, b: &Path) -> bool {
    a == b
        || match (fs::canonicalize(a), fs::canonicalize(b)) {
            (Ok(x), Ok(y)) => x == y,
            _ => false,
        }
}

/// What a symlink at `dst` should point at.
///
/// A bare file name when the two sit in the same directory, so the pair can be
/// moved or renamed as a unit. An absolute target would bake in wherever the
/// binary happened to be when `install` ran, which breaks the moment anything
/// relocates the directory. Pointing across directories leaves no choice.
fn symlink_target(src: &Path, dst: &Path) -> PathBuf {
    match (src.parent(), dst.parent()) {
        (Some(a), Some(b)) if same_dir(a, b) => {
            PathBuf::from(src.file_name().unwrap_or(src.as_os_str()))
        }
        _ => src.to_path_buf(),
    }
}

fn try_method(m: Method, src: &Path, dst: &Path) -> io::Result<()> {
    match m {
        Method::Hardlink => fs::hard_link(src, dst),
        Method::Symlink => try_symlink(&symlink_target(src, dst), dst),
        Method::Copy => fs::copy(src, dst).map(|_| ()),
    }
}

/// Create one shim, degrading through the fallbacks until something works.
///
/// `want` pins a single method instead — if it fails, that is an error rather
/// than a cue to try something else, since the caller asked for it by name.
fn link_one(src: &Path, dst: &Path, want: Option<Method>) -> io::Result<Method> {
    let pinned;
    let order: &[Method] = match want {
        Some(m) => {
            pinned = [m];
            &pinned
        }
        None => &DEFAULT_ORDER,
    };

    let mut last = None;
    for &m in order {
        match try_method(m, src, dst) {
            Ok(()) => return Ok(m),
            // Something is already sitting there; that is the caller's call to
            // make, not something to work around by trying another method.
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => return Err(e),
            Err(e) => last = Some(e),
        }
    }
    Err(last.unwrap_or_else(|| io::Error::other("no way to create a link")))
}

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

#[derive(Debug, Default)]
pub struct Report {
    pub created: usize,
    pub already: usize,
    pub replaced: usize,
    pub removed: usize,
    pub conflicts: Vec<PathBuf>,
    pub methods: Vec<Method>,
}

/// Probe before creating sixty-odd files, so a permission problem surfaces as
/// one clear message instead of halfway through the run.
fn check_writable(dir: &Path) -> io::Result<()> {
    let probe = dir.join(format!(".from2to-write-probe-{}", std::process::id()));
    match fs::File::create(&probe) {
        Ok(_) => {
            let _ = fs::remove_file(&probe);
            Ok(())
        }
        Err(e) => Err(io::Error::other(format!(
            "cannot write to {} ({e}) — choose somewhere else with --dir",
            dir.display()
        ))),
    }
}

pub fn install(
    dir: Option<&str>,
    dry_run: bool,
    force: bool,
    method: Option<Method>,
) -> io::Result<Report> {
    let target = Target::resolve(dir)?;
    if !target.dir.is_dir() {
        return Err(io::Error::other(format!(
            "{} is not a directory",
            target.dir.display()
        )));
    }
    if !dry_run {
        check_writable(&target.dir)?;
    }

    let mut report = Report::default();
    let mut planned = Vec::new();

    for name in all_names() {
        let dst = target.path_for(&name);

        if dst.exists() {
            // It *is* the binary doing the installing.
            if target.is_self(&dst) {
                report.already += 1;
                continue;
            }
            match target.classify(&dst) {
                Kind::Current => {
                    report.already += 1;
                    continue;
                }
                // Ours from an earlier build: refresh it, no --force needed.
                Kind::Stale => {
                    if !dry_run {
                        fs::remove_file(&dst)?;
                    }
                    report.replaced += 1;
                }
                Kind::Foreign => {
                    if !force {
                        report.conflicts.push(dst);
                        continue;
                    }
                    if !dry_run {
                        fs::remove_file(&dst)?;
                    }
                    report.replaced += 1;
                }
            }
        }

        planned.push(dst);
    }

    if dry_run {
        for p in &planned {
            println!("would create {}", p.display());
        }
        report.created = planned.len();
        return Ok(report);
    }

    for dst in planned {
        let used = link_one(&target.exe, &dst, method).map_err(|e| {
            io::Error::other(format!("could not create {}: {e}", dst.display()))
        })?;
        if !report.methods.contains(&used) {
            report.methods.push(used);
        }
        report.created += 1;
    }

    Ok(report)
}

pub fn uninstall(dir: Option<&str>, dry_run: bool) -> io::Result<Report> {
    let target = Target::resolve(dir)?;
    let mut report = Report::default();

    for name in all_names() {
        let dst = target.path_for(&name);
        if !dst.exists() {
            continue;
        }
        // Never delete the binary that is doing the uninstalling.
        if target.is_self(&dst) {
            continue;
        }
        // A shim from any build of ours is fair game; anything else is not.
        if target.classify(&dst) == Kind::Foreign {
            report.conflicts.push(dst);
            continue;
        }
        if dry_run {
            println!("would remove {}", dst.display());
        } else {
            fs::remove_file(&dst)?;
        }
        report.removed += 1;
    }

    Ok(report)
}

/// Is this directory on `PATH`?
///
/// Worth saying out loud: with the fallback in `Target::resolve`, the commands
/// can land somewhere the shell will not find them, and silently installing
/// sixty files that cannot be run is a poor outcome.
fn on_path(dir: &Path) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return true; // Nothing to check against; do not cry wolf.
    };
    let want = fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
    std::env::split_paths(&path)
        .any(|p| fs::canonicalize(&p).unwrap_or(p) == want)
}

pub fn print_install_report(target_dir: &Path, r: &Report, dry_run: bool) {
    let verb = if dry_run { "would install" } else { "installed" };
    let how = if r.methods.is_empty() {
        String::new()
    } else {
        format!(
            " via {}",
            r.methods.iter().map(|m| m.label()).collect::<Vec<_>>().join(" + ")
        )
    };
    println!(
        "{verb} {} command{}{} in {}",
        r.created,
        if r.created == 1 { "" } else { "s" },
        how,
        target_dir.display()
    );
    if !on_path(target_dir) {
        eprintln!("  note: {} is not on your PATH", target_dir.display());
    }
    if r.already > 0 {
        println!("  {} already present", r.already);
    }
    if r.replaced > 0 {
        println!("  {} replaced", r.replaced);
    }
    if !r.conflicts.is_empty() {
        eprintln!(
            "  {} name{} already taken by something else (use --force to replace):",
            r.conflicts.len(),
            if r.conflicts.len() == 1 { "" } else { "s" }
        );
        for c in &r.conflicts {
            eprintln!("    {}", c.display());
        }
    }
}

pub fn print_uninstall_report(target_dir: &Path, r: &Report, dry_run: bool) {
    let verb = if dry_run { "would remove" } else { "removed" };
    println!("{verb} {} commands from {}", r.removed, target_dir.display());
    if !r.conflicts.is_empty() {
        eprintln!(
            "  left {} file{} alone (not ours):",
            r.conflicts.len(),
            if r.conflicts.len() == 1 { "" } else { "s" }
        );
        for c in &r.conflicts {
            eprintln!("    {}", c.display());
        }
    }
}

/// Print every command name and what it does.
pub fn list() {
    for (name, from, to) in names::shim_names() {
        println!("{name:<12} {from} -> {to}");
    }
    println!("{:<12} identify the format of some text", names::DETECT_NAME);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn writability_is_probed_by_trying() {
        let dir = std::env::temp_dir().join(format!("f2t-writable-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        assert!(writable(&dir));
        // A directory that is not there cannot be written to.
        assert!(!writable(&dir.join("no-such-subdir")));
        // The probe must not leave anything behind.
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
        let _ = fs::remove_dir_all(&dir);
    }

    /// The fallback has to produce somewhere real, or a system package leaves
    /// the user with a permission error and no suggestion.
    #[test]
    fn the_user_bin_fallback_is_writable() {
        let sentinel = PathBuf::from("definitely-not-a-real-directory");
        let dir = user_bin_dir(sentinel.clone());
        if dir != sentinel {
            assert!(writable(&dir), "{} is not writable", dir.display());
        }
    }

    #[test]
    fn on_path_recognizes_a_directory_from_path() {
        // Whatever PATH holds, its own first entry must read as being on it.
        if let Some(p) = std::env::var_os("PATH")
            .and_then(|v| std::env::split_paths(&v).find(|d| d.is_dir()))
        {
            assert!(on_path(&p), "{} should read as on PATH", p.display());
        }
        let off = std::env::temp_dir().join("f2t-definitely-not-on-path");
        assert!(!on_path(&off));
    }

    #[test]
    fn all_names_includes_shims_and_short_self_name() {
        let names = all_names();
        assert_eq!(names.len(), 84);
        assert!(names.contains(&"hex2bin".to_string()));
        // An identity pair that earns its name: `hex2hex` does arithmetic.
        assert!(names.contains(&"hex2hex".to_string()));
        assert!(!names.contains(&"char2char".to_string()));
        assert!(names.contains(&"f2t".to_string()));
        assert!(names.contains(&"whatbase".to_string()));
        // Numeric shorthands resolve, but a file called `1628` never lands in
        // a directory on PATH.
        assert!(!names.contains(&"1628".to_string()));
        // The real binary name is never a shim; it is what shims point at.
        assert!(!names.contains(&"from2to".to_string()));
    }

    #[test]
    fn a_file_that_is_not_ours_is_not_claimed() {
        let dir = std::env::temp_dir().join(format!("f2t-test-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let impostor = dir.join("hex2bin.txt");
        fs::write(&impostor, b"not the binary").unwrap();
        let target = Target::resolve(None).unwrap();
        assert_eq!(target.classify(&impostor), Kind::Foreign);
        fs::remove_dir_all(&dir).ok();
    }

    /// The marker has to survive compilation, or every shim looks foreign
    /// after the next rebuild.
    #[test]
    fn the_marker_is_present_in_our_own_binary() {
        let exe = std::env::current_exe().unwrap();
        let bytes = fs::read(&exe).unwrap();
        assert!(
            contains(&bytes, SHIM_MARKER),
            "SHIM_MARKER was optimized out of {}",
            exe.display()
        );
    }

    #[test]
    fn a_build_that_is_not_this_one_still_reads_as_ours() {
        let dir = std::env::temp_dir().join(format!("f2t-stale-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let target = Target::resolve(None).unwrap();

        // Stand in for a different version: carries the marker, differs byte-wise.
        let stale = dir.join("hex2bin.bin");
        let mut bytes = target.exe_bytes().unwrap().clone();
        bytes.extend_from_slice(b"a later build");
        fs::write(&stale, &bytes).unwrap();
        assert_eq!(target.classify(&stale), Kind::Stale);

        // And the exact same bytes read as current.
        let current = dir.join("hex2dec.bin");
        fs::write(&current, target.exe_bytes().unwrap()).unwrap();
        assert_eq!(target.classify(&current), Kind::Current);

        fs::remove_dir_all(&dir).ok();
    }

    /// The property that makes a package relocatable: a shim next to the binary
    /// points at a bare name, never at wherever `install` happened to run.
    #[test]
    fn a_symlink_beside_the_binary_uses_a_bare_name() {
        let src = Path::new("/opt/somewhere/bin/from2to");
        let dst = Path::new("/opt/somewhere/bin/hex2bin");
        assert_eq!(symlink_target(src, dst), PathBuf::from("from2to"));

        // Across directories there is nothing to be relative to.
        let far = Path::new("/usr/local/bin/hex2bin");
        assert_eq!(symlink_target(src, far), src.to_path_buf());
    }

    #[test]
    fn method_names_round_trip() {
        for m in Method::ALL {
            assert_eq!(Method::parse(m.label()), Some(m));
        }
        assert_eq!(Method::parse("nonsense"), None);
    }

    /// `uninstall` skips anything that is "self". Before the symlink switch
    /// that only ever matched the real binary; a symlink resolves to it too, so
    /// treating one as self would make uninstall silently remove nothing.
    #[test]
    #[cfg(unix)]
    fn a_symlink_to_the_binary_is_not_itself() {
        let dir = std::env::temp_dir().join(format!("f2t-self-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let target = Target::resolve(None).unwrap();

        let link = dir.join("hex2bin");
        try_symlink(&target.exe, &link).unwrap();
        assert!(!target.is_self(&link), "a symlink shim is not the binary");
        assert!(target.is_self(&target.exe), "the binary still is");

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn substring_search_finds_edges_and_misses() {
        assert!(contains(b"abcdef", b"abc"));
        assert!(contains(b"abcdef", b"def"));
        assert!(contains(b"abcdef", b"cd"));
        assert!(!contains(b"abcdef", b"dc"));
        assert!(!contains(b"ab", b"abc"));
        assert!(!contains(b"", b"a"));
    }
}