blob: f322332d979a462e76fdc740b36cbe171fe045a5 [file] [log] [blame]
Monty Taylorf45f6ca2012-05-01 17:11:48 -04001#!/usr/bin/env python
2# Copyright (c) 2011 OpenStack, LLC.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
16# This is designed to be called by a gerrit hook. It searched new
17# patchsets for strings like "bug FOO" and updates corresponding Launchpad
18# bugs status.
19
20from launchpadlib.launchpad import Launchpad
21from launchpadlib.uris import LPNET_SERVICE_ROOT
22import os
23import argparse
24import re
25import subprocess
26
27
28BASE_DIR = '/home/gerrit2/review_site'
29GERRIT_CACHE_DIR = os.path.expanduser(os.environ.get('GERRIT_CACHE_DIR',
30 '~/.launchpadlib/cache'))
31GERRIT_CREDENTIALS = os.path.expanduser(os.environ.get('GERRIT_CREDENTIALS',
32 '~/.launchpadlib/creds'))
33
34
35def add_change_proposed_message(bugtask, change_url, project, branch):
36 subject = 'Fix proposed to %s (%s)' % (short_project(project), branch)
37 body = 'Fix proposed to branch: %s\nReview: %s' % (branch, change_url)
38 bugtask.bug.newMessage(subject=subject, content=body)
39
40
41def add_change_merged_message(bugtask, change_url, project, commit,
42 submitter, branch, git_log):
43 subject = 'Fix merged to %s (%s)' % (short_project(project), branch)
44 git_url = 'http://github.com/%s/commit/%s' % (project, commit)
45 body = '''Reviewed: %s
46Committed: %s
47Submitter: %s
48Branch: %s\n''' % (change_url, git_url, submitter, branch)
49 body = body + '\n' + git_log
50 bugtask.bug.newMessage(subject=subject, content=body)
51
52
53def set_in_progress(bugtask, launchpad, uploader, change_url):
54 """Set bug In progress with assignee being the uploader"""
55
56 # Retrieve uploader from Launchpad. Use email as search key if
57 # provided, and only set if there is a clear match.
58 try:
59 searchkey = uploader[uploader.rindex("(") + 1:-1]
60 except ValueError:
61 searchkey = uploader
62 persons = launchpad.people.findPerson(text=searchkey)
63 if len(persons) == 1:
64 bugtask.assignee = persons[0]
65
66 bugtask.status = "In Progress"
67 bugtask.lp_save()
68
69
70def set_fix_committed(bugtask):
71 """Set bug fix committed"""
72
73 bugtask.status = "Fix Committed"
74 bugtask.lp_save()
75
76
77def release_fixcommitted(bugtask):
78 """Set bug FixReleased if it was FixCommitted"""
79
80 if bugtask.status == u'Fix Committed':
81 bugtask.status = "Fix Released"
82 bugtask.lp_save()
83
84
85def tag_in_branchname(bugtask, branch):
86 """Tag bug with in-branch-name tag (if name is appropriate)"""
87
88 lp_bug = bugtask.bug
89 branch_name = branch.replace('/', '-')
90 if branch_name.replace('-', '').isalnum():
91 lp_bug.tags = lp_bug.tags + ["in-%s" % branch_name]
92 lp_bug.tags.append("in-%s" % branch_name)
93 lp_bug.lp_save()
94
95
96def short_project(full_project_name):
97 """Return the project part of the git repository name"""
98 return full_project_name.split('/')[-1]
99
100
101def git2lp(full_project_name):
102 """Convert Git repo name to Launchpad project"""
103 project_map = {
Monty Taylorde5f3f82012-05-03 13:11:53 -0700104 'openstack/python-cinderclient': 'cinder',
Monty Taylorf45f6ca2012-05-01 17:11:48 -0400105 'openstack/python-glanceclient': 'glance',
106 'openstack/python-keystoneclient': 'keystone',
107 'openstack/python-melangeclient': 'melange',
108 'openstack/python-novaclient': 'nova',
109 'openstack/python-quantumclient': 'quantum',
110 'openstack/openstack-ci-puppet': 'openstack-ci',
111 'openstack-ci/devstack-gate': 'openstack-ci',
112 }
113 return project_map.get(full_project_name, short_project(full_project_name))
114
115
116def process_bugtask(launchpad, bugtask, git_log, args):
117 """Apply changes to bugtask, based on hook / branch..."""
118
119 if args.hook == "change-merged":
120 if args.branch == 'master':
121 set_fix_committed(bugtask)
122 elif args.branch == 'milestone-proposed':
123 release_fixcommitted(bugtask)
124 else:
125 tag_in_branchname(bugtask, args.branch)
126 add_change_merged_message(bugtask, args.change_url, args.project,
127 args.commit, args.submitter, args.branch,
128 git_log)
129
130 if args.hook == "patchset-created":
131 if args.branch == 'master':
132 set_in_progress(bugtask, launchpad, args.uploader, args.change_url)
133 if args.patchset == '1':
134 add_change_proposed_message(bugtask, args.change_url,
135 args.project, args.branch)
136
137
138def find_bugs(launchpad, git_log, args):
139 """Find bugs referenced in the git log and return related bugtasks"""
140
141 bug_regexp = r'([Bb]ug|[Ll][Pp])[\s#:]*(\d+)'
142 tokens = re.split(bug_regexp, git_log)
143
144 # Extract unique bug tasks
145 bugtasks = {}
146 for token in tokens:
147 if re.match('^\d+$', token) and (token not in bugtasks):
148 try:
149 lp_bug = launchpad.bugs[token]
150 for lp_task in lp_bug.bug_tasks:
151 if lp_task.bug_target_name == git2lp(args.project):
152 bugtasks[token] = lp_task
153 break
154 except KeyError:
155 # Unknown bug
156 pass
157
158 return bugtasks.values()
159
160
161def extract_git_log(args):
162 """Extract git log of all merged commits"""
163 cmd = ['git',
164 '--git-dir=' + BASE_DIR + '/git/' + args.project + '.git',
165 'log', '--no-merges', args.commit + '^1..' + args.commit]
166 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
167
168
169def main():
170 parser = argparse.ArgumentParser()
171 parser.add_argument('hook')
172 #common
173 parser.add_argument('--change', default=None)
174 parser.add_argument('--change-url', default=None)
175 parser.add_argument('--project', default=None)
176 parser.add_argument('--branch', default=None)
177 parser.add_argument('--commit', default=None)
178 #change-merged
179 parser.add_argument('--submitter', default=None)
180 #patchset-created
181 parser.add_argument('--uploader', default=None)
182 parser.add_argument('--patchset', default=None)
183
184 args = parser.parse_args()
185
186 # Connect to Launchpad
187 launchpad = Launchpad.login_with('Gerrit User Sync', LPNET_SERVICE_ROOT,
188 GERRIT_CACHE_DIR,
189 credentials_file=GERRIT_CREDENTIALS,
190 version='devel')
191
192 # Get git log
193 git_log = extract_git_log(args)
194
195 # Process bugtasks found in git log
196 for bugtask in find_bugs(launchpad, git_log, args):
197 process_bugtask(launchpad, bugtask, git_log, args)
198
199
200if __name__ == '__main__':
201 main()