use std::path::Path;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Language {
Rust,
Python,
JavaScript,
C,
Go,
}
impl Language {
pub fn from_path(path: &str) -> Option<Self> {
let extension = Path::new(path).extension()?.to_str()?;
match extension.to_ascii_lowercase().as_str() {
"rs" => Some(Self::Rust),
"py" => Some(Self::Python),
"js" | "jsx" | "ts" | "tsx" | "mjs" => Some(Self::JavaScript),
"c" | "h" | "cc" | "cpp" | "hpp" => Some(Self::C),
"go" => Some(Self::Go),
_ => None,
}
}
fn snippets(self) -> &'static [(&'static str, &'static str)] {
match self {
Self::Rust => &[
("fn", "fn $0() {\n \n}"),
("main", "fn main() {\n $0\n}"),
("struct", "struct $0 {\n \n}"),
("enum", "enum $0 {\n \n}"),
("impl", "impl $0 {\n \n}"),
("match", "match $0 {\n _ => {}\n}"),
("if", "if $0 {\n \n}"),
("for", "for item in $0 {\n \n}"),
("while", "while $0 {\n \n}"),
("loop", "loop {\n $0\n}"),
("test", "#[test]\nfn $0() {\n \n}"),
(
"tests",
"#[cfg(test)]\nmod tests {\n use super::*;\n\n $0\n}",
),
("pl", "println!(\"$0\");"),
],
Self::Python => &[
("def", "def $0():\n pass"),
("class", "class $0:\n pass"),
("if", "if $0:\n pass"),
("for", "for item in $0:\n pass"),
("while", "while $0:\n pass"),
("main", "if __name__ == \"__main__\":\n $0"),
("try", "try:\n $0\nexcept Exception as error:\n raise"),
],
Self::JavaScript => &[
("fn", "function $0() {\n \n}"),
("afn", "const $0 = () => {\n \n};"),
("if", "if ($0) {\n \n}"),
("for", "for (const item of $0) {\n \n}"),
("while", "while ($0) {\n \n}"),
("log", "console.log($0);"),
],
Self::C => &[
("main", "int main(void) {\n $0\n return 0;\n}"),
("if", "if ($0) {\n \n}"),
("for", "for (int i = 0; i < $0; i++) {\n \n}"),
("while", "while ($0) {\n \n}"),
("inc", "#include <$0>"),
],
Self::Go => &[
("fn", "func $0() {\n \n}"),
("main", "func main() {\n $0\n}"),
("if", "if $0 {\n \n}"),
("for", "for $0 {\n \n}"),
("err", "if err != nil {\n return err$0\n}"),
],
}
}
pub fn snippet(self, trigger: &str) -> Option<&'static str> {
self.snippets()
.iter()
.find(|(name, _)| *name == trigger)
.map(|(_, body)| *body)
}
}