|
| 1 | +import micromatch from 'micromatch'; |
| 2 | + |
| 3 | +// GitAttributes holds parsed .gitattributes rules for overriding language detection. |
| 4 | +export interface GitAttributes { |
| 5 | + rules: GitAttributeRule[]; |
| 6 | +} |
| 7 | + |
| 8 | +interface GitAttributeRule { |
| 9 | + pattern: string; |
| 10 | + attrs: Record<string, string>; |
| 11 | +} |
| 12 | + |
| 13 | +// parseGitAttributes parses the content of a .gitattributes file. |
| 14 | +// Each non-comment, non-empty line has the form: pattern attr1 attr2=value ... |
| 15 | +// Attributes can be: |
| 16 | +// - "linguist-vendored" (set/true), "-linguist-vendored" (unset/false) |
| 17 | +// - "linguist-language=Go" |
| 18 | +// - etc. |
| 19 | +export function parseGitAttributes(content: string): GitAttributes { |
| 20 | + const rules: GitAttributeRule[] = []; |
| 21 | + |
| 22 | + for (const raw of content.split('\n')) { |
| 23 | + const line = raw.trim(); |
| 24 | + if (line === '' || line.startsWith('#')) { |
| 25 | + continue; |
| 26 | + } |
| 27 | + |
| 28 | + const fields = line.split(/\s+/); |
| 29 | + if (fields.length < 2) { |
| 30 | + continue; |
| 31 | + } |
| 32 | + |
| 33 | + const pattern = fields[0]; |
| 34 | + const attrs: Record<string, string> = {}; |
| 35 | + |
| 36 | + for (const field of fields.slice(1)) { |
| 37 | + if (field.startsWith('!')) { |
| 38 | + // !attr means unspecified (reset to default) |
| 39 | + attrs[field.slice(1)] = 'unspecified'; |
| 40 | + } else if (field.startsWith('-')) { |
| 41 | + // -attr means unset (false) |
| 42 | + attrs[field.slice(1)] = 'false'; |
| 43 | + } else { |
| 44 | + const eqIdx = field.indexOf('='); |
| 45 | + if (eqIdx !== -1) { |
| 46 | + // attr=value |
| 47 | + attrs[field.slice(0, eqIdx)] = field.slice(eqIdx + 1); |
| 48 | + } else { |
| 49 | + // attr alone means set (true) |
| 50 | + attrs[field] = 'true'; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + rules.push({ pattern, attrs }); |
| 56 | + } |
| 57 | + |
| 58 | + return { rules }; |
| 59 | +} |
| 60 | + |
| 61 | +// resolveLanguageFromGitAttributes returns the linguist-language override for |
| 62 | +// the given file path based on the parsed .gitattributes rules, or undefined |
| 63 | +// if no rule matches. Last matching rule wins, consistent with gitattributes semantics. |
| 64 | +export function resolveLanguageFromGitAttributes(filePath: string, gitAttributes: GitAttributes): string | undefined { |
| 65 | + let language: string | undefined; |
| 66 | + for (const rule of gitAttributes.rules) { |
| 67 | + if (micromatch.isMatch(filePath, rule.pattern) && rule.attrs['linguist-language']) { |
| 68 | + language = rule.attrs['linguist-language']; |
| 69 | + } |
| 70 | + } |
| 71 | + return language; |
| 72 | +} |
0 commit comments