Advertisement
Guest User

Untitled

a guest
Oct 24th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.74 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import requests
  3. import json
  4. import git
  5. import argparse
  6. from git import Git
  7.  
  8. username = 'almamgr'
  9. password = 'c0blmf!'
  10. host_bb = 'https://bitbucket.sco.alma.cl/'
  11. host_jira = 'https://ictjira.alma.cl/'
  12.  
  13. class NotFoundException(Exception):
  14. pass
  15.  
  16. def get_open_pull_requests(project='ALMA', repo='almasw'):
  17. url = host_bb + 'rest/api/1.0/projects/' + project + '/repos/' + repo + '/pull-requests'
  18. params = {'state': 'OPEN', 'order': 'OLDEST', 'limit': 1000}
  19. r = requests.get(url, params=params, auth=(username, password))
  20. if r.status_code != 200:
  21. print r.text
  22. return False
  23. from StringIO import StringIO
  24. io = StringIO(r.text)
  25. return json.load(io)
  26.  
  27.  
  28. def get_ictjira_ticket_associated(pull_request_id=None, project='ALMA', repo='almasw'):
  29. if pull_request_id is None:
  30. raise Exception("pull_request_id could not be None")
  31. url = host_bb + 'rest/jira/1.0/projects/' + project + '/repos/' + repo + '/pull-requests/' + pull_request_id + '/issues'
  32. r = requests.get(url, auth=(username, password))
  33. if r.status_code != 200:
  34. print r.text
  35. raise Exception(r.text)
  36. from StringIO import StringIO
  37. io = StringIO(r.text)
  38. return json.load(io)
  39.  
  40.  
  41. def get_jira_data(ticket_id=None):
  42. if ticket_id is None:
  43. raise Exception("ticket_id could not be None")
  44. url = host_jira + 'rest/api/latest/issue/' + ticket_id
  45. print url
  46. r = requests.get(url, auth=(username, password))
  47. if not (("ICT-" in r.text) or ("SCCB-" in r.text)):
  48. return False
  49. if r.status_code == 404:
  50. raise NotFoundException(url)
  51. if r.status_code != 200:
  52. print r.text
  53. raise Exception(str(r.status_code) + ' ' + r.text)
  54. from StringIO import StringIO
  55. io = StringIO(r.text)
  56. return json.load(io)
  57.  
  58.  
  59. def get_pull_requests_to_merge():
  60. pull_requests = get_open_pull_requests()
  61. ret_val = {}
  62. for pr in pull_requests['values']:
  63. if pr['properties'].has_key('mergeResult'):
  64. print pr['id'], pr['properties']['mergeResult']['outcome'], pr['fromRef']['displayId']
  65. else:
  66. print pr['id'], pr['fromRef']['displayId']
  67. if pr['toRef']['displayId'] != 'master':
  68. continue
  69. ret_val[pr['id']] = {}
  70. ret_val[pr['id']]['branch'] = pr['fromRef']['displayId']
  71. ret_val[pr['id']]['fixVersion'] = []
  72. for ticket_id in get_ictjira_ticket_associated(str(pr['id'])):
  73. try:
  74. jira_info = get_jira_data(ticket_id['key'])
  75. except NotFoundException as ex:
  76. print 'No info found for', ex
  77. try:
  78. if ticket_id['key'].startswith('ICT'):
  79. print jira_info['fields']['fixVersions'][0]['name'], jira_info['fields']['status']['name']
  80. ret_val[pr['id']]['fixVersion'].append(jira_info['fields']['fixVersions'][0]['name'])
  81. elif ticket_id['key'].startswith('SCCB'):
  82. try:
  83. print jira_info['fields']['customfield_10500'][0]['name'], jira_info['fields']['status']['name']
  84. ret_val[pr['id']]['fixVersion'].append(jira_info['fields']['customfield_10500'][0]['name'])
  85. except TypeError:
  86. print 'Ignoring', ticket_id['key'], 'given branch is null.'
  87. except IndexError:
  88. print "No info for", ticket_id['key']
  89. print "-------------------------------------------"
  90. return ret_val
  91.  
  92.  
  93. def init():
  94. parser = argparse.ArgumentParser(description='Check for pull requests in bitbucket and merge the '
  95. 'branches to a given branch locally.')
  96. parser.add_argument('repo_path', help='The git repo path to use.', type=str)
  97. parser.add_argument('dest_branch', help='The destination branch on which the merge will be done.', type=str)
  98. parser.add_argument('fix_version', help='fixVersion reported in associated jira tickets to check.')
  99.  
  100. return parser.parse_args()
  101.  
  102.  
  103. def main():
  104. args = init()
  105. repo = git.Repo(args.repo_path)
  106. origin = repo.remotes['origin']
  107. origin.fetch()
  108.  
  109. master = repo.branches.master
  110. master.checkout()
  111. origin.pull()
  112.  
  113. try:
  114. new_branch = repo.create_head(args.dest_branch, master)
  115. new_branch.checkout()
  116. except OSError:
  117. new_branch = repo.branches[args.dest_branch]
  118. new_branch.checkout()
  119. try:
  120. origin.pull()
  121. except git.exc.GitCommandError:
  122. pass # Nothing to do, branch is not at upstream
  123.  
  124. branches_dict = get_pull_requests_to_merge()
  125. g = Git(args.repo_path)
  126. g.merge('master')
  127. for b in branches_dict:
  128. merging = False
  129. if branches_dict[b].has_key('fixVersion'):
  130. for branch in branches_dict[b]['fixVersion']:
  131. if branch == args.fix_version:
  132. merging = True
  133. print 'Merging origin/' + branches_dict[b]['branch']
  134. g.merge('origin/' + branches_dict[b]['branch'])
  135. break
  136. if not merging:
  137. if branches_dict[b].has_key('fixVersion'):
  138. print 'Ignoring pull request', branches_dict[b]['branch'], 'given fix version is not',\
  139. args.fix_version, ':', branches_dict[b]['fixVersion']
  140. else:
  141. print 'Ignoring pull request', branches_dict[b]['branch'], 'given fix version is None'
  142.  
  143. print 'The merge seems to be ok. You are ready to push the branch'
  144.  
  145.  
  146. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement