1 |
#!/usr/bin/python |
2 |
|
3 |
# A lot of the code comes from ftpadmin, see |
4 |
# http://git.gnome.org/browse/sysadmin-bin/tree/ftpadmin |
5 |
# Written by Olav Vitters |
6 |
|
7 |
# basic modules: |
8 |
import os |
9 |
import os.path |
10 |
import sys |
11 |
import re |
12 |
import subprocess |
13 |
|
14 |
# command line parsing, error handling: |
15 |
import argparse |
16 |
import errno |
17 |
|
18 |
# overwriting files by moving them (safer): |
19 |
import tempfile |
20 |
import shutil |
21 |
|
22 |
# version comparison: |
23 |
import rpm |
24 |
|
25 |
# opening tarballs: |
26 |
import tarfile |
27 |
import gzip |
28 |
import bz2 |
29 |
import lzma # pyliblzma |
30 |
|
31 |
# getting links from HTML document: |
32 |
from sgmllib import SGMLParser |
33 |
import urllib2 |
34 |
import urlparse |
35 |
|
36 |
MEDIA="Core Release Source" |
37 |
URL="http://download.gnome.org/sources/" |
38 |
PKGROOT='~/pkgs' |
39 |
|
40 |
re_version = re.compile(r'([-.]|\d+|[^-.\d]+)') |
41 |
|
42 |
def version_cmp(a, b): |
43 |
"""Compares two versions |
44 |
|
45 |
Returns |
46 |
-1 if a < b |
47 |
0 if a == b |
48 |
1 if a > b |
49 |
""" |
50 |
|
51 |
return rpm.labelCompare(('1', a, '1'), ('1', b, '1')) |
52 |
|
53 |
def get_latest_version(versions, max_version=None): |
54 |
"""Gets the latest version number |
55 |
|
56 |
if max_version is specified, gets the latest version number before |
57 |
max_version""" |
58 |
latest = None |
59 |
for version in versions: |
60 |
if ( latest is None or version_cmp(version, latest) > 0 ) \ |
61 |
and ( max_version is None or version_cmp(version, max_version) < 0 ): |
62 |
latest = version |
63 |
return latest |
64 |
|
65 |
def judge_version_increase(version_old, version_new): |
66 |
"""Judge quality of version increase: |
67 |
|
68 |
Returns a tuple containing judgement and message |
69 |
|
70 |
Judgement: |
71 |
Less than 0: Error |
72 |
0 to 4: Better not |
73 |
5+: Ok""" |
74 |
versions = (version_old, version_new) |
75 |
|
76 |
print " => ".join(versions) |
77 |
|
78 |
# First do a basic version comparison to ensure version_new is actually newer |
79 |
compare = version_cmp(version_new, version_old) |
80 |
|
81 |
if compare == 0: |
82 |
return (-2, "Already at version %s!" % (version_old)) |
83 |
|
84 |
if compare != 1: |
85 |
return (-3, "Version %s is older than current version %s!" % (version_new, version_old)) |
86 |
|
87 |
# Version is newer, but we don't want to see if it follows the GNOME versioning scheme |
88 |
majmins = [re_majmin.sub(r'\1', ver) for ver in versions if re_majmin.match(ver) is not None] |
89 |
|
90 |
if len(majmins) == 1: |
91 |
return (-1, "Version number scheme changes: %s" % (", ".join(versions))) |
92 |
|
93 |
if len(majmins) == 0: |
94 |
return (0, "Unsupported version numbers: %s" % (", ".join(versions))) |
95 |
|
96 |
# Follows GNOME versioning scheme |
97 |
# Meaning: x.y.z |
98 |
# x = major |
99 |
# y = minor : even if stable |
100 |
# z = micro |
101 |
|
102 |
# Major+minor the same? Then go ahead and upgrade! |
103 |
if majmins[0] == majmins[1]: |
104 |
# Majmin of both versions are the same, looks good! |
105 |
return (10, None) |
106 |
|
107 |
# More detailed analysis needed, so figure out the numbers |
108 |
majmin_nrs = [map(long, ver.split('.')) for ver in majmins] |
109 |
|
110 |
# Check/ensure major version number is the same |
111 |
if majmin_nrs[0][0] != majmin_nrs[1][0]: |
112 |
return (1, "Major version number increase") |
113 |
|
114 |
# Minor indicates stable/unstable |
115 |
devstate = (majmin_nrs[0][1] % 2 == 0, majmin_nrs[1][1] % 2 == 0) |
116 |
|
117 |
# Upgrading to unstable is weird |
118 |
if not devstate[1]: |
119 |
if devstate[0]: |
120 |
return (1, "Stable to unstable increase") |
121 |
|
122 |
return (4, "Unstable to unstable version increase") |
123 |
|
124 |
# Unstable => stable is always ok |
125 |
if not devstate[0]: |
126 |
return (5, "Unstable to stable") |
127 |
|
128 |
# Can only be increase of minors from one stable to the next |
129 |
return (6, "Stable version increase") |
130 |
|
131 |
def line_input (file): |
132 |
for line in file: |
133 |
if line[-1] == '\n': |
134 |
yield line[:-1] |
135 |
else: |
136 |
yield line |
137 |
|
138 |
def call_editor(filename): |
139 |
"""Return a sequence of possible editor binaries for the current platform""" |
140 |
|
141 |
editors = [] |
142 |
|
143 |
for varname in 'VISUAL', 'EDITOR': |
144 |
if varname in os.environ: |
145 |
editors.append(os.environ[varname]) |
146 |
|
147 |
editors.extend(('/usr/bin/editor', 'vi', 'pico', 'nano', 'joe')) |
148 |
|
149 |
for editor in editors: |
150 |
try: |
151 |
ret = subprocess.call([editor, filename]) |
152 |
except OSError, e: |
153 |
if e.errno == 2: |
154 |
continue |
155 |
raise |
156 |
|
157 |
if ret == 127: |
158 |
continue |
159 |
|
160 |
return True |
161 |
|
162 |
class urllister(SGMLParser): |
163 |
def reset(self): |
164 |
SGMLParser.reset(self) |
165 |
self.urls = [] |
166 |
|
167 |
def start_a(self, attrs): |
168 |
href = [v for k, v in attrs if k=='href'] |
169 |
if href: |
170 |
self.urls.extend(href) |
171 |
|
172 |
class XzTarFile(tarfile.TarFile): |
173 |
|
174 |
OPEN_METH = tarfile.TarFile.OPEN_METH.copy() |
175 |
OPEN_METH["xz"] = "xzopen" |
176 |
|
177 |
@classmethod |
178 |
def xzopen(cls, name, mode="r", fileobj=None, **kwargs): |
179 |
"""Open gzip compressed tar archive name for reading or writing. |
180 |
Appending is not allowed. |
181 |
""" |
182 |
if len(mode) > 1 or mode not in "rw": |
183 |
raise ValueError("mode must be 'r' or 'w'") |
184 |
|
185 |
if fileobj is not None: |
186 |
fileobj = _LMZAProxy(fileobj, mode) |
187 |
else: |
188 |
fileobj = lzma.LZMAFile(name, mode) |
189 |
|
190 |
try: |
191 |
# lzma doesn't immediately return an error |
192 |
# try and read a bit of data to determine if it is a valid xz file |
193 |
fileobj.read(_LZMAProxy.blocksize) |
194 |
fileobj.seek(0) |
195 |
t = cls.taropen(name, mode, fileobj, **kwargs) |
196 |
except IOError: |
197 |
raise tarfile.ReadError("not a xz file") |
198 |
except lzma.error: |
199 |
raise tarfile.ReadError("not a xz file") |
200 |
t._extfileobj = False |
201 |
return t |
202 |
|
203 |
if not hasattr(tarfile.TarFile, 'xzopen'): |
204 |
tarfile.open = XzTarFile.open |
205 |
|
206 |
class SpecFile(object): |
207 |
re_update_version = re.compile(r'^(?P<pre>Version:\s*)(?P<version>.+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE) |
208 |
re_update_release = re.compile(r'^(?P<pre>Release:\s*)(?P<release>%mkrel \d+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE) |
209 |
|
210 |
def __init__(self, path): |
211 |
self.path = path |
212 |
self.cwd = os.path.dirname(path) |
213 |
|
214 |
@property |
215 |
def version(self): |
216 |
return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0] |
217 |
|
218 |
def update(self, version): |
219 |
"""Update specfile (increase version)""" |
220 |
cur_version = self.version |
221 |
|
222 |
(judgement, msg) = judge_version_increase(cur_version, version) |
223 |
|
224 |
if judgement < 0: |
225 |
print >>sys.stderr, "ERROR: %s!" % (msg) |
226 |
return False |
227 |
|
228 |
if judgement < 5: |
229 |
print "WARNING: %s!" % (msg) |
230 |
return False |
231 |
|
232 |
# XXX - os.path.join is hackish |
233 |
if subprocess.check_output(["svn", "diff", os.path.join(self.path, '..')]) != '': |
234 |
print >>sys.stderr, "ERROR: Package has uncommitted changes!" |
235 |
return False |
236 |
|
237 |
with open(self.path, "rw") as f: |
238 |
data = f.read() |
239 |
|
240 |
if data.count("%mkrel") != 1: |
241 |
print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!" |
242 |
return False |
243 |
|
244 |
data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1) |
245 |
if nr != 1: |
246 |
print >>sys.stderr, "ERROR: Could not increase version!" |
247 |
return False |
248 |
|
249 |
data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1) |
250 |
if nr != 1: |
251 |
print >>sys.stderr, "ERROR: Could not reset release!" |
252 |
return False |
253 |
|
254 |
# Overwrite file with new version number |
255 |
write_file(self.path, data) |
256 |
|
257 |
|
258 |
# Verify that RPM also agrees that version number has changed |
259 |
if self.version != version: |
260 |
print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version |
261 |
return False |
262 |
|
263 |
try: |
264 |
# Download new tarball |
265 |
subprocess.check_call(['mgarepo', 'sync', '-d'], cwd=self.cwd) |
266 |
# Check patches still apply |
267 |
subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd) |
268 |
except subprocess.CalledProcessError: |
269 |
return False |
270 |
|
271 |
return True |
272 |
|
273 |
class Patch(object): |
274 |
"""Do things with patches""" |
275 |
|
276 |
re_dep3 = re.compile(r'^(?:#\s*)?(?P<header>[-A-Za-z0-9]+?):\s*(?P<data>.*)$') |
277 |
re_dep3_cont = re.compile(r'^#?\s+(?P<data>.*)$') |
278 |
|
279 |
def __init__(self, path, show_path=False): |
280 |
"""Path: path to patch (might not exist)""" |
281 |
self.path = path |
282 |
self.show_path = show_path |
283 |
|
284 |
def __str__(self): |
285 |
return self.path if self.show_path else os.path.basename(self.path) |
286 |
|
287 |
def add_dep3(self): |
288 |
"""Add DEP-3 headers to a patch file""" |
289 |
if self.dep3['valid']: |
290 |
return False |
291 |
|
292 |
new_headers = ( |
293 |
('Author', self.svn_author), |
294 |
('Subject', ''), |
295 |
('Applied-Upstream', ''), |
296 |
('Forwarded', ''), |
297 |
('Bug', ''), |
298 |
) |
299 |
|
300 |
with tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False) as fdst: |
301 |
with open(self.path, "r") as fsrc: |
302 |
# Start with any existing DEP3 headers |
303 |
for i in range(self.dep3['last_nr']): |
304 |
fdst.write(fsrc.read()) |
305 |
|
306 |
# After that add the DEP3 headers |
307 |
add_line = False |
308 |
for header, data in new_headers: |
309 |
if header in self.dep3['headers']: |
310 |
continue |
311 |
|
312 |
# XXX - wrap this at 80 chars |
313 |
add_line = True |
314 |
print >>fdst, "%s: %s" % (header, "" if data is None else data) |
315 |
|
316 |
if add_line: print >>fdst, "" |
317 |
# Now copy any other data and the patch |
318 |
shutil.copyfileobj(fsrc, fdst) |
319 |
|
320 |
fdst.flush() |
321 |
os.rename(fdst.name, self.path) |
322 |
|
323 |
call_editor(self.path) |
324 |
|
325 |
#Author: fwang |
326 |
#Subject: Build fix: Fix glib header inclusion |
327 |
#Applied-Upstream: commit:30602 |
328 |
#Forwarded: yes |
329 |
#Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247 |
330 |
|
331 |
def _read_dep3(self): |
332 |
"""Read DEP-3 headers from an existing patch file |
333 |
|
334 |
This will also parse git headers""" |
335 |
dep3 = {} |
336 |
headers = {} |
337 |
|
338 |
last_header = None |
339 |
last_nr = 0 |
340 |
nr = 0 |
341 |
try: |
342 |
with open(self.path, "r") as f: |
343 |
for line in line_input(f): |
344 |
nr += 1 |
345 |
# stop trying to parse when real patch begins |
346 |
if line == '---': |
347 |
break |
348 |
|
349 |
r = self.re_dep3.match(line) |
350 |
if r: |
351 |
info = r.groupdict() |
352 |
|
353 |
# Avoid matching URLS |
354 |
if info['data'].startswith('//') and info['header'].lower () == info['header']: |
355 |
continue |
356 |
|
357 |
headers[info['header']] = info['data'] |
358 |
last_header = info['header'] |
359 |
last_nr = nr |
360 |
continue |
361 |
|
362 |
r = self.re_dep3_cont.match(line) |
363 |
if r: |
364 |
info = r.groupdict() |
365 |
if last_header: |
366 |
headers[last_header] = " ".join((headers[last_header], info['data'])) |
367 |
last_nr = nr |
368 |
continue |
369 |
|
370 |
last_header = None |
371 |
except IOError: |
372 |
pass |
373 |
|
374 |
dep3['valid'] = \ |
375 |
(('Description' in headers and headers['Description'].strip() != '') |
376 |
or ('Subject' in headers and headers['Subject'].strip() != '')) \ |
377 |
and (('Origin' in headers and headers['Origin'].strip() != '') \ |
378 |
or ('Author' in headers and headers['Author'].strip() != '') \ |
379 |
or ('From' in headers and headers['From'].strip() != '')) |
380 |
dep3['last_nr'] = last_nr |
381 |
dep3['headers'] = headers |
382 |
|
383 |
self._dep3 = dep3 |
384 |
|
385 |
@property |
386 |
def dep3(self): |
387 |
if not hasattr(self, '_dep3'): |
388 |
self._read_dep3() |
389 |
|
390 |
return self._dep3 |
391 |
|
392 |
@property |
393 |
def svn_author(self): |
394 |
if not hasattr(self, '_svn_author'): |
395 |
try: |
396 |
contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines() |
397 |
|
398 |
for line in contents: |
399 |
if ' | ' not in line: |
400 |
continue |
401 |
|
402 |
fields = line.split(' | ') |
403 |
if len(fields) >= 3: |
404 |
self._svn_author = fields[1] |
405 |
except subprocess.CalledProcessError: |
406 |
pass |
407 |
|
408 |
if not hasattr(self, '_svn_author'): |
409 |
return None |
410 |
|
411 |
return self._svn_author |
412 |
|
413 |
def get_upstream_names(): |
414 |
urlopen = urllib2.build_opener() |
415 |
|
416 |
good_dir = re.compile('^[-A-Za-z0-9_+.]+/$') |
417 |
|
418 |
# Get the files |
419 |
usock = urlopen.open(URL) |
420 |
parser = urllister() |
421 |
parser.feed(usock.read()) |
422 |
usock.close() |
423 |
parser.close() |
424 |
files = parser.urls |
425 |
|
426 |
tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)]) |
427 |
|
428 |
return tarballs |
429 |
|
430 |
def get_downstream_names(): |
431 |
re_file = re.compile(r'^(?P<module>.*?)[_-](?:(?P<oldversion>([0-9]+[\.])*[0-9]+)-)?(?P<version>([0-9]+[\.\-])*[0-9]+)\.(?P<format>(?:tar\.|diff\.)?[a-z][a-z0-9]*)$') |
432 |
|
433 |
contents = subprocess.check_output(['urpmf', '--files', '.', "--media", MEDIA], close_fds=True).strip("\n").splitlines() |
434 |
|
435 |
FILES = {} |
436 |
TARBALLS = {} |
437 |
|
438 |
for line in contents: |
439 |
try: |
440 |
srpm, filename = line.split(":") |
441 |
except ValueError: |
442 |
print >>sys.stderr, line |
443 |
continue |
444 |
|
445 |
if '.tar' in filename: |
446 |
r = re_file.match(filename) |
447 |
if r: |
448 |
fileinfo = r.groupdict() |
449 |
module = fileinfo['module'] |
450 |
|
451 |
if module not in TARBALLS: |
452 |
TARBALLS[module] = set() |
453 |
TARBALLS[module].add(srpm) |
454 |
|
455 |
if srpm not in FILES: |
456 |
FILES[srpm] = set() |
457 |
FILES[srpm].add(filename) |
458 |
|
459 |
return TARBALLS, FILES |
460 |
|
461 |
|
462 |
def write_file(path, data): |
463 |
with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst: |
464 |
fdst.write(data) |
465 |
fdst.flush() |
466 |
os.rename(fdst.name, path) |
467 |
|
468 |
def cmd_co(options, parser): |
469 |
upstream = get_upstream_names() |
470 |
downstream, downstream_files = get_downstream_names() |
471 |
|
472 |
cwd = os.path.expanduser(PKGROOT) |
473 |
|
474 |
matches = upstream & set(downstream.keys()) |
475 |
for module in matches: |
476 |
print module, "\t".join(downstream[module]) |
477 |
for package in downstream[module]: |
478 |
subprocess.call(['mgarepo', 'co', package], cwd=cwd) |
479 |
|
480 |
def cmd_ls(options, parser): |
481 |
upstream = get_upstream_names() |
482 |
downstream, downstream_files = get_downstream_names() |
483 |
|
484 |
matches = upstream & set(downstream.keys()) |
485 |
for module in matches: |
486 |
print "\n".join(sorted(downstream[module])) |
487 |
|
488 |
def cmd_patches(options, parser): |
489 |
upstream = get_upstream_names() |
490 |
downstream, downstream_files = get_downstream_names() |
491 |
|
492 |
path = os.path.expanduser(PKGROOT) |
493 |
|
494 |
import pprint |
495 |
|
496 |
matches = upstream & set(downstream.keys()) |
497 |
for module in sorted(matches): |
498 |
for srpm in downstream[module]: |
499 |
for filename in downstream_files[srpm]: |
500 |
if '.patch' in filename or '.diff' in filename: |
501 |
|
502 |
p = Patch(os.path.join(path, srpm, "SOURCES", filename), show_path=options.path) |
503 |
valid = "" |
504 |
forwarded = "" |
505 |
if p.dep3['headers']: |
506 |
forwarded = p.dep3['headers'].get('Forwarded', "no") |
507 |
if p.dep3['valid']: |
508 |
valid="VALID" |
509 |
print "\t".join((module, srpm, str(p), forwarded, valid)) |
510 |
|
511 |
def cmd_dep3(options, parser): |
512 |
p = Patch(options.patch) |
513 |
p.add_dep3() |
514 |
|
515 |
def cmd_package_new_version(options, parser): |
516 |
# Determine the package name |
517 |
if options.upstream: |
518 |
downstream, downstream_files = get_downstream_names() |
519 |
|
520 |
if options.package not in downstream: |
521 |
print >>sys.stderr, "ERROR: No packages for upstream name: %s" % options.package |
522 |
sys.exit(1) |
523 |
|
524 |
if len(downstream[options.package]) != 1: |
525 |
# XXX - Make it more intelligent |
526 |
print >>sys.stderr, "ERROR: Multiple packages found for %s: %s" % (options.package, ", ".join(downstream[options.package])) |
527 |
sys.exit(1) |
528 |
|
529 |
package = list(downstream[options.package])[0] |
530 |
else: |
531 |
package = options.package |
532 |
|
533 |
# Directories packages are located in |
534 |
root = os.path.expanduser(PKGROOT) |
535 |
cwd = os.path.join(root, package) |
536 |
|
537 |
# Checkout package to ensure the checkout reflects the latest changes |
538 |
try: |
539 |
subprocess.check_call(['mgarepo', 'co', package], cwd=root) |
540 |
except subprocess.CalledProcessError: |
541 |
sys.exit(1) |
542 |
|
543 |
# SpecFile class handles the actual version+release change |
544 |
s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)) |
545 |
print "%s => %s" % (s.version, options.version) |
546 |
if not s.update(options.version): |
547 |
sys.exit(1) |
548 |
|
549 |
# We can even checkin and submit :-) |
550 |
if options.submit: |
551 |
try: |
552 |
# checkin changes |
553 |
subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd) |
554 |
# and submit |
555 |
subprocess.check_call(['mgarepo', 'submit'], cwd=cwd) |
556 |
except subprocess.CalledProcessError: |
557 |
sys.exit(1) |
558 |
|
559 |
|
560 |
def main(): |
561 |
description = """Mageia GNOME commands.""" |
562 |
epilog="""Report bugs to Olav Vitters""" |
563 |
parser = argparse.ArgumentParser(description=description,epilog=epilog) |
564 |
|
565 |
# SUBPARSERS |
566 |
subparsers = parser.add_subparsers(title='subcommands') |
567 |
# install |
568 |
subparser = subparsers.add_parser('co', help='checkout all GNOME modules') |
569 |
subparser.set_defaults( |
570 |
func=cmd_co |
571 |
) |
572 |
|
573 |
subparser = subparsers.add_parser('packages', help='list all GNOME packages') |
574 |
subparser.set_defaults( |
575 |
func=cmd_ls |
576 |
) |
577 |
|
578 |
subparser = subparsers.add_parser('patches', help='list all GNOME patches') |
579 |
subparser.add_argument("-p", "--path", action="store_true", dest="path", |
580 |
help="Show full path to patch") |
581 |
subparser.set_defaults( |
582 |
func=cmd_patches, path=False |
583 |
) |
584 |
|
585 |
subparser = subparsers.add_parser('dep3', help='Add dep3 headers') |
586 |
subparser.add_argument("patch", help="Patch") |
587 |
subparser.set_defaults( |
588 |
func=cmd_dep3, path=False |
589 |
) |
590 |
|
591 |
subparser = subparsers.add_parser('increase', help='Increase version number') |
592 |
subparser.add_argument("package", help="Package name") |
593 |
subparser.add_argument("version", help="Version number") |
594 |
subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream", |
595 |
help="Package name reflects the upstream name") |
596 |
subparser.add_argument("-s", "--submit", action="store_true", dest="submit", |
597 |
help="Commit changes and submit") |
598 |
subparser.set_defaults( |
599 |
func=cmd_package_new_version, submit=False, upstream=False |
600 |
) |
601 |
|
602 |
if len(sys.argv) == 1: |
603 |
parser.print_help() |
604 |
sys.exit(2) |
605 |
|
606 |
options = parser.parse_args() |
607 |
|
608 |
try: |
609 |
options.func(options, parser) |
610 |
except KeyboardInterrupt: |
611 |
print('Interrupted') |
612 |
sys.exit(1) |
613 |
except EOFError: |
614 |
print('EOF') |
615 |
sys.exit(1) |
616 |
except IOError, e: |
617 |
if e.errno != errno.EPIPE: |
618 |
raise |
619 |
sys.exit(0) |
620 |
|
621 |
if __name__ == "__main__": |
622 |
main() |