pytorch

Форк
0
/
shellcheck_linter.py 
118 строк · 2.9 Кб
1
import argparse
2
import json
3
import logging
4
import shutil
5
import subprocess
6
import sys
7
import time
8
from enum import Enum
9
from typing import List, NamedTuple, Optional
10

11

12
LINTER_CODE = "SHELLCHECK"
13

14

15
class LintSeverity(str, Enum):
16
    ERROR = "error"
17
    WARNING = "warning"
18
    ADVICE = "advice"
19
    DISABLED = "disabled"
20

21

22
class LintMessage(NamedTuple):
23
    path: Optional[str]
24
    line: Optional[int]
25
    char: Optional[int]
26
    code: str
27
    severity: LintSeverity
28
    name: str
29
    original: Optional[str]
30
    replacement: Optional[str]
31
    description: Optional[str]
32

33

34
def run_command(
35
    args: List[str],
36
) -> "subprocess.CompletedProcess[bytes]":
37
    logging.debug("$ %s", " ".join(args))
38
    start_time = time.monotonic()
39
    try:
40
        return subprocess.run(
41
            args,
42
            capture_output=True,
43
        )
44
    finally:
45
        end_time = time.monotonic()
46
        logging.debug("took %dms", (end_time - start_time) * 1000)
47

48

49
def check_files(
50
    files: List[str],
51
) -> List[LintMessage]:
52
    try:
53
        proc = run_command(
54
            ["shellcheck", "--external-sources", "--format=json1"] + files
55
        )
56
    except OSError as err:
57
        return [
58
            LintMessage(
59
                path=None,
60
                line=None,
61
                char=None,
62
                code=LINTER_CODE,
63
                severity=LintSeverity.ERROR,
64
                name="command-failed",
65
                original=None,
66
                replacement=None,
67
                description=(f"Failed due to {err.__class__.__name__}:\n{err}"),
68
            )
69
        ]
70
    stdout = str(proc.stdout, "utf-8").strip()
71
    results = json.loads(stdout)["comments"]
72
    return [
73
        LintMessage(
74
            path=result["file"],
75
            name=f"SC{result['code']}",
76
            description=result["message"],
77
            line=result["line"],
78
            char=result["column"],
79
            code=LINTER_CODE,
80
            severity=LintSeverity.ERROR,
81
            original=None,
82
            replacement=None,
83
        )
84
        for result in results
85
    ]
86

87

88
if __name__ == "__main__":
89
    parser = argparse.ArgumentParser(
90
        description="shellcheck runner",
91
        fromfile_prefix_chars="@",
92
    )
93
    parser.add_argument(
94
        "filenames",
95
        nargs="+",
96
        help="paths to lint",
97
    )
98

99
    if shutil.which("shellcheck") is None:
100
        err_msg = LintMessage(
101
            path="<none>",
102
            line=None,
103
            char=None,
104
            code=LINTER_CODE,
105
            severity=LintSeverity.ERROR,
106
            name="command-failed",
107
            original=None,
108
            replacement=None,
109
            description="shellcheck is not installed, did you forget to run `lintrunner init`?",
110
        )
111
        print(json.dumps(err_msg._asdict()), flush=True)
112
        sys.exit(0)
113

114
    args = parser.parse_args()
115

116
    lint_messages = check_files(args.filenames)
117
    for lint_message in lint_messages:
118
        print(json.dumps(lint_message._asdict()), flush=True)
119

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.