split.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. """This script splits httplib.h into .h and .cc parts."""
  3. import os
  4. import sys
  5. from argparse import ArgumentParser, Namespace
  6. from typing import List
  7. BORDER: str = '// ----------------------------------------------------------------------------'
  8. def main() -> None:
  9. """Main entry point for the script."""
  10. args_parser: ArgumentParser = ArgumentParser(description=__doc__)
  11. args_parser.add_argument(
  12. "-e", "--extension", help="extension of the implementation file (default: cc)", default="cc"
  13. )
  14. args_parser.add_argument(
  15. "-o", "--out", help="where to write the files (default: out)", default="out"
  16. )
  17. args: Namespace = args_parser.parse_args()
  18. cur_dir: str = os.path.dirname(sys.argv[0])
  19. if not cur_dir:
  20. cur_dir = '.'
  21. lib_name: str = "httplib"
  22. header_name: str = f"/{lib_name}.h"
  23. source_name: str = f"/{lib_name}.{args.extension}"
  24. # get the input file
  25. in_file: str = f"{cur_dir}{header_name}"
  26. # get the output file
  27. h_out: str = f"{args.out}{header_name}"
  28. cc_out: str = f"{args.out}{source_name}"
  29. # if the modification time of the out file is after the in file,
  30. # don't split (as it is already finished)
  31. do_split: bool = True
  32. if os.path.exists(h_out):
  33. in_time: float = os.path.getmtime(in_file)
  34. out_time: float = os.path.getmtime(h_out)
  35. do_split: bool = in_time > out_time
  36. if do_split:
  37. with open(in_file) as f:
  38. lines: List[str] = f.readlines()
  39. os.makedirs(args.out, exist_ok=True)
  40. in_implementation: bool = False
  41. cc_out: str = args.out + source_name
  42. with open(h_out, 'w') as fh, open(cc_out, 'w') as fc:
  43. # Write source file
  44. fc.write("#include \"httplib.h\"\n")
  45. fc.write("namespace httplib {\n")
  46. # Process lines for header and source split
  47. for line in lines:
  48. is_border_line: bool = BORDER in line
  49. if is_border_line:
  50. in_implementation: bool = not in_implementation
  51. elif in_implementation:
  52. fc.write(line.replace("inline ", ""))
  53. else:
  54. fh.write(line)
  55. fc.write("} // namespace httplib\n")
  56. print(f"Wrote {h_out} and {cc_out}")
  57. else:
  58. print(f"{h_out} and {cc_out} are up to date")
  59. if __name__ == "__main__":
  60. main()