| 1 | import path from 'node:path'; |
| 2 | |
| 3 | import { LINGUIST_ATTRIBUTES, type |
| 4 | |
| 5 | import { withTempDir } |
| 6 | import { runGit } |
| 7 | |
| 8 | /** Symlinks and submodules are not files of the repository, so they hold no bytes. */ |
| 9 | export const SKIPPED_MODES = |
| 10 | |
| 11 | interface Side { |
| 12 | path: string; |
| 13 | oid: string; |
| 14 | } |
| 15 | |
| 16 | export interface RawChange |
| 17 | before?: Side |
| 18 | after?: Side |
| 19 | } |
| 20 | |
| 21 | /** Each entry is ":<srcmode> <dstmode> <srcoid> <dstoid> <status>" followed by one path, or two for a rename or copy. Symlinks and submodules are dropped per side, so a file becoming a symlink still subtracts its old bytes. */ |
| 22 | export async function readRawDiff |
| 23 | gitDir: string, |
| 24 | from: string, |
| 25 | to: string, |
| 26 | ): Promise<RawChange |
| 27 | const raw = |
| 28 | args: [ |
| 29 | 'diff', |
| 30 | '--raw', |
| 31 | '-r', |
| 32 | '-z', |
| 33 | '--no-abbrev', // full oids are what cat-file echoes back |
| 34 | '--end-of-options', |
| 35 | from, |
| 36 | to, |
| 37 | ], |
| 38 | gitDir, |
| 39 | }); |
| 40 | |
| 41 | const fields = |
| 42 | const changes: |
| 43 | |
| 44 | for (let i |
| 45 | if (!fields[i |
| 46 | |
| 47 | const [srcMode, |
| 48 | .slice(1) |
| 49 | .split(' ') |
| 50 | // a rename or a copy names the destination in a second path field |
| 51 | const renamed = |
| 52 | const srcPath = |
| 53 | const dstPath = |
| 54 | if (srcPath === |
| 55 | |
| 56 | changes.push({ |
| 57 | before: isCounted(srcMode |
| 58 | ? { path: srcPath |
| 59 | : undefined, |
| 60 | after: isCounted(dstMode |
| 61 | ? { path: dstPath |
| 62 | : undefined, |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | return changes; |
| 67 | } |
| 68 | |
| 69 | function isCounted(mode: |
| 70 | return !SKIPPED_MODES.has |
| 71 | } |
| 72 | |
| 73 | export function isGitAttributes(file |
| 74 | return file === |
| 75 | } |
| 76 | |
| 77 | /** Paths with no linguist attributes are left out. Read through a throwaway index, which works in a bare repository and on git older than 2.40's `check-attr --source`. */ |
| 78 | export async function readAttributes |
| 79 | gitDir: string, |
| 80 | tree: string, |
| 81 | files: string[] |
| 82 | ): Promise<Map |
| 83 | const attributes = |
| 84 | if (files.length |
| 85 | |
| 86 | await withTempDir('ghost-attributes- |
| 87 | const env = |
| 88 | await runGit({ |
| 89 | const output = |
| 90 | args: ['check-attr', |
| 91 | gitDir, |
| 92 | env, |
| 93 | input: Buffer.from |
| 94 | }); |
| 95 | |
| 96 | // "<path>\0<attribute>\0<value>\0" for every path and attribute asked for |
| 97 | const fields = |
| 98 | for (let i |
| 99 | const [file, |
| 100 | if (value === |
| 101 | attributes.set(file |
| 102 | ...attributes.get( |
| 103 | [name]: value |
| 104 | }); |
| 105 | } |
| 106 | }); |
| 107 | |
| 108 | return attributes; |
| 109 | } |