check-idl-files.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import pathlib
  5. import re
  6. import subprocess
  7. import sys
  8. script_name = pathlib.Path(__file__).resolve().name
  9. lines_to_skip = re.compile(
  10. r"^($| *//|\};|#import |.+ includes .+|\[[^\]]+\]"
  11. r"|interface |(?:partial )?dictionary |enum |namespace |typedef |callback )"
  12. )
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument("--overwrite-inplace", action=argparse.BooleanOptionalAction)
  15. parser.add_argument('filenames', nargs='*')
  16. args = parser.parse_args()
  17. SINGLE_PAGE_HTML_SPEC_LINK = re.compile('//.*https://html\\.spec\\.whatwg\\.org/#')
  18. def find_files_here_or_argv():
  19. if args.filenames:
  20. raw_list = args.filenames
  21. else:
  22. process = subprocess.run(["git", "ls-files"], check=True, capture_output=True)
  23. raw_list = process.stdout.decode().strip("\n").split("\n")
  24. return filter(lambda filename: filename.endswith(".idl"), raw_list)
  25. def run():
  26. """Lint WebIDL files checked into git for four leading spaces on each line."""
  27. files_without_four_leading_spaces = set()
  28. """Also lint for them not containing any links to the single-page HTML spec."""
  29. files_with_single_page_html_spec_link = set()
  30. did_fail = False
  31. for filename in find_files_here_or_argv():
  32. lines = []
  33. with open(filename, "r") as f:
  34. for line_number, line in enumerate(f, start=1):
  35. if SINGLE_PAGE_HTML_SPEC_LINK.search(line):
  36. files_with_single_page_html_spec_link.add(filename)
  37. if lines_to_skip.match(line):
  38. lines.append(line)
  39. continue
  40. if not line.startswith(" "):
  41. if args.overwrite_inplace:
  42. line = " " + line.lstrip()
  43. lines.append(line)
  44. continue
  45. did_fail = True
  46. files_without_four_leading_spaces.add(filename)
  47. print(
  48. f"{filename}:{line_number} error: Line does not start with four spaces:{line.rstrip()}")
  49. lines.append(line)
  50. if args.overwrite_inplace:
  51. with open(filename, "w") as f:
  52. f.writelines(lines)
  53. if files_without_four_leading_spaces:
  54. print("\nWebIDL files that have lines without four leading spaces:",
  55. " ".join(files_without_four_leading_spaces))
  56. if not args.overwrite_inplace:
  57. print(
  58. f"\nTo fix the WebIDL files in place, run: ./Meta/{script_name} --overwrite-inplace")
  59. if files_with_single_page_html_spec_link:
  60. print("\nWebIDL files that have links to the single-page HTML spec:",
  61. " ".join(files_with_single_page_html_spec_link))
  62. if did_fail:
  63. sys.exit(1)
  64. if __name__ == "__main__":
  65. os.chdir(os.path.dirname(__file__) + "/..")
  66. run()