Skip to main content

gosh_runner/cli/
apps.rs

1// [[file:../../runners.note::cb0a82ee][cb0a82ee]]
2use super::*;
3// cb0a82ee ends here
4
5// [[file:../../runners.note::8e91b7e1][8e91b7e1]]
6use gut::fs::ShellEscapeExt;
7
8#[derive(Debug, Clone, ValueEnum)]
9enum PathOp {
10    Append,
11    Prepend,
12    Remove,
13}
14
15impl PathOp {
16    fn apply(&self, path_key: &str, path_value: &str) -> String {
17        let path_key = path_key.trim();
18        let path_value = path_value.trim();
19
20        if let Some(paths) = std::env::var_os(path_key) {
21            let path_value_: std::path::PathBuf = path_value.into();
22            let mut paths = std::env::split_paths(&paths).collect_vec();
23            paths.retain(|path| path != &path_value_);
24
25            match self {
26                Self::Remove => {}
27                Self::Append => {
28                    paths.push(path_value_);
29                }
30                Self::Prepend => {
31                    paths.insert(0, path_value_);
32                }
33            }
34            match std::env::join_paths(paths) {
35                Ok(path_values) => path_values.to_string_lossy().into_owned(),
36                Err(err) => {
37                    eprintln!("found invalid char in path: {err:?}");
38                    format!("{}", path_value)
39                }
40            }
41        } else {
42            format!("{path_value}")
43        }
44    }
45}
46
47#[test]
48fn test_environ() {
49    let value = PathOp::Append.apply("PATH", "/usr/bin");
50    assert!(value.ends_with("/usr/bin"));
51
52    let value = PathOp::Prepend.apply("PATH", "/usr/bin");
53    assert!(value.starts_with("/usr/bin"));
54
55    let value = PathOp::Remove.apply("PATH", "/usr/bin");
56    let usr_bin: &Path = "/usr/bin".as_ref();
57    assert!(!std::env::split_paths(&value).any(|path| path == usr_bin));
58}
59
60pub fn prepend_path(path_key: &str, new_path: &str) -> String {
61    let path_value = PathOp::Prepend.apply(path_key, new_path);
62    format!("export {path_key}={}", path_value.as_str().shell_escape())
63}
64
65pub fn append_path(path_key: &str, new_path: &str) -> String {
66    let path_value = PathOp::Append.apply(path_key, new_path);
67    format!("export {path_key}={}", path_value.as_str().shell_escape())
68}
69
70pub fn remove_path(path_key: &str, new_path: &str) -> String {
71    let path_value = PathOp::Remove.apply(path_key, new_path);
72    format!("export {path_key}={}", path_value.as_str().shell_escape())
73}
74// 8e91b7e1 ends here
75
76// [[file:../../runners.note::b185bee5][b185bee5]]
77fn show_available_modules(apps_root_dir: &Path) -> Result<()> {
78    for entry in apps_root_dir.read_dir()? {
79        let path = entry?.path();
80        if path.is_dir() && path.join(".envrc").is_file() {
81            eprintln!("{:^10} => {path:?}", path.file_name().unwrap().to_string_lossy());
82        }
83    }
84    Ok(())
85}
86
87fn set_module_env_vars(apps_root_dir: &Path, module_name: &str, remove: bool) -> Result<String> {
88    let mod_root = apps_root_dir.join(module_name);
89    let mod_bin = mod_root.join("bin");
90
91    let mut lines = String::new();
92
93    // PATH
94    if mod_bin.is_dir() {
95        let line = path_env_cmd(&mod_bin, "PATH", remove);
96        lines.push_str(&format!("{line};"));
97    }
98
99    // LD_LIBRARY_PATH
100    for lib in ["lib", "lib64"] {
101        let mod_lib = mod_root.join(lib);
102        if mod_lib.is_dir() {
103            for path in ["LIBRARY_PATH", "LD_LIBRARY_PATH", "LD_RUN_PATH"] {
104                let line = path_env_cmd(&mod_lib, path, remove);
105                lines.push_str(&format!("{line};"));
106            }
107        }
108        // PKG_CONFIG_PATH
109        let root = mod_lib.join("pkgconfig");
110        if root.is_dir() {
111            let line = path_env_cmd(&root, "PKG_CONFIG_PATH", remove);
112            lines.push_str(&format!("{line};"));
113        }
114    }
115
116    // CPATH
117    let include = mod_root.join("include");
118    if include.is_dir() {
119        let line = path_env_cmd(&include, "CPATH", remove);
120        lines.push_str(&format!("{line};"));
121    }
122
123    // source .envrc
124    let mod_envrc = mod_root.join(".envrc");
125    if mod_envrc.is_file() {
126        info!("load .envrc {mod_envrc:?}");
127        let dir = mod_root.shell_escape_lossy();
128        // source .envrc in module's root dir
129        lines.push_str(&format!("pushd {dir};"));
130        lines.push_str("source .envrc;");
131        lines.push_str("popd;")
132    }
133
134    Ok(lines)
135}
136
137fn path_env_cmd(root: &Path, path: &str, remove: bool) -> String {
138    if remove {
139        remove_path(path, &format!("{}", root.display()))
140    } else {
141        prepend_path(path, &format!("{}", root.display()))
142    }
143}
144// b185bee5 ends here
145
146// [[file:../../runners.note::54d72d8a][54d72d8a]]
147use gut::cli::*;
148
149#[derive(Debug, Clone, Subcommand)]
150enum AppsOp {
151    /// Load module environment variables
152    Load {
153        /// The requested module to be loaded
154        module: String,
155    },
156    /// Unload module environment variables
157    Unload {
158        /// The requested module to be unloaded
159        module: String,
160    },
161    /// Show available modules
162    Avail,
163}
164
165/// A shell environment manager as a poor-man's modulefiles (for bash only now)
166#[derive(Parser)]
167#[clap(disable_help_subcommand=true, disable_help_flag=true)]
168pub struct Apps {
169    #[clap(flatten)]
170    verbose: gut::cli::Verbosity,
171
172    #[clap(subcommand)]
173    action: AppsOp,
174}
175
176impl Apps {
177    pub fn enter_main() -> Result<()> {
178        let args = Self::parse();
179        args.verbose.setup_logger();
180
181        let apps_root_dir = std::env::var("BBM_APPS_DIR").unwrap_or("/share/apps".into());
182        match args.action {
183            AppsOp::Load { module } => {
184                let bash_script = set_module_env_vars(apps_root_dir.as_ref(), &module, false)?;
185                debug!("Load env vars in bash:\n{bash_script}");
186                println!("{bash_script}");
187            }
188            AppsOp::Unload { module } => {
189                let bash_script = set_module_env_vars(apps_root_dir.as_ref(), &module, true)?;
190                debug!("Unload env vars in bash:\n{bash_script}");
191                println!("{bash_script}");
192            }
193            AppsOp::Avail => {
194                show_available_modules(apps_root_dir.as_ref())?;
195            }
196        }
197
198        Ok(())
199    }
200}
201// 54d72d8a ends here