/
index.js
95 lines (84 loc) · 2.33 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import scms from './scms';
import processFiles from './processFiles';
import createIgnorer from './createIgnorer';
import createMatcher from './createMatcher';
import isSupportedExtension from './isSupportedExtension';
export default (
currentDirectory,
{
config,
since,
staged,
pattern,
restage = true,
branch,
bail,
check,
verbose,
onFoundSinceRevision,
onFoundChangedFiles,
onPartiallyStagedFile,
onExamineFile,
onCheckFile,
onWriteFile,
} = {}
) => {
const scm = scms(currentDirectory);
if (!scm) {
throw new Error('Unable to detect a source control manager.');
}
const directory = scm.rootDirectory;
const revision = since || scm.getSinceRevision(directory, { staged, branch });
onFoundSinceRevision && onFoundSinceRevision(scm.name, revision);
const rootIgnorer = createIgnorer(directory);
const cwdIgnorer =
currentDirectory !== directory
? createIgnorer(currentDirectory)
: () => true;
const changedFiles = scm
.getChangedFiles(directory, revision, staged)
.filter(isSupportedExtension)
.filter(createMatcher(pattern))
.filter(rootIgnorer)
.filter(cwdIgnorer);
const unstagedFiles = staged
? scm
.getUnstagedChangedFiles(directory, revision)
.filter(isSupportedExtension)
.filter(createMatcher(pattern))
.filter(rootIgnorer)
.filter(cwdIgnorer)
: [];
const wasFullyStaged = f => unstagedFiles.indexOf(f) < 0;
onFoundChangedFiles && onFoundChangedFiles(changedFiles);
const failReasons = new Set();
processFiles(directory, changedFiles, {
check,
config,
onWriteFile: file => {
onWriteFile && onWriteFile(file);
if (bail) {
failReasons.add('BAIL_ON_WRITE');
}
if (staged && restage) {
if (wasFullyStaged(file)) {
scm.stageFile(directory, file);
} else {
onPartiallyStagedFile && onPartiallyStagedFile(file);
failReasons.add('PARTIALLY_STAGED_FILE');
}
}
},
onCheckFile: (file, isFormatted) => {
onCheckFile && onCheckFile(file, isFormatted);
if (!isFormatted) {
failReasons.add('CHECK_FAILED');
}
},
onExamineFile: verbose && onExamineFile,
});
return {
success: failReasons.size === 0,
errors: Array.from(failReasons),
};
};