check_gn_flags.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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(
  53. '-f',
  54. '--flags-gn',
  55. type=Path,
  56. default=default_flags_gn,
  57. help='Path to the GN flags to use. Default: %(default)s')
  58. args = parser.parse_args()
  59. if check_gn_flags(args.flags_gn):
  60. exit(1)
  61. exit(0)
  62. if __name__ == '__main__':
  63. main()