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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.30