(path: string, warnIfNotGitRepo = false)
| 2 | import { dirname } from 'node:path'; |
| 3 | |
| 4 | export async function checkIsFileGitIgnored(path: string, warnIfNotGitRepo = false) { |
| 5 | try { |
| 6 | // Use spawnAsync with array arguments to properly handle paths with spaces |
| 7 | // Pass cwd to run git from the file's directory |
| 8 | await spawnAsync('git', ['check-ignore', path, '-q'], { cwd: dirname(path) }); |
| 9 | return true; |
| 10 | } catch (err) { |
| 11 | // git binary not found (not installed or not in PATH) - check this first |
| 12 | // before accessing err.data which won't exist on native spawn ENOENT errors |
| 13 | if ((err as any).code === 'ENOENT') return undefined; |
| 14 | |
| 15 | const errorOutput = (err as any).data as string | undefined; |
| 16 | // git is not installed, so we can't check |
| 17 | if ( |
| 18 | (err as any).exitCode === 127 |
| 19 | || errorOutput?.includes('not found') |
| 20 | || errorOutput?.includes('not recognized') // windows |
| 21 | ) { |
| 22 | return undefined; |
| 23 | } |
| 24 | // `git check-ignore -q` exits with code 1 but no other error if is not ignored |
| 25 | if (errorOutput === '') return false; |
| 26 | if (errorOutput?.includes('not a git repository')) { |
| 27 | if (warnIfNotGitRepo) { |
| 28 | // eslint-disable-next-line no-console |
| 29 | console.log('🔶 Your code is not currently in a git repository - run `git init` to initialize a new repo.'); |
| 30 | } |
| 31 | return false; |
| 32 | } |
| 33 | // file is outside the current git repository (e.g., importing from home directory) |
| 34 | if (errorOutput?.includes('is outside repository')) { |
| 35 | return undefined; |
| 36 | } |
| 37 | // otherwise we'll let it throw since something else is happening |
| 38 | throw err; |
| 39 | } |
| 40 | } |
no test coverage detected