generate_module.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. """This script generates httplib.cppm module file from httplib.h."""
  3. import os
  4. import sys
  5. from argparse import ArgumentParser, Namespace
  6. from typing import List
  7. def main() -> None:
  8. """Main entry point for the script."""
  9. args_parser: ArgumentParser = ArgumentParser(description=__doc__)
  10. args_parser.add_argument(
  11. "-o", "--out", help="where to write the files (default: out)", default="out"
  12. )
  13. args: Namespace = args_parser.parse_args()
  14. cur_dir: str = os.path.dirname(sys.argv[0])
  15. if not cur_dir:
  16. cur_dir = '.'
  17. lib_name: str = "httplib"
  18. header_name: str = f"/{lib_name}.h"
  19. # get the input file
  20. in_file: str = f"{cur_dir}{header_name}"
  21. # get the output file
  22. cppm_out: str = f"{args.out}/{lib_name}.cppm"
  23. # if the modification time of the out file is after the in file,
  24. # don't generate (as it is already finished)
  25. do_generate: bool = True
  26. if os.path.exists(cppm_out):
  27. in_time: float = os.path.getmtime(in_file)
  28. out_time: float = os.path.getmtime(cppm_out)
  29. do_generate: bool = in_time > out_time
  30. if do_generate:
  31. with open(in_file) as f:
  32. lines: List[str] = f.readlines()
  33. os.makedirs(args.out, exist_ok=True)
  34. # Find the Headers and Declaration comment markers
  35. headers_start: int = -1
  36. declaration_start: int = -1
  37. for i, line in enumerate(lines):
  38. if ' * Headers' in line:
  39. headers_start = i - 1 # Include the /* line
  40. elif ' * Declaration' in line:
  41. declaration_start = i - 1 # Stop before the /* line
  42. break
  43. with open(cppm_out, 'w') as fm:
  44. # Write module file
  45. fm.write("module;\n\n")
  46. # Write global module fragment (from Headers to Declaration comment)
  47. # Filter out 'using' declarations to avoid conflicts
  48. if headers_start >= 0 and declaration_start >= 0:
  49. for i in range(headers_start, declaration_start):
  50. line: str = lines[i]
  51. if 'using' not in line:
  52. fm.write(line)
  53. fm.write("\nexport module httplib;\n\n")
  54. fm.write("export extern \"C++\" {\n")
  55. fm.write(f"{' ' * 4}#include \"httplib.h\"\n")
  56. fm.write("}\n")
  57. print(f"Wrote {cppm_out}")
  58. else:
  59. print(f"{cppm_out} is up to date")
  60. if __name__ == "__main__":
  61. main()