Guest User

Untitled

a guest
Jan 27th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """ Git post-receive hook to publish commit data to an AMQP topic.
  3.  
  4. apt-get install python-git python-amqplib
  5. or:
  6. easy_install amqplib gitpython
  7. """
  8. import os, sys, json
  9. from datetime import datetime
  10. from git import *
  11. from amqplib import client_0_8 as amqp
  12.  
  13. AMQP_HOST = 'localhost'
  14. AMQP_PORT = 5672
  15. AMQP_USER = 'git'
  16. AMQP_PASSWORD = 'git'
  17. AMQP_VHOST = '/development'
  18. AMQP_EXCHANGE = 'git'
  19.  
  20. def get_commits(repo, ref, from_commit, to_commit):
  21. if from_commit == '0' * 40:
  22. # Branch create
  23. return get_new_revisions(repo, ref, to_commit)
  24. if to_commit == '0' * 40:
  25. # Branch delete
  26. return []
  27. return get_new_revisions(repo, ref, '%s..%s' % (from_commit, to_commit))
  28.  
  29. def format_actor(actor):
  30. return {'name': actor.name, 'email': actor.email}
  31.  
  32. def format_commit(commit):
  33. return {'author': format_actor(commit.author),
  34. 'committer': format_actor(commit.committer),
  35. 'message': commit.message,
  36. 'sha': commit.hexsha,
  37. 'date': commit.committed_date}
  38.  
  39. def format_branch(commits):
  40. return [format_commit(commit) for commit in commits]
  41.  
  42. def get_new_revisions(repo, ref, revspec):
  43. """ This magic fetches previously-unseen revisions, and is based on the
  44. show-new-revisions function in git's post-receive-email hook."""
  45. other_branches = repo.git.for_each_ref('refs/heads', format='%(refname)').split("\n")
  46. other_branches.remove(ref)
  47. revs = repo.git.rev_parse("--not", other_branches).split("\n")
  48. return repo.iter_commits(revs + [revspec])
  49.  
  50. def send_message(host, port, user, password, vhost, exchange_name, key, message):
  51. conn = amqp.Connection(host=host, port=port, userid=user, password=password, virtual_host=vhost)
  52. channel = conn.channel()
  53. channel.access_request('/data', active=True, read=True)
  54. channel.exchange_declare(exchange_name, type='topic', durable=True, auto_delete=False)
  55. message = amqp.Message(timestamp=datetime.utcnow(), body=json.dumps(message),
  56. content_type='application/json', routing_key=key)
  57. channel.basic_publish(message, exchange_name)
  58.  
  59. if __name__ == '__main__':
  60. repo = Repo(os.environ['GIT_DIR'])
  61. out = {}
  62. for line in sys.stdin.xreadlines():
  63. old, new, ref = line.strip().split(' ')
  64. commits = list(get_commits(repo, ref, old, new))
  65. if len(commits) > 0:
  66. out[ref] = format_branch(commits)
  67. if len(out) > 0:
  68. key = os.path.basename(repo.working_dir)
  69. send_message(AMQP_HOST, AMQP_PORT, AMQP_USER, AMQP_PASSWORD, AMQP_VHOST, AMQP_EXCHANGE, key, out)
Add Comment
Please, Sign In to add comment