summaryrefslogtreecommitdiffstats
path: root/src/poem/anthology/cd.rs
blob: 5b393593822d13344194654e481d5c3dd680f031 (plain)
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
use crate::poem::Verse;
use std::env;

/// cd
///
/// The builtin `cd` command. Used to change directories. This must be
/// implemented by the shell, since the `pwd` is context sensitive within a
/// process. If no arguments are given, `cd` will take the user back to their
/// home directory (i.e. `~`).
///
/// # Shell Example
/// ```sh
/// cd ~/.config # Change into /home/<user>/.config
/// ```
pub fn incant(verse: &Verse) -> i32 {
    let path = match verse.clause() {
        Some(path) => path[0].to_string(),
        None => match env::var("HOME") {
            Ok(val) => val,
            Err(_) => {
                eprintln!("cd: unknown home, staying in pwd");
                return 1;
            }
        },
    };

    match std::env::set_current_dir(&path) {
        Ok(_) => 0,
        Err(e) => {
            eprintln!(
                "cd: unable to change into {}: {}",
                path,
                e.to_string().to_lowercase()
            );
            1
        }
    }
}