forked from hhvm/hhast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NewlineAtEndOfFileLinter.hack
67 lines (58 loc) · 1.77 KB
/
NewlineAtEndOfFileLinter.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
/*
* 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;
use type Facebook\HHAST\File;
use namespace HH\Lib\{C, Math, Str, Vec};
final class NewlineAtEndOfFileLinter
extends BaseLinter
implements AutoFixingLinter<LintError> {
use AutoFixingLinterTrait<LintError>;
<<__Override>>
public async function getLintErrorsAsync(): Awaitable<vec<LintError>> {
$contents = $this->getFile()->getContents();
$fixed = $this->getFixedFile(vec[])->getContents();
if ($contents === $fixed) {
return vec[];
}
$trimmed = Str\trim_right($contents);
$trailing = Str\slice($contents, Str\length($trimmed));
$blame = $trimmed
|> Str\split($$, "\n")
|> Vec\slice($$, Math\maxva(0, C\count($$) - 3))
|> Str\join($$, "\n")
|> $$.$trailing;
$lines = Str\split($contents, "\n") |> C\count($$);
return (
new BuiltLintError(
$this,
'Files should end with a single trailing newline',
)
)
->withPosition($lines, 0)
->withBlameCode($blame)
|> vec[$$];
}
protected function getTitleForFix(LintError $_): string {
$contents = $this->getFile()->getContents();
if (Str\ends_with($contents, "\n")) {
return 'Remove extra trailing whitespace';
}
if (Str\trim_right($contents) === $contents) {
return 'Add trailing newline';
}
return 'Replace trailng whitespace with newline';
}
public function getFixedFile(Traversable<LintError> $_): File {
return $this->getFile()->withContents(
$this->getFile()->getContents()
|> Str\trim_right($$)
|> $$."\n",
);
}
}