-
-
Notifications
You must be signed in to change notification settings - Fork 188
/
options.ts
194 lines (179 loc) · 7.48 KB
/
options.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
import * as fs from 'fs';
import * as path from 'path';
import sade from 'sade';
import { URI } from 'vscode-uri';
export interface SvelteCheckCliOptions {
workspaceUri: URI;
outputFormat: OutputFormat;
watch: boolean;
preserveWatchOutput: boolean;
tsconfig?: string;
filePathsToIgnore: string[];
failOnWarnings: boolean;
compilerWarnings: Record<string, 'error' | 'ignore'>;
diagnosticSources: DiagnosticSource[];
threshold: Threshold;
}
export function parseOptions(cb: (opts: SvelteCheckCliOptions) => any) {
const prog = sade('svelte-check', true)
.version(require('../../package.json').version) // ends up in dist/src, that's why we go two levels up
.option(
'--workspace',
'Path to your workspace. All subdirectories except node_modules and those listed in `--ignore` are checked. Defaults to current working directory.'
)
.option(
'--output',
'What output format to use. Options are human, human-verbose, machine.',
'human-verbose'
)
.option(
'--watch',
'Will not exit after one pass but keep watching files for changes and rerun diagnostics',
false
)
.option('--preserveWatchOutput', 'Do not clear the screen in watch mode', false)
.option(
'--tsconfig',
'Pass a path to a tsconfig or jsconfig file. The path can be relative to the workspace path or absolute. Doing this means that only files matched by the files/include/exclude pattern of the config file are diagnosed. It also means that errors from TypeScript and JavaScript files are reported. When not given, searches for the next upper tsconfig/jsconfig in the workspace path.'
)
.option(
'--no-tsconfig',
'Use this if you only want to check the Svelte files found in the current directory and below and ignore any JS/TS files (they will not be type-checked)',
false
)
.option(
'--ignore',
'Only has an effect when ussing `--no-tsconfig` option. Files/folders to ignore - relative to workspace root, comma-separated, inside quotes. Example: `--ignore "dist,build"`'
)
.option(
'--fail-on-warnings',
'Will also exit with error code when there are warnings',
false
)
.option(
'--compiler-warnings',
'A list of Svelte compiler warning codes. Each entry defines whether that warning should be ignored or treated as an error. Warnings are comma-separated, between warning code and error level is a colon; all inside quotes. Example: `--compiler-warnings "css-unused-selector:ignore,unused-export-let:error"`'
)
.option(
'--diagnostic-sources',
'A list of diagnostic sources which should run diagnostics on your code. Possible values are `js` (includes TS), `svelte`, `css`. Comma-separated, inside quotes. By default all are active. Example: `--diagnostic-sources "js,svelte"`'
)
.option(
'--threshold',
'Filters the diagnostics to display. `error` will output only errors while `warning` will output warnings and errors.',
'warning'
)
.action((opts) => {
const workspaceUri = getWorkspaceUri(opts);
cb({
workspaceUri,
outputFormat: getOutputFormat(opts),
watch: !!opts.watch,
preserveWatchOutput: !!opts.preserveWatchOutput,
tsconfig: getTsconfig(opts, workspaceUri.fsPath),
filePathsToIgnore: getFilepathsToIgnore(opts),
failOnWarnings: !!opts['fail-on-warnings'],
compilerWarnings: getCompilerWarnings(opts),
diagnosticSources: getDiagnosticSources(opts),
threshold: getThreshold(opts)
});
});
prog.parse(process.argv, {
unknown: (arg) => `Unknown option ${arg}`
});
}
const outputFormats = ['human', 'human-verbose', 'machine'] as const;
type OutputFormat = (typeof outputFormats)[number];
function getOutputFormat(opts: Record<string, any>): OutputFormat {
return outputFormats.includes(opts.output) ? opts.output : 'human-verbose';
}
function getWorkspaceUri(opts: Record<string, any>) {
let workspaceUri;
let workspacePath = opts.workspace;
if (workspacePath) {
if (!path.isAbsolute(workspacePath)) {
workspacePath = path.resolve(process.cwd(), workspacePath);
}
workspaceUri = URI.file(workspacePath);
} else {
workspaceUri = URI.file(process.cwd());
}
return workspaceUri;
}
function findFile(searchPath: string, fileName: string) {
try {
for (;;) {
const filePath = path.join(searchPath, fileName);
if (fs.existsSync(filePath)) {
return filePath;
}
const parentPath = path.dirname(searchPath);
if (parentPath === searchPath) {
return;
}
searchPath = parentPath;
}
} catch (e) {
return;
}
}
function getTsconfig(myArgs: Record<string, any>, workspacePath: string) {
// Work around undocumented behavior in Sade where `no-tsconfig` is never true / means "tsconfig is false"
if (myArgs['no-tsconfig'] || process.argv.includes('--no-tsconfig')) {
return undefined;
}
let tsconfig: string | undefined =
typeof myArgs.tsconfig === 'string' ? myArgs.tsconfig : undefined;
if (!tsconfig) {
const ts = findFile(workspacePath, 'tsconfig.json');
const js = findFile(workspacePath, 'jsconfig.json');
tsconfig = !!ts && (!js || ts.length >= js.length) ? ts : js;
}
if (tsconfig && !path.isAbsolute(tsconfig)) {
tsconfig = path.join(workspacePath, tsconfig);
}
if (tsconfig && !fs.existsSync(tsconfig)) {
throw new Error('Could not find tsconfig/jsconfig file at ' + myArgs.tsconfig);
}
return tsconfig;
}
function getCompilerWarnings(opts: Record<string, any>) {
return stringToObj(opts['compiler-warnings']);
function stringToObj(str = '') {
return str
.split(',')
.map((s) => s.trim())
.filter((s) => !!s)
.reduce((settings, setting) => {
const [name, val] = setting.split(':');
if (val === 'error' || val === 'ignore') {
settings[name] = val;
}
return settings;
}, <Record<string, 'error' | 'ignore'>>{});
}
}
const diagnosticSources = ['js', 'css', 'svelte'] as const;
type DiagnosticSource = (typeof diagnosticSources)[number];
function getDiagnosticSources(opts: Record<string, any>): DiagnosticSource[] {
const sources = opts['diagnostic-sources'];
return sources
? sources
.split(',')
?.map((s: string) => s.trim())
.filter((s: any) => diagnosticSources.includes(s))
: diagnosticSources;
}
function getFilepathsToIgnore(opts: Record<string, any>): string[] {
return opts.ignore?.split(',') || [];
}
const thresholds = ['warning', 'error'] as const;
type Threshold = (typeof thresholds)[number];
function getThreshold(opts: Record<string, any>): Threshold {
if (thresholds.includes(opts.threshold)) {
return opts.threshold;
} else {
console.warn(`Invalid threshold "${opts.threshold}", using "warning" instead`);
return 'warning';
}
}