Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

17.9 KB
Raw Blame
#!/usr/bin/env python3
"""Usage: comments.py check|strip|list [files...]

check: fail on comments outside KEEP. strip: remove them in place. list: print them.
No files: every tracked source file."""
import ast, io, re, subprocess, sys, tokenize
from pathlib import Path

KEEP = re.compile(
    r"^\s*(?:"
    r"TODO|FIXME|MARK\b|"
    r"swift-tools-version|swift-format-ignore|swiftlint:|sourcery:|"
    r"noqa|type:|pragma\b|pylint:|fmt:|-\*-|coding[:=]|"
    r"requires\b|shellcheck\s|eslint|@ts-|prettier-ignore|istanbul\s|c8\s|"
    r"ktlint|noinspection|language=|ReSharper\s|<auto-generated|"
    r"SPDX-|Copyright\b)"
    r"|\b(?:CC BY|GPL|Apache License|MIT License|SPDX)\b"
)

C_LIKE = {".swift": "swift", ".kt": "kotlin", ".kts": "kotlin", ".cs": "csharp",
          ".c": "c", ".h": "c", ".js": "js", ".mjs": "js"}
HASH = {".sh": "sh", ".py": "py", ".ps1": "ps1"}
MARKUP = (".html", ".css")
REASON = re.compile(r"^(#\s*noqa\b[^-]*?)\s+-\s.*$", re.S)

def body(text):
    t = re.sub(r"^(//+|/\*+|#+)", "", text.strip())
    return re.sub(r"\*+/$", "", t)

def kept(text):
    return any(KEEP.search(re.sub(r"^\s*\*\s?", "", line)) for line in body(text).splitlines() or [""])

class CLike:

    def __init__(self, src, lang):
        self.s, self.lang, self.out = src, lang, []
        self.nested = lang in ("swift", "kotlin")

    def run(self):
        self.code(0, None)
        return self.out

    def code(self, i, close):
        s, depth = self.s, 0
        prev = ""
        while i < len(s):
            c = s[i]
            if s.startswith("//", i):
                j = s.find("\n", i)
                j = len(s) if j < 0 else j
                self.out.append((i, j))
                i = j
                continue
            if s.startswith("/*", i):
                j = self.block(i)
                self.out.append((i, j))
                i = j
                continue
            if close and c in "({[":
                depth += 1
            elif close and c in ")}]":
                if depth == 0 and c == close:
                    return i + 1
                depth -= 1
            if c == '"' or (c == "#" and self.lang == "swift" and re.match(r'#+"', s[i:])):
                i = self.string(i)
                prev = '"'
                continue
            if c in "@$" and self.lang == "csharp" and re.match(r'[@$]+"', s[i:]):
                i = self.string(i)
                prev = '"'
                continue
            if c == "'" and self.lang in ("kotlin", "csharp", "c"):
                i = self.char(i)
                continue
            if c in "'`" and self.lang == "js":
                i = self.jsquote(i, c)
                continue
            if c == "/" and self.lang == "js" and self.regex_ok(prev):
                i = self.jsregex(i)
                prev = "r"
                continue
            if not c.isspace():
                prev = c
            i += 1
        return i

    def block(self, i):
        s, depth, j = self.s, 0, i
        while j < len(s):
            if s.startswith("/*", j):
                depth += 1 if (self.nested or depth == 0) else 0
                j += 2
            elif s.startswith("*/", j):
                depth -= 1
                j += 2
                if depth == 0:
                    return j
            else:
                j += 1
        raise SyntaxError("unterminated block comment")

    def char(self, i):
        s, j = self.s, i + 1
        while j < len(s) and s[j] != "'":
            j += 2 if s[j] == "\\" else 1
        return j + 1

    def string(self, i):
        s, lang = self.s, self.lang
        m = re.match(r'(#*)', s[i:]) if lang == "swift" else re.match(r'([@$]*)', s[i:])
        pre = m.group(1)
        j = i + len(pre)
        triple = s.startswith('"""', j)
        q = '"""' if triple else '"'
        j += len(q)
        if lang == "swift":
            end, interp, esc = q + pre, "\\" + pre + "(", "\\" + pre
        elif lang == "kotlin":
            end, interp, esc = q, "${", None if triple else "\\"
        elif lang == "csharp":
            verbatim, dollars = "@" in pre, pre.count("$")
            end = q
            interp = "{" * max(dollars, 1) if dollars else None
            esc = None if (verbatim or triple) else "\\"
        else:
            end, interp, esc = q, None, "\\"
        while j < len(s):
            if lang == "csharp" and not triple and "@" in pre and s.startswith('""', j):
                j += 2
                continue
            if interp and s.startswith(interp, j):
                if lang == "csharp" and not triple and s.startswith(interp + "{", j) and pre.count("$") == 1:
                    j += 2
                    continue
                j = self.code(j + len(interp), ")" if lang == "swift" else "}")
                continue
            if esc and s.startswith(esc, j):
                j += len(esc) + 1
                continue
            if s.startswith(end, j):
                j += len(end)
                if triple:
                    while j < len(s) and s[j] == '"':
                        j += 1
                return j
            j += 1
        raise SyntaxError(f"unterminated string at {i}")

    def jsquote(self, i, q):
        s, j = self.s, i + 1
        while j < len(s):
            if s[j] == "\\":
                j += 2
                continue
            if q == "`" and s.startswith("${", j):
                j = self.code(j + 2, "}")
                continue
            if s[j] == q:
                return j + 1
            j += 1
        raise SyntaxError("unterminated js string")

    def regex_ok(self, prev):
        return prev == "" or prev in "(,=:[!&|?{};+-*%<>~^" or prev == "\n"

    def jsregex(self, i):
        s, j, cls = self.s, i + 1, False
        if s.startswith("//", i) or s.startswith("/*", i):
            return i
        while j < len(s) and s[j] != "\n":
            if s[j] == "\\":
                j += 2
                continue
            if s[j] == "[":
                cls = True
            elif s[j] == "]":
                cls = False
            elif s[j] == "/" and not cls:
                j += 1
                while j < len(s) and s[j].isalpha():
                    j += 1
                return j
            j += 1
        return i + 1

class Sh:

    def __init__(self, src):
        self.s, self.out, self.heredocs = src, [], []

    def run(self):
        self.code(0, None)
        return self.out

    def code(self, i, close):
        s, n, depth, word = self.s, len(self.s), 0, True
        while i < n:
            c = s[i]
            if c == "\n":
                i = self.newline(i)
                word = True
                continue
            if c == "\\":
                i, word = i + 2, False
                continue
            if c == "#" and word:
                j = s.find("\n", i)
                j = n if j < 0 else j
                self.out.append((i, j))
                i = j
                continue
            if c in "'\"`$":
                i, word = self.quoted(i), False
                continue
            m = re.match(r"<<(-?)\s*(['\"]?)([A-Za-z_]\w*)\2", s[i:])
            if m:
                self.heredocs.append((m.group(3), bool(m.group(1))))
                i, word = i + m.end(), False
                continue
            if close:
                if c == "(":
                    depth += 1
                elif c == ")":
                    if depth == 0 and close == ")":
                        return i + 1
                    depth -= 1
            word = c in " \t;|&()"
            i += 1
        return i

    def newline(self, i):
        s, n = self.s, len(self.s)
        i += 1
        for tag, dash in self.heredocs:
            while i < n:
                j = s.find("\n", i)
                j = n if j < 0 else j
                line = s[i:j]
                i = j + 1
                if (line.lstrip("\t") if dash else line) == tag:
                    break
        self.heredocs = []
        return i

    def quoted(self, i):
        s = self.s
        c = s[i]
        if c == "'":
            return s.index("'", i + 1) + 1
        if c == "`":
            j = i + 1
            while s[j] != "`":
                j += 2 if s[j] == "\\" else 1
            return j + 1
        if c == '"':
            j = i + 1
            while s[j] != '"':
                if s[j] == "\\":
                    j += 2
                elif s[j] in "$`":
                    j = self.quoted(j)
                else:
                    j += 1
            return j + 1
        nxt = s[i + 1:i + 2]
        if nxt == "'":
            j = i + 2
            while s[j] != "'":
                j += 2 if s[j] == "\\" else 1
            return j + 1
        if nxt == "(":
            return self.code(i + 2, ")")
        if nxt == "{":
            j, depth = i + 2, 1
            while depth:
                if s[j] in "'\"`" or (s[j] == "$" and s[j + 1:j + 2] in "({"):
                    j = self.quoted(j)
                    continue
                if s[j] == "\\":
                    j += 2
                    continue
                depth += {"{": 1, "}": -1}.get(s[j], 0)
                j += 1
            return j
        return i + 2 if nxt else i + 1

class Ps:

    def __init__(self, src):
        self.s, self.out = src, []

    def run(self):
        self.code(0, None)
        return self.out

    def code(self, i, close):
        s, n, depth, word = self.s, len(self.s), 0, True
        while i < n:
            c = s[i]
            if s.startswith("<#", i):
                j = s.index("#>", i + 2) + 2
                self.out.append((i, j))
                i = j
                continue
            if c == "#" and word:
                j = s.find("\n", i)
                j = n if j < 0 else j
                self.out.append((i, j))
                i = j
                continue
            if c == "`":
                i, word = i + 2, False
                continue
            m = re.match(r"@(['\"])[ \t]*\r?\n", s[i:])
            if m:
                q = m.group(1)
                j = re.compile(r"\n" + q + "@").search(s, i + m.end() - 1)
                i, word = j.end(), False
                continue
            if c == "'":
                j = i + 1
                while not (s[j] == "'" and s[j + 1:j + 2] != "'"):
                    j += 2 if s[j] == "'" else 1
                i, word = j + 1, False
                continue
            if c == '"':
                j = i + 1
                while not (s[j] == '"' and s[j + 1:j + 2] != '"'):
                    if s[j] == "`" or s[j:j + 2] == '""':
                        j += 2
                    elif s.startswith("$(", j):
                        j = self.code(j + 2, ")")
                    else:
                        j += 1
                i, word = j + 1, False
                continue
            if s.startswith("${", i):
                i, word = s.index("}", i) + 1, False
                continue
            if close:
                if c in "({":
                    depth += 1
                elif c in ")}":
                    if depth == 0:
                        return i + 1
                    depth -= 1
            word = c in " \t\n;|&(){}=,"
            i += 1
        return i


def css_spans(s, base=0):
    out, i = [], 0
    while i < len(s):
        c = s[i]
        if c in "'\"":
            j = i + 1
            while s[j] != c:
                j += 2 if s[j] == "\\" else 1
            i = j + 1
        elif s.startswith("/*", i):
            j = s.index("*/", i + 2) + 2
            out.append((base + i, base + j))
            i = j
        else:
            i += 1
    return out


def html_spans(s):
    out, i = [], 0
    while True:
        m = re.compile(r"<!--|<script\b[^>]*>|<style\b[^>]*>", re.I).search(s, i)
        if not m:
            return out
        if m.group(0) == "<!--":
            j = s.index("-->", m.end()) + 3
            out.append((m.start(), j))
            i = j
            continue
        tag = "script" if m.group(0).lower().startswith("<script") else "style"
        end = s.lower().index("</" + tag, m.end())
        inner = s[m.end():end]
        if tag == "style":
            out += css_spans(inner, m.end())
        elif "src=" not in m.group(0) and "json" not in m.group(0):
            out += [(m.end() + a, m.end() + b) for a, b in CLike(inner, "js").run()]
        i = end


def offsets(src):
    starts, pos = [0], 0
    for line in src.splitlines(keepends=True):
        pos += len(line)
        starts.append(pos)
    return starts

def py_spans(src, path):
    tree = ast.parse(src)
    usage = "__doc__" in src
    starts = offsets(src)
    lines = src.splitlines(keepends=True)
    at = lambda line, col: starts[line - 1] + len(lines[line - 1].encode()[:col].decode())
    spans, holders = [], []
    for node in ast.walk(tree):
        if isinstance(node, (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.body:
            first = node.body[0]
            if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):
                if usage and isinstance(node, ast.Module):
                    continue
                a, b = at(first.lineno, first.col_offset), at(first.end_lineno, first.end_col_offset)
                spans.append((a, b, "doc", len(node.body) == 1))
    for tok in tokenize.generate_tokens(io.StringIO(src).readline):
        if tok.type == tokenize.COMMENT:
            a = starts[tok.start[0] - 1] + tok.start[1]
            spans.append((a, a + len(tok.string), "#", False))
    return spans

def spans_for(path, src):
    ext = path.suffix
    if ext in C_LIKE:
        return [(a, b, None, False) for a, b in CLike(src, C_LIKE[ext]).run()]
    if ext == ".py":
        return py_spans(src, path)
    if ext == ".ps1":
        return [(a, b, None, False) for a, b in Ps(src).run()]
    if ext == ".css":
        return [(a, b, None, False) for a, b in css_spans(src)]
    if ext == ".html":
        return [(a, b, None, False) for a, b in html_spans(src)]
    if ext == ".sh" or (ext == "" and src.startswith("#!") and "sh" in src.split("\n", 1)[0]):
        return [(a, b, None, False) for a, b in Sh(src).run()]
    return []

CUT = "\x00"


def drop(src, spans):
    spans = [sp for sp in spans if not (sp[0] == 0 and src.startswith("#!"))]
    spans = [sp for sp in spans if not kept(src[sp[0]:sp[1]]) or sp[2] == "doc"]
    if not spans:
        return src
    out, last = [], 0
    for a, b, kind, only in sorted(spans):
        ls = src.rfind("\n", 0, a) + 1
        le = src.find("\n", b)
        le = len(src) if le < 0 else le
        before, after = src[ls:a], src[b:le]
        if not before.strip() and not after.strip():
            if only:
                out.append(src[last:a] + "pass")
                last = b
            else:
                out.append(src[last:ls] + CUT)
                last = le + 1
        else:
            seg = src[last:a]
            nxt = src[b:b + 1]
            if not after.strip():
                seg = seg.rstrip(" \t")
            elif seg[-1:].isspace() and (nxt.isspace() or nxt in ",;)]}"):
                seg = seg.rstrip(" \t")
            elif seg[-1:] and not seg[-1:].isspace() and nxt and not nxt.isspace() and seg[-1] not in "([{" and nxt not in ")]},;":
                seg += " "
            if only:
                seg += "pass"
            out.append(seg)
            last = b
    out.append(src[last:])
    return tidy("".join(out))


def tidy(text):
    lines, res = text.split("\n"), []
    for line in lines:
        if not line.startswith(CUT):
            res.append(line)
            continue
        line = line.lstrip(CUT)
        prev = res[-1] if res else None
        blank = not line.strip()
        if blank and (prev is None or not prev.strip() or prev.rstrip().endswith(("{", "(", "[", ":")) or prev.startswith("#!")):
            continue
        if prev is not None and not prev.strip() and line.lstrip().startswith(("}", ")", "]")):
            res.pop()
        res.append(line)
    return "\n".join(res)

def tracked():
    files = subprocess.run(["git", "ls-files"], capture_output=True, text=True, check=True).stdout.split()
    files = [f for f in files if not f.startswith("docs/")]
    return [f for f in files if Path(f).suffix in C_LIKE or Path(f).suffix in HASH or Path(f).suffix in MARKUP or
            (Path(f).suffix == "" and Path(f).is_file() and Path(f).read_bytes()[:2] == b"#!" and b"sh" in Path(f).read_bytes().split(b"\n", 1)[0])]

def main():
    if len(sys.argv) < 2 or sys.argv[1] not in ("check", "strip", "list"):
        sys.exit(__doc__)
    mode, files = sys.argv[1], sys.argv[2:] or tracked()
    bad = 0
    for f in files:
        p = Path(f)
        if not p.is_file():
            continue
        src = p.read_text(encoding="utf-8")
        try:
            spans = spans_for(p, src)
        except (SyntaxError, ValueError, IndexError) as e:
            print(f"{f}: cannot scan: {e}", file=sys.stderr)
            bad += 1
            continue
        if mode == "strip":
            new = src
            for a, b, kind, _ in sorted(spans, reverse=True):
                m = kind != "doc" and REASON.match(src[a:b])
                if m:
                    new = new[:a] + m.group(1) + new[b:]
            new = drop(new, spans_for(p, new))
            if new != src:
                p.write_text(new, encoding="utf-8")
            continue
        for a, b, kind, _ in spans:
            text = src[a:b]
            if (a == 0 and text.startswith("#!")) or (kind != "doc" and kept(text) and not REASON.match(text)):
                continue
            bad += 1
            if mode == "list" or bad <= 20:
                line = src.count("\n", 0, a) + 1
                print(f"{f}:{line}: {text.splitlines()[0][:100]}")
    if mode == "check" and bad:
        print(f"{bad} comments: only TODO, FIXME, MARK, tool directives and license lines are allowed "
              f"(scripts/comments.py strip <file> removes the rest)", file=sys.stderr)
    sys.exit(1 if bad and mode != "list" else 0)

if __name__ == "__main__":
    main()