UNPKG

927 BJavaScriptView Raw
1import path from 'path'
2
3import normalize from 'normalize-path'
4
5import { execGit } from './execGit.js'
6
7export const getStagedFiles = async ({ cwd = process.cwd() } = {}) => {
8 try {
9 // Docs for --diff-filter option: https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203
10 // Docs for -z option: https://git-scm.com/docs/git-diff#Documentation/git-diff.txt--z
11 const lines = await execGit(['diff', '--staged', '--diff-filter=ACMR', '--name-only', '-z'], {
12 cwd,
13 })
14
15 if (!lines) return []
16
17 // With `-z`, git prints `fileA\u0000fileB\u0000fileC\u0000` so we need to
18 // remove the last occurrence of `\u0000` before splitting
19 return (
20 lines
21 // eslint-disable-next-line no-control-regex
22 .replace(/\u0000$/, '')
23 .split('\u0000')
24 .map((file) => normalize(path.resolve(cwd, file)))
25 )
26 } catch {
27 return null
28 }
29}