check_gn_flags.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """Run sanity checking algorithms over GN flags
  7. It checks the following:
  8. * GN flags in flags.gn are sorted and not duplicated
  9. Exit codes:
  10. * 0 if no problems detected
  11. * 1 if warnings or errors occur
  12. """
  13. import argparse
  14. import sys
  15. from pathlib import Path
  16. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'utils'))
  17. from _common import ENCODING, get_logger
  18. sys.path.pop(0)
  19. def check_gn_flags(gn_flags_path):
  20. """
  21. Checks if GN flags are sorted and not duplicated.
  22. gn_flags_path is a pathlib.Path to the GN flags file to check
  23. Returns True if warnings were logged; False otherwise
  24. """
  25. keys_seen = set()
  26. warnings = False
  27. with gn_flags_path.open(encoding=ENCODING) as file_obj:
  28. iterator = iter(file_obj.read().splitlines())
  29. try:
  30. previous = next(iterator)
  31. except StopIteration:
  32. return warnings
  33. for current in iterator:
  34. gn_key = current.split('=')[0]
  35. if gn_key in keys_seen:
  36. get_logger().warning('In GN flags %s, "%s" appears at least twice', gn_flags_path,
  37. gn_key)
  38. warnings = True
  39. else:
  40. keys_seen.add(gn_key)
  41. if current < previous:
  42. get_logger().warning('In GN flags %s, "%s" should be sorted before "%s"', gn_flags_path,
  43. current, previous)
  44. warnings = True
  45. previous = current
  46. return warnings
  47. def main():
  48. """CLI entrypoint"""
  49. root_dir = Path(__file__).resolve().parent.parent
  50. default_flags_gn = root_dir / 'flags.gn'
  51. parser = argparse.ArgumentParser(description=__doc__)
  52. parser.add_argument('-f',
  53. '--flags-gn',
  54. type=Path,
  55. default=default_flags_gn,
  56. help='Path to the GN flags to use. Default: %(default)s')
  57. args = parser.parse_args()
  58. if check_gn_flags(args.flags_gn):
  59. sys.exit(1)
  60. sys.exit(0)
  61. if __name__ == '__main__':
  62. main()