summaryrefslogtreecommitdiff
path: root/src/util/language.rs
blob: 8819a1ee32e991169a35cdd7bb8eaedb7820cb23 (plain) (blame)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use std::path::Path;

pub fn detect_language(filename: &Path, contents: &str) -> &'static str {
    detect_from_extension(filename)
        .or_else(|| detect_from_shebang(contents))
        .unwrap_or("")
}

fn detect_from_extension(filename: &Path) -> Option<&'static str> {
    let ext = filename
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase());
    let ext_str = ext.as_deref();
    match ext_str {
        Some("rs") => Some("rust"),
        Some("py") => Some("python"),
        Some("json") => Some("json"),
        _ => None,
    }
}

fn detect_from_shebang(contents: &str) -> Option<&'static str> {
    if let Some(first_line) = contents.lines().next()
        && first_line.starts_with("#!")
    {
        if first_line.contains("python") {
            return Some("python");
        }
        if first_line.contains("bash") {
            return Some("bash");
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::detect_language;

    #[test]
    fn non_shebang_line_does_not_trigger_detection() {
        let contents = "this mentions bash but is not a shebang";
        assert_eq!(detect_language(Path::new("file"), contents), "");
    }

    #[test]
    fn detects_python_from_shebang() {
        let contents = "#!/usr/bin/python3\nprint('hi')";
        assert_eq!(detect_language(Path::new("file"), contents), "python");
    }
}