/
cli.test.ts
528 lines (488 loc) · 22.7 KB
/
cli.test.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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import { expect } from 'chai';
import gfs from 'graceful-fs';
const { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, rmdirSync, statSync, unlinkSync, writeSync } = gfs;
import mocha from 'mocha';
const { describe, it } = mocha;
import { dirname, join } from 'path';
import { env } from 'process';
import sc from 'supports-color';
const { stdout: supportsColorStdout } = sc;
import { fileURLToPath } from 'url';
import { format as printf } from 'util';
import { execute as run } from './cmd.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const LIB_DIR = join(__dirname, env.APP_CODE_PATH || '../../dist');
// os.tmpdir() is not used here, to stay inside project folder
const TMP_DIR = join(__dirname, env.PROJECT_TARGET_PATH || '../.tmp-dir');
// See https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
/*eslint max-len: ["off"]*/
const semverPattern = /(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?/.source;
function createTempDir(format: string, path = TMP_DIR, suffix = 'fse-cli-test-') {
try {
mkdirSync(path, { recursive: true });
const newDirPath = mkdtempSync(join(path, suffix));
return newDirPath;
} catch (e) {
throw new Error(printf(format, path, suffix, e));
}
}
const DEBUG = env.CLI_TEST_DEBUG && env.CLI_TEST_DEBUG === 'true';
describe("The fs-extra CLI", () => {
describe("Calling CLI", () => {
it("When no task is specified, an error message must be log", function (done) { // don't pass 'done' as argument if async/await
const script = `${LIB_DIR}`; // ie index.js
const args = {};
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
const foundRegex = new RegExp('^ERROR:\\s+No\\s+task\\s+specified', 'm');
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(result).to.match(foundRegex);
done();
})
.catch(error => {
done(error);
});
});
it("When an unknown task is specified, an error message must be log", function (done) { // don't pass 'done' as argument! with async/await
const script = `${LIB_DIR}`; // ie index.js
const unknownTask = 'unknown';
const args = { app: [unknownTask] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
const foundRegex = new RegExp(`^ERROR:\\s+Unknown\\s+task\\s+'${unknownTask}'`, 'm');
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(result).to.match(foundRegex);
done();
})
.catch(error => {
done(error);
});
});
});
describe("Calling 'emptyDir'", () => {
it("When existing directory, it will be purged", function (done) { // don't pass 'done' as argument! with async/await
const dirToBePurged = createTempDir("Test 'Purge a directory', unable to create a temporary directory based on '%s' & '%s': %s");
const fileToBeRemoved = join(dirToBePurged, 'toBeRemoved.txt');
closeSync(openSync(fileToBeRemoved, 'w'));
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['emptyDir', dirToBePurged] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
run(
script,
args,
userInputs,
options
)
.then(() => {
expect(existsSync(dirToBePurged), "directory should still exists").to.be.true;
expect(!existsSync(fileToBeRemoved), "file should have been removed").to.be.true;
done();
})
.catch(error => {
done(error);
})
.finally(() => {
try {
rmdirSync(dirToBePurged, { recursive: true });
} catch (e) { /* do nothing */ }
});
});
});
describe("Calling 'remove'", () => {
// first check if the job is done
it("When existing directory, it will be removed", function (done) { // don't pass 'done' as argument! with async/await
const dirToBeRemoved = createTempDir("Test 'Remove a directory', unable to create a temporary directory based on '%s' & '%s': %s");
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['remove', dirToBeRemoved] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
const foundRegex = new RegExp('^\\s*Removing\\s+directory\\s', 'm');
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(existsSync(dirToBeRemoved)).to.be.false;
expect(result).to.match(foundRegex);
done();
})
.catch(error => {
done(error);
})
.finally(() => {
try {
rmdirSync(dirToBeRemoved, { recursive: true });
} catch (e) { /* do nothing */ }
});
});
it("When existing directory, it will be removed with '--quiet'", function (done) { // don't pass 'done' as argument! with async/await
const dirToBeRemoved = createTempDir("Test 'Remove a directory', unable to create a temporary directory based on '%s' & '%s': %s");
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['remove', '-q', dirToBeRemoved] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(existsSync(dirToBeRemoved)).to.be.false;
expect((result as string).trim()).to.be.empty;
done();
})
.catch(error => {
done(error);
})
.finally(() => {
try {
rmdirSync(dirToBeRemoved, { recursive: true });
} catch (e) { /* do nothing */ }
});
});
it("When existing directory, it will be removed with 'FSE_CLI_QUIET'", function (done) { // don't pass 'done' as argument! with async/await
const dirToBeRemoved = createTempDir("Test 'Remove a directory', unable to create a temporary directory based on '%s' & '%s': %s");
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['remove', dirToBeRemoved] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: {
DEBUG, // false by default
FSE_CLI_QUIET: 'true' // false by default
}
};
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(existsSync(dirToBeRemoved)).to.be.false;
expect((result as string).trim()).to.be.empty;
done();
})
.catch(error => {
done(error);
})
.finally(() => {
try {
rmdirSync(dirToBeRemoved, { recursive: true });
} catch (e) { /* do nothing */ }
});
});
});
describe("Calling 'mkdir'", () => {
// first check if the job is done
it("When non existing directory, it will be created", function (done) { // don't pass 'done' as argument! with async/await
const baseDir = createTempDir("Test 'Create a directory', unable to create a temporary parent directory based on '%s' & '%s': %s");
const dirToBeCreated = join(baseDir, 'theNewDir');
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['mkdirp', dirToBeCreated] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
const foundRegex = new RegExp('^\\s*Checking\\s+if\\s+existing\\s+and,\\s+if\\s+not,\\s+creating\\s+directory\\s', 'm');
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(existsSync(dirToBeCreated)).to.be.true;
expect(statSync(dirToBeCreated).isDirectory()).to.be.true;
expect(result).to.match(foundRegex);
done();
})
.catch(error => {
done(error);
})
.finally(() => {
// to avoid ENOTEMPTY with the second rmdirSync, even with `recursive: true`
rmdirSync(dirToBeCreated, { recursive: true });
rmdirSync(baseDir, { recursive: true });
});
});
it("When non existing directory, it will be created with '--quiet'", function (done) { // don't pass 'done' as argument! with async/await
const baseDir = createTempDir("Test 'Create a directory', unable to create a temporary parent directory based on '%s' & '%s': %s");
const dirToBeCreated = join(baseDir, 'theNewDir');
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['mkdirp', '-q', dirToBeCreated] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
run(
script,
args,
userInputs,
options
)
.then(result => {
expect(existsSync(dirToBeCreated)).to.be.true;
expect(statSync(dirToBeCreated).isDirectory()).to.be.true;
expect((result as string).trim()).to.be.empty;
done();
})
.catch(error => {
done(error);
})
.finally(() => {
// to avoid ENOTEMPTY with the second rmdirSync, even with `recursive: true`
rmdirSync(dirToBeCreated, { recursive: true });
rmdirSync(baseDir, { recursive: true });
});
});
});
describe("Calling 'touch'", () => {
// first check if the job is done
it("When non existing file, it will be created", function (done) { // don't pass 'done' as argument! with async/await
const baseDir = createTempDir("Test 'Create a file', unable to create a temporary parent directory based on '%s' & '%s': %s");
const fileToBeCreated = join(baseDir, 'theNewFile');
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['ensureFile', fileToBeCreated] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0 , // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
run(
script,
args,
userInputs,
options
)
.then(() => {
expect(existsSync(fileToBeCreated), "No new file").to.be.true;
expect(statSync(fileToBeCreated).isFile(), "New item is not a file").to.be.true;
done();
})
.catch(error => {
done(error);
})
.finally(() => {
// to avoid ENOTEMPTY with the latter rmdirSync, even with `recursive: true`
try {
unlinkSync(fileToBeCreated);
} catch (e) { /* do nothing */ }
rmdirSync(baseDir, { recursive: true });
});
});
});
describe("Calling 'copy'", () => {
// first check if the job is done
it("When destination file doesn't exist, a new file is created with the same content", function (done) { // don't pass 'done' as argument! with async/await
const destDirName = "sub-dir-";
const srcFileName = "theFileToBeCopied";
const srcFileContent = 'theFileToBeCopied-content';
const destFileName = "theFileCopy";
const baseDir = createTempDir("Test 'Copy a file', unable to create a temporary source directory based on '%s' & '%s': %s");
const destDirPath = createTempDir("Test 'Copy a file', unable to create a temporary destination directory based on '%s' & '%s': %s", baseDir, destDirName);
const fileToBeCopied = join(baseDir, srcFileName);
// dixit fs-extra doc, "if src is a file, dest cannot be a directory"
const fileCopy = join(destDirPath, destFileName);
try {
const fileToBeCopiedDescriptor = openSync(fileToBeCopied, 'w');
writeSync(fileToBeCopiedDescriptor, srcFileContent, undefined, 'utf8');
closeSync(fileToBeCopiedDescriptor);
} catch (e) {
throw new Error(printf("Test 'Copy a file', unable to create a temporary file '%s': %s", fileToBeCopied, e));
}
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['copy', fileToBeCopied, fileCopy] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
run(
script,
args,
userInputs,
options
)
.then(() => {
expect(existsSync(fileCopy), "no copied file").to.be.true;
expect(statSync(fileCopy).isFile(), "new item is not a file").to.be.true;
expect(readFileSync(fileCopy, { encoding: 'utf8' })).to.equal(srcFileContent);
done();
})
.catch(error => {
done(error);
})
.finally(() => {
// to avoid ENOTEMPTY with the latter rmdirSync-s, even with `recursive: true`
try {
unlinkSync(fileCopy);
} catch (e) { /* do nothing */ }
try {
unlinkSync(fileToBeCopied);
} catch (e) { /* do nothing */ }
rmdirSync(destDirPath, { recursive: true });
rmdirSync(baseDir, { recursive: true });
});
});
});
describe("Calling 'move'", () => {
// first check if the job is done
it("Then source has been removed, destination exists and content is untouched", function (done) { // don't pass 'done' as argument! with async/await
const destDirName = "sub-dir-";
const srcFileName = "theFileToBeMoved";
const srcFileContent = 'theFileToBeMoved-content';
const baseDir = createTempDir("Test 'Move a file', unable to create a temporary source directory based on '%s' & '%s': %s");
const destDirPath = createTempDir("Test 'Move a file', unable to create a temporary destination directory based on '%s' & '%s': %s", baseDir, destDirName);
const fileToBeMovedPath = join(baseDir, srcFileName);
const movedFilePath = join(destDirPath, srcFileName);
try {
const fileToBeMovedDescriptor = openSync(fileToBeMovedPath, 'w');
writeSync(fileToBeMovedDescriptor, srcFileContent, undefined, 'utf8');
closeSync(fileToBeMovedDescriptor);
} catch (e) {
throw new Error(printf("Test 'Move a file', unable to create a temporary file '%s': %s", fileToBeMovedPath, e));
}
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['move', fileToBeMovedPath, movedFilePath] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
run(
script,
args,
userInputs,
options
)
.then(() => {
expect(existsSync(fileToBeMovedPath), "source file still existing").to.be.false;
expect(existsSync(movedFilePath), "no moved file").to.be.true;
expect(statSync(movedFilePath).isFile(), "new item is not a file").to.be.true;
expect(readFileSync(movedFilePath, { encoding: 'utf8' })).to.equal(srcFileContent);
done();
})
.catch(error => {
done(error);
})
.finally(() => {
// to avoid ENOTEMPTY with the latter rmdirSync-s, even with `recursive: true`
try {
unlinkSync(movedFilePath);
} catch (e) { /* do nothing */ }
try {
unlinkSync(fileToBeMovedPath);
} catch (e) { /* do nothing */ }
rmdirSync(destDirPath, { recursive: true });
rmdirSync(baseDir, { recursive: true });
});
});
});
describe("Calling 'version'", () => {
it("Show version", function (done) { // don't pass 'done' as argument with async/await
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['version'] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: { DEBUG } // false by default
};
const foundRegex = new RegExp(`^@atao60/fse-cli\\s+${semverPattern}\\s+\\(fs-extra\\s+${semverPattern}\\)$`);
run(
script,
args,
userInputs,
options
)
.then(result => {
expect((result as string).trim()).to.match(foundRegex);
done();
})
.catch(error => {
done(error);
});
});
});
describe("Calling 'help'", () => {
it("Show help", function (done) { // don't pass 'done' as argument with async/await
const script = `${LIB_DIR}`; // ie index.js
const args = { app: ['help'] };
const userInputs = [];
const options = {
// timeout: 200, // 100 ms by default
// maxTimeout: 0, // 10 s by default; if "0" then no timeout
env: {
DEBUG, // false by default
// See Add ability to force disable colors with an environment variable #31
// https://github.com/chalk/supports-color/pull/31
FORCE_COLOR: supportsColorStdout ? supportsColorStdout.level : 0
}
};
const versionRegex = new RegExp(`^@atao60/fse-cli\\s+${semverPattern}\\s+\\(fs-extra\\s+${semverPattern}\\)`);
const manualRegex = new RegExp(`File system extra CLI - Usage`, 'm');
run(
script,
args,
userInputs,
options
)
.then(result => {
const help = result as string;
expect(help.trim()).to.match(versionRegex); // check package version was retrieved from npm-shrinkwrap.json
expect(help).to.match(manualRegex); // check help content was retrieved from USAGE file
// eslint-disable-next-line no-control-regex
expect(help.replace(/\x1b\[([0-9;]*[mGKF])/g, '\\x1b[$1')).to.match(/\\x1b\[[0-9;]*[mGKF]/); // just check if at least one style ANSI code is present
done();
})
.catch(error => {
done(error);
});
});
});
});