linguist-js 2.6.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,389 +1,418 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- const fs_1 = __importDefault(require("fs"));
6
- const path_1 = __importDefault(require("path"));
7
- const js_yaml_1 = __importDefault(require("js-yaml"));
8
- const ignore_1 = __importDefault(require("ignore"));
9
- const common_path_prefix_1 = __importDefault(require("common-path-prefix"));
10
- const binary_extensions_1 = __importDefault(require("binary-extensions"));
11
- const isbinaryfile_1 = require("isbinaryfile");
12
- const walk_tree_1 = __importDefault(require("./helpers/walk-tree"));
13
- const load_data_1 = __importDefault(require("./helpers/load-data"));
14
- const read_file_1 = __importDefault(require("./helpers/read-file"));
15
- const convert_pcre_1 = __importDefault(require("./helpers/convert-pcre"));
16
- async function analyse(input, opts = {}) {
17
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
18
- var _t, _u;
19
- const useRawContent = opts.fileContent !== undefined;
20
- input = [input !== null && input !== void 0 ? input : []].flat();
21
- opts.fileContent = [(_a = opts.fileContent) !== null && _a !== void 0 ? _a : []].flat();
22
- // Load data from github-linguist web repo
23
- const langData = await (0, load_data_1.default)('languages.yml', opts.offline).then(js_yaml_1.default.load);
24
- const vendorData = await (0, load_data_1.default)('vendor.yml', opts.offline).then(js_yaml_1.default.load);
25
- const docData = await (0, load_data_1.default)('documentation.yml', opts.offline).then(js_yaml_1.default.load);
26
- const heuristicsData = await (0, load_data_1.default)('heuristics.yml', opts.offline).then(js_yaml_1.default.load);
27
- const generatedData = await (0, load_data_1.default)('generated.rb', opts.offline).then(text => { var _a; return (_a = text.match(/(?<=name\.match\(\/).+?(?=(?<!\\)\/)/gm)) !== null && _a !== void 0 ? _a : []; });
28
- const vendorPaths = [...vendorData, ...docData, ...generatedData];
29
- // Setup main variables
30
- const fileAssociations = {};
31
- const extensions = {};
32
- const overrides = {};
33
- const results = {
34
- files: { count: 0, bytes: 0, results: {}, alternatives: {} },
35
- languages: { count: 0, bytes: 0, results: {} },
36
- unknown: { count: 0, bytes: 0, extensions: {}, filenames: {} },
37
- };
38
- // Prepare list of ignored files
39
- const gitignores = (0, ignore_1.default)();
40
- const regexIgnores = [];
41
- gitignores.add('/.git');
42
- if (!opts.keepVendored)
43
- regexIgnores.push(...vendorPaths.map(path => RegExp(path, 'i')));
44
- if (opts.ignoredFiles)
45
- gitignores.add(opts.ignoredFiles);
46
- // Set a common root path so that vendor paths do not incorrectly match parent folders
47
- const resolvedInput = input.map(path => path_1.default.resolve(path).replace(/\\/g, '/'));
48
- const commonRoot = (input.length > 1 ? (0, common_path_prefix_1.default)(resolvedInput) : resolvedInput[0]).replace(/\/?$/, '');
49
- const relPath = (file) => path_1.default.relative(commonRoot, file).replace(/\\/g, '/');
50
- const unRelPath = (file) => path_1.default.resolve(commonRoot, file).replace(/\\/g, '/');
51
- // Load file paths and folders
52
- let files, folders;
53
- if (useRawContent) {
54
- // Uses raw file content
55
- files = input;
56
- folders = [''];
57
- }
58
- else {
59
- // Uses directory on disc
60
- const data = (0, walk_tree_1.default)(true, commonRoot, input, gitignores, regexIgnores);
61
- files = data.files;
62
- folders = data.folders;
63
- }
64
- // Apply aliases
65
- opts = {
66
- checkIgnored: !opts.quick,
67
- checkAttributes: !opts.quick,
68
- checkHeuristics: !opts.quick,
69
- checkShebang: !opts.quick,
70
- checkModeline: !opts.quick,
71
- ...opts
72
- };
73
- // Ignore specific languages
74
- for (const lang of (_b = opts.ignoredLanguages) !== null && _b !== void 0 ? _b : []) {
75
- for (const key in langData) {
76
- if (lang.toLowerCase() === key.toLowerCase()) {
77
- delete langData[key];
78
- break;
79
- }
80
- }
81
- }
82
- // Load gitignores and gitattributes
83
- const customBinary = (0, ignore_1.default)();
84
- const customText = (0, ignore_1.default)();
85
- if (!useRawContent && opts.checkAttributes) {
86
- for (const folder of folders) {
87
- // Skip if folder is marked in gitattributes
88
- if (relPath(folder) && gitignores.ignores(relPath(folder))) {
89
- continue;
90
- }
91
- // Parse gitignores
92
- const ignoresFile = path_1.default.join(folder, '.gitignore');
93
- if (opts.checkIgnored && fs_1.default.existsSync(ignoresFile)) {
94
- const ignoresData = await (0, read_file_1.default)(ignoresFile);
95
- gitignores.add(ignoresData);
96
- }
97
- // Parse gitattributes
98
- const attributesFile = path_1.default.join(folder, '.gitattributes');
99
- if (opts.checkAttributes && fs_1.default.existsSync(attributesFile)) {
100
- const attributesData = await (0, read_file_1.default)(attributesFile);
101
- // Explicit text/binary associations
102
- const contentTypeMatches = attributesData.matchAll(/^(\S+).*?(-?binary|-?text)(?!=auto)/gm);
103
- for (const [_line, path, type] of contentTypeMatches) {
104
- if (['text', '-binary'].includes(type)) {
105
- customText.add(path);
106
- }
107
- if (['-text', 'binary'].includes(type)) {
108
- customBinary.add(path);
109
- }
110
- }
111
- // Custom vendor options
112
- const vendorMatches = attributesData.matchAll(/^(\S+).*[^-]linguist-(vendored|generated|documentation)(?!=false)/gm);
113
- for (const [_line, path] of vendorMatches) {
114
- gitignores.add(path);
115
- }
116
- // Custom file associations
117
- const customLangMatches = attributesData.matchAll(/^(\S+).*[^-]linguist-language=(\S+)/gm);
118
- for (let [_line, path, forcedLang] of customLangMatches) {
119
- // If specified language is an alias, associate it with its full name
120
- if (!langData[forcedLang]) {
121
- const overrideLang = Object.entries(langData).find(entry => { var _a; return (_a = entry[1].aliases) === null || _a === void 0 ? void 0 : _a.includes(forcedLang.toLowerCase()); });
122
- if (overrideLang) {
123
- forcedLang = overrideLang[0];
124
- }
125
- }
126
- const fullPath = path_1.default.join(relPath(folder), path);
127
- overrides[fullPath] = forcedLang;
128
- }
129
- }
130
- }
131
- }
132
- // Check vendored files
133
- if (!opts.keepVendored) {
134
- // Filter out any files that match a vendor file path
135
- if (useRawContent) {
136
- files = gitignores.filter(files);
137
- files = files.filter(file => !regexIgnores.find(match => match.test(file)));
138
- }
139
- else {
140
- files = gitignores.filter(files.map(relPath)).map(unRelPath);
141
- }
142
- }
143
- // Load all files and parse languages
144
- const addResult = (file, result) => {
145
- if (!fileAssociations[file]) {
146
- fileAssociations[file] = [];
147
- extensions[file] = '';
148
- }
149
- // Set parent to result group if it is present
150
- // Is nullish if either `opts.childLanguages` is set or if there is no group
151
- const finalResult = !opts.childLanguages && result && langData[result].group || result;
152
- if (!fileAssociations[file].includes(finalResult))
153
- fileAssociations[file].push(finalResult);
154
- extensions[file] = path_1.default.extname(file).toLowerCase();
155
- };
156
- const overridesArray = Object.entries(overrides);
157
- // List all languages that could be associated with a given file
158
- const definiteness = {};
159
- const fromShebang = {};
160
- for (const file of files) {
161
- let firstLine;
162
- if (useRawContent) {
163
- firstLine = (_e = (_d = (_c = opts.fileContent) === null || _c === void 0 ? void 0 : _c[files.indexOf(file)]) === null || _d === void 0 ? void 0 : _d.split('\n')[0]) !== null && _e !== void 0 ? _e : null;
164
- }
165
- else if (fs_1.default.existsSync(file) && !fs_1.default.lstatSync(file).isDirectory()) {
166
- firstLine = await (0, read_file_1.default)(file, true).catch(() => null);
167
- }
168
- else
169
- continue;
170
- // Skip if file is unreadable
171
- if (firstLine === null)
172
- continue;
173
- // Check first line for explicit classification
174
- const hasShebang = opts.checkShebang && /^#!/.test(firstLine);
175
- const hasModeline = opts.checkModeline && /-\*-|(syntax|filetype|ft)\s*=/.test(firstLine);
176
- if (!opts.quick && (hasShebang || hasModeline)) {
177
- const matches = [];
178
- for (const [lang, data] of Object.entries(langData)) {
179
- const langMatcher = (lang) => `\\b${lang.toLowerCase().replace(/\W/g, '\\$&')}(?![\\w#+*]|-\*-)`;
180
- // Check for interpreter match
181
- if (opts.checkShebang && hasShebang) {
182
- const matchesInterpretor = (_f = data.interpreters) === null || _f === void 0 ? void 0 : _f.some(interpreter => firstLine.match(`\\b${interpreter}\\b`));
183
- if (matchesInterpretor)
184
- matches.push(lang);
185
- }
186
- // Check modeline declaration
187
- if (opts.checkModeline && hasModeline) {
188
- const modelineText = firstLine.toLowerCase().replace(/^.*-\*-(.+)-\*-.*$/, '$1');
189
- const matchesLang = modelineText.match(langMatcher(lang));
190
- const matchesAlias = (_g = data.aliases) === null || _g === void 0 ? void 0 : _g.some(lang => modelineText.match(langMatcher(lang)));
191
- if (matchesLang || matchesAlias)
192
- matches.push(lang);
193
- }
194
- }
195
- // Add identified language(s)
196
- if (matches.length) {
197
- for (const match of matches)
198
- addResult(file, match);
199
- if (matches.length === 1)
200
- definiteness[file] = true;
201
- fromShebang[file] = true;
202
- continue;
203
- }
204
- }
205
- // Check override for manual language classification
206
- if (!useRawContent && !opts.quick && opts.checkAttributes) {
207
- const isOverridden = (path) => (0, ignore_1.default)().add(path).ignores(relPath(file));
208
- const match = overridesArray.find(item => isOverridden(item[0]));
209
- if (match) {
210
- const forcedLang = match[1];
211
- addResult(file, forcedLang);
212
- definiteness[file] = true;
213
- continue;
214
- }
215
- }
216
- // Search each language
217
- let skipExts = false;
218
- // Check if filename is a match
219
- for (const lang in langData) {
220
- const matchesName = (_h = langData[lang].filenames) === null || _h === void 0 ? void 0 : _h.some(name => path_1.default.basename(file.toLowerCase()) === name.toLowerCase());
221
- if (matchesName) {
222
- addResult(file, lang);
223
- skipExts = true;
224
- }
225
- }
226
- // Check if extension is a match
227
- const possibleExts = [];
228
- if (!skipExts)
229
- for (const lang in langData) {
230
- const extMatches = (_j = langData[lang].extensions) === null || _j === void 0 ? void 0 : _j.filter(ext => file.toLowerCase().endsWith(ext.toLowerCase()));
231
- if (extMatches === null || extMatches === void 0 ? void 0 : extMatches.length) {
232
- for (const ext of extMatches)
233
- possibleExts.push({ ext, lang });
234
- }
235
- }
236
- // Apply more specific extension if available
237
- const isComplexExt = (ext) => /\..+\./.test(ext);
238
- const hasComplexExt = possibleExts.some(data => isComplexExt(data.ext));
239
- for (const { ext, lang } of possibleExts) {
240
- if (hasComplexExt && !isComplexExt(ext))
241
- continue;
242
- if (!hasComplexExt && isComplexExt(ext))
243
- continue;
244
- addResult(file, lang);
245
- }
246
- // Fallback to null if no language matches
247
- if (!fileAssociations[file]) {
248
- addResult(file, null);
249
- }
250
- }
251
- // Narrow down file associations to the best fit
252
- for (const file in fileAssociations) {
253
- // Skip if file has explicit association
254
- if (definiteness[file]) {
255
- results.files.results[file] = fileAssociations[file][0];
256
- continue;
257
- }
258
- // Skip binary files
259
- if (!useRawContent && !opts.keepBinary) {
260
- const isCustomText = customText.ignores(relPath(file));
261
- const isCustomBinary = customBinary.ignores(relPath(file));
262
- const isBinaryExt = binary_extensions_1.default.some(ext => file.endsWith('.' + ext));
263
- if (!isCustomText && (isCustomBinary || isBinaryExt || await (0, isbinaryfile_1.isBinaryFile)(file))) {
264
- continue;
265
- }
266
- }
267
- // Parse heuristics if applicable
268
- if (opts.checkHeuristics)
269
- for (const heuristics of heuristicsData.disambiguations) {
270
- // Make sure the extension matches the current file
271
- if (!fromShebang[file] && !heuristics.extensions.includes(extensions[file]))
272
- continue;
273
- // Load heuristic rules
274
- for (const heuristic of heuristics.rules) {
275
- // Make sure the language is not an array
276
- if (Array.isArray(heuristic.language)) {
277
- heuristic.language = heuristic.language[0];
278
- }
279
- // Make sure the results includes this language
280
- const languageGroup = (_k = langData[heuristic.language]) === null || _k === void 0 ? void 0 : _k.group;
281
- const matchesLang = fileAssociations[file].includes(heuristic.language);
282
- const matchesParent = languageGroup && fileAssociations[file].includes(languageGroup);
283
- if (!matchesLang && !matchesParent)
284
- continue;
285
- // Normalise heuristic data
286
- const patterns = [];
287
- const normalise = (contents) => patterns.push(...[contents].flat());
288
- if (heuristic.pattern)
289
- normalise(heuristic.pattern);
290
- if (heuristic.named_pattern)
291
- normalise(heuristicsData.named_patterns[heuristic.named_pattern]);
292
- if (heuristic.and) {
293
- for (const data of heuristic.and) {
294
- if (data.pattern)
295
- normalise(data.pattern);
296
- if (data.named_pattern)
297
- normalise(heuristicsData.named_patterns[data.named_pattern]);
298
- }
299
- }
300
- // Check file contents and apply heuristic patterns
301
- const fileContent = ((_l = opts.fileContent) === null || _l === void 0 ? void 0 : _l.length) ? opts.fileContent[files.indexOf(file)] : await (0, read_file_1.default)(file).catch(() => null);
302
- // Skip if file read errors
303
- if (fileContent === null)
304
- continue;
305
- // Apply heuristics
306
- if (!patterns.length || patterns.some(pattern => (0, convert_pcre_1.default)(pattern).test(fileContent))) {
307
- results.files.results[file] = heuristic.language;
308
- break;
309
- }
310
- }
311
- }
312
- // If no heuristics, assign a language
313
- if (!results.files.results[file]) {
314
- const possibleLangs = fileAssociations[file];
315
- // Assign first language as a default option
316
- const defaultLang = possibleLangs[0];
317
- const alternativeLangs = possibleLangs.slice(1);
318
- results.files.results[file] = defaultLang;
319
- // List alternative languages if there are any
320
- if (alternativeLangs.length > 0)
321
- results.files.alternatives[file] = alternativeLangs;
322
- }
323
- }
324
- // Skip specified categories
325
- if ((_m = opts.categories) === null || _m === void 0 ? void 0 : _m.length) {
326
- const categories = ['data', 'markup', 'programming', 'prose'];
327
- const hiddenCategories = categories.filter(cat => !opts.categories.includes(cat));
328
- for (const [file, lang] of Object.entries(results.files.results)) {
329
- if (!hiddenCategories.some(cat => { var _a; return lang && ((_a = langData[lang]) === null || _a === void 0 ? void 0 : _a.type) === cat; })) {
330
- continue;
331
- }
332
- delete results.files.results[file];
333
- if (lang) {
334
- delete results.languages.results[lang];
335
- }
336
- }
337
- for (const category of hiddenCategories) {
338
- for (const [lang, { type }] of Object.entries(results.languages.results)) {
339
- if (type === category) {
340
- delete results.languages.results[lang];
341
- }
342
- }
343
- }
344
- }
345
- // Convert paths to relative
346
- if (!useRawContent && opts.relativePaths) {
347
- const newMap = {};
348
- for (const [file, lang] of Object.entries(results.files.results)) {
349
- let relPath = path_1.default.relative(process.cwd(), file).replace(/\\/g, '/');
350
- if (!relPath.startsWith('../')) {
351
- relPath = './' + relPath;
352
- }
353
- newMap[relPath] = lang;
354
- }
355
- results.files.results = newMap;
356
- }
357
- // Load language bytes size
358
- for (const [file, lang] of Object.entries(results.files.results)) {
359
- if (lang && !langData[lang])
360
- continue;
361
- const fileSize = (_q = (_p = (_o = opts.fileContent) === null || _o === void 0 ? void 0 : _o[files.indexOf(file)]) === null || _p === void 0 ? void 0 : _p.length) !== null && _q !== void 0 ? _q : fs_1.default.statSync(file).size;
362
- results.files.bytes += fileSize;
363
- // If no language found, add extension in other section
364
- if (!lang) {
365
- const ext = path_1.default.extname(file);
366
- const unknownType = ext === '' ? 'filenames' : 'extensions';
367
- const name = ext === '' ? path_1.default.basename(file) : ext;
368
- (_r = (_t = results.unknown[unknownType])[name]) !== null && _r !== void 0 ? _r : (_t[name] = 0);
369
- results.unknown[unknownType][name] += fileSize;
370
- results.unknown.bytes += fileSize;
371
- continue;
372
- }
373
- // Add language and bytes data to corresponding section
374
- const { type } = langData[lang];
375
- (_s = (_u = results.languages.results)[lang]) !== null && _s !== void 0 ? _s : (_u[lang] = { type, bytes: 0, color: langData[lang].color });
376
- if (opts.childLanguages) {
377
- results.languages.results[lang].parent = langData[lang].group;
378
- }
379
- results.languages.results[lang].bytes += fileSize;
380
- results.languages.bytes += fileSize;
381
- }
382
- // Set counts
383
- results.files.count = Object.keys(results.files.results).length;
384
- results.languages.count = Object.keys(results.languages.results).length;
385
- results.unknown.count = Object.keys({ ...results.unknown.extensions, ...results.unknown.filenames }).length;
386
- // Return
387
- return results;
388
- }
389
- module.exports = analyse;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ const fs_1 = __importDefault(require("fs"));
29
+ const path_1 = __importDefault(require("path"));
30
+ const js_yaml_1 = __importDefault(require("js-yaml"));
31
+ const ignore_1 = __importDefault(require("ignore"));
32
+ const common_path_prefix_1 = __importDefault(require("common-path-prefix"));
33
+ const binary_extensions_1 = __importDefault(require("binary-extensions"));
34
+ const isbinaryfile_1 = require("isbinaryfile");
35
+ const walk_tree_1 = __importDefault(require("./helpers/walk-tree"));
36
+ const load_data_1 = __importStar(require("./helpers/load-data"));
37
+ const read_file_1 = __importDefault(require("./helpers/read-file"));
38
+ const convert_pcre_1 = __importDefault(require("./helpers/convert-pcre"));
39
+ async function analyse(input, opts = {}) {
40
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
41
+ var _t, _u;
42
+ const useRawContent = opts.fileContent !== undefined;
43
+ input = [input !== null && input !== void 0 ? input : []].flat();
44
+ opts.fileContent = [(_a = opts.fileContent) !== null && _a !== void 0 ? _a : []].flat();
45
+ // Load data from github-linguist web repo
46
+ const langData = await (0, load_data_1.default)('languages.yml', opts.offline).then(js_yaml_1.default.load);
47
+ const vendorData = await (0, load_data_1.default)('vendor.yml', opts.offline).then(js_yaml_1.default.load);
48
+ const docData = await (0, load_data_1.default)('documentation.yml', opts.offline).then(js_yaml_1.default.load);
49
+ const heuristicsData = await (0, load_data_1.default)('heuristics.yml', opts.offline).then(js_yaml_1.default.load);
50
+ const generatedData = await (0, load_data_1.default)('generated.rb', opts.offline).then(load_data_1.parseGeneratedDataFile);
51
+ const vendorPaths = [...vendorData, ...docData, ...generatedData];
52
+ // Setup main variables
53
+ const fileAssociations = {};
54
+ const extensions = {};
55
+ const overrides = {};
56
+ const results = {
57
+ files: { count: 0, bytes: 0, results: {}, alternatives: {} },
58
+ languages: { count: 0, bytes: 0, results: {} },
59
+ unknown: { count: 0, bytes: 0, extensions: {}, filenames: {} },
60
+ };
61
+ // Prepare list of ignored files
62
+ const gitignores = (0, ignore_1.default)();
63
+ const regexIgnores = [];
64
+ gitignores.add('.git');
65
+ if (!opts.keepVendored)
66
+ regexIgnores.push(...vendorPaths.map(path => RegExp(path, 'i')));
67
+ if (opts.ignoredFiles)
68
+ gitignores.add(opts.ignoredFiles);
69
+ // Set a common root path so that vendor paths do not incorrectly match parent folders
70
+ const normPath = (file) => file.replace(/\\/g, '/');
71
+ const resolvedInput = input.map(path => normPath(path_1.default.resolve(path)));
72
+ const commonRoot = (input.length > 1 ? (0, common_path_prefix_1.default)(resolvedInput) : resolvedInput[0]).replace(/\/?$/, '');
73
+ const localRoot = (folder) => folder.replace(commonRoot, '').replace(/^\//, '');
74
+ const relPath = (file) => normPath(path_1.default.relative(commonRoot, file));
75
+ const unRelPath = (file) => normPath(path_1.default.resolve(commonRoot, file));
76
+ const localPath = (file) => localRoot(unRelPath(file));
77
+ // Load file paths and folders
78
+ let files, folders;
79
+ if (useRawContent) {
80
+ // Uses raw file content
81
+ files = input;
82
+ folders = [''];
83
+ }
84
+ else {
85
+ // Uses directory on disc
86
+ const data = (0, walk_tree_1.default)({ init: true, commonRoot, folderRoots: resolvedInput, folders: resolvedInput, gitignores, regexIgnores });
87
+ files = data.files;
88
+ folders = data.folders;
89
+ }
90
+ // Apply aliases
91
+ opts = {
92
+ checkIgnored: !opts.quick,
93
+ checkAttributes: !opts.quick,
94
+ checkHeuristics: !opts.quick,
95
+ checkShebang: !opts.quick,
96
+ checkModeline: !opts.quick,
97
+ ...opts
98
+ };
99
+ // Ignore specific languages
100
+ for (const lang of (_b = opts.ignoredLanguages) !== null && _b !== void 0 ? _b : []) {
101
+ for (const key in langData) {
102
+ if (lang.toLowerCase() === key.toLowerCase()) {
103
+ delete langData[key];
104
+ break;
105
+ }
106
+ }
107
+ }
108
+ // Load gitignores and gitattributes
109
+ const customBinary = (0, ignore_1.default)();
110
+ const customText = (0, ignore_1.default)();
111
+ if (!useRawContent && opts.checkAttributes) {
112
+ for (const folder of folders) {
113
+ // TODO FIX: this is absolute when only 1 path given
114
+ const localFilePath = (path) => localRoot(folder) ? localRoot(folder) + '/' + localPath(path) : path;
115
+ // Skip if folder is marked in gitattributes
116
+ if (relPath(folder) && gitignores.ignores(relPath(folder))) {
117
+ continue;
118
+ }
119
+ // Parse gitignores
120
+ const ignoresFile = path_1.default.join(folder, '.gitignore');
121
+ if (opts.checkIgnored && fs_1.default.existsSync(ignoresFile)) {
122
+ const ignoresData = await (0, read_file_1.default)(ignoresFile);
123
+ const localIgnoresData = ignoresData.replace(/^[\/\\]/g, localRoot(folder) + '/');
124
+ gitignores.add(localIgnoresData);
125
+ }
126
+ // Parse gitattributes
127
+ const attributesFile = path_1.default.join(folder, '.gitattributes');
128
+ if (opts.checkAttributes && fs_1.default.existsSync(attributesFile)) {
129
+ const attributesData = await (0, read_file_1.default)(attributesFile);
130
+ // Explicit text/binary associations
131
+ const contentTypeMatches = attributesData.matchAll(/^(\S+).*?(-?binary|-?text)(?!=auto)/gm);
132
+ for (const [_line, path, type] of contentTypeMatches) {
133
+ if (['text', '-binary'].includes(type)) {
134
+ customText.add(localFilePath(path));
135
+ }
136
+ if (['-text', 'binary'].includes(type)) {
137
+ customBinary.add(localFilePath(path));
138
+ }
139
+ }
140
+ // Custom vendor options
141
+ const vendorMatches = attributesData.matchAll(/^(\S+).*[^-]linguist-(vendored|generated|documentation)(?!=false)/gm);
142
+ for (const [_line, path] of vendorMatches) {
143
+ gitignores.add(localFilePath(path));
144
+ }
145
+ // Custom file associations
146
+ const customLangMatches = attributesData.matchAll(/^(\S+).*[^-]linguist-language=(\S+)/gm);
147
+ for (let [_line, path, forcedLang] of customLangMatches) {
148
+ // If specified language is an alias, associate it with its full name
149
+ if (!langData[forcedLang]) {
150
+ const overrideLang = Object.entries(langData).find(entry => { var _a; return (_a = entry[1].aliases) === null || _a === void 0 ? void 0 : _a.includes(forcedLang.toLowerCase()); });
151
+ if (overrideLang) {
152
+ forcedLang = overrideLang[0];
153
+ }
154
+ }
155
+ const fullPath = path_1.default.join(relPath(folder), path);
156
+ overrides[fullPath] = forcedLang;
157
+ }
158
+ }
159
+ }
160
+ }
161
+ // Check vendored files
162
+ if (!opts.keepVendored) {
163
+ // Filter out any files that match a vendor file path
164
+ if (useRawContent) {
165
+ files = gitignores.filter(files);
166
+ files = files.filter(file => !regexIgnores.find(match => match.test(file)));
167
+ }
168
+ else {
169
+ files = gitignores.filter(files.map(localPath)).map(unRelPath);
170
+ }
171
+ }
172
+ // Load all files and parse languages
173
+ const addResult = (file, result) => {
174
+ if (!fileAssociations[file]) {
175
+ fileAssociations[file] = [];
176
+ extensions[file] = '';
177
+ }
178
+ // Set parent to result group if it is present
179
+ // Is nullish if either `opts.childLanguages` is set or if there is no group
180
+ const finalResult = !opts.childLanguages && result && langData[result].group || result;
181
+ if (!fileAssociations[file].includes(finalResult))
182
+ fileAssociations[file].push(finalResult);
183
+ extensions[file] = path_1.default.extname(file).toLowerCase();
184
+ };
185
+ const overridesArray = Object.entries(overrides);
186
+ // List all languages that could be associated with a given file
187
+ const definiteness = {};
188
+ const fromShebang = {};
189
+ for (const file of files) {
190
+ let firstLine;
191
+ if (useRawContent) {
192
+ firstLine = (_e = (_d = (_c = opts.fileContent) === null || _c === void 0 ? void 0 : _c[files.indexOf(file)]) === null || _d === void 0 ? void 0 : _d.split('\n')[0]) !== null && _e !== void 0 ? _e : null;
193
+ }
194
+ else if (fs_1.default.existsSync(file) && !fs_1.default.lstatSync(file).isDirectory()) {
195
+ firstLine = await (0, read_file_1.default)(file, true).catch(() => null);
196
+ }
197
+ else
198
+ continue;
199
+ // Skip if file is unreadable
200
+ if (firstLine === null)
201
+ continue;
202
+ // Check first line for explicit classification
203
+ const hasShebang = opts.checkShebang && /^#!/.test(firstLine);
204
+ const hasModeline = opts.checkModeline && /-\*-|(syntax|filetype|ft)\s*=/.test(firstLine);
205
+ if (!opts.quick && (hasShebang || hasModeline)) {
206
+ const matches = [];
207
+ for (const [lang, data] of Object.entries(langData)) {
208
+ const langMatcher = (lang) => `\\b${lang.toLowerCase().replace(/\W/g, '\\$&')}(?![\\w#+*]|-\*-)`;
209
+ // Check for interpreter match
210
+ if (opts.checkShebang && hasShebang) {
211
+ const matchesInterpretor = (_f = data.interpreters) === null || _f === void 0 ? void 0 : _f.some(interpreter => firstLine.match(`\\b${interpreter}\\b`));
212
+ if (matchesInterpretor)
213
+ matches.push(lang);
214
+ }
215
+ // Check modeline declaration
216
+ if (opts.checkModeline && hasModeline) {
217
+ const modelineText = firstLine.toLowerCase().replace(/^.*-\*-(.+)-\*-.*$/, '$1');
218
+ const matchesLang = modelineText.match(langMatcher(lang));
219
+ const matchesAlias = (_g = data.aliases) === null || _g === void 0 ? void 0 : _g.some(lang => modelineText.match(langMatcher(lang)));
220
+ if (matchesLang || matchesAlias)
221
+ matches.push(lang);
222
+ }
223
+ }
224
+ // Add identified language(s)
225
+ if (matches.length) {
226
+ for (const match of matches)
227
+ addResult(file, match);
228
+ if (matches.length === 1)
229
+ definiteness[file] = true;
230
+ fromShebang[file] = true;
231
+ continue;
232
+ }
233
+ }
234
+ // Check override for manual language classification
235
+ if (!useRawContent && !opts.quick && opts.checkAttributes) {
236
+ const isOverridden = (path) => (0, ignore_1.default)().add(path).ignores(relPath(file));
237
+ const match = overridesArray.find(item => isOverridden(item[0]));
238
+ if (match) {
239
+ const forcedLang = match[1];
240
+ addResult(file, forcedLang);
241
+ definiteness[file] = true;
242
+ continue;
243
+ }
244
+ }
245
+ // Search each language
246
+ let skipExts = false;
247
+ // Check if filename is a match
248
+ for (const lang in langData) {
249
+ const matchesName = (_h = langData[lang].filenames) === null || _h === void 0 ? void 0 : _h.some(name => path_1.default.basename(file.toLowerCase()) === name.toLowerCase());
250
+ if (matchesName) {
251
+ addResult(file, lang);
252
+ skipExts = true;
253
+ }
254
+ }
255
+ // Check if extension is a match
256
+ const possibleExts = [];
257
+ if (!skipExts)
258
+ for (const lang in langData) {
259
+ const extMatches = (_j = langData[lang].extensions) === null || _j === void 0 ? void 0 : _j.filter(ext => file.toLowerCase().endsWith(ext.toLowerCase()));
260
+ if (extMatches === null || extMatches === void 0 ? void 0 : extMatches.length) {
261
+ for (const ext of extMatches)
262
+ possibleExts.push({ ext, lang });
263
+ }
264
+ }
265
+ // Apply more specific extension if available
266
+ const isComplexExt = (ext) => /\..+\./.test(ext);
267
+ const hasComplexExt = possibleExts.some(data => isComplexExt(data.ext));
268
+ for (const { ext, lang } of possibleExts) {
269
+ if (hasComplexExt && !isComplexExt(ext))
270
+ continue;
271
+ if (!hasComplexExt && isComplexExt(ext))
272
+ continue;
273
+ addResult(file, lang);
274
+ }
275
+ // Fallback to null if no language matches
276
+ if (!fileAssociations[file]) {
277
+ addResult(file, null);
278
+ }
279
+ }
280
+ // Narrow down file associations to the best fit
281
+ for (const file in fileAssociations) {
282
+ // Skip if file has explicit association
283
+ if (definiteness[file]) {
284
+ results.files.results[file] = fileAssociations[file][0];
285
+ continue;
286
+ }
287
+ // Skip binary files
288
+ if (!useRawContent && !opts.keepBinary) {
289
+ const isCustomText = customText.ignores(relPath(file));
290
+ const isCustomBinary = customBinary.ignores(relPath(file));
291
+ const isBinaryExt = binary_extensions_1.default.some(ext => file.endsWith('.' + ext));
292
+ if (!isCustomText && (isCustomBinary || isBinaryExt || await (0, isbinaryfile_1.isBinaryFile)(file))) {
293
+ continue;
294
+ }
295
+ }
296
+ // Parse heuristics if applicable
297
+ if (opts.checkHeuristics)
298
+ for (const heuristics of heuristicsData.disambiguations) {
299
+ // Make sure the extension matches the current file
300
+ if (!fromShebang[file] && !heuristics.extensions.includes(extensions[file]))
301
+ continue;
302
+ // Load heuristic rules
303
+ for (const heuristic of heuristics.rules) {
304
+ // Make sure the language is not an array
305
+ if (Array.isArray(heuristic.language)) {
306
+ heuristic.language = heuristic.language[0];
307
+ }
308
+ // Make sure the results includes this language
309
+ const languageGroup = (_k = langData[heuristic.language]) === null || _k === void 0 ? void 0 : _k.group;
310
+ const matchesLang = fileAssociations[file].includes(heuristic.language);
311
+ const matchesParent = languageGroup && fileAssociations[file].includes(languageGroup);
312
+ if (!matchesLang && !matchesParent)
313
+ continue;
314
+ // Normalise heuristic data
315
+ const patterns = [];
316
+ const normalise = (contents) => patterns.push(...[contents].flat());
317
+ if (heuristic.pattern)
318
+ normalise(heuristic.pattern);
319
+ if (heuristic.named_pattern)
320
+ normalise(heuristicsData.named_patterns[heuristic.named_pattern]);
321
+ if (heuristic.and) {
322
+ for (const data of heuristic.and) {
323
+ if (data.pattern)
324
+ normalise(data.pattern);
325
+ if (data.named_pattern)
326
+ normalise(heuristicsData.named_patterns[data.named_pattern]);
327
+ }
328
+ }
329
+ // Check file contents and apply heuristic patterns
330
+ const fileContent = ((_l = opts.fileContent) === null || _l === void 0 ? void 0 : _l.length) ? opts.fileContent[files.indexOf(file)] : await (0, read_file_1.default)(file).catch(() => null);
331
+ // Skip if file read errors
332
+ if (fileContent === null)
333
+ continue;
334
+ // Apply heuristics
335
+ if (!patterns.length || patterns.some(pattern => (0, convert_pcre_1.default)(pattern).test(fileContent))) {
336
+ results.files.results[file] = heuristic.language;
337
+ break;
338
+ }
339
+ }
340
+ }
341
+ // If no heuristics, assign a language
342
+ if (!results.files.results[file]) {
343
+ const possibleLangs = fileAssociations[file];
344
+ // Assign first language as a default option
345
+ const defaultLang = possibleLangs[0];
346
+ const alternativeLangs = possibleLangs.slice(1);
347
+ results.files.results[file] = defaultLang;
348
+ // List alternative languages if there are any
349
+ if (alternativeLangs.length > 0)
350
+ results.files.alternatives[file] = alternativeLangs;
351
+ }
352
+ }
353
+ // Skip specified categories
354
+ if ((_m = opts.categories) === null || _m === void 0 ? void 0 : _m.length) {
355
+ const categories = ['data', 'markup', 'programming', 'prose'];
356
+ const hiddenCategories = categories.filter(cat => !opts.categories.includes(cat));
357
+ for (const [file, lang] of Object.entries(results.files.results)) {
358
+ if (!hiddenCategories.some(cat => { var _a; return lang && ((_a = langData[lang]) === null || _a === void 0 ? void 0 : _a.type) === cat; })) {
359
+ continue;
360
+ }
361
+ delete results.files.results[file];
362
+ if (lang) {
363
+ delete results.languages.results[lang];
364
+ }
365
+ }
366
+ for (const category of hiddenCategories) {
367
+ for (const [lang, { type }] of Object.entries(results.languages.results)) {
368
+ if (type === category) {
369
+ delete results.languages.results[lang];
370
+ }
371
+ }
372
+ }
373
+ }
374
+ // Convert paths to relative
375
+ if (!useRawContent && opts.relativePaths) {
376
+ const newMap = {};
377
+ for (const [file, lang] of Object.entries(results.files.results)) {
378
+ let relPath = path_1.default.relative(process.cwd(), file).replace(/\\/g, '/');
379
+ if (!relPath.startsWith('../')) {
380
+ relPath = './' + relPath;
381
+ }
382
+ newMap[relPath] = lang;
383
+ }
384
+ results.files.results = newMap;
385
+ }
386
+ // Load language bytes size
387
+ for (const [file, lang] of Object.entries(results.files.results)) {
388
+ if (lang && !langData[lang])
389
+ continue;
390
+ const fileSize = (_q = (_p = (_o = opts.fileContent) === null || _o === void 0 ? void 0 : _o[files.indexOf(file)]) === null || _p === void 0 ? void 0 : _p.length) !== null && _q !== void 0 ? _q : fs_1.default.statSync(file).size;
391
+ results.files.bytes += fileSize;
392
+ // If no language found, add extension in other section
393
+ if (!lang) {
394
+ const ext = path_1.default.extname(file);
395
+ const unknownType = ext === '' ? 'filenames' : 'extensions';
396
+ const name = ext === '' ? path_1.default.basename(file) : ext;
397
+ (_r = (_t = results.unknown[unknownType])[name]) !== null && _r !== void 0 ? _r : (_t[name] = 0);
398
+ results.unknown[unknownType][name] += fileSize;
399
+ results.unknown.bytes += fileSize;
400
+ continue;
401
+ }
402
+ // Add language and bytes data to corresponding section
403
+ const { type } = langData[lang];
404
+ (_s = (_u = results.languages.results)[lang]) !== null && _s !== void 0 ? _s : (_u[lang] = { type, bytes: 0, color: langData[lang].color });
405
+ if (opts.childLanguages) {
406
+ results.languages.results[lang].parent = langData[lang].group;
407
+ }
408
+ results.languages.results[lang].bytes += fileSize;
409
+ results.languages.bytes += fileSize;
410
+ }
411
+ // Set counts
412
+ results.files.count = Object.keys(results.files.results).length;
413
+ results.languages.count = Object.keys(results.languages.results).length;
414
+ results.unknown.count = Object.keys({ ...results.unknown.extensions, ...results.unknown.filenames }).length;
415
+ // Return
416
+ return results;
417
+ }
418
+ module.exports = analyse;