forked from hhvm/hhast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LintRunConfig.hack
351 lines (322 loc) · 11.4 KB
/
LintRunConfig.hack
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
/*
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
namespace Facebook\HHAST\__Private;
use namespace Facebook\{HHAST, TypeAssert};
use namespace HH\Lib\{C, Dict, Keyset, Str, Vec};
use type Facebook\HHAST\Linter;
final class LintRunConfig {
const type TOverride = shape(
// Which files this override applies to (uses `fnmatch()`)
'patterns' => vec<string>,
?'builtinLinters' => NamedLinterGroup,
?'extraLinters' => vec<string>,
?'disabledLinters' => vec<string>,
?'disabledAutoFixes' => vec<string>,
?'disableAllAutoFixes' => bool,
?'disableAllLinters' => bool,
?'linterConfigs' => dict<string, dynamic>,
);
const type TConfigFile = shape(
// Where to lint, eg '[ "src/", "codegen/", "tests/" ]
'roots' => vec<string>,
// HHAST includes several linters - which do you want?
// 'all' | 'default' | 'none'
// 'default' is currently the same as 'all', but may be more conservative
// in the future
?'builtinLinters' => NamedLinterGroup,
// Equivalent to 'use namespace' for the config options that take
// linter classnames - e.g:
// "namespaceAliases": { "HHAST": "Facebook\\HHAST\\Linters" },
// "extraLinters": [ "HHAST\\SomeContentiousLinter" ],
?'namespaceAliases' => dict<string, string>,
// Class names for additional linters that should be used for this project
?'extraLinters' => vec<string>,
// Class names for specific linters you'd like to disable; useful if you'd
// like `"builtinLinters": "all"` or `"default"` except for one or two.
?'disabledLinters' => vec<string>,
// Class names for linters where the autofixes should never be applied
?'disabledAutoFixes' => vec<string>,
// Disable all autofixes; probably more useful as an override - for example,
// hhast disables all autofixes in the codegen/ directory.
// Defaults to false.
?'disableAllAutoFixes' => bool,
// Override any of the above for a subset of files in the project
?'overrides' => vec<self::TOverride>,
// Each linter may specify a type for itself.
// The type of this key is effectively `dict<classname<TLinter>, TLinter::TConfig>`
// for example:
// "linterConfigs": { "Facebook\\HHAST\\HHClientLinter": { "ignore": [5624, 5639] }}
?'linterConfigs' => dict<string, dynamic>,
);
const type TFileConfig = shape(
'linters' => keyset<classname<Linter>>,
'autoFixBlacklist' => keyset<classname<Linter>>,
);
const vec<classname<Linter>> DEFAULT_LINTERS = vec[
HHAST\AsyncFunctionAndMethodLinter::class,
HHAST\CamelCasedMethodsUnderscoredFunctionsLinter::class,
HHAST\DontAwaitInALoopLinter::class,
HHAST\LicenseHeaderLinter::class,
HHAST\NewlineAtEndOfFileLinter::class,
HHAST\MustUseBracesForControlFlowLinter::class,
HHAST\NoNewlineAtStartOfControlFlowBlockLinter::class,
HHAST\MustUseOverrideAttributeLinter::class,
HHAST\NoPHPEqualityLinter::class,
HHAST\UnusedParameterLinter::class,
HHAST\UnusedVariableLinter::class,
HHAST\UnusedUseClauseLinter::class,
HHAST\UseStatementWithLeadingBackslashLinter::class,
HHAST\UseStatementWithoutKindLinter::class,
HHAST\GroupUseStatementsLinter::class,
HHAST\GroupUseStatementAlphabetizationLinter::class,
HHAST\NoWhitespaceAtEndOfLineLinter::class,
HHAST\PreferRequireOnceLinter::class,
HHAST\ConsistentLineEndingsLinter::class,
HHAST\UnreachableCodeLinter::class,
];
const vec<classname<Linter>> NON_DEFAULT_LINTERS = vec[
HHAST\DontUseAsioJoinLinter::class,
HHAST\PreferSingleQuotedStringLiteralLinter::class,
HHAST\NoStringInterpolationLinter::class,
HHAST\ShoutCaseEnumMembersLinter::class,
HHAST\StrictModeOnlyLinter::class,
HHAST\UseStatementWithAsLinter::class,
HHAST\NoFinalMethodInFinalClassLinter::class,
HHAST\NamespacePrivateLinter::class,
HHAST\DontHaveTwoEmptyLinesInARowLinter::class,
HHAST\DontCreateForwardingLambdasLinter::class,
HHAST\PreferLambdasLinter::class,
HHAST\NoEmptyStatementsLinter::class,
HHAST\FinalOrAbstractClassLinter::class,
];
private static function getNamedLinterGroup(
NamedLinterGroup $group,
): vec<classname<Linter>> {
switch ($group) {
case NamedLinterGroup::NO_BUILTINS:
return vec[];
case NamedLinterGroup::DEFAULT_BUILTINS:
return self::DEFAULT_LINTERS;
case NamedLinterGroup::ALL_BUILTINS:
return Vec\concat(self::DEFAULT_LINTERS, self::NON_DEFAULT_LINTERS);
}
}
private function __construct(
private string $projectRoot,
private self::TConfigFile $configFile,
) {
}
<<__Memoize>>
public static function getFromConfigFile(string $path): this {
return new self(\dirname($path), self::getConfigFromFile($path));
}
<<__Memoize>>
private static function getDefault(): this {
return new self(\getcwd(), shape('roots' => vec[]));
}
public static function getForPath(string $path): this {
$path = \realpath($path);
if (\is_dir($path)) {
return self::getForPathImpl($path);
}
return self::getForPathImpl(\dirname($path));
}
<<__Memoize>>
private static function getForPathImpl(string $path): this {
if ($path === '') {
return self::getDefault();
}
$config_file = $path.'/hhast-lint.json';
if (\file_exists($config_file)) {
return self::getFromConfigFile($config_file);
}
return Str\split($path, '/')
|> Vec\take($$, C\count($$) - 1)
|> Str\join($$, '/')
|> self::getForPathImpl($$);
}
public function getRoots(): vec<string> {
return
Vec\map($this->configFile['roots'], $dir ==> $this->projectRoot.'/'.$dir);
}
private function findOverride(string $file_path): ?self::TOverride {
return C\find(
$this->configFile['overrides'] ?? vec[],
$override ==> C\find(
$override['patterns'],
$pattern ==> \fnmatch($pattern, $file_path),
) is nonnull,
);
}
private function relativeFilePath(string $file_path): ?string {
$roots = Vec\map(
$this->configFile['roots'],
$s ==> Str\strip_suffix($s, '/').'/' |> Str\strip_prefix($$, './'),
);
$file_path = Str\strip_prefix($file_path, $this->projectRoot.'/')
|> Str\strip_prefix($$, './');
if (
$roots !== vec[] &&
!C\any($roots, $root ==> Str\starts_with($file_path, $root))
) {
return null;
}
return $file_path;
}
public function getConfigForFile(string $file_path): self::TFileConfig {
$file_path = $this->relativeFilePath($file_path);
if ($file_path is null) {
return shape(
'linters' => keyset[],
'autoFixBlacklist' => keyset[],
);
}
$builtin_linters =
$this->configFile['builtinLinters'] ?? NamedLinterGroup::DEFAULT_BUILTINS;
$linters = $this->configFile['extraLinters'] ?? vec[];
$blacklist = $this->configFile['disabledLinters'] ?? vec[];
$autofix_blacklist = $this->configFile['disabledAutoFixes'] ?? vec[];
$no_autofixes = $this->configFile['disableAllAutoFixes'] ?? false;
$override = $this->findOverride($file_path);
if ($override is nonnull) {
if ($override['disableAllLinters'] ?? false) {
return shape(
'linters' => keyset[],
'autoFixBlacklist' => keyset[],
);
}
if (Shapes::keyExists($override, 'builtinLinters')) {
$builtin_linters = $override['builtinLinters'];
}
$linters = Vec\concat($linters, $override['extraLinters'] ?? vec[]);
$blacklist =
Vec\concat($blacklist, $override['disabledLinters'] ?? vec[]);
$autofix_blacklist =
Vec\concat($autofix_blacklist, $override['disabledAutoFixes'] ?? vec[]);
$no_autofixes =
$no_autofixes || ($override['disableAllAutoFixes'] ?? false);
}
$normalize = (vec<string> $list) ==> Keyset\map(
$list,
$linter ==> $this->getFullyQualifiedLinterName($linter),
);
$linters = $normalize($linters);
$blacklist = $normalize($blacklist);
$autofix_blacklist = $normalize($autofix_blacklist);
$linters =
Keyset\union($linters, self::getNamedLinterGroup($builtin_linters));
$linters = Keyset\diff($linters, $blacklist);
if ($no_autofixes) {
$autofix_blacklist = $linters;
}
$assert_types = (keyset<string> $list) ==>
Keyset\map($list, $str ==> TypeAssert\classname_of(Linter::class, $str));
$linters = $assert_types($linters);
$autofix_blacklist = $assert_types($autofix_blacklist);
return shape(
'linters' => $linters,
'autoFixBlacklist' => $autofix_blacklist,
);
}
public function getLinterConfigForLinter<TLinter as Linter, TConfig>(
classname<TLinter> $classname,
?string $file_path = null,
): ?TConfig where TConfig = TLinter::TConfig {
$global_linter_config =
$this->configFile['linterConfigs'][$classname] ?? null;
$file_linter_config =
$file_path is null ? null : $this->relativeFilePath($file_path)
|> $$ is null
? null
: $this->findOverride($$)['linterConfigs'][$classname] ?? null;
if ($global_linter_config is null) {
if ($file_linter_config is null) {
return null;
} else {
$config = $file_linter_config;
}
} else {
if ($file_linter_config is null) {
$config = $global_linter_config;
} else {
$config = Dict\merge(
$global_linter_config as dict<_, _>,
$file_linter_config as dict<_, _>,
);
}
}
try {
return TypeAssert\matches_type_structure(
type_structure($classname, 'TConfig'),
$config,
);
} catch (TypeAssert\UnsupportedTypeException $e) {
throw new \InvalidOperationException(
Str\format(
'%s specified an unsupported config type. See previous exception:',
$classname,
),
$e->getCode(),
$e,
);
} catch (TypeAssert\IncorrectTypeException $e) {
throw new \Exception(
Str\format(
'Configuration for %s is not of the correct type. See previous exception:',
$classname,
),
$e->getCode(),
$e,
);
}
}
private function getFullyQualifiedLinterName(string $name): string {
if (Str\starts_with($name, 'Facebook\\HHAST\\Linters')) {
$name =
'Facebook\\HHAST'.Str\strip_prefix($name, 'Facebook\\HHAST\\Linters');
}
$aliases = $this->configFile['namespaceAliases'] ?? dict[];
if (C\is_empty($aliases)) {
return $name;
}
foreach ($aliases as $alias => $ns) {
$alias = $alias.'\\';
if (Str\starts_with($name, $alias)) {
return $ns.'\\'.Str\strip_prefix($name, $alias);
}
}
return $name;
}
private static function getConfigFromFile(string $file): self::TConfigFile {
$json = \file_get_contents($file);
$data = \json_decode(
$json,
/* as array = */ true,
/* depth = [default] */ 512,
\JSON_FB_LOOSE | \JSON_FB_HACK_ARRAYS,
);
if ($data === null) {
throw new \Exception('Failed to parse JSON in configuration file '.$file);
}
try {
return TypeAssert\matches_type_structure(
type_structure(self::class, 'TConfigFile'),
$data,
);
} catch (TypeAssert\IncorrectTypeException $e) {
throw new \Exception(
Str\format(
"Invalid configuration file: %s\n %s",
$file,
$e->getMessage(),
),
);
}
}
}