lowercase_comments.py•1.32 kB
import argparse
import io
import os
import tokenize
from pathlib import Path
def lowercase_comments(path: Path) -> None:
"""rewrite ``path`` in-place, converting # comments to lowercase.
docstrings are left untouched because they are ``STRING`` tokens, not ``COMMENT``.
"""
with path.open("rb") as f:
tokens = list(tokenize.tokenize(f.readline))
new_tokens = []
for tok in tokens:
if tok.type == tokenize.COMMENT:
# keep leading '#', lowercase the rest
text = tok.string[:1] + tok.string[1:].lower()
tok = tokenize.TokenInfo(tok.type, text, tok.start, tok.end, tok.line)
new_tokens.append(tok)
# re-emit source
new_code = tokenize.untokenize(new_tokens)
path.write_bytes(new_code)
def main() -> None: # pragma: no cover
parser = argparse.ArgumentParser(description="lowercase all comments in codebase")
parser.add_argument("paths", nargs="*", default=["src"], help="files or directories to process")
args = parser.parse_args()
for p in args.paths:
p = Path(p)
if p.is_dir():
for file in p.rglob("*.py"):
lowercase_comments(file)
elif p.suffix == ".py":
lowercase_comments(p)
if __name__ == "__main__": # pragma: no cover
main()