__main__.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if 'clang_format_bin' in params.extra_params:
  13. # custom clang-format
  14. clang_format_binary = params.depends[params.extra_params['clang_format_bin']]
  15. else:
  16. clang_format_binary = os.path.join(params.global_resources[CLANG_FORMAT_RESOURCE], 'clang-format')
  17. style_config_path = params.configs[0]
  18. with open(style_config_path) as f:
  19. style_config = yaml.safe_load(f)
  20. style_config_json = json.dumps(style_config)
  21. report = reporter.LintReport()
  22. for file_name in params.files:
  23. start_time = time.time()
  24. status, message = check_file(clang_format_binary, style_config_json, file_name)
  25. elapsed = time.time() - start_time
  26. report.add(file_name, status, message, elapsed=elapsed)
  27. report.dump(params.report_file)
  28. def check_file(clang_format_binary, style_config_json, filename):
  29. with open(filename, "rb") as f:
  30. actual_source = f.read()
  31. skip_reason = rules.get_skip_reason(filename, actual_source, skip_links=False)
  32. if skip_reason:
  33. return reporter.LintStatus.SKIPPED, "Style check is omitted: {}".format(skip_reason)
  34. command = [clang_format_binary, '-assume-filename=' + filename, '-style=' + style_config_json]
  35. styled_source = subprocess.check_output(command, input=actual_source)
  36. if styled_source == actual_source:
  37. return reporter.LintStatus.GOOD, ""
  38. else:
  39. diff = make_diff(actual_source, styled_source)
  40. return reporter.LintStatus.FAIL, diff
  41. def make_diff(left, right):
  42. result = ""
  43. for line in difflib.unified_diff(left.decode().splitlines(), right.decode().splitlines(), fromfile='L', tofile='R'):
  44. line = line.rstrip("\n")
  45. if line:
  46. if line[0] == "-":
  47. line = "[[bad]]" + line + "[[rst]]"
  48. elif line[0] == "+":
  49. line = "[[good]]" + line + "[[rst]]"
  50. result += line + "\n"
  51. return result
  52. if __name__ == "__main__":
  53. main()