summaryrefslogtreecommitdiff
path: root/src/util/language.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/util/language.rs')
-rw-r--r--src/util/language.rs33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/util/language.rs b/src/util/language.rs
new file mode 100644
index 0000000..fae7bf9
--- /dev/null
+++ b/src/util/language.rs
@@ -0,0 +1,33 @@
+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() {
+ if first_line.contains("python") {
+ return Some("python");
+ }
+ if first_line.contains("bash") {
+ return Some("bash");
+ }
+ }
+ None
+}