38 lines
852 B
Python
38 lines
852 B
Python
#!/usr/bin/env python3
|
|
"""Remove all C/C++ comments from a file."""
|
|
|
|
import sys
|
|
import re
|
|
|
|
|
|
def remove_comments(source):
|
|
pattern = re.compile(
|
|
r'//.*?$|/\*.*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'',
|
|
re.DOTALL | re.MULTILINE,
|
|
)
|
|
|
|
def replacer(match):
|
|
s = match.group(0)
|
|
if s.startswith("/"):
|
|
return " " if s.startswith("/*") else ""
|
|
return s
|
|
|
|
return pattern.sub(replacer, source)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print(f"Usage: {sys.argv[0]} <file> [--inplace]", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
path = sys.argv[1]
|
|
inplace = "--inplace" in sys.argv
|
|
|
|
with open(path) as f:
|
|
result = remove_comments(f.read())
|
|
|
|
if inplace:
|
|
with open(path, "w") as f:
|
|
f.write(result)
|
|
else:
|
|
print(result, end="")
|