-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
398 lines (314 loc) · 10.6 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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env node
/**
* [remembrance]{@link https://github.com/UmamiAppearance/remembrance}
*
* @version 0.3.1
* @author UmamiAppearance [mail@umamiappearance.eu]
* @license MIT
*/
import { join as joinPath } from "path";
import { readdir, readFile, stat } from "fs/promises";
import picomatch from "picomatch";
// helpers
const CWD = process.cwd();
const isDirectory = async filePath => (await stat(filePath)).isDirectory();
// ensure array and resolve relative paths
const renderList = rawInput => {
const ensureArray = arr => Array.isArray(arr) ? arr : [arr];
return ensureArray(rawInput).map(pattern => {
if (pattern.at(0) === ".") {
return joinPath(CWD, pattern);
}
return pattern;
});
};
const throwError = message => {
console.error(message);
process.exit(1);
};
const debugInfo = info => console.log(`\nDEBUG INFO\n==========\n${info}\n`);
// read config vars
let data;
try {
data = await readFile(joinPath(CWD, ".remembrance.json"), "utf8");
} catch(err) {
if (err) {
if (err.code === "ENOENT") {
throwError("Could not find config file '.remembrance.json' in projects root folder.");
}
throwError(err);
}
}
const config = JSON.parse(data);
// set a variable for solo package.json tests
let jsonSolo = false;
// test for the two mandatory keys "src" and "dist" (unless "packageJSON" is set to "solo")
if (config.packageJSON !== "solo") {
if (!config.src) {
throwError("Key 'src' must be set in '.remembrance.json'.");
}
if (!config.dist) {
throwError("Key 'dist' must be set in '.remembrance.json'.");
}
} else {
jsonSolo = true;
}
// set other config default parameters
if (config.debug === undefined) {
config.debug = false;
}
if (!Array.isArray(config.extensions)) {
config.extensions = [ "cjs", "js", "map", "mjs", "ts" ];
}
if (config.packageJSON === undefined) {
config.packageJSON = true;
}
if (config.warnOnly === undefined) {
if (process.env.NODE_ENV && process.env.NODE_ENV === "development") {
config.warnOnly = true;
} else {
config.warnOnly = false;
}
}
if (config.silent === undefined) {
config.silent = false;
}
// set default tolerance in ms
if (config.tolerance === undefined) {
config.tolerance = 5000;
}
// log config settings in debug mode
if (config.debug) {
debugInfo(`Config-Settings ${JSON.stringify(config, null, 4)}`);
}
// test package.json anf package-lock.json if not disabled
let preError = false;
if (config.packageJSON) {
if (config.debug) {
debugInfo("Testing if 'package-lock.json' is up to date...");
}
const testPKGJson = async file => {
let mtime;
try {
mtime = (await stat(joinPath(CWD, file))).mtime;
} catch(err) {
if (err.code !== "ENOENT") {
throwError(err);
} else if (config.debug) {
console.log(`... '${file}' was not found --> skipped`);
}
}
return mtime;
};
let packageJSONmTime = await testPKGJson("package.json");
if (packageJSONmTime) {
packageJSONmTime = new Date(packageJSONmTime.setMilliseconds(packageJSONmTime.getMilliseconds() - config.tolerance));
const packageLockJSONmTime = await testPKGJson("package-lock.json");
if (packageLockJSONmTime) {
if (packageLockJSONmTime < packageJSONmTime) {
if (!config.silent) {
console.warn(" ==> 'package-lock.json' is not up to date");
}
if (!config.warnOnly) {
process.exit(1);
} else {
preError = true;
}
}
else if (config.debug) {
console.log("... PASSED!\n");
}
}
}
}
// end here if jsonSolo
if (jsonSolo) {
process.exit(0);
}
// ignore typical test folders by default (cf. https://github.com/avajs/ava/blob/main/docs/05-command-line.md)
const excludeList = !config.includeTests
? [
"**/__tests__/**/__helper__/**/*",
"**/__tests__/**/__helpers__/**/*",
"**/__tests__/**/__fixture__/**/*",
"**/__tests__/**/__fixtures__/**/*",
"**/test/**/helper/**/*",
"**/test/**/helpers/**/*",
"**/test/**/fixture/**/*",
"**/test/**/fixtures/**/*",
"**/tests/**/helper/**/*",
"**/tests/**/helpers/**/*",
"**/tests/**/fixture/**/*",
"**/tests/**/fixtures/**/*"
]
: [];
// set verbose debugging if requested
let verboseDebugging = false;
if (config.debug) {
if (config.debug === "verbose") {
verboseDebugging = true;
}
if (excludeList.length) {
debugInfo(`Test folder exclude pattern:\n${JSON.stringify(config, null, 4)}`);
} else {
debugInfo("No test folders are explicitly excluded.");
}
}
// add user defined folders/files to exclude list
if (config.exclude) {
excludeList.push(...renderList(config.exclude));
if (config.debug) {
debugInfo("Found user defined exclude files");
}
} else if (config.debug) {
debugInfo("No exclude files/directories defined by the user.");
}
// build a picomatch function to ignore the exclude list (always return false if list is empty)
const exclude = excludeList.length
? picomatch(excludeList)
: () => false;
// always ignore node_modules and git(hub) files
const reMatch = (arr) => new RegExp(arr.join("|"));
const noWayDirs = reMatch([
"^\\.git(:?hub)?$",
"^node_modules$"
]);
// build a function to match the defined extensions
const ensureExtension = reMatch(
config.extensions
.map(ext => `\\.${ext}$`)
);
// source and dist file picomatch functions
const matchSrc = picomatch(renderList(config.src));
const matchDist = picomatch(renderList(config.dist));
// file collecting function
const collectFiles = async () => {
if (config.debug) {
debugInfo("Start collecting files!");
}
const srcFiles = [];
const distFiles = [];
// recursive collect function
const collect = async dirPath => {
const files = await readdir(dirPath);
if (verboseDebugging) {
debugInfo(`Entering directory: '${dirPath}'`);
console.log(`File List: ${JSON.stringify(files, null, 4)}\n`);
}
for (const file of files) {
// if file is a directory call collect function recursively
if (await isDirectory(joinPath(dirPath, file))) {
if (!noWayDirs.test(file)) {
await collect(joinPath(dirPath, file));
}
}
// otherwise test the file if the file extension is valid
else if (ensureExtension.test(file)) {
const fullPath = joinPath(dirPath, file);
if (!exclude(fullPath)) {
if (verboseDebugging) {
console.log(`(File '${file}' gets tested against the match list)`);
}
if (matchSrc(fullPath)) {
srcFiles.push(fullPath);
if (config.debug) {
console.log(` * Found match for source file list: '${fullPath}'`);
}
}
else if (matchDist(fullPath)) {
distFiles.push(fullPath);
if (config.debug) {
console.log(` * Found match for dist file list: '${fullPath}'`);
}
}
else if (verboseDebugging) {
console.log(" - no match --> skipped");
}
}
else if (verboseDebugging) {
console.log(` * File '${file}' found on exclusion list --> skipped`);
}
} else if (verboseDebugging) {
console.log(`(File '${file}' is not part of the extension list) --> skipped`);
}
}
};
// start collection function at the current working directory (the project's root folder)
await collect(CWD);
if (!srcFiles.length) {
throwError("Could not find any source files");
} else if (!distFiles.length) {
throwError("Could not find any dist files");
}
return { srcFiles, distFiles };
};
// collect source and dist files in different vars
const { srcFiles, distFiles } = await collectFiles();
// list all
if (config.debug) {
debugInfo("Source Files Collection:");
console.table(srcFiles);
debugInfo("Dist Files Collection:");
console.table(distFiles);
}
// initialize a last modified value for the source files
// start at unix-time zero (to allow immediate overwriting)
let sTime = new Date(0);
let mostCurrentFile;
// search for the most current source file
if (verboseDebugging) {
debugInfo("Analyzing Source Files:");
}
for (const file of srcFiles) {
const { mtime } = await stat(file);
if (verboseDebugging) {
console.log(` * Source-File: '${file}\n * Modified: ${mtime}'`);
}
// overwrite source greatest modified time if the value is bigger
if (mtime > sTime) {
sTime = mtime;
mostCurrentFile = file;
}
}
// remove some milliseconds to add tolerance (according to config.tolerance)
sTime = new Date(sTime.setMilliseconds(sTime.getMilliseconds() - config.tolerance));
if (config.debug) {
debugInfo(`Most current source file is '${mostCurrentFile}' (${sTime})`);
}
// search for outdated dist files
if (verboseDebugging) {
debugInfo("Analyzing Dist Files:");
}
let outdated = false;
for (const file of distFiles) {
const { mtime } = await stat(file);
if (verboseDebugging) {
console.log(` * Dist-File: '${file}\n * Modified: ${mtime}'`);
}
// any source file, which is modified after the most current source file
// produces an error case
if (mtime < sTime) {
outdated = true;
if (!config.silent) {
console.warn(` ==> '${file}' is not up to date`);
}
}
}
// exit with an error if error case not deliberately ignored
if (outdated) {
if (config.debug) {
debugInfo("Finished tests, but found errors.");
}
if (!config.warnOnly) {
process.exitCode = 1;
} else if (config.debug) {
debugInfo("Due to current settings errors are ignored.");
}
}
else if (config.debug) {
if (!preError) {
debugInfo("Finished tests without errors.");
} else {
debugInfo("Main tests passed.");
}
}