1use std::path::Path;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct ShellConfig {
10 pub shell: String,
11 pub args: Vec<String>,
12}
13
14impl ShellConfig {
15 fn bash(shell: &str) -> Self {
16 ShellConfig {
17 shell: shell.to_string(),
18 args: vec!["-c".into()],
19 }
20 }
21
22 pub fn argv(&self, command: &str) -> Vec<String> {
23 let mut argv = vec![self.shell.clone()];
24 argv.extend(self.args.iter().cloned());
25 argv.push(command.to_string());
26 argv
27 }
28}
29
30pub fn shell_config(
32 custom: Option<&str>,
33 exists: &dyn Fn(&Path) -> bool,
34 which: &dyn Fn(&str) -> Option<String>,
35) -> Result<ShellConfig, String> {
36 if let Some(custom) = custom.filter(|c| !c.is_empty()) {
37 if exists(Path::new(custom)) {
38 return Ok(ShellConfig::bash(custom));
39 }
40 return Err(format!("Custom shell path not found: {custom}"));
41 }
42 if exists(Path::new("/bin/bash")) {
43 return Ok(ShellConfig::bash("/bin/bash"));
44 }
45 if let Some(bash) = which("bash") {
46 return Ok(ShellConfig::bash(&bash));
47 }
48 Ok(ShellConfig {
49 shell: "sh".into(),
50 args: vec!["-c".into()],
51 })
52}
53
54pub fn system_shell_config(custom: Option<&str>) -> Result<ShellConfig, String> {
56 let path = std::env::var("PATH").ok();
57 shell_config_on_path(custom, path.as_deref())
58}
59
60pub fn shell_config_on_path(custom: Option<&str>, path: Option<&str>) -> Result<ShellConfig, String> {
62 let which = |name: &str| {
63 std::env::split_paths(path?)
64 .map(|dir| dir.join(name))
65 .find(|candidate| candidate.is_file())
66 .map(|p| p.to_string_lossy().into_owned())
67 };
68 shell_config(custom, &|p: &Path| p.exists(), &which)
69}
70
71pub fn prefixed_command(prefix: Option<&str>, command: &str) -> String {
74 match prefix.filter(|p| !p.is_empty()) {
75 Some(prefix) => format!("{prefix}\n{command}"),
76 None => command.to_string(),
77 }
78}