summaryrefslogtreecommitdiff
blob: c7b676f4e0bd0d1afd6e738011f690feb1f5532e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python
# Copyright 2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

import glob
import itertools
import optparse
import os
import pickle
import re
import shutil
import subprocess
import sys

from bugz.bugzilla import BugzillaProxy
from common import login
import portage.versions

BUG_REGEX = re.compile("[Bb]ug #?(\d+)")

def print_and_log(message, log):
	try:
		print message
		log.write(message + '\n')
	finally:
		log.flush()

def run_command(args, cwd, log):
	try:
		message = "Running %r in %s...\n" % (args, cwd)
		sys.stdout.write(message)
		log.write(message)

		cmd  = subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
		output = cmd.communicate()[0]
		log.write("Finished with exit code %d\n" % cmd.returncode)
		log.write(output)
		return (cmd.returncode, output)
	finally:
		log.flush()

def save_state(done_bugs):
	with open('batch-stabilize.state', 'w') as state_file:
		pickle.dump(done_bugs, state_file)

if __name__ == "__main__":
	parser = optparse.OptionParser()
	parser.add_option("--arch", dest="arch", help="Gentoo arch to use, e.g. x86, amd64, ...")
	parser.add_option("-i", "--input", dest="input_filename", default="package.keywords", help="Input filename for generated package.keywords file [default=%default]")
	parser.add_option("--repo", dest="repo", help="Path to portage CVS repository")
	parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False)

	(options, args) = parser.parse_args()
	if not options.arch:
		parser.error("--arch option is required")
	if not options.input_filename:
		parser.error("--input option is required")
	if not options.repo:
		parser.error("--repo option is required")
	if args:
		parser.error("unrecognized command-line args")

	done_bugs = []
	if os.path.exists('batch-stabilize.state'):
		with open('batch-stabilize.state', 'r') as state_file:
			done_bugs = pickle.load(state_file)

	url = 'https://bugs.gentoo.org/xmlrpc.cgi'
	print 'You will be prompted for your Gentoo Bugzilla username and password (%s).' % url
	bugzilla = BugzillaProxy(url)
	login(bugzilla)
	
	with open(options.input_filename, "r") as input_file:
		stabilization_dict = {}
		bug_id = -1
		for line in input_file:
			line = line.strip()

			# Skip empty/whitespace lines.
			if not line:
				continue

			if line.startswith("#"):
				match = BUG_REGEX.search(line, re.IGNORECASE)
				if not match:
					print 'Ignoring comment line [%s]...' % line
					continue
				else:
					bug_id = int(match.group(1))
				continue

			if bug_id == -1:
				print 'Could not recognize bug id'
				sys.exit(1)

			# Drop the leading '='.
			cpv = line[1:]

			p = portage.versions.catsplit(cpv)[1]
			pn = portage.versions.pkgsplit(cpv)[0]
			ebuild_name = p + ".ebuild"
			if bug_id not in stabilization_dict:
				stabilization_dict[bug_id] = []
			stabilization_dict[bug_id].append((pn, ebuild_name))

		# Sanity check.
		success = True
		for bug_id in stabilization_dict:
			for (pn, ebuild_name) in stabilization_dict[bug_id]:
				ebuild_path = os.path.join(options.repo, pn, ebuild_name)
				if not os.path.exists(ebuild_path):
					print '%s: file does not exist' % ebuild_path
					success = False
		if not success:
			print 'Sanity check failed. Please make sure your CVS repo is up to date (cvs up).'
			sys.exit(1)

		with open('batch-stabilize.log', 'a') as log_file:
			for bug_id in stabilization_dict:
				if bug_id in done_bugs:
					print_and_log('Skipping bug #%d because it is marked as done.' % bug_id, log_file)
					continue

				print_and_log('Working on bug %d...' % bug_id, log_file)
				commit_message = "%s stable wrt bug #%d" % (options.arch, bug_id)
				for (pn, ebuild_name) in stabilization_dict[bug_id]:
					cvs_path = os.path.join(options.repo, pn)
					print_and_log('Working in %s...' % cvs_path, log_file)

					# Remove whole directory to prevent problems with conflicts.
					if os.path.exists(cvs_path):
						try:
							shutil.rmtree(cvs_path)
						except OSError:
							print '!!! rmtree %s failed' % cvs_path
							sys.exit(1)

					if run_command(["cvs", "up", pn], options.repo, log_file)[0] != 0:
						print '!!! cvs up failed'
						sys.exit(1)
				for (pn, ebuild_name) in stabilization_dict[bug_id]:
					cvs_path = os.path.join(options.repo, pn)
					print_and_log('Working in %s...' % cvs_path, log_file)
					if run_command(["ekeyword", options.arch, ebuild_name], cvs_path, log_file)[0] != 0:
						print '!!! ekeyword failed'
						sys.exit(1)
					if run_command(["repoman", "manifest"], cvs_path, log_file)[0] != 0:
						print '!!! repoman manifest failed'
						sys.exit(1)
				for (pn, ebuild_name) in stabilization_dict[bug_id]:
					cvs_path = os.path.join(options.repo, pn)
					print_and_log('Working in %s...' % cvs_path, log_file)
					return_code, output = run_command(["cvs", "diff"], cvs_path, log_file)
					# It seems that cvs diff returns 1 if there are differences.
					if return_code == 0 and not output:
						print_and_log('Seems already keyworded, skipping.', log_file)
						done_bugs.append(bug_id)
						save_state(done_bugs)
						continue
					if run_command(["echangelog", commit_message], cvs_path, log_file)[0] != 0:
						print_and_log('echangelog failed, maybe just the Manifest is being updated; continuing', log_file)
					if run_command(["repoman", "manifest"], cvs_path, log_file)[0] != 0:
						print '!!! repoman manifest failed'
						sys.exit(1)
					if run_command(["repoman", "commit", "--ignore-arches", "-m", commit_message], cvs_path, log_file)[0] != 0:
						print '!!! repoman commit failed'
						sys.exit(1)
				params = {}
				params['ids'] = [bug_id]
				bug_xml = bugzilla.Bug.get(params)['bugs'][0]
				has_my_arch = False
				has_other_arches = False
				for cc in bug_xml['cc']:
					body, domain = cc.split('@', 1)
					if domain == 'gentoo.org':
						if body == options.arch:
							has_my_arch = True
						elif body in portage.archlist:
							has_other_arches=True

				if not has_my_arch:
					print_and_log('Seems that bugzilla has already been updated.', log_file)
					done_bugs.append(bug_id)
					save_state(done_bugs)
					continue

				print_and_log('Posting automated reply in bugzilla...', log_file)
				# We don't close bugs which still have other arches for obvious reasons,
				# and security bugs because stabilization is not the last step for them.
				params = {}
				params['ids'] = [bug_id]
				params['cc'] = {}
				params['cc']['remove'] = ['%s@gentoo.org' % options.arch]
				params['comment'] = {}
				if has_other_arches or 'Security' in bug_xml['product']:
					params['comment']['body'] = '%s stable' % options.arch
					log_msg = 'Successfully updated'
				else:
					params['comment']['body'] = '%s stable, closing' % options.arch
					params['status'] = 'RESOLVED'
					params['resolution'] = 'FIXED'
					log_msg = 'Successfully updated and closed'

				bugzilla.Bug.update(params)
				print_and_log('%s bug %d.' % (log_msg, bug_id), log_file)
				done_bugs.append(bug_id)
				save_state(done_bugs)
	
	if os.path.exists('batch-stabilize.state'):
		os.remove('batch-stabilize.state')