-
Notifications
You must be signed in to change notification settings - Fork 1
/
git-off-my-land-lib.js
283 lines (238 loc) · 8.06 KB
/
git-off-my-land-lib.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"use strict";
import {promisify} from "util";
import {exec as cpexec} from "child_process";
import {EOL} from "os";
import {readFile as FSRReadFile, stat as FSStat} from "fs";
import {extname} from "path";
// Promisified functions for use in async/await
const exec = promisify(cpexec);
const readFile = promisify(FSRReadFile);
const stat = promisify(FSStat);
// Flow type definitions etc.
// @flow
type hookName = "pre-commit"; // eslint-disable-line no-undef
async function filterFilesList(rawStdOut: string, ignoreGitStatusResultPrefixes: Array, EOLChar: string)
{
let err;
let committedFilenames = new Set();
try
{
const committedFilesArray = rawStdOut.trim().split(EOLChar);
committedFilesArray.forEach((f) =>
{
const filenameArray = f.trim().split(" ");
// Get the filename which is the final element of the array
const filename = filenameArray.pop();
// Get the list of git operations (Add, Modify, Delete etc.) which is the final character from 0th element in the array
const lastOperation = filenameArray[0].split("").pop();
if(ignoreGitStatusResultPrefixes.includes(lastOperation) === false)
{
committedFilenames.add(filename);
}
});
}
catch(e)
{
err = e;
}
const p = new Promise((resolve, reject) =>
{
if(err)
{
reject(err);
}
else
{
resolve(committedFilenames);
}
});
return p;
}
async function scanFilteredFiles(committedFiles: Set, fileContentRegexps: Array, violatingFilenameExtensions: Array, filesToIgnore: Array) //eslint-disable-line complexity
{
let err;
let filteredViolations = [];
try
{
let rawViolations = {};
const committedFilesArray = [...committedFiles];
// Note: The method for handling async/await in a for loop is from https://blog.lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795
for(let i in committedFilesArray)
{
const committedFile = committedFilesArray[i];
const stats = await stat(committedFile);
if(stats.isFile()) // Check we're not going to try to read a dir because that would 💣
{
if(rawViolations[committedFile] === undefined)
{
rawViolations[committedFile] =
{
content: [],
extension: []
};
}
// Content-based scanning
const content = await readFile(committedFile, "utf8");
for(let j in fileContentRegexps)
{
const pattern = fileContentRegexps[j];
if(content.match(pattern.regexp) && filesToIgnore.includes(committedFile) === false)
{
rawViolations[committedFile]["content"].push(pattern.name);
// NOTE: We don't break here because a file may violate > 1 rule
}
}
// Filename extension-based scanning
const extension = extname(committedFile).toLocaleLowerCase();
for(let k in violatingFilenameExtensions) // eslint-disable-line no-unused-vars
{
if(violatingFilenameExtensions.includes(extension) === true)
{
rawViolations[committedFile]["extension"].push(extension);
break;
}
}
}
}
// Prune any empty array items
let prunedViolations = [];
for(let violation in rawViolations)
{
const contentLength = rawViolations[violation].content.length;
const extensionLength = rawViolations[violation].extension.length;
if(contentLength > 0 || extensionLength > 0)
{
prunedViolations[violation] = rawViolations[violation];
}
}
// Filter for files the user has chosen to ignore
for(let violation in prunedViolations)
{
let ignore = false;
for(let i in filesToIgnore)
{
const match = violation.match(filesToIgnore[i]);
if(match)
{
ignore = true;
}
}
if(ignore === false)
{
filteredViolations[violation] = prunedViolations[violation];
}
}
}
catch(e)
{
err = e;
}
const p = new Promise((resolve, reject) =>
{
if(err)
{
reject(err);
}
else
{
resolve(filteredViolations);
}
});
return p;
}
async function formatOutput(header: string, violations: Object, footer: string)
{
let err;
let output: string = "";
try
{
if(Object.keys(violations).length > 0)
{
let violationsDetails: Array = [];
for(let i in violations)
{
const contentViolationsMessage = violations[i].content.join(", ");
const extensionsViolationsMessage = violations[i].extension.join(", ");
const violationsMessage = `Content: ${contentViolationsMessage || "none"}. Filename extension: ${extensionsViolationsMessage || "none"}`;
violationsDetails.push(`${i} - ${violationsMessage}`);
}
const sortedViolationsDetails = violationsDetails.sort();
output = [header, ...sortedViolationsDetails, footer].join(EOL);
}
}
catch(e)
{
err = e;
}
const p = new Promise((resolve, reject) =>
{
if(err)
{
reject(err);
}
else
{
resolve(output);
}
});
return p;
}
// Main handler function. This is the only exported function in the lib
/* istanbul ignore next */
async function runGitHook(config: Object, hookType: hookName)
{
let err;
let output;
// Pre-commit hook handler
// Note: it may be that the only thing which changes for non pre-commit usage is the cmd to run to get the files
// Note: It might be worth splitting this out into another function if we add other handlers
if(hookType === "pre-commit")
{
try
{
const rawFilesList = await exec(config.gitStatusCmd, config.execOptions);
if(rawFilesList.stderr != "")
{
err = rawFilesList.stderr;
}
else if(rawFilesList.stdout != "")
{
const filteredFiles = await filterFilesList(rawFilesList.stdout, config.ignoreGitStatusResultPrefixes, EOL);
if(filteredFiles.size > 0)
{
const violations = await scanFilteredFiles(filteredFiles, config.fileContentRegexps, config.violatingFilenameExtensions, config.filesToIgnore);
if(violations)
{
output = await formatOutput(config.violationsMessageHeader, violations, config.violationsMessageFooter);
}
}
}
}
catch(e)
{
err = e;
}
}
const p = new Promise((resolve, reject) =>
{
// We only reject the promise if there is an actual error...
// ...we don't reject on finding violating files, that will be handled in the pre-commit script
if(err)
{
reject(err);
}
else
{
resolve(output);
}
});
return p;
}
// Note: We export all the functions in order to unit test them. Only runGitHook should be used externally
module.exports =
{
filterFilesList: filterFilesList,
scanFilteredFiles:scanFilteredFiles,
formatOutput: formatOutput,
runGitHook: runGitHook
};