yaml_validate.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. #
  3. # python yaml validator for a git commit
  4. #
  5. '''
  6. python yaml validator for a git commit
  7. '''
  8. import shutil
  9. import sys
  10. import os
  11. import glob
  12. import tempfile
  13. import subprocess
  14. import yaml
  15. def get_changes(oldrev, newrev, tempdir):
  16. '''Get a list of git changes from oldrev to newrev'''
  17. proc = subprocess.Popen(['/usr/bin/git', 'diff', '--name-only', oldrev,
  18. newrev, '--diff-filter=ACM'], stdout=subprocess.PIPE)
  19. proc.wait()
  20. files = proc.stdout.read().strip().split('\n')
  21. # No file changes
  22. if not files:
  23. return []
  24. cmd = '/usr/bin/git archive %s %s | /bin/tar x -C %s' % (newrev, " ".join(files), tempdir)
  25. proc = subprocess.Popen(cmd, shell=True)
  26. proc.wait()
  27. return [fmod for fmod in glob.glob('%s/**/*' % tempdir) if not os.path.isdir(fmod)]
  28. def main():
  29. '''
  30. Perform yaml validation
  31. '''
  32. results = []
  33. try:
  34. tmpdir = tempfile.mkdtemp(prefix='jenkins-git-')
  35. old, new, _ = sys.argv[1:]
  36. for file_mod in get_changes(old, new, tmpdir):
  37. print "+++++++ Received: %s" % file_mod
  38. if not file_mod.endswith('.yml') or not file_mod.endswith('.yaml'):
  39. continue
  40. try:
  41. yaml.load(file_mod)
  42. results.append(True)
  43. except yaml.scanner.ScannerError as yerr:
  44. print yerr.message
  45. results.append(False)
  46. finally:
  47. shutil.rmtree(tmpdir)
  48. if not all(results):
  49. sys.exit(1)
  50. if __name__ == "__main__":
  51. main()