cargo-hoist 0.1.5

Dead simple, memoized cargo subcommand to hoist cargo-built binaries into scope.
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
use anyhow::Result;
use clap::{ArgAction, Parser, Subcommand};
use inquire::Confirm;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::hash::Hash;
use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use tracing::{instrument, Level};

/// Command line arguments
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Args {
    /// Verbosity level (0-4)
    #[arg(long, short, action = ArgAction::Count, default_value = "0")]
    pub verbosity: u8,

    /// The cargo-hoist subcommand
    #[clap(subcommand)]
    pub command: Option<Command>,
}

/// Subcommands
#[derive(Subcommand, Debug)]
pub enum Command {
    /// Hoist dependencies
    Hoist {
        /// An optional list of binaries to bring into scope from the hoist toml registry
        bins: Option<Vec<String>>,

        /// Binary list flag. Merged ad de-duplicated with any binaries provided in the inline
        /// argument.
        #[clap(short, long)]
        binaries: Option<Vec<String>>,
    },
    /// List registered dependencies.
    List,
    /// Search for a binary in the hoist toml registry.
    #[clap(alias = "find")]
    Search {
        /// The binary to search for in the hoist toml registry.
        binary: String,
    },
    /// Nuke wipes the hoist toml registry.
    Nuke,
    /// Registers a binary in the global hoist toml registry
    #[clap(alias = "install")]
    Register {
        /// An optional list of binaries to install in the hoist toml registry
        bins: Option<Vec<String>>,

        /// Binary list flag. Merged ad de-duplicated with any binaries provided in the inline
        /// argument.
        #[clap(short, long)]
        binaries: Option<Vec<String>>,
    },
}

/// The bash function to install the hoist cargo pre-hook.
pub const INSTALL_BASH_FUNCTION: &str = r#"
function cargo() {
    if ~/.cargo/bin/cargo hoist --help &>/dev/null; then
      ~/.cargo/bin/cargo hoist install
    fi
    ~/.cargo/bin/cargo "$@"
}
"#;

/// Run the main hoist command
pub fn run() -> Result<()> {
    let Args { verbosity, command } = Args::parse();
    init_tracing_subscriber(verbosity)?;

    // On first run, we want to install the hoist pre-hook in the user's bash file.
    // So we want to create it using inquire's confirm prompt.
    tracing::debug!("Gracefully creating pre hook");
    HoistRegistry::create_pre_hook(true)?;

    // Match on the subcommand and run hoist.
    tracing::debug!("Running command {:?}", command);
    match command {
        None => HoistRegistry::install(Vec::new()),
        Some(c) => match c {
            Command::Hoist { binaries, bins } => {
                HoistRegistry::hoist(merge_and_dedup_vecs(binaries, bins))
            }
            Command::Search { binary } => HoistRegistry::find(binary),
            Command::List => HoistRegistry::list(),
            Command::Register { binaries, bins } => {
                HoistRegistry::install(merge_and_dedup_vecs(binaries, bins))
            }
            Command::Nuke => HoistRegistry::nuke(),
        },
    }
}

/// Helper function to merge two optional string vectors and dedup any duplicate entries.
pub fn merge_and_dedup_vecs<T: Eq + Hash + Clone + Ord>(
    a: Option<Vec<T>>,
    b: Option<Vec<T>>,
) -> Vec<T> {
    let mut merged = vec![];
    if let Some(a) = a {
        merged.extend(a);
    }
    if let Some(b) = b {
        merged.extend(b);
    }
    merged.sort();
    merged.dedup();
    merged
}

/// Binary Metadata Object
#[derive(Debug, Default, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct HoistedBinary {
    /// The binary name
    pub name: String,
    /// The binary location
    pub location: PathBuf,
}

impl HoistedBinary {
    /// Creates a new hoisted binary.
    #[instrument(skip(name, location))]
    pub fn new(name: String, location: PathBuf) -> Self {
        Self { name, location }
    }

    /// Copies the binary to the current directory.
    #[instrument]
    pub fn copy_to_current_dir(&self) -> Result<()> {
        let current_dir = std::env::current_dir()?;
        let binary_path = current_dir.join(&self.name);
        tracing::debug!("Copying binary to current directory: {:?}", binary_path);
        std::fs::copy(&self.location, binary_path)?;
        Ok(())
    }
}

/// Hoist Registry
///
/// The global hoist registry is stored in ~/.hoist/registry.toml
/// and contains the memoized list of binaries that have been
/// built with cargo and saved as [HoistedBinary] objects.
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct HoistRegistry {
    /// The list of hoisted binaries.
    #[serde(default, skip_serializing_if = "HashSet::is_empty")]
    pub binaries: HashSet<HoistedBinary>,
}

impl HoistRegistry {
    /// Inserts a [HoistedBinary] into the registry.
    /// Will not insert if the binary already exists in the registry.
    #[instrument(skip(self, binary))]
    pub fn insert(&mut self, binary: HoistedBinary) {
        if !self.binaries.contains(&binary) {
            tracing::debug!("Binary not found in registry. Inserting.");
            self.binaries.insert(binary);
        }
    }

    /// The path to the hoist directory.
    pub fn dir() -> Result<PathBuf> {
        let hoist_dir = std::env::var("HOME")? + "/.hoist/";
        Ok(PathBuf::from(hoist_dir))
    }

    /// The path to the hoist registry file.
    pub fn path() -> Result<PathBuf> {
        let hoist_dir = HoistRegistry::dir()?;
        Ok(hoist_dir.join("registry.toml"))
    }

    /// Hook identifier file.
    /// This is used to indicate that the hoist pre-hook has been installed.
    pub fn hook_identifier() -> Result<PathBuf> {
        let hoist_dir = HoistRegistry::dir()?;
        Ok(hoist_dir.join("hook"))
    }

    /// Create the hoist directory if it doesn't exist.
    pub fn create_dir() -> Result<()> {
        let hoist_dir = HoistRegistry::dir()?;
        if !std::path::Path::new(&hoist_dir).exists() {
            tracing::info!("Creating ~/.hoist/ directory");
            std::fs::create_dir(hoist_dir)?;
        }
        Ok(())
    }

    /// Create the hoist registry file.
    pub fn create_registry() -> Result<()> {
        HoistRegistry::create_dir()?;
        let registry_file = HoistRegistry::path()?;
        if !std::path::Path::new(&registry_file).exists() {
            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .create(true)
                .open(registry_file)?;
            let default_registry = HoistRegistry::default();
            let toml = toml::to_string(&default_registry)?;
            file.write_all(toml.as_bytes())?;
        }
        Ok(())
    }

    /// Create the hoist pre-hook in the user bash file.
    pub fn create_pre_hook(with_confirm: bool) -> Result<()> {
        HoistRegistry::create_dir()?;
        let hook_file = HoistRegistry::hook_identifier()?;
        if !std::path::Path::new(&hook_file).exists() {
            if with_confirm && !Confirm::new("Cargo hoist pre-cargo hook not installed. Do you want to install? ([y]/n) Once installed, this prompt will not bother you again :)").prompt()? {
                anyhow::bail!("cargo hoist installation rejected");
            }
            // Write the bash function to the user's bash file.
            let shell_config = get_shell_config_file(detect_shell()?)?;
            if !shell_config.as_path().exists() {
                anyhow::bail!("~/.bashrc file does not exist");
            }
            let mut file = std::fs::OpenOptions::new()
                .append(true)
                .open(shell_config)?;
            file.write_all(INSTALL_BASH_FUNCTION.as_bytes())?;

            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .create(true)
                .open(hook_file)?;
            file.write_all("hook".as_bytes())?;
        }
        Ok(())
    }

    /// Installs the hoist registry to a `.hoist/` subdir in the
    /// user's home directory.
    #[instrument]
    pub fn setup() -> Result<()> {
        HoistRegistry::create_dir()?;
        HoistRegistry::create_registry()?;
        HoistRegistry::create_pre_hook(false)?;
        Ok(())
    }

    /// Returns the fully qualified path for a given binary
    /// if it is an executable.
    #[instrument]
    pub fn exec_path(exec: &Path) -> Result<String> {
        let is_file = std::fs::metadata(exec)?.is_file();
        let is_exec = std::fs::metadata(exec)?.permissions().mode() & 0o111 != 0;
        if !is_file || !is_exec {
            anyhow::bail!("{} is not executable", exec.display());
        }
        let bin_file_name = exec
            .file_name()
            .ok_or(anyhow::anyhow!("[std] failed to extract binary name"))?;
        let binary_name = bin_file_name
            .to_str()
            .ok_or(anyhow::anyhow!(
                "[std] failed to convert binary path name to string"
            ))?
            .to_string();
        tracing::debug!("retrieved binary name: {}", binary_name);
        Ok(binary_name)
    }

    /// Attempt to grab built binaries from the target directory.
    #[instrument]
    pub fn grab_binaries() -> Result<Vec<String>> {
        let target_dir = std::env::current_dir()?.join("target/release/");
        tracing::debug!("Parsing binaries in target directory: {:?}", target_dir);
        let mut binaries = vec![];
        for entry in std::fs::read_dir(target_dir)? {
            let Ok(e) = entry else {
                tracing::warn!("Failed to read entry: {:?}", entry);
                continue;
            };
            let Ok(exec) = HoistRegistry::exec_path(&e.path()) else {
                tracing::warn!("Failed to get exec path: {:?}", e);
                continue;
            };
            tracing::debug!("Found binary: {}", exec);
            binaries.push(exec);
        }
        tracing::debug!("Returning {} binaries", binaries.len());
        Ok(binaries)
    }

    /// Nukes the hoist toml registry.
    /// This writes an empty registry to the registry file.
    #[instrument]
    pub fn nuke() -> Result<()> {
        HoistRegistry::setup()?;
        let registry_file = HoistRegistry::path()?;
        // Clear the file before writing the empty registry.
        std::fs::File::create(&registry_file)?;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .open(registry_file)?;
        let registry = HoistRegistry::default();
        let toml = toml::to_string(&registry)?;
        file.write_all(toml.as_bytes())?;
        tracing::info!("Successfully nuked the hoist registry");
        Ok(())
    }

    /// Installs binaries in the hoist toml registry.
    #[instrument(skip(binaries))]
    pub fn install(binaries: Vec<String>) -> Result<()> {
        HoistRegistry::setup()?;
        tracing::debug!("Installing binaries: {:?}", binaries);

        // Then we read the registry file into a HoistRegistry object.
        let registry_file = HoistRegistry::path()?;
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&registry_file)?;
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml)?;
        let mut registry: HoistRegistry = toml::from_str(&registry_toml)?;
        tracing::debug!("Registry: {:?}", registry);

        // Then we iterate over the binaries and add them to the registry.
        let binaries = if binaries.is_empty() {
            HoistRegistry::grab_binaries().unwrap_or_default()
        } else {
            binaries
        };

        tracing::debug!("Hoisting {} binaries", binaries.len());
        for binary in &binaries {
            let binary_path = std::env::current_dir()?
                .join("target/release/")
                .join(binary);
            let binary_path = binary_path.canonicalize()?;
            let bin_file_name = binary_path
                .file_name()
                .ok_or(anyhow::anyhow!("[std] failed to extract binary name"))?;
            let binary_name = bin_file_name
                .to_str()
                .ok_or(anyhow::anyhow!(
                    "[std] failed to convert binary path name to string"
                ))?
                .to_string();
            tracing::debug!("Hoisted binary: {}", binary_name);
            let binary = HoistedBinary::new(binary_name, binary_path);
            registry.insert(binary);
        }

        // Only perform a writeback if there are binaries to hoist.
        match binaries.len() {
            0 => tracing::warn!("No binaries found in the target directory"),
            _ => {
                // first write no bytes to wipe the registry file
                let mut file = std::fs::OpenOptions::new()
                    .read(true)
                    .write(true)
                    .open(&registry_file)?;
                let toml = toml::to_string(&registry)?;
                let _ = file.write(toml.as_bytes())?;
                file.flush()?;
                tracing::info!("Successfully installed binaries to the registry")
            }
        }

        Ok(())
    }

    /// Finds a given binary in the hoist registry toml.
    #[instrument(skip(binary))]
    pub fn find(binary: impl AsRef<str>) -> Result<()> {
        HoistRegistry::setup()?;

        // Then we read the registry file into a HoistRegistry object.
        let registry_file = HoistRegistry::path()?;
        let mut file = std::fs::OpenOptions::new().read(true).open(registry_file)?;
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml)?;
        let registry: HoistRegistry = toml::from_str(&registry_toml)?;

        // Find the binary in the registry.
        let binary = binary.as_ref();
        let binary = registry
            .binaries
            .iter()
            .find(|b| b.name == binary)
            .ok_or(anyhow::anyhow!("Failed to find binary in hoist registry"))?;
        HoistRegistry::print_color(&format!("{}: ", binary.name), Color::Blue, false)?;
        HoistRegistry::print_color(&binary.location.display().to_string(), Color::Cyan, true)?;
        Ok(())
    }

    /// Lists the binaries in the hoist toml registry.
    #[instrument]
    pub fn list() -> Result<()> {
        HoistRegistry::setup()?;

        // Then we read the registry file into a HoistRegistry object.
        let registry_file = HoistRegistry::path()?;
        let mut file = std::fs::OpenOptions::new().read(true).open(registry_file)?;
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml)?;
        let registry: HoistRegistry = toml::from_str(&registry_toml)?;

        // Then we iterate over the binaries and print them.
        for binary in registry.binaries {
            HoistRegistry::print_color(&format!("{}: ", binary.name), Color::Blue, false)?;
            HoistRegistry::print_color(&binary.location.display().to_string(), Color::Cyan, true)?;
        }

        Ok(())
    }

    /// Prints text to stdout in the provided color.
    #[instrument]
    pub fn print_color(text: &str, color: Color, newline: bool) -> Result<()> {
        let mut stdout = StandardStream::stdout(ColorChoice::Always);
        stdout.set_color(ColorSpec::new().set_fg(Some(color)))?;
        let newline = if newline { "\n" } else { "" };
        write!(&mut stdout, "{}{}", text, newline)?;
        Ok(())
    }

    /// Hoists binaries from the hoist toml registry into scope.
    #[instrument(skip(binaries))]
    pub fn hoist(binaries: Vec<String>) -> Result<()> {
        HoistRegistry::setup()?;

        // Then we read the registry file into a HoistRegistry object.
        let registry_file = HoistRegistry::path()?;
        let mut file = std::fs::OpenOptions::new().read(true).open(registry_file)?;
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml)?;
        let registry: HoistRegistry = toml::from_str(&registry_toml)?;

        if !registry.binaries.iter().any(|b| binaries.contains(&b.name)) {
            anyhow::bail!("Failed to find binaries in hoist registry");
        }

        tracing::debug!("Hoisting {} binaries", std::env::current_dir()?.display());
        registry
            .binaries
            .iter()
            .filter(|b| binaries.contains(&b.name))
            .try_for_each(|b| b.copy_to_current_dir())?;

        Ok(())
    }
}

/// The type of shell
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShellType {
    /// Zsh
    Zsh,
    /// Bash
    Bash,
    /// Other
    Other,
}

/// Detect the type of shell a user is using.
pub fn detect_shell() -> Result<ShellType> {
    if let Ok(shell_path) = std::env::var("SHELL") {
        if shell_path.contains("zsh") {
            Ok(ShellType::Zsh)
        } else if shell_path.contains("bash") {
            Ok(ShellType::Bash)
        } else {
            Ok(ShellType::Other)
        }
    } else {
        // default to bash for now
        Ok(ShellType::Bash)
        // Err(anyhow::anyhow!("Unable to determine the user's shell."))
    }
}

/// Helper to get the path to the user's shell config file.
pub fn get_shell_config_file(shell_type: ShellType) -> Result<PathBuf> {
    let home_dir = std::env::var("HOME")?;
    match shell_type {
        ShellType::Zsh => Ok(PathBuf::from(format!("{}/.zshrc", home_dir))),
        _ => Ok(PathBuf::from(format!("{}/.bashrc", home_dir))),
        // ShellType::Other => Err(anyhow::anyhow!("Unsupported shell type.")),
    }
}

/// Initializes the tracing subscriber.
///
/// The verbosity level determines the maximum level of tracing.
/// - 0: ERROR
/// - 1: WARN
/// - 2: INFO
/// - 3: DEBUG
/// - 4+: TRACE
///
/// # Arguments
/// * `verbosity_level` - The verbosity level (0-4)
///
/// # Returns
/// * `Result<()>` - Ok if successful, Err otherwise.
pub fn init_tracing_subscriber(verbosity_level: u8) -> Result<()> {
    let subscriber = tracing_subscriber::fmt()
        .with_max_level(match verbosity_level {
            0 => Level::ERROR,
            1 => Level::WARN,
            2 => Level::INFO,
            3 => Level::DEBUG,
            _ => Level::TRACE,
        })
        .finish();
    tracing::subscriber::set_global_default(subscriber).map_err(|e| anyhow::anyhow!(e))
}

#[cfg(test)]
mod tests {
    use std::os::unix::prelude::OpenOptionsExt;

    use super::*;
    use serial_test::serial;

    #[test]
    #[serial]
    fn test_setup() {
        // Create a tempdir and set it as the current working directory
        let tempdir = tempfile::tempdir().unwrap();
        let test_tempdir = tempdir.path().join("test_setup");
        std::fs::create_dir(&test_tempdir).unwrap();
        std::env::set_current_dir(&test_tempdir).unwrap();
        let bash_file = test_tempdir.join(".bashrc");
        std::fs::File::create(&bash_file).unwrap();
        let zshrc = test_tempdir.join(".zshrc");
        std::fs::File::create(&zshrc).unwrap();
        let original_home = std::env::var_os("HOME").unwrap();
        std::env::set_var("HOME", test_tempdir);

        HoistRegistry::setup().unwrap();

        let hoist_dir = HoistRegistry::dir().unwrap();
        assert!(std::path::Path::new(&hoist_dir).exists());
        let registry_file = HoistRegistry::path().unwrap();
        assert!(std::path::Path::new(&registry_file).exists());
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .open(registry_file)
            .unwrap();
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml).unwrap();
        let registry: HoistRegistry = toml::from_str(&registry_toml).unwrap();
        assert_eq!(registry, HoistRegistry::default());
        let hook_file = HoistRegistry::hook_identifier().unwrap();
        assert!(std::path::Path::new(&hook_file).exists());
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .open(bash_file)
            .unwrap();
        let mut bash_file_contents = String::new();
        file.read_to_string(&mut bash_file_contents).unwrap();

        // If the bash file is empty, try to read the zshrc file.
        if bash_file_contents.is_empty() {
            let mut file = std::fs::OpenOptions::new().read(true).open(zshrc).unwrap();
            let mut zshrc_file_contents = String::new();
            file.read_to_string(&mut zshrc_file_contents).unwrap();
            assert_eq!(zshrc_file_contents, INSTALL_BASH_FUNCTION);
        } else {
            assert_eq!(bash_file_contents, INSTALL_BASH_FUNCTION);
        }

        // Restore the original HOME directory.
        std::env::set_var("HOME", original_home);
    }

    #[test]
    #[serial]
    fn test_install() {
        // Populate the temporary directory.
        let tempdir = tempfile::tempdir().unwrap();
        let test_tempdir = tempdir.path().join("test_install");
        std::fs::create_dir(&test_tempdir).unwrap();
        std::env::set_current_dir(&test_tempdir).unwrap();
        let bash_file = test_tempdir.join(".bashrc");
        std::fs::File::create(&bash_file).unwrap();
        let zshrc = test_tempdir.join(".zshrc");
        std::fs::File::create(&zshrc).unwrap();
        let target_dir = test_tempdir.join("target/release/");
        std::fs::create_dir_all(&target_dir).unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary1"))
            .unwrap();
        opts.sync_all().unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary2"))
            .unwrap();
        opts.sync_all().unwrap();

        let original_home = std::env::var_os("HOME").unwrap();
        std::env::set_var("HOME", test_tempdir);

        HoistRegistry::install(Vec::new()).unwrap();

        let registry_file = HoistRegistry::path().unwrap();
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .open(registry_file)
            .unwrap();
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml).unwrap();
        let registry: HoistRegistry = toml::from_str(&registry_toml).unwrap();
        assert_eq!(
            registry,
            HoistRegistry {
                binaries: HashSet::from([
                    HoistedBinary::new(
                        "binary1".to_string(),
                        target_dir.join("binary1").canonicalize().unwrap()
                    ),
                    HoistedBinary::new(
                        "binary2".to_string(),
                        target_dir.join("binary2").canonicalize().unwrap()
                    ),
                ])
            }
        );

        // Restore the original HOME directory.
        std::env::set_var("HOME", original_home);
    }

    #[test]
    #[serial]
    fn test_multiple_installs() {
        // Populate the temporary directory.
        let tempdir = tempfile::tempdir().unwrap();
        let test_tempdir = tempdir.path().join("test_multiple_installs");
        std::fs::create_dir(&test_tempdir).unwrap();
        std::env::set_current_dir(&test_tempdir).unwrap();
        let bash_file = test_tempdir.join(".bashrc");
        std::fs::File::create(&bash_file).unwrap();
        let zshrc = test_tempdir.join(".zshrc");
        std::fs::File::create(&zshrc).unwrap();
        let target_dir = test_tempdir.join("target/release/");
        std::fs::create_dir_all(&target_dir).unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary1"))
            .unwrap();
        opts.sync_all().unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary2"))
            .unwrap();
        opts.sync_all().unwrap();

        let original_home = std::env::var_os("HOME").unwrap();
        std::env::set_var("HOME", test_tempdir);

        HoistRegistry::install(Vec::new()).unwrap();
        HoistRegistry::install(Vec::new()).unwrap();
        HoistRegistry::install(Vec::new()).unwrap();
        HoistRegistry::install(Vec::new()).unwrap();

        let registry_file = HoistRegistry::path().unwrap();
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .open(registry_file)
            .unwrap();
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml).unwrap();
        let registry: HoistRegistry = toml::from_str(&registry_toml).unwrap();
        assert_eq!(
            registry,
            HoistRegistry {
                binaries: HashSet::from([
                    HoistedBinary::new(
                        "binary1".to_string(),
                        target_dir.join("binary1").canonicalize().unwrap()
                    ),
                    HoistedBinary::new(
                        "binary2".to_string(),
                        target_dir.join("binary2").canonicalize().unwrap()
                    ),
                ])
            }
        );

        // Restore the original HOME directory.
        std::env::set_var("HOME", original_home);
    }

    #[test]
    #[serial]
    fn test_hoist() {
        // Populate the temporary directory.
        let tempdir = tempfile::tempdir().unwrap();
        let test_tempdir = tempdir.path().join("test_hoist");
        std::fs::create_dir(&test_tempdir).unwrap();
        std::env::set_current_dir(&test_tempdir).unwrap();
        let bash_file = test_tempdir.join(".bashrc");
        std::fs::File::create(&bash_file).unwrap();
        let zshrc = test_tempdir.join(".zshrc");
        std::fs::File::create(&zshrc).unwrap();
        let target_dir = test_tempdir.join("target/release/");
        std::fs::create_dir_all(&target_dir).unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary1"))
            .unwrap();
        opts.sync_all().unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary2"))
            .unwrap();
        opts.sync_all().unwrap();

        // Install the binaries in the hoist registry.
        let original_home = std::env::var_os("HOME").unwrap();
        std::env::set_var("HOME", test_tempdir);
        HoistRegistry::install(Vec::new()).unwrap();

        // Hoist binary1 and not binary2 into the current directory.
        HoistRegistry::hoist(vec!["binary1".to_string()]).unwrap();
        HoistRegistry::hoist(vec!["binary1".to_string()]).unwrap();

        // Check that binary1 was hoisted.
        let binary1 = std::env::current_dir().unwrap().join("binary1");
        assert!(std::path::Path::new(&binary1).exists());
        let binary2 = std::env::current_dir().unwrap().join("binary2");
        assert!(!std::path::Path::new(&binary2).exists());

        // Restore the original HOME directory.
        std::env::set_var("HOME", original_home);
    }

    #[test]
    #[serial]
    fn test_nuke() {
        // Populate the temporary directory.
        let tempdir = tempfile::tempdir().unwrap();
        let test_tempdir = tempdir.path().join("test_nuke");
        std::fs::create_dir(&test_tempdir).unwrap();
        std::env::set_current_dir(&test_tempdir).unwrap();
        let bash_file = test_tempdir.join(".bashrc");
        std::fs::File::create(&bash_file).unwrap();
        let zshrc = test_tempdir.join(".zshrc");
        std::fs::File::create(&zshrc).unwrap();
        let target_dir = test_tempdir.join("target/release/");
        std::fs::create_dir_all(&target_dir).unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary1"))
            .unwrap();
        opts.sync_all().unwrap();
        let opts = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o755)
            .open(target_dir.join("binary2"))
            .unwrap();
        opts.sync_all().unwrap();

        // Install the binaries in the hoist registry.
        let original_home = std::env::var_os("HOME").unwrap();
        std::env::set_var("HOME", test_tempdir);
        HoistRegistry::install(Vec::new()).unwrap();

        // Nuke the hoist registry.
        HoistRegistry::nuke().unwrap();

        // Check that the registry is empty.
        let registry_file = HoistRegistry::path().unwrap();
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .open(registry_file)
            .unwrap();
        let mut registry_toml = String::new();
        file.read_to_string(&mut registry_toml).unwrap();
        let registry: HoistRegistry = toml::from_str(&registry_toml).unwrap();
        assert_eq!(registry, HoistRegistry::default());

        // Restore the original HOME directory.
        std::env::set_var("HOME", original_home);
    }
}