Skip to main content

Module bin

Module bin 

Source
Available on crate feature fs only.
Expand description

Binary path registry

This util provides a unified way of getting the path of a program to run, for example, let’s say you are making a build script for a project, and you want to find the compiler program gcc in the following manner:

  • Most users would use the project-provided toolchain at ./toolchain/compiler/gcc
  • If the user want to use the compiler on their system instead, we would first try to finding gcc in PATH, then fallback to the toolchain.
  • Or some user may want to specify a particular path on their system with the CC environment variable. We would try this first

With cu::bin, you can register this logic once, then just use cu::which whenever you need to get the resolved path:

use std::path::PathBuf;
use cu::pre::*;

fn find_gcc(use_system: bool) -> cu::Result<PathBuf> {
    let provided = cu::bin::location("./toolchain/compiler/gcc".as_ref());
    if use_system {
        cu::bin::find("gcc", [
            cu::bin::from_env("CC"),
            cu::bin::in_PATH(),
            provided
        ])
    } else {
        cu::bin::find("gcc", [
            cu::bin::from_env("CC"),
            provided
        ])
    }
}

// would use clap in a real program, here, just an example
let use_system = std::env::args().any(|x| x == "--use-system-compiler");
// register the path with the logic in find_gcc
let _: PathBuf = find_gcc(use_system).context("cannot find gcc")?;

// ... later in the progam
cu::which("gcc")?.command()
    //... configure the command

Enums§

Strategy
Strategy to find a binary

Functions§

clear
Clear the cached path for the binary name, if previously set
find
Find the executable using a series of strategies.
from_env
Strategy to read the environment variable and resolve that path as the program
get
Get a previously cached path.
in_PATH
Strategy to find the program in the PATH environment variable
location
Strategy to resolve the given path as path for the program
resolve
Resolve an executable at the location provided, or use a previously registered path.
set
Check and set bin name to the specified path. Return the absolute path that is set.
which
Find an executable in PATH, or use a previously registered path (also available as cu::which).