import re
import sys
from pathlib import Path
def fix_file(path: Path, in_place: bool = True):
pattern = re.compile(r'^(?P<indent>\s*)(?P<var>\w+)\s+if\s+(?P=var)\s*==\s*(?P<val>0x[0-9A-Fa-f]+)(?P<after>\s*=>)', re.MULTILINE)
text = path.read_text()
new_text = pattern.sub(lambda m: f"{m.group('indent')}{m.group('val')}{m.group('after')}", text)
if in_place:
path.write_text(new_text)
print(f"Rewrote {path}")
else:
print(new_text)
def main():
import argparse
p = argparse.ArgumentParser(
description="Remove redundant guards of the form `v if v == 0xNN => …`"
)
p.add_argument('file', help="The .rs file to process", type=Path)
p.add_argument('-n', '--no-in-place', action='store_false', dest='in_place',
help="Print to stdout instead of overwriting")
args = p.parse_args()
if not args.file.exists():
print(f"Error: {args.file} not found", file=sys.stderr)
sys.exit(1)
fix_file(args.file, args.in_place)
if __name__ == '__main__':
main()