-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
git.ts
110 lines (95 loc) · 2.51 KB
/
git.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import fs from 'fs'
import path from 'path'
import execa from 'execa'
import findUp from 'find-up'
export const name = 'git'
export const detect = (directory: string) => {
if (fs.existsSync(path.join(directory, '.git'))) {
return directory
}
const gitDirectory = findUp.sync('.git', {
cwd: directory,
type: 'directory',
})
const gitWorkTreeFile = findUp.sync('.git', {
cwd: directory,
type: 'file',
})
// if both of these are null then return null
if (!gitDirectory && !gitWorkTreeFile) {
return null
}
// if only one of these exists then return it
if (gitDirectory && !gitWorkTreeFile) {
return path.dirname(gitDirectory)
}
if (gitWorkTreeFile && !gitDirectory) {
return path.dirname(gitWorkTreeFile)
}
const gitRepoDirectory = path.dirname(gitDirectory!)
const gitWorkTreeDirectory = path.dirname(gitWorkTreeFile!)
// return the deeper of these two
return gitRepoDirectory.length > gitWorkTreeDirectory.length
? gitRepoDirectory
: gitWorkTreeDirectory
}
const runGit = (directory: string, args: string[]) =>
execa.sync('git', args, {
cwd: directory,
})
const getLines = (execaResult: execa.ExecaSyncReturnValue) =>
execaResult.stdout.split('\n')
export const getSinceRevision = (
directory: string,
{ staged, branch }: { staged?: boolean; branch?: string },
) => {
try {
const revision = staged
? 'HEAD'
: runGit(directory, [
'merge-base',
'HEAD',
branch || 'master',
]).stdout.trim()
return runGit(directory, ['rev-parse', '--short', revision]).stdout.trim()
} catch (err) {
const error = err as Error
if (
/HEAD/.test(error.message) ||
(staged && /Needed a single revision/.test(error.message))
) {
return null
}
throw error
}
}
export const getChangedFiles = (
directory: string,
revision: string | null,
staged?: boolean | undefined,
) =>
[
...getLines(
runGit(
directory,
[
'diff',
'--name-only',
staged ? '--cached' : null,
'--diff-filter=ACMRTUB',
revision,
].filter(Boolean),
),
),
...(staged
? []
: getLines(
runGit(directory, ['ls-files', '--others', '--exclude-standard']),
)),
].filter(Boolean)
export const getUnstagedChangedFiles = (directory: string) => {
return getChangedFiles(directory, null, false)
}
export const stageFile = (directory: string, file: string) => {
runGit(directory, ['add', file])
}