yaml_validation.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 tempfile
  12. import subprocess
  13. import yaml
  14. def get_changes(oldrev, newrev, tempdir):
  15. '''Get a list of git changes from oldrev to newrev'''
  16. proc = subprocess.Popen(['/usr/bin/git', 'diff', '--name-only', oldrev,
  17. newrev, '--diff-filter=ACM'], stdout=subprocess.PIPE)
  18. stdout, _ = proc.communicate()
  19. files = stdout.split('\n')
  20. # No file changes
  21. if not files:
  22. return []
  23. cmd = '/usr/bin/git archive %s %s | /bin/tar x -C %s' % (newrev, " ".join(files), tempdir)
  24. proc = subprocess.Popen(cmd, shell=True)
  25. _, _ = proc.communicate()
  26. rfiles = []
  27. for dirpath, _, fnames in os.walk(tempdir):
  28. for fname in fnames:
  29. rfiles.append(os.path.join(dirpath, fname))
  30. return rfiles
  31. def main():
  32. '''
  33. Perform yaml validation
  34. '''
  35. results = []
  36. try:
  37. tmpdir = tempfile.mkdtemp(prefix='jenkins-git-')
  38. old, new, _ = sys.argv[1:]
  39. for file_mod in get_changes(old, new, tmpdir):
  40. print "+++++++ Received: %s" % file_mod
  41. if not file_mod.endswith('.yml') and not file_mod.endswith('.yaml') and not os.path.islink(file_mod):
  42. continue
  43. try:
  44. yaml.load(open(file_mod))
  45. results.append(True)
  46. except yaml.scanner.ScannerError as yerr:
  47. print yerr
  48. results.append(False)
  49. finally:
  50. shutil.rmtree(tmpdir)
  51. if not all(results):
  52. sys.exit(1)
  53. if __name__ == "__main__":
  54. main()