/
cli.js
1227 lines (926 loc) · 46 KB
/
cli.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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Tests for cli.
* @author Ian Christian Myers
*/
"use strict";
/*
* NOTE: If you are adding new tests for cli.js, use verifyESLintOpts(). The
* test only needs to verify that ESLint receives the correct opts.
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const assert = require("chai").assert,
stdAssert = require("assert"),
{ ESLint } = require("../../lib/eslint"),
BuiltinRules = require("../../lib/rules"),
path = require("path"),
sinon = require("sinon"),
fs = require("fs"),
os = require("os"),
sh = require("shelljs");
const proxyquire = require("proxyquire").noCallThru().noPreserveCache();
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
describe("cli", () => {
let fixtureDir;
const log = {
info: sinon.spy(),
error: sinon.spy()
};
const RuntimeInfo = {
environment: sinon.stub(),
version: sinon.stub()
};
const cli = proxyquire("../../lib/cli", {
"./shared/logging": log,
"./shared/runtime-info": RuntimeInfo
});
/**
* Verify that ESLint class receives correct opts via await cli.execute().
* @param {string} cmd CLI command.
* @param {Object} opts Options hash that should match that received by ESLint class.
* @returns {void}
*/
async function verifyESLintOpts(cmd, opts) {
// create a fake ESLint class to test with
const fakeESLint = sinon.mock().withExactArgs(sinon.match(opts));
Object.defineProperties(fakeESLint.prototype, Object.getOwnPropertyDescriptors(ESLint.prototype));
sinon.stub(fakeESLint.prototype, "lintFiles").returns([]);
sinon.stub(fakeESLint.prototype, "loadFormatter").returns({ format: sinon.spy() });
const localCLI = proxyquire("../../lib/cli", {
"./eslint": { ESLint: fakeESLint },
"./shared/logging": log
});
await localCLI.execute(cmd);
sinon.verifyAndRestore();
}
// verifyESLintOpts
/**
* Returns the path inside of the fixture directory.
* @param {...string} args file path segments.
* @returns {string} The path inside the fixture directory.
* @private
*/
function getFixturePath(...args) {
return path.join(fixtureDir, ...args);
}
// copy into clean area so as not to get "infected" by this project's .eslintrc files
before(function() {
/*
* GitHub Actions Windows and macOS runners occasionally exhibit
* extremely slow filesystem operations, during which copying fixtures
* exceeds the default test timeout, so raise it just for this hook.
* Mocha uses `this` to set timeouts on an individual hook level.
*/
this.timeout(60 * 1000); // eslint-disable-line no-invalid-this -- Mocha API
fixtureDir = `${os.tmpdir()}/eslint/fixtures`;
sh.mkdir("-p", fixtureDir);
sh.cp("-r", "./tests/fixtures/.", fixtureDir);
});
afterEach(() => {
log.info.resetHistory();
log.error.resetHistory();
});
after(() => {
sh.rm("-r", fixtureDir);
});
describe("execute()", () => {
it("should return error when text with incorrect quotes is passed as argument", async () => {
const configFile = getFixturePath("configurations", "quotes-error.json");
const result = await cli.execute(`-c ${configFile}`, "var foo = 'bar';");
assert.strictEqual(result, 1);
});
it("should not print debug info when passed the empty string as text", async () => {
const result = await cli.execute(["--stdin", "--no-eslintrc"], "");
assert.strictEqual(result, 0);
assert.isTrue(log.info.notCalled);
});
it("should return no error when --ext .js2 is specified", async () => {
const filePath = getFixturePath("files");
const result = await cli.execute(`--ext .js2 ${filePath}`);
assert.strictEqual(result, 0);
});
it("should exit with console error when passed unsupported arguments", async () => {
const filePath = getFixturePath("files");
const result = await cli.execute(`--blah --another ${filePath}`);
assert.strictEqual(result, 2);
});
});
describe("when given a config file", () => {
it("should load the specified config file", async () => {
const configPath = getFixturePath(".eslintrc");
const filePath = getFixturePath("passing.js");
await cli.execute(`--config ${configPath} ${filePath}`);
});
});
describe("when there is a local config file", () => {
const code = "lib/cli.js";
it("should load the local config file", async () => {
// Mock CWD
process.eslintCwd = getFixturePath("configurations", "single-quotes");
await cli.execute(code);
process.eslintCwd = null;
});
});
describe("when given a config with rules with options and severity level set to error", () => {
it("should exit with an error status (1)", async () => {
const configPath = getFixturePath("configurations", "quotes-error.json");
const filePath = getFixturePath("single-quoted.js");
const code = `--no-ignore --config ${configPath} ${filePath}`;
const exitStatus = await cli.execute(code);
assert.strictEqual(exitStatus, 1);
});
});
describe("when given a config file and a directory of files", () => {
it("should load and execute without error", async () => {
const configPath = getFixturePath("configurations", "semi-error.json");
const filePath = getFixturePath("formatters");
const code = `--config ${configPath} ${filePath}`;
const exitStatus = await cli.execute(code);
assert.strictEqual(exitStatus, 0);
});
});
describe("when given a config with environment set to browser", () => {
it("should execute without any errors", async () => {
const configPath = getFixturePath("configurations", "env-browser.json");
const filePath = getFixturePath("globals-browser.js");
const code = `--config ${configPath} ${filePath}`;
const exit = await cli.execute(code);
assert.strictEqual(exit, 0);
});
});
describe("when given a config with environment set to Node.js", () => {
it("should execute without any errors", async () => {
const configPath = getFixturePath("configurations", "env-node.json");
const filePath = getFixturePath("globals-node.js");
const code = `--config ${configPath} ${filePath}`;
const exit = await cli.execute(code);
assert.strictEqual(exit, 0);
});
});
describe("when given a config with environment set to Nashorn", () => {
it("should execute without any errors", async () => {
const configPath = getFixturePath("configurations", "env-nashorn.json");
const filePath = getFixturePath("globals-nashorn.js");
const code = `--config ${configPath} ${filePath}`;
const exit = await cli.execute(code);
assert.strictEqual(exit, 0);
});
});
describe("when given a config with environment set to WebExtensions", () => {
it("should execute without any errors", async () => {
const configPath = getFixturePath("configurations", "env-webextensions.json");
const filePath = getFixturePath("globals-webextensions.js");
const code = `--config ${configPath} ${filePath}`;
const exit = await cli.execute(code);
assert.strictEqual(exit, 0);
});
});
describe("when given a valid built-in formatter name", () => {
it("should execute without any errors", async () => {
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`-f checkstyle ${filePath}`);
assert.strictEqual(exit, 0);
});
});
describe("when given a valid built-in formatter name that uses rules meta.", () => {
it("should execute without any errors", async () => {
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`-f json-with-metadata ${filePath} --no-eslintrc`);
assert.strictEqual(exit, 0);
// Check metadata.
const { metadata } = JSON.parse(log.info.args[0][0]);
const expectedMetadata = {
cwd: process.cwd(),
rulesMeta: Array.from(BuiltinRules).reduce((obj, [ruleId, rule]) => {
obj[ruleId] = rule.meta;
return obj;
}, {})
};
assert.deepStrictEqual(metadata, expectedMetadata);
});
});
describe("when given an invalid built-in formatter name", () => {
it("should execute with error", async () => {
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`-f fakeformatter ${filePath}`);
assert.strictEqual(exit, 2);
});
});
describe("when given a valid formatter path", () => {
it("should execute without any errors", async () => {
const formatterPath = getFixturePath("formatters", "simple.js");
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`-f ${formatterPath} ${filePath}`);
assert.strictEqual(exit, 0);
});
});
describe("when given an invalid formatter path", () => {
it("should execute with error", async () => {
const formatterPath = getFixturePath("formatters", "file-does-not-exist.js");
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`-f ${formatterPath} ${filePath}`);
assert.strictEqual(exit, 2);
});
});
describe("when given an async formatter path", () => {
it("should execute without any errors", async () => {
const formatterPath = getFixturePath("formatters", "async.js");
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`-f ${formatterPath} ${filePath}`);
assert.strictEqual(log.info.getCall(0).args[0], "from async formatter");
assert.strictEqual(exit, 0);
});
});
describe("when executing a file with a lint error", () => {
it("should exit with error", async () => {
const filePath = getFixturePath("undef.js");
const code = `--no-ignore --rule no-undef:2 ${filePath}`;
const exit = await cli.execute(code);
assert.strictEqual(exit, 1);
});
});
describe("when using --fix-type without --fix or --fix-dry-run", () => {
it("should exit with error", async () => {
const filePath = getFixturePath("passing.js");
const code = `--fix-type suggestion ${filePath}`;
const exit = await cli.execute(code);
assert.strictEqual(exit, 2);
});
});
describe("when executing a file with a syntax error", () => {
it("should exit with error", async () => {
const filePath = getFixturePath("syntax-error.js");
const exit = await cli.execute(`--no-ignore ${filePath}`);
assert.strictEqual(exit, 1);
});
});
describe("when calling execute more than once", () => {
it("should not print the results from previous execution", async () => {
const filePath = getFixturePath("missing-semicolon.js");
const passingPath = getFixturePath("passing.js");
await cli.execute(`--no-ignore --rule semi:2 ${filePath}`);
assert.isTrue(log.info.called, "Log should have been called.");
log.info.resetHistory();
await cli.execute(`--no-ignore --rule semi:2 ${passingPath}`);
assert.isTrue(log.info.notCalled);
});
});
describe("when executing with version flag", () => {
it("should print out current version", async () => {
assert.strictEqual(await cli.execute("-v"), 0);
assert.strictEqual(log.info.callCount, 1);
});
});
describe("when executing with env-info flag", () => {
it("should print out environment information", async () => {
assert.strictEqual(await cli.execute("--env-info"), 0);
assert.strictEqual(log.info.callCount, 1);
});
it("should print error message and return error code", async () => {
RuntimeInfo.environment.throws("There was an error!");
assert.strictEqual(await cli.execute("--env-info"), 2);
assert.strictEqual(log.error.callCount, 1);
});
});
describe("when executing without no-error-on-unmatched-pattern flag", () => {
it("should throw an error on unmatched glob pattern", async () => {
const filePath = getFixturePath("unmatched-patterns");
const globPattern = "*.js3";
await stdAssert.rejects(async () => {
await cli.execute(`"${filePath}/${globPattern}"`);
}, new Error(`No files matching '${filePath}/${globPattern}' were found.`));
});
it("should throw an error on unmatched --ext", async () => {
const filePath = getFixturePath("unmatched-patterns");
const extension = ".js3";
await stdAssert.rejects(async () => {
await cli.execute(`--ext ${extension} ${filePath}`);
}, `No files matching '${filePath}' were found`);
});
});
describe("when executing with no-error-on-unmatched-pattern flag", () => {
it("should not throw an error on unmatched node glob syntax patterns", async () => {
const filePath = getFixturePath("unmatched-patterns");
const exit = await cli.execute(`--no-error-on-unmatched-pattern "${filePath}/*.js3"`);
assert.strictEqual(exit, 0);
});
it("should not throw an error on unmatched --ext", async () => {
const filePath = getFixturePath("unmatched-patterns");
const exit = await cli.execute(`--no-error-on-unmatched-pattern --ext .js3 ${filePath}`);
assert.strictEqual(exit, 0);
});
});
describe("when executing with no-error-on-unmatched-pattern flag and multiple patterns", () => {
it("should not throw an error on multiple unmatched node glob syntax patterns", async () => {
const filePath = getFixturePath("unmatched-patterns");
const exit = await cli.execute(`--no-error-on-unmatched-pattern ${filePath}/*.js3 ${filePath}/*.js4`);
assert.strictEqual(exit, 0);
});
it("should still throw an error on when a matched pattern has lint errors", async () => {
const filePath = getFixturePath("unmatched-patterns");
const exit = await cli.execute(`--no-error-on-unmatched-pattern ${filePath}/*.js3 ${filePath}/*.js`);
assert.strictEqual(exit, 1);
});
});
describe("when executing with no-error-on-unmatched-pattern flag and multiple --ext arguments", () => {
it("should not throw an error on multiple unmatched --ext arguments", async () => {
const filePath = getFixturePath("unmatched-patterns");
const exit = await cli.execute(`--no-error-on-unmatched-pattern --ext .js3 --ext .js4 ${filePath}`);
assert.strictEqual(exit, 0);
});
it("should still throw an error on when a matched pattern has lint errors", async () => {
const filePath = getFixturePath("unmatched-patterns");
const exit = await cli.execute(`--no-error-on-unmatched-pattern --ext .js3 --ext .js ${filePath}`);
assert.strictEqual(exit, 1);
});
});
describe("when executing with help flag", () => {
it("should print out help", async () => {
assert.strictEqual(await cli.execute("-h"), 0);
assert.strictEqual(log.info.callCount, 1);
});
});
describe("when given a directory with eslint excluded files in the directory", () => {
it("should throw an error and not process any files", async () => {
const ignorePath = getFixturePath(".eslintignore");
const filePath = getFixturePath("cli");
await stdAssert.rejects(async () => {
await cli.execute(`--ignore-path ${ignorePath} ${filePath}`);
}, new Error(`All files matched by '${filePath}' are ignored.`));
});
});
describe("when given a file in excluded files list", () => {
it("should not process the file", async () => {
const ignorePath = getFixturePath(".eslintignore");
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`--ignore-path ${ignorePath} ${filePath}`);
// a warning about the ignored file
assert.isTrue(log.info.called);
assert.strictEqual(exit, 0);
});
it("should process the file when forced", async () => {
const ignorePath = getFixturePath(".eslintignore");
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`--ignore-path ${ignorePath} --no-ignore ${filePath}`);
// no warnings
assert.isFalse(log.info.called);
assert.strictEqual(exit, 0);
});
});
describe("when given a pattern to ignore", () => {
it("should not process any files", async () => {
const ignoredFile = getFixturePath("cli/syntax-error.js");
const filePath = getFixturePath("cli/passing.js");
const exit = await cli.execute(`--ignore-pattern cli/ ${ignoredFile} ${filePath}`);
// warnings about the ignored files
assert.isTrue(log.info.called);
assert.strictEqual(exit, 0);
});
});
describe("when given patterns to ignore", () => {
it("should not process any matching files", async () => {
const ignorePaths = ["a", "b"];
const cmd = ignorePaths.map(ignorePath => `--ignore-pattern ${ignorePath}`).concat(".").join(" ");
const opts = {
overrideConfig: {
ignorePatterns: ignorePaths
}
};
await verifyESLintOpts(cmd, opts);
});
});
describe("when executing a file with a shebang", () => {
it("should execute without error", async () => {
const filePath = getFixturePath("shebang.js");
const exit = await cli.execute(`--no-ignore ${filePath}`);
assert.strictEqual(exit, 0);
});
});
describe("when loading a custom rule", () => {
it("should return an error when rule isn't found", async () => {
const rulesPath = getFixturePath("rules", "wrong");
const configPath = getFixturePath("rules", "eslint.json");
const filePath = getFixturePath("rules", "test", "test-custom-rule.js");
const code = `--rulesdir ${rulesPath} --config ${configPath} --no-ignore ${filePath}`;
await stdAssert.rejects(async () => {
const exit = await cli.execute(code);
assert.strictEqual(exit, 2);
}, /Error while loading rule 'custom-rule': Boom!/u);
});
it("should return a warning when rule is matched", async () => {
const rulesPath = getFixturePath("rules");
const configPath = getFixturePath("rules", "eslint.json");
const filePath = getFixturePath("rules", "test", "test-custom-rule.js");
const code = `--rulesdir ${rulesPath} --config ${configPath} --no-ignore ${filePath}`;
await cli.execute(code);
assert.isTrue(log.info.calledOnce);
assert.isTrue(log.info.neverCalledWith(""));
});
it("should return warnings from multiple rules in different directories", async () => {
const rulesPath = getFixturePath("rules", "dir1");
const rulesPath2 = getFixturePath("rules", "dir2");
const configPath = getFixturePath("rules", "multi-rulesdirs.json");
const filePath = getFixturePath("rules", "test-multi-rulesdirs.js");
const code = `--rulesdir ${rulesPath} --rulesdir ${rulesPath2} --config ${configPath} --no-ignore ${filePath}`;
const exit = await cli.execute(code);
const call = log.info.getCall(0);
assert.isTrue(log.info.calledOnce);
assert.isTrue(call.args[0].indexOf("String!") > -1);
assert.isTrue(call.args[0].indexOf("Literal!") > -1);
assert.isTrue(call.args[0].indexOf("2 problems") > -1);
assert.isTrue(log.info.neverCalledWith(""));
assert.strictEqual(exit, 1);
});
});
describe("when executing with no-eslintrc flag", () => {
it("should ignore a local config file", async () => {
const filePath = getFixturePath("eslintrc", "quotes.js");
const exit = await cli.execute(`--no-eslintrc --no-ignore ${filePath}`);
assert.isTrue(log.info.notCalled);
assert.strictEqual(exit, 0);
});
});
describe("when executing without no-eslintrc flag", () => {
it("should load a local config file", async () => {
const filePath = getFixturePath("eslintrc", "quotes.js");
const exit = await cli.execute(`--no-ignore ${filePath}`);
assert.isTrue(log.info.calledOnce);
assert.strictEqual(exit, 1);
});
});
describe("when executing without env flag", () => {
it("should not define environment-specific globals", async () => {
const files = [
getFixturePath("globals-browser.js"),
getFixturePath("globals-node.js")
];
await cli.execute(`--no-eslintrc --config ./conf/eslint-recommended.js --no-ignore ${files.join(" ")}`);
assert.strictEqual(log.info.args[0][0].split("\n").length, 10);
});
});
describe("when executing with global flag", () => {
it("should default defined variables to read-only", async () => {
const filePath = getFixturePath("undef.js");
const exit = await cli.execute(`--global baz,bat --no-ignore --rule no-global-assign:2 ${filePath}`);
assert.isTrue(log.info.calledOnce);
assert.strictEqual(exit, 1);
});
it("should allow defining writable global variables", async () => {
const filePath = getFixturePath("undef.js");
const exit = await cli.execute(`--global baz:false,bat:true --no-ignore ${filePath}`);
assert.isTrue(log.info.notCalled);
assert.strictEqual(exit, 0);
});
it("should allow defining variables with multiple flags", async () => {
const filePath = getFixturePath("undef.js");
const exit = await cli.execute(`--global baz --global bat:true --no-ignore ${filePath}`);
assert.isTrue(log.info.notCalled);
assert.strictEqual(exit, 0);
});
});
describe("when supplied with rule flag and severity level set to error", () => {
it("should exit with an error status (2)", async () => {
const filePath = getFixturePath("single-quoted.js");
const code = `--no-ignore --rule 'quotes: [2, double]' ${filePath}`;
const exitStatus = await cli.execute(code);
assert.strictEqual(exitStatus, 1);
});
});
describe("when the quiet option is enabled", () => {
it("should only print error", async () => {
const filePath = getFixturePath("single-quoted.js");
const cliArgs = `--no-ignore --quiet -f compact --rule 'quotes: [2, double]' --rule 'no-unused-vars: 1' ${filePath}`;
await cli.execute(cliArgs);
sinon.assert.calledOnce(log.info);
const formattedOutput = log.info.firstCall.args[0];
assert.include(formattedOutput, "Error");
assert.notInclude(formattedOutput, "Warning");
});
it("should print nothing if there are no errors", async () => {
const filePath = getFixturePath("single-quoted.js");
const cliArgs = `--quiet -f compact --rule 'quotes: [1, double]' --rule 'no-unused-vars: 1' ${filePath}`;
await cli.execute(cliArgs);
sinon.assert.notCalled(log.info);
});
});
describe("when supplied with report output file path", () => {
afterEach(() => {
sh.rm("-rf", "tests/output");
});
it("should write the file and create dirs if they don't exist", async () => {
const filePath = getFixturePath("single-quoted.js");
const code = `--no-ignore --rule 'quotes: [1, double]' --o tests/output/eslint-output.txt ${filePath}`;
await cli.execute(code);
assert.include(fs.readFileSync("tests/output/eslint-output.txt", "utf8"), filePath);
assert.isTrue(log.info.notCalled);
});
it("should return an error if the path is a directory", async () => {
const filePath = getFixturePath("single-quoted.js");
const code = `--no-ignore --rule 'quotes: [1, double]' --o tests/output ${filePath}`;
fs.mkdirSync("tests/output");
const exit = await cli.execute(code);
assert.strictEqual(exit, 2);
assert.isTrue(log.info.notCalled);
assert.isTrue(log.error.calledOnce);
});
it("should return an error if the path could not be written to", async () => {
const filePath = getFixturePath("single-quoted.js");
const code = `--no-ignore --rule 'quotes: [1, double]' --o tests/output/eslint-output.txt ${filePath}`;
fs.writeFileSync("tests/output", "foo");
const exit = await cli.execute(code);
assert.strictEqual(exit, 2);
assert.isTrue(log.info.notCalled);
assert.isTrue(log.error.calledOnce);
});
});
describe("when supplied with a plugin", () => {
it("should pass plugins to ESLint", async () => {
const examplePluginName = "eslint-plugin-example";
await verifyESLintOpts(`--no-ignore --plugin ${examplePluginName} foo.js`, {
overrideConfig: {
plugins: [examplePluginName]
}
});
});
});
describe("when supplied with a plugin-loading path", () => {
it("should pass the option to ESLint", async () => {
const examplePluginDirPath = "foo/bar";
await verifyESLintOpts(`--resolve-plugins-relative-to ${examplePluginDirPath} foo.js`, {
resolvePluginsRelativeTo: examplePluginDirPath
});
});
});
describe("when given an parser name", () => {
it("should exit with a fatal error if parser is invalid", async () => {
const filePath = getFixturePath("passing.js");
await stdAssert.rejects(async () => await cli.execute(`--no-ignore --parser test111 ${filePath}`), "Cannot find module 'test111'");
});
it("should exit with no error if parser is valid", async () => {
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`--no-ignore --parser espree ${filePath}`);
assert.strictEqual(exit, 0);
});
});
describe("when given parser options", () => {
it("should exit with error if parser options are invalid", async () => {
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`--no-ignore --parser-options test111 ${filePath}`);
assert.strictEqual(exit, 2);
});
it("should exit with no error if parser is valid", async () => {
const filePath = getFixturePath("passing.js");
const exit = await cli.execute(`--no-ignore --parser-options=ecmaVersion:6 ${filePath}`);
assert.strictEqual(exit, 0);
});
it("should exit with an error on ecmaVersion 7 feature in ecmaVersion 6", async () => {
const filePath = getFixturePath("passing-es7.js");
const exit = await cli.execute(`--no-ignore --parser-options=ecmaVersion:6 ${filePath}`);
assert.strictEqual(exit, 1);
});
it("should exit with no error on ecmaVersion 7 feature in ecmaVersion 7", async () => {
const filePath = getFixturePath("passing-es7.js");
const exit = await cli.execute(`--no-ignore --parser-options=ecmaVersion:7 ${filePath}`);
assert.strictEqual(exit, 0);
});
it("should exit with no error on ecmaVersion 7 feature with config ecmaVersion 6 and command line ecmaVersion 7", async () => {
const configPath = getFixturePath("configurations", "es6.json");
const filePath = getFixturePath("passing-es7.js");
const exit = await cli.execute(`--no-ignore --config ${configPath} --parser-options=ecmaVersion:7 ${filePath}`);
assert.strictEqual(exit, 0);
});
});
describe("when given the max-warnings flag", () => {
it("should not change exit code if warning count under threshold", async () => {
const filePath = getFixturePath("max-warnings");
const exitCode = await cli.execute(`--no-ignore --max-warnings 10 ${filePath}`);
assert.strictEqual(exitCode, 0);
});
it("should exit with exit code 1 if warning count exceeds threshold", async () => {
const filePath = getFixturePath("max-warnings");
const exitCode = await cli.execute(`--no-ignore --max-warnings 5 ${filePath}`);
assert.strictEqual(exitCode, 1);
assert.ok(log.error.calledOnce);
assert.include(log.error.getCall(0).args[0], "ESLint found too many warnings");
});
it("should exit with exit code 1 without printing warnings if the quiet option is enabled and warning count exceeds threshold", async () => {
const filePath = getFixturePath("max-warnings");
const exitCode = await cli.execute(`--no-ignore --quiet --max-warnings 5 ${filePath}`);
assert.strictEqual(exitCode, 1);
assert.ok(log.error.calledOnce);
assert.include(log.error.getCall(0).args[0], "ESLint found too many warnings");
assert.ok(log.info.notCalled); // didn't print warnings
});
it("should not change exit code if warning count equals threshold", async () => {
const filePath = getFixturePath("max-warnings");
const exitCode = await cli.execute(`--no-ignore --max-warnings 6 ${filePath}`);
assert.strictEqual(exitCode, 0);
});
it("should not change exit code if flag is not specified and there are warnings", async () => {
const filePath = getFixturePath("max-warnings");
const exitCode = await cli.execute(filePath);
assert.strictEqual(exitCode, 0);
});
});
describe("when given the exit-on-fatal-error flag", () => {
it("should not change exit code if no fatal errors are reported", async () => {
const filePath = getFixturePath("exit-on-fatal-error", "no-fatal-error.js");
const exitCode = await cli.execute(`--no-ignore --exit-on-fatal-error ${filePath}`);
assert.strictEqual(exitCode, 0);
});
it("should exit with exit code 1 if no fatal errors are found, but rule violations are found", async () => {
const filePath = getFixturePath("exit-on-fatal-error", "no-fatal-error-rule-violation.js");
const exitCode = await cli.execute(`--no-ignore --exit-on-fatal-error ${filePath}`);
assert.strictEqual(exitCode, 1);
});
it("should exit with exit code 2 if fatal error is found", async () => {
const filePath = getFixturePath("exit-on-fatal-error", "fatal-error.js");
const exitCode = await cli.execute(`--no-ignore --exit-on-fatal-error ${filePath}`);
assert.strictEqual(exitCode, 2);
});
it("should exit with exit code 2 if fatal error is found in any file", async () => {
const filePath = getFixturePath("exit-on-fatal-error");
const exitCode = await cli.execute(`--no-ignore --exit-on-fatal-error ${filePath}`);
assert.strictEqual(exitCode, 2);
});
});
describe("when passed --no-inline-config", () => {
let localCLI;
afterEach(() => {
sinon.verifyAndRestore();
});
it("should pass allowInlineConfig:false to ESLint when --no-inline-config is used", async () => {
// create a fake ESLint class to test with
const fakeESLint = sinon.mock().withExactArgs(sinon.match({ allowInlineConfig: false }));
Object.defineProperties(fakeESLint.prototype, Object.getOwnPropertyDescriptors(ESLint.prototype));
sinon.stub(fakeESLint.prototype, "lintFiles").returns([{
filePath: "./foo.js",
output: "bar",
messages: [
{
severity: 2,
message: "Fake message"
}
],
errorCount: 1,
warningCount: 0
}]);
sinon.stub(fakeESLint.prototype, "loadFormatter").returns({ format: () => "done" });
fakeESLint.outputFixes = sinon.stub();
localCLI = proxyquire("../../lib/cli", {
"./eslint": { ESLint: fakeESLint },
"./shared/logging": log
});
await localCLI.execute("--no-inline-config .");
});
it("should not error and allowInlineConfig should be true by default", async () => {
// create a fake ESLint class to test with
const fakeESLint = sinon.mock().withExactArgs(sinon.match({ allowInlineConfig: true }));
Object.defineProperties(fakeESLint.prototype, Object.getOwnPropertyDescriptors(ESLint.prototype));
sinon.stub(fakeESLint.prototype, "lintFiles").returns([]);
sinon.stub(fakeESLint.prototype, "loadFormatter").returns({ format: () => "done" });
fakeESLint.outputFixes = sinon.stub();
localCLI = proxyquire("../../lib/cli", {
"./eslint": { ESLint: fakeESLint },
"./shared/logging": log
});
const exitCode = await localCLI.execute(".");
assert.strictEqual(exitCode, 0);
});
});
describe("when passed --fix", () => {
let localCLI;
afterEach(() => {
sinon.verifyAndRestore();
});
it("should pass fix:true to ESLint when executing on files", async () => {
// create a fake ESLint class to test with
const fakeESLint = sinon.mock().withExactArgs(sinon.match({ fix: true }));
Object.defineProperties(fakeESLint.prototype, Object.getOwnPropertyDescriptors(ESLint.prototype));
sinon.stub(fakeESLint.prototype, "lintFiles").returns([]);
sinon.stub(fakeESLint.prototype, "loadFormatter").returns({ format: () => "done" });
fakeESLint.outputFixes = sinon.mock().once();
localCLI = proxyquire("../../lib/cli", {
"./eslint": { ESLint: fakeESLint },
"./shared/logging": log
});
const exitCode = await localCLI.execute("--fix .");
assert.strictEqual(exitCode, 0);
});
it("should rewrite files when in fix mode", async () => {
const report = [{
filePath: "./foo.js",
output: "bar",
messages: [
{
severity: 2,
message: "Fake message"
}
],
errorCount: 1,
warningCount: 0
}];
// create a fake ESLint class to test with
const fakeESLint = sinon.mock().withExactArgs(sinon.match({ fix: true }));
Object.defineProperties(fakeESLint.prototype, Object.getOwnPropertyDescriptors(ESLint.prototype));
sinon.stub(fakeESLint.prototype, "lintFiles").returns(report);
sinon.stub(fakeESLint.prototype, "loadFormatter").returns({ format: () => "done" });
fakeESLint.outputFixes = sinon.mock().withExactArgs(report);
localCLI = proxyquire("../../lib/cli", {
"./eslint": { ESLint: fakeESLint },
"./shared/logging": log
});
const exitCode = await localCLI.execute("--fix .");
assert.strictEqual(exitCode, 1);
});
it("should provide fix predicate and rewrite files when in fix mode and quiet mode", async () => {
const report = [{
filePath: "./foo.js",
output: "bar",
messages: [
{
severity: 1,
message: "Fake message"
}
],
errorCount: 0,
warningCount: 1
}];
// create a fake ESLint class to test with
const fakeESLint = sinon.mock().withExactArgs(sinon.match({ fix: sinon.match.func }));
Object.defineProperties(fakeESLint.prototype, Object.getOwnPropertyDescriptors(ESLint.prototype));
sinon.stub(fakeESLint.prototype, "lintFiles").returns(report);
sinon.stub(fakeESLint.prototype, "loadFormatter").returns({ format: () => "done" });
fakeESLint.getErrorResults = sinon.stub().returns([]);
fakeESLint.outputFixes = sinon.mock().withExactArgs(report);
localCLI = proxyquire("../../lib/cli", {
"./eslint": { ESLint: fakeESLint },
"./shared/logging": log