cppp
1 #!/usr/bin/env python3 2 3 import argparse 4 import os 5 import shutil 6 from pathlib import Path 7 8 UGLIES = "{};" 9 10 parser = argparse.ArgumentParser( 11 prog="cppp", 12 description="Formats a C/C++ file as if it were python", 13 ) 14 parser.add_argument("file", type=Path) 15 parser.add_argument("-l", "--line-length", 16 type=int, 17 default=100) 18 parser.add_argument("-o", "--out", 19 help="Print to stdout", 20 action="store_true") 21 22 args = parser.parse_args() 23 24 # Ensure it's actually a file 25 # No checks are done to ensure it's actually actually source code 26 cpp_file = args.file 27 if not cpp_file.is_file(): 28 print("file must be a file") 29 exit(1) 30 31 # Make a backup, just in case 32 backup_file = cpp_file.parent / f"{cpp_file.name}.bak" 33 shutil.copyfile(cpp_file, backup_file) 34 35 # Read it into memory - no optimizations here 36 input_lines = cpp_file.read_text().split(os.linesep) 37 output_lines = [] 38 39 for line in input_lines: 40 # Check if the last char is an ugly char 41 # And move it further back into the given column 42 if line and (term := line[-1]) in UGLIES: 43 to_write = f"%-{args.line_length}s{term}" % line[:-1] 44 else: 45 to_write = line 46 47 # Print out or store for writing to file 48 if args.out: 49 print(to_write) 50 else: 51 output_lines.append(to_write) 52 53 if not args.out: 54 cpp_file.write_text(os.linesep.join(output_lines))