/
git.js
73 lines (65 loc) · 1.61 KB
/
git.js
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
import findUp from 'find-up';
import execa from 'execa';
import { dirname } from 'path';
export const name = 'git';
export const detect = directory => {
const gitDirectory = findUp.sync('.git', {
cwd: directory,
type: 'directory',
});
if (gitDirectory) {
return dirname(gitDirectory);
}
};
const runGit = (directory, args) =>
execa.sync('git', args, {
cwd: directory,
});
const getLines = execaResult => execaResult.stdout.split('\n');
export const getSinceRevision = (directory, { staged, branch }) => {
try {
const revision = staged
? 'HEAD'
: runGit(directory, [
'merge-base',
'HEAD',
branch || 'master',
]).stdout.trim();
return runGit(directory, ['rev-parse', '--short', revision]).stdout.trim();
} catch (error) {
if (
/HEAD/.test(error.message) ||
(staged && /Needed a single revision/.test(error.message))
) {
return null;
}
throw error;
}
};
export const getChangedFiles = (directory, revision, staged) => {
return [
...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 => {
return getChangedFiles(directory, null, false);
};
export const stageFile = (directory, file) => {
runGit(directory, ['add', file]);
};