blob: 72d1a46d201be4de4deb32fc70144998b569d545 [file] [log] [blame]
Monty Taylor6c9634c2012-07-28 11:27:47 -05001#!/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 set_fix_released(bugtask):
78 """Set bug fix released"""
79
80 bugtask.status = "Fix Released"
81 bugtask.lp_save()
82
83
84def release_fixcommitted(bugtask):
85 """Set bug FixReleased if it was FixCommitted"""
86
87 if bugtask.status == u'Fix Committed':
88 set_fix_released(bugtask)
89
90
91def tag_in_branchname(bugtask, branch):
92 """Tag bug with in-branch-name tag (if name is appropriate)"""
93
94 lp_bug = bugtask.bug
95 branch_name = branch.replace('/', '-')
96 if branch_name.replace('-', '').isalnum():
97 lp_bug.tags = lp_bug.tags + ["in-%s" % branch_name]
98 lp_bug.tags.append("in-%s" % branch_name)
99 lp_bug.lp_save()
100
101
102def short_project(full_project_name):
103 """Return the project part of the git repository name"""
104 return full_project_name.split('/')[-1]
105
106
107def git2lp(full_project_name):
108 """Convert Git repo name to Launchpad project"""
109 project_map = {
110 'openstack/openstack-ci-puppet': 'openstack-ci',
111 'openstack-ci/devstack-gate': 'openstack-ci',
112 'openstack-ci/gerrit': 'openstack-ci',
113 'openstack-ci/lodgeit': 'openstack-ci',
114 'openstack-ci/meetbot': 'openstack-ci',
115 }
116 return project_map.get(full_project_name, short_project(full_project_name))
117
118
119def is_direct_release(full_project_name):
120 """Test against a list of projects who directly release changes."""
121 return full_project_name in [
122 'openstack-ci/devstack-gate',
123 'openstack-ci/lodgeit',
124 'openstack-ci/meetbot',
125 'openstack-dev/devstack',
126 'openstack/openstack-ci',
127 'openstack/openstack-ci-puppet',
128 'openstack/openstack-manuals',
129 ]
130
131
132def process_bugtask(launchpad, bugtask, git_log, args):
133 """Apply changes to bugtask, based on hook / branch..."""
134
135 if args.hook == "change-merged":
136 if args.branch == 'master':
137 if is_direct_release(args.project):
138 set_fix_released(bugtask)
139 else:
140 set_fix_committed(bugtask)
141 elif args.branch == 'milestone-proposed':
142 release_fixcommitted(bugtask)
143 elif args.branch.startswith('stable/'):
144 series = args.branch[7:]
145 # Look for a related task matching the series
146 for reltask in bugtask.related_tasks:
147 if reltask.bug_target_name.endswith("/" + series):
148 # Use fixcommitted if there is any
149 set_fix_committed(reltask)
150 break
151 else:
152 # Use tagging if there isn't any
153 tag_in_branchname(bugtask, args.branch)
154
155 add_change_merged_message(bugtask, args.change_url, args.project,
156 args.commit, args.submitter, args.branch,
157 git_log)
158
159 if args.hook == "patchset-created":
160 if args.branch == 'master':
161 set_in_progress(bugtask, launchpad, args.uploader, args.change_url)
162 elif args.branch.startswith('stable/'):
163 series = args.branch[7:]
164 for reltask in bugtask.related_tasks:
165 if reltask.bug_target_name.endswith("/" + series):
166 set_in_progress(reltask, launchpad,
167 args.uploader, args.change_url)
168 break
169
170 if args.patchset == '1':
171 add_change_proposed_message(bugtask, args.change_url,
172 args.project, args.branch)
173
174
175def find_bugs(launchpad, git_log, args):
176 """Find bugs referenced in the git log and return related bugtasks"""
177
178 bug_regexp = r'([Bb]ug|[Ll][Pp])[\s#:]*(\d+)'
179 tokens = re.split(bug_regexp, git_log)
180
181 # Extract unique bug tasks
182 bugtasks = {}
183 for token in tokens:
184 if re.match('^\d+$', token) and (token not in bugtasks):
185 try:
186 lp_bug = launchpad.bugs[token]
187 for lp_task in lp_bug.bug_tasks:
188 if lp_task.bug_target_name == git2lp(args.project):
189 bugtasks[token] = lp_task
190 break
191 except KeyError:
192 # Unknown bug
193 pass
194
195 return bugtasks.values()
196
197
198def extract_git_log(args):
199 """Extract git log of all merged commits"""
200 cmd = ['git',
201 '--git-dir=' + BASE_DIR + '/git/' + args.project + '.git',
202 'log', '--no-merges', args.commit + '^1..' + args.commit]
203 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
204
205
206def main():
207 parser = argparse.ArgumentParser()
208 parser.add_argument('hook')
209 #common
210 parser.add_argument('--change', default=None)
211 parser.add_argument('--change-url', default=None)
212 parser.add_argument('--project', default=None)
213 parser.add_argument('--branch', default=None)
214 parser.add_argument('--commit', default=None)
215 #change-merged
216 parser.add_argument('--submitter', default=None)
217 #patchset-created
218 parser.add_argument('--uploader', default=None)
219 parser.add_argument('--patchset', default=None)
220
221 args = parser.parse_args()
222
223 # Connect to Launchpad
224 launchpad = Launchpad.login_with('Gerrit User Sync', LPNET_SERVICE_ROOT,
225 GERRIT_CACHE_DIR,
226 credentials_file=GERRIT_CREDENTIALS,
227 version='devel')
228
229 # Get git log
230 git_log = extract_git_log(args)
231
232 # Process bugtasks found in git log
233 for bugtask in find_bugs(launchpad, git_log, args):
234 process_bugtask(launchpad, bugtask, git_log, args)
235
236
237if __name__ == '__main__':
238 main()