Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active February 25, 2024 14:46
Show Gist options
  • Save max-itzpapalotl/3442fbc1d4ab7f4fcb0e8dc2c420cd20 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/3442fbc1d4ab7f4fcb0e8dc2c420cd20 to your computer and use it in GitHub Desktop.
19. Environment and paths

19. Environment (command line args, env vars, paths, exit code)

In this video I give a guided tour over features dealing with the environment of a process.

Command line arguments and environment variables

use std::env;
use std::collections::HashMap;
use std::ffi::OsString;

fn main() {
    let a : Vec<String> = env::args().collect();
    println!("Args: {a:?}");
    let a : Vec<OsString> = env::args_os().collect();
    println!("Args: {a:?}");
    let m : HashMap<String, String> = env::vars().collect();
    println!("Env: {m:?}");
    let m : HashMap<OsString, OsString> = env::vars_os().collect();
    println!("Env: {m:?}");
}

The current working directory and paths

use std::env;

fn main() {
    let mut pwd = env::current_dir().unwrap();
    println!("Current working directory: {:?}", pwd);
    for f in pwd.iter() {
        println!("{:?}", f);
    }
    pwd.pop();
    println!("One up: {:?}", pwd);
    pwd.push("xyz");
    println!("And down again: {:?}", pwd);

    let key = "PATH";
    match env::var_os(key) {
        Some(paths) => {
            for path in env::split_paths(&paths) {
                println!("'{}'", path.display());
            }
        }
        None => println!("{key} is not defined in the environment."),
    }

    println!("Current executable: {:?}", env::current_exe());
    println!("Temporary directory: {:?}", env::temp_dir());
    println!("Path: {:?}", pwd.as_path().to_str().unwrap());
}

Creating and listing directories

use std::fs;

fn main() {
    let mut pwd = std::env::current_dir().unwrap();
    let mut builder = fs::DirBuilder::new();
    builder.recursive(true).create("a/b/c").unwrap();
    pwd.push("a");
    let dir = fs::read_dir(pwd).unwrap();
    for f in dir {
        let ff = f.unwrap();
        println!("{:?} {:?} {:?}", ff, ff.path(), ff.metadata());
    }
}

Exit codes

use std::env;

fn main() {
    let args : Vec<String> = env::args().collect();
    if args.len() > 1 && args[1] == "yes" {
        std::process::exit(0);
    } else {
        std::process::exit(17);
    }
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment