linguist-js
Version:
Analyse the programming languages used in a folder or from raw content, using the same rules that GitHub Linguist does.
32 lines (31 loc) • 1.11 kB
JavaScript
import { getFileExtension } from '../../program/fs/normalisedPath.js';
function isComplexExt(ext) {
return /\..+\./.test(ext);
}
export default function byExtension(file, langData) {
// Check if extension is a match
const extension = file.extension ?? getFileExtension(file.path);
if (!extension)
return [];
const possible = [];
for (const [lang, data] of Object.entries(langData)) {
const extMatches = data.extensions?.filter((ext) => file.path.toLowerCase().endsWith(ext.toLowerCase()));
if (extMatches?.length) {
for (const ext of extMatches) {
possible.push({ ext, lang });
}
}
}
// Apply more specific extension if available
const hasComplexExt = possible.some((entry) => isComplexExt(entry.ext));
return possible
.filter((entry) => {
const complex = isComplexExt(entry.ext);
if (hasComplexExt && !complex)
return false;
if (!hasComplexExt && complex)
return false;
return true;
})
.map((entry) => entry.lang);
}