/[soft]/mga-gnome/trunk/mga-gnome
ViewVC logotype

Contents of /mga-gnome/trunk/mga-gnome

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.28