linguist-js
Version:
Analyse languages used in a folder. Powered by GitHub Linguist, although it doesn't need to be installed.
38 lines (37 loc) • 1.74 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseGeneratedDataFile = parseGeneratedDataFile;
exports.default = loadFile;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const node_cache_1 = __importDefault(require("node-cache"));
const cache = new node_cache_1.default({});
async function loadWebFile(file) {
// Return cache if it exists
const cachedContent = cache.get(file);
if (cachedContent)
return cachedContent;
// Otherwise cache the request
const dataUrl = (file) => `https://raw.githubusercontent.com/github/linguist/HEAD/lib/linguist/${file}`;
// Load file content, falling back to the local file if the request fails
const fileContent = await (0, cross_fetch_1.default)(dataUrl(file)).then(data => data.text()).catch(async () => await loadLocalFile(file));
cache.set(file, fileContent);
return fileContent;
}
async function loadLocalFile(file) {
const filePath = path_1.default.resolve(__dirname, '../../ext', file);
return fs_1.default.promises.readFile(filePath).then(buffer => buffer.toString());
}
/** Nukes unused `generated.rb` file content. */
function parseGeneratedDataFile(fileContent) {
var _a;
return [...(_a = fileContent.match(/(?<=name\.match\(\/).+?(?=(?<!\\)\/)/gm)) !== null && _a !== void 0 ? _a : []];
}
/** Load a data file from github-linguist. */
function loadFile(file, offline = false) {
return offline ? loadLocalFile(file) : loadWebFile(file);
}