1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | const fs = require('fs');
|
12 | const path = require('path');
|
13 | const debug = require('debug')('mocha:cli:config');
|
14 | const findUp = require('find-up');
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | exports.CONFIG_FILES = [
|
24 | '.mocharc.cjs',
|
25 | '.mocharc.js',
|
26 | '.mocharc.yaml',
|
27 | '.mocharc.yml',
|
28 | '.mocharc.jsonc',
|
29 | '.mocharc.json'
|
30 | ];
|
31 |
|
32 | const isModuleNotFoundError = err =>
|
33 | err.code !== 'MODULE_NOT_FOUND' ||
|
34 | err.message.indexOf('Cannot find module') !== -1;
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | const parsers = (exports.parsers = {
|
41 | yaml: filepath =>
|
42 | require('js-yaml').safeLoad(fs.readFileSync(filepath, 'utf8')),
|
43 | js: filepath => {
|
44 | const cwdFilepath = path.resolve(filepath);
|
45 | try {
|
46 | debug(`parsers: load using cwd-relative path: "${cwdFilepath}"`);
|
47 | return require(cwdFilepath);
|
48 | } catch (err) {
|
49 | if (isModuleNotFoundError(err)) {
|
50 | debug(`parsers: retry load as module-relative path: "${filepath}"`);
|
51 | return require(filepath);
|
52 | } else {
|
53 | throw err;
|
54 | }
|
55 | }
|
56 | },
|
57 | json: filepath =>
|
58 | JSON.parse(
|
59 | require('strip-json-comments')(fs.readFileSync(filepath, 'utf8'))
|
60 | )
|
61 | });
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | exports.loadConfig = filepath => {
|
72 | let config = {};
|
73 | debug(`loadConfig: "${filepath}"`);
|
74 |
|
75 | const ext = path.extname(filepath);
|
76 | try {
|
77 | if (ext === '.yml' || ext === '.yaml') {
|
78 | config = parsers.yaml(filepath);
|
79 | } else if (ext === '.js' || ext === '.cjs') {
|
80 | config = parsers.js(filepath);
|
81 | } else {
|
82 | config = parsers.json(filepath);
|
83 | }
|
84 | } catch (err) {
|
85 | throw new Error(`failed to parse config "${filepath}": ${err}`);
|
86 | }
|
87 | return config;
|
88 | };
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 | exports.findConfig = (cwd = process.cwd()) => {
|
97 | const filepath = findUp.sync(exports.CONFIG_FILES, {cwd});
|
98 | if (filepath) {
|
99 | debug(`findConfig: found "${filepath}"`);
|
100 | }
|
101 | return filepath;
|
102 | };
|