__main__.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import difflib
  2. import json
  3. import os
  4. import subprocess
  5. import time
  6. import yaml
  7. from build.plugins.lib.test_const import CLANG_FORMAT_RESOURCE
  8. from library.python.testing.custom_linter_util import linter_params, reporter
  9. from library.python.testing.style import rules
  10. def main():
  11. params = linter_params.get_params()
  12. clang_format_binary = os.path.join(params.global_resources[CLANG_FORMAT_RESOURCE], 'clang-format')
  13. style_config_path = params.configs[0]
  14. with open(style_config_path) as f:
  15. style_config = yaml.safe_load(f)
  16. style_config_json = json.dumps(style_config)
  17. report = reporter.LintReport()
  18. for file_name in params.files:
  19. start_time = time.time()
  20. status, message = check_file(clang_format_binary, style_config_json, file_name)
  21. elapsed = time.time() - start_time
  22. report.add(file_name, status, message, elapsed=elapsed)
  23. report.dump(params.report_file)
  24. def check_file(clang_format_binary, style_config_json, filename):
  25. with open(filename, "rb") as f:
  26. actual_source = f.read()
  27. skip_reason = rules.get_skip_reason(filename, actual_source, skip_links=False)
  28. if skip_reason:
  29. return reporter.LintStatus.SKIPPED, "Style check is omitted: {}".format(skip_reason)
  30. command = [clang_format_binary, '-assume-filename=' + filename, '-style=' + style_config_json]
  31. styled_source = subprocess.check_output(command, input=actual_source)
  32. if styled_source == actual_source:
  33. return reporter.LintStatus.GOOD, ""
  34. else:
  35. diff = make_diff(actual_source, styled_source)
  36. return reporter.LintStatus.FAIL, diff
  37. def make_diff(left, right):
  38. result = ""
  39. for line in difflib.unified_diff(left.decode().splitlines(), right.decode().splitlines(), fromfile='L', tofile='R'):
  40. line = line.rstrip("\n")
  41. if line:
  42. if line[0] == "-":
  43. line = "[[bad]]" + line + "[[rst]]"
  44. elif line[0] == "+":
  45. line = "[[good]]" + line + "[[rst]]"
  46. result += line + "\n"
  47. return result
  48. if __name__ == "__main__":
  49. main()