Skip to main content

codeint_lang_shell/
dialect.rs

1use std::fmt;
2
3use codeint_model::path_file_name;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6pub enum ShellDialect {
7    PosixSh,
8    Bash,
9    Zsh,
10}
11
12impl fmt::Display for ShellDialect {
13    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
14        formatter.write_str(self.as_str())
15    }
16}
17
18impl ShellDialect {
19    pub const fn as_str(self) -> &'static str {
20        match self {
21            Self::PosixSh => "sh",
22            Self::Bash => "bash",
23            Self::Zsh => "zsh",
24        }
25    }
26}
27
28pub fn detect_dialect(path: &str, source: &str) -> ShellDialect {
29    let trimmed_bom = source.strip_prefix('\u{feff}').unwrap_or(source);
30    if let Some(first_line) = trimmed_bom.lines().next()
31        && let Some(dialect) = parse_shebang_dialect(first_line)
32    {
33        return dialect;
34    }
35    dialect_from_extension(path)
36}
37
38pub(crate) fn parse_shebang_flags(source: &str) -> Vec<String> {
39    let trimmed_bom = source.strip_prefix('\u{feff}').unwrap_or(source);
40    let Some(first_line) = trimmed_bom.lines().next() else {
41        return Vec::new();
42    };
43    let Some(rest) = first_line.strip_prefix("#!") else {
44        return Vec::new();
45    };
46    let mut parts = rest.trim().split_ascii_whitespace();
47    let Some(first) = parts.next() else {
48        return Vec::new();
49    };
50    if !is_launcher(path_file_name(first)) {
51        return parts.map(str::to_owned).collect();
52    }
53    extract_env_shell_flags(parts)
54}
55
56fn extract_env_shell_flags<'a>(parts: impl Iterator<Item = &'a str>) -> Vec<String> {
57    let mut found_shell = false;
58    let mut flags = Vec::new();
59    for part in parts {
60        if found_shell {
61            flags.push(part.to_owned());
62            continue;
63        }
64        if part.starts_with('-') || part.contains('=') {
65            continue;
66        }
67        if dialect_from_interpreter(path_file_name(part)).is_some() {
68            found_shell = true;
69        }
70    }
71    flags
72}
73
74fn parse_shebang_dialect(first_line: &str) -> Option<ShellDialect> {
75    let rest = first_line.strip_prefix("#!")?.trim();
76    let mut parts = rest.split_ascii_whitespace();
77    let first = parts.next()?;
78    let cmd = path_file_name(first);
79    if !is_launcher(cmd) {
80        return dialect_from_interpreter(cmd);
81    }
82    for part in parts {
83        if part.starts_with('-') || part.contains('=') {
84            continue;
85        }
86        return dialect_from_interpreter(path_file_name(part));
87    }
88    None
89}
90
91fn is_launcher(name: &str) -> bool {
92    matches!(name, "env" | "busybox")
93}
94
95fn dialect_from_interpreter(name: &str) -> Option<ShellDialect> {
96    if name == "bash" || is_versioned_name(name, "bash") {
97        Some(ShellDialect::Bash)
98    } else if name == "zsh" || is_versioned_name(name, "zsh") {
99        Some(ShellDialect::Zsh)
100    } else if matches!(name, "sh" | "dash" | "ash" | "posix-sh") {
101        Some(ShellDialect::PosixSh)
102    } else {
103        None
104    }
105}
106
107fn is_versioned_name(name: &str, prefix: &str) -> bool {
108    name.strip_prefix(prefix).is_some_and(|rest| {
109        !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit() || b == b'.')
110    })
111}
112
113fn dialect_from_extension(path: &str) -> ShellDialect {
114    match path_file_name(path).rsplit_once('.') {
115        Some((_, "bash")) => ShellDialect::Bash,
116        Some((_, "zsh")) => ShellDialect::Zsh,
117        _ => ShellDialect::PosixSh,
118    }
119}