Spaces:
Sleeping
Sleeping
File size: 1,355 Bytes
161cb23 | 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 | const SNIFF_RULES = [
{
extension: "go",
linePrefixes: ["package ", "func "],
fragments: [" := "],
},
{
extension: "rs",
linePrefixes: ["fn ", "pub fn ", "let mut ", "impl ", "use std::"],
fragments: ["-> Option<", "-> Result<"],
},
{
extension: "ts",
linePrefixes: ["interface ", "export interface ", "type ", "export type "],
fragments: [": string", ": number", ": boolean"],
},
{
extension: "js",
linePrefixes: ["const ", "let ", "function ", "export function ", "export default "],
fragments: [" => "],
},
{
extension: "py",
linePrefixes: ["def ", "class ", "import ", "from ", "elif "],
fragments: ["self."],
},
];
function matchesRule(rule, trimmedLines, text) {
const startsRule = (line) => rule.linePrefixes.some((prefix) => line.startsWith(prefix));
return trimmedLines.some(startsRule) || rule.fragments.some((fragment) => text.includes(fragment));
}
export function extensionOf(filename) {
const dotIndex = filename.lastIndexOf(".");
return dotIndex <= 0 ? "" : filename.slice(dotIndex + 1).toLowerCase();
}
export function sniffExtension(text) {
const trimmedLines = text.split("\n").map((line) => line.trimStart());
const rule = SNIFF_RULES.find((candidate) => matchesRule(candidate, trimmedLines, text));
return rule ? rule.extension : "py";
}
|