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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 7322 - (show annotations) (download)
Wed Feb 13 18:31:26 2013 UTC (11 years, 2 months ago) by ovitters
File size: 38172 byte(s)
ensure module names are passed to get_majmin
1 #!/usr/bin/python -u
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 # to be able to sleep for a while
44 import time
45
46 # version freeze
47 import datetime
48
49 # packages --sort
50 import itertools
51
52 # check-latest
53 import requests
54
55 SLEEP_INITIAL=180
56 SLEEP_REPEAT=30
57 SLEEP_TIMES=30
58
59 re_majmin = re.compile(r'^([0-9]+\.[0-9]+).*')
60 re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')
61
62 def version_cmp(a, b):
63 """Compares two versions
64
65 Returns
66 -1 if a < b
67 0 if a == b
68 1 if a > b
69 """
70
71 return rpm.labelCompare(('1', a, '1'), ('1', b, '1'))
72
73 def get_latest_version(versions, max_version=None):
74 """Gets the latest version number
75
76 if max_version is specified, gets the latest version number before
77 max_version"""
78 latest = None
79 for version in versions:
80 if ( latest is None or version_cmp(version, latest) > 0 ) \
81 and ( max_version is None or version_cmp(version, max_version) < 0 ):
82 latest = version
83 return latest
84
85 MAJOR_VERSIONS = {
86 # NAMES MUST BE IN LOWERCASE!
87 'networkmanager': set(('0.9',)),
88 'networkmanager-applet': set(('0.9',)),
89 'networkmanager-openconnect': set(('0.9',)),
90 'networkmanager-openvpn': set(('0.9',)),
91 'networkmanager-pptp': set(('0.9',)),
92 'networkmanager-vpnc': set(('0.9',))
93 }
94
95 def get_majmin(version, module=None):
96 nrs = version.split('.')
97
98 if module and module.lower() in MAJOR_VERSIONS:
99 module_versions = [version.split(".") for version in MAJOR_VERSIONS[module.lower()]]
100
101 nrstest = nrs[:]
102
103 while len(nrstest) >= 2:
104 if nrstest in module_versions:
105 return (".".join(nrs[:len(nrstest)]), nrs[len(nrstest)])
106
107 nrstest.pop()
108
109 return (nrs[0], nrs[1])
110
111
112 def get_safe_max_version(version, module=None):
113 if not re_majmin.match(version):
114 return None
115
116 majmin = get_majmin(version, module)
117
118 min_nr = long(majmin[1])
119
120 if min_nr % 2 == 0:
121 return "%s.%d" % (majmin[0], min_nr + 1)
122 else:
123 return "%s.%d" % (majmin[0], min_nr + 2)
124
125 def judge_version_increase(version_old, version_new, module=None):
126 """Judge quality of version increase:
127
128 Returns a tuple containing judgement and message
129
130 Judgement:
131 Less than 0: Error
132 0 to 4: Better not
133 5+: Ok"""
134 versions = (version_old, version_new)
135
136 # First do a basic version comparison to ensure version_new is actually newer
137 compare = version_cmp(version_new, version_old)
138
139 if compare == 0:
140 # 1.0.0 -> 1.0.1
141 return (-2, "Already at version %s!" % (version_old))
142
143 if compare != 1:
144 # 1.0.1 -> 1.0.0
145 return (-3, "Version %s is older than current version %s!" % (version_new, version_old))
146
147 # Version is newer, but we don't want to see if it follows the GNOME versioning scheme
148 majmins = [get_majmin(ver, module) for ver in versions if re_majmin.match(ver) is not None]
149
150 if len(majmins) == 1:
151 return (-1, "Version number scheme changes: %s" % (", ".join(versions)))
152
153 if len(majmins) == 0:
154 return (0, "Unsupported version numbers: %s" % (", ".join(versions)))
155
156 # Follows GNOME versioning scheme
157 # Meaning: x.y.z
158 # x = major
159 # y = minor : even if stable
160 # z = micro
161
162 # Major+minor the same? Then go ahead and upgrade!
163 if majmins[0] == majmins[1]:
164 # Majmin of both versions are the same, looks good!
165 # 1.1.x -> 1.1.x or 1.0.x -> 1.0.x
166 return (10, None)
167
168 # Check/ensure major version number is the same
169 if majmins[0][0] != majmins[1][0]:
170 # 1.0.x -> 2.0.x
171 return (1, "Major version number increase")
172
173 # Minor indicates stable/unstable
174 devstate = (long(majmins[0][1]) % 2 == 0, long(majmins[1][1]) % 2 == 0)
175
176 # Upgrading to unstable is weird
177 if not devstate[1]:
178 if devstate[0]:
179 # 1.2.x -> 1.3.x
180 return (1, "Stable to unstable increase")
181
182 # 1.3.x -> 1.5.x
183 return (4, "Unstable to unstable version increase")
184
185 # Unstable => stable is always ok
186 if not devstate[0]:
187 # 1.1.x -> 1.2.x
188 return (5, "Unstable to stable")
189
190 # Can only be increase of minors from one stable to the next
191 # 1.0.x -> 1.2.x
192 return (6, "Stable version increase")
193
194 def line_input (file):
195 for line in file:
196 if line[-1] == '\n':
197 yield line[:-1]
198 else:
199 yield line
200
201 def call_editor(filename):
202 """Return a sequence of possible editor binaries for the current platform"""
203
204 editors = []
205
206 for varname in 'VISUAL', 'EDITOR':
207 if varname in os.environ:
208 editors.append(os.environ[varname])
209
210 editors.extend(('/usr/bin/editor', 'vi', 'pico', 'nano', 'joe'))
211
212 for editor in editors:
213 try:
214 ret = subprocess.call([editor, filename])
215 except OSError, e:
216 if e.errno == 2:
217 continue
218 raise
219
220 if ret == 127:
221 continue
222
223 return True
224
225 class urllister(SGMLParser):
226 def reset(self):
227 SGMLParser.reset(self)
228 self.urls = []
229
230 def start_a(self, attrs):
231 href = [v for k, v in attrs if k=='href']
232 if href:
233 self.urls.extend(href)
234
235 class XzTarFile(tarfile.TarFile):
236
237 OPEN_METH = tarfile.TarFile.OPEN_METH.copy()
238 OPEN_METH["xz"] = "xzopen"
239
240 @classmethod
241 def xzopen(cls, name, mode="r", fileobj=None, **kwargs):
242 """Open gzip compressed tar archive name for reading or writing.
243 Appending is not allowed.
244 """
245 if len(mode) > 1 or mode not in "rw":
246 raise ValueError("mode must be 'r' or 'w'")
247
248 if fileobj is not None:
249 fileobj = _LMZAProxy(fileobj, mode)
250 else:
251 fileobj = lzma.LZMAFile(name, mode)
252
253 try:
254 # lzma doesn't immediately return an error
255 # try and read a bit of data to determine if it is a valid xz file
256 fileobj.read(_LZMAProxy.blocksize)
257 fileobj.seek(0)
258 t = cls.taropen(name, mode, fileobj, **kwargs)
259 except IOError:
260 raise tarfile.ReadError("not a xz file")
261 except lzma.error:
262 raise tarfile.ReadError("not a xz file")
263 t._extfileobj = False
264 return t
265
266 if not hasattr(tarfile.TarFile, 'xzopen'):
267 tarfile.open = XzTarFile.open
268
269 def is_valid_hash(path, algo, hexdigest):
270 if algo not in hashlib.algorithms:
271 raise ValueError("Unknown hash algorithm: %s" % algo)
272
273 local_hash = getattr(hashlib, algo)()
274
275 with open(path, 'rb') as fp:
276 data = fp.read(32768)
277 while data:
278 local_hash.update(data)
279 data = fp.read(32768)
280
281 return local_hash.hexdigest() == hexdigest
282
283 class SpecFile(object):
284 re_update_version = re.compile(r'^(?P<pre>Version:\s*)(?P<version>.+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)
285 re_update_release = re.compile(r'^(?P<pre>Release:\s*)(?P<release>%mkrel \d+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)
286
287 def __init__(self, path, module=None):
288 self.path = path
289 self.cwd = os.path.dirname(path)
290 self.module = module
291
292 @property
293 def version(self):
294 return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0]
295 @property
296 def sources(self):
297 ts = rpm.ts()
298 spec = ts.parseSpec(self.path)
299 srclist = spec.sources if isinstance(spec.sources, (list, tuple)) \
300 else spec.sources()
301 return dict((os.path.basename(name), name) for name, no, flags in srclist)
302
303 def update(self, version, force=False):
304 """Update specfile (increase version)"""
305 cur_version = self.version
306
307 (judgement, msg) = judge_version_increase(cur_version, version, self.module)
308
309 if judgement < 0:
310 print >>sys.stderr, "ERROR: %s!" % (msg)
311 return False
312
313 if judgement < 5:
314 print "WARNING: %s!" % (msg)
315 if not force: return False
316
317 # XXX - os.path.join is hackish
318 svn_diff_output = subprocess.check_output(["svn", "diff", os.path.join(self.path, '..')])
319 if svn_diff_output != '':
320 print svn_diff_output
321 print >>sys.stderr, "ERROR: Package has uncommitted changes!"
322 if not force:
323 return False
324
325 # Forcing package submission: revert changes
326 try:
327 print >>sys.stderr, "WARNING: Force used; reverting svn changes"
328 subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')])
329 except subprocess.CalledProcessError:
330 return False
331
332 with open(self.path, "rw") as f:
333 data = f.read()
334
335 if data.count("%subrel") != 0:
336 print >>sys.stderr, "ERROR: %subrel found; don't know what to do!"
337 return False
338
339 if data.count("%mkrel") != 1:
340 print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!"
341 return False
342
343 data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1)
344 if nr != 1:
345 print >>sys.stderr, "ERROR: Could not increase version!"
346 return False
347
348 data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1)
349 if nr != 1:
350 print >>sys.stderr, "ERROR: Could not reset release!"
351 return False
352
353 # Overwrite file with new version number
354 write_file(self.path, data)
355
356
357 # Verify that RPM also agrees that version number has changed
358 if self.version != version:
359 print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
360 return False
361
362
363 # Try to download the new tarball various times and wait between attempts
364 tries = 0
365 while tries < SLEEP_TIMES:
366 tries += 1
367 if tries > 1: time.sleep(SLEEP_REPEAT * 2 ** (tries // 10))
368 try:
369 # Download new tarball
370 subprocess.check_call(['mgarepo', 'sync', '-d'], cwd=self.cwd)
371 # success, so exit loop
372 break
373 except subprocess.CalledProcessError, e:
374 # mgarepo sync returns 1 if the tarball cannot be downloaded
375 if e.returncode != 1:
376 subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')])
377 return False
378 else:
379 # failed to download tarball
380 subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')])
381 return False
382
383
384 try:
385 # Check patches still apply
386 subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd)
387 except subprocess.CalledProcessError:
388 logfile = os.path.join(os.path.dirname(self.path), 'log.%s' % os.path.splitext(os.path.basename(self.path))[0])
389 if os.path.exists(logfile):
390 subprocess.call(['tail', '-n', '15', logfile])
391 return False
392
393 return True
394
395 class Patch(object):
396 """Do things with patches"""
397
398 re_dep3 = re.compile(r'^(?:#\s*)?(?P<header>[-A-Za-z0-9]+?):\s*(?P<data>.*)$')
399 re_dep3_cont = re.compile(r'^#?\s+(?P<data>.*)$')
400
401 def __init__(self, path, show_path=False):
402 """Path: path to patch (might not exist)"""
403 self.path = path
404 self.show_path = show_path
405
406 def __str__(self):
407 return self.path if self.show_path else os.path.basename(self.path)
408
409 def add_dep3(self):
410 """Add DEP-3 headers to a patch file"""
411 if self.dep3['valid']:
412 return False
413
414 new_headers = (
415 ('Author', self.svn_author),
416 ('Subject', ''),
417 ('Applied-Upstream', ''),
418 ('Forwarded', ''),
419 ('Bug', ''),
420 )
421
422 with tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False) as fdst:
423 with open(self.path, "r") as fsrc:
424 # Start with any existing DEP3 headers
425 for i in range(self.dep3['last_nr']):
426 fdst.write(fsrc.read())
427
428 # After that add the DEP3 headers
429 add_line = False
430 for header, data in new_headers:
431 if header in self.dep3['headers']:
432 continue
433
434 # XXX - wrap this at 80 chars
435 add_line = True
436 print >>fdst, "%s: %s" % (header, "" if data is None else data)
437
438 if add_line: print >>fdst, ""
439 # Now copy any other data and the patch
440 shutil.copyfileobj(fsrc, fdst)
441
442 fdst.flush()
443 os.rename(fdst.name, self.path)
444
445 call_editor(self.path)
446
447 #Author: fwang
448 #Subject: Build fix: Fix glib header inclusion
449 #Applied-Upstream: commit:30602
450 #Forwarded: yes
451 #Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247
452
453 def _read_dep3(self):
454 """Read DEP-3 headers from an existing patch file
455
456 This will also parse git headers"""
457 dep3 = {}
458 headers = {}
459
460 last_header = None
461 last_nr = 0
462 nr = 0
463 try:
464 with open(self.path, "r") as f:
465 for line in line_input(f):
466 nr += 1
467 # stop trying to parse when real patch begins
468 if line == '---':
469 break
470
471 r = self.re_dep3.match(line)
472 if r:
473 info = r.groupdict()
474
475 # Avoid matching URLS
476 if info['data'].startswith('//') and info['header'].lower () == info['header']:
477 continue
478
479 headers[info['header']] = info['data']
480 last_header = info['header']
481 last_nr = nr
482 continue
483
484 r = self.re_dep3_cont.match(line)
485 if r:
486 info = r.groupdict()
487 if last_header:
488 headers[last_header] = " ".join((headers[last_header], info['data']))
489 last_nr = nr
490 continue
491
492 last_header = None
493 except IOError:
494 pass
495
496 dep3['valid'] = \
497 (('Description' in headers and headers['Description'].strip() != '')
498 or ('Subject' in headers and headers['Subject'].strip() != '')) \
499 and (('Origin' in headers and headers['Origin'].strip() != '') \
500 or ('Author' in headers and headers['Author'].strip() != '') \
501 or ('From' in headers and headers['From'].strip() != ''))
502 dep3['last_nr'] = last_nr
503 dep3['headers'] = headers
504
505 self._dep3 = dep3
506
507 @property
508 def dep3(self):
509 if not hasattr(self, '_dep3'):
510 self._read_dep3()
511
512 return self._dep3
513
514 @property
515 def svn_author(self):
516 if not hasattr(self, '_svn_author'):
517 try:
518 contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines()
519
520 for line in contents:
521 if ' | ' not in line:
522 continue
523
524 fields = line.split(' | ')
525 if len(fields) >= 3:
526 self._svn_author = fields[1]
527 except subprocess.CalledProcessError:
528 pass
529
530 if not hasattr(self, '_svn_author'):
531 return None
532
533 return self._svn_author
534
535
536 class Upstream(object):
537
538 URL="http://download.gnome.org/sources/"
539 limit = None
540 _cache_versions = {}
541
542 def __init__(self):
543 urlopen = urllib2.build_opener()
544
545 good_dir = re.compile('^[-A-Za-z0-9_+.]+/$')
546
547 # Get the files
548 usock = urlopen.open(self.URL)
549 parser = urllister()
550 parser.feed(usock.read())
551 usock.close()
552 parser.close()
553 files = parser.urls
554
555 tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)])
556 if self.limit is not None:
557 tarballs.intersection_update(self.limit)
558
559 self.names = tarballs
560
561 @classmethod
562 def versions(cls, module):
563 # XXX - ugly
564 if module not in cls._cache_versions:
565 versions = None
566
567 url = '%s%s/cache.json' % (cls.URL, module)
568 r = requests.get(url)
569 j = r.json
570 if j is not None and len(j) > 2 and module in j[2]:
571 versions = j[2][module]
572
573 cls._cache_versions[module] = versions
574
575 return cls._cache_versions[module]
576
577 class Downstream(object):
578 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]*)$')
579
580 MEDIA="Core Release Source"
581 PKGROOT='~/pkgs'
582 DISTRO=None
583
584 def __init__(self):
585 contents = subprocess.check_output(['urpmf', '--qf', '%name|%version|%files', '.', "--media", self.MEDIA], close_fds=True).strip("\n").splitlines()
586
587 FILES = {}
588 TARBALLS = {}
589
590 for line in contents:
591 try:
592 srpm, version, filename = line.split("|")
593 except ValueError:
594 print >>sys.stderr, line
595 continue
596
597 if '.tar' in filename:
598 r = self.re_file.match(filename)
599 if r:
600 fileinfo = r.groupdict()
601 module = fileinfo['module']
602
603 if module not in TARBALLS:
604 TARBALLS[module] = {}
605
606 if srpm in TARBALLS[module]:
607 # srpm seen before, check if version is newer
608 if version_cmp(TARBALLS[module][srpm], version) == 1:
609 TARBALLS[module][srpm] = version
610 else:
611 TARBALLS[module][srpm] = version
612
613 if srpm not in FILES:
614 FILES[srpm] = set()
615 FILES[srpm].add(filename)
616
617 self.tarballs = TARBALLS
618 self.files = FILES
619
620 @classmethod
621 def co(cls, package, cwd=None):
622 if cwd is None:
623 cwd = os.path.expanduser(cls.PKGROOT)
624
625 cmd = ['mgarepo', 'co']
626 if cls.DISTRO:
627 cmd.extend(('-d', cls.DISTRO))
628 cmd.append(package)
629 return subprocess.check_call(cmd, cwd=cwd)
630
631 def get_downstream_from_upstream(self, upstream, version):
632 if upstream not in self.tarballs:
633 raise ValueError("No packages for upstream name: %s" % upstream)
634
635 if len(self.tarballs[upstream]) == 1:
636 return self.tarballs[upstream].keys()
637
638 # Directories packages are located in
639 root = os.path.expanduser(self.PKGROOT)
640
641 packages = {}
642 for package in self.tarballs[upstream].keys():
643 cwd = os.path.join(root, package)
644
645 # Checkout package to ensure the checkout reflects the latest changes
646 try:
647 self.co(package, cwd=root)
648 except subprocess.CalledProcessError:
649 raise ValueError("Multiple packages found and cannot checkout %s" % package)
650
651 # Determine version from spec file
652 try:
653 packages[package] = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=upstream).version
654 except subprocess.CalledProcessError:
655 raise ValueError("Multiple packages found and cannot determine version of %s" % package)
656
657 # Return all packages reflecting the current version
658 matches = [package for package in packages if packages[package] == version]
659 if len(matches):
660 return matches
661
662 # Return all packages reflecting the version before the current version
663 latest_version = get_latest_version(packages.values(), max_version=version)
664 matches = [package for package in packages if packages[package] == latest_version]
665 if len(matches):
666 return matches
667
668 # Give up
669 raise ValueError("Multiple packages found and cannot determine package for version %s" % version)
670
671 def write_file(path, data):
672 with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst:
673 fdst.write(data)
674 fdst.flush()
675 os.rename(fdst.name, path)
676
677 def cmd_co(options, parser):
678 for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
679 print "%s => %s" % (module, package)
680 try:
681 Downstream.co(package)
682 except subprocess.CalledProcessError:
683 pass
684
685 def join_streams(show_version=False, only_diff_version=False):
686 root = os.path.expanduser(Downstream.PKGROOT)
687
688 upstream = Upstream().names
689 downstream = Downstream()
690
691 matches = upstream & set(downstream.tarballs.keys())
692 for module in matches:
693 for package in downstream.tarballs[module].keys():
694 package_version = downstream.tarballs[module][package]
695 spec_version = None
696 if show_version or only_diff_version:
697 cwd = os.path.join(root, package)
698 try:
699 spec_version = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=module).version
700 except subprocess.CalledProcessError:
701 spec_version = 'N/A'
702
703 if only_diff_version and package_version == spec_version:
704 continue
705
706 yield (package, module, package_version, spec_version, downstream.files[package])
707
708 def cmd_group_owner(options, parser):
709 groups = set(options.group)
710
711 output = [pkg.split("\t") for pkg in subprocess.check_output(["urpmf", "-F|", "--qf", "%group\t%name\t%sourcerpm\t%version\t%release", "."]).splitlines()]
712 if not output: return
713
714 # Filter by groups
715 output = [pkg for pkg in output if pkg[0] in groups]
716 if not output: return
717
718 packages = {}
719 for group, name, sourcerpm, version, release in output:
720 if group not in packages:
721 packages[group] = {}
722
723 source = sourcerpm if sourcerpm else name
724 end = ".src.rpm"
725 if source.endswith(end): source = source[:len(source) - len(end)]
726 end = "-%s-%s" %(version, release)
727 if source.endswith(end): source = source[:len(source) - len(end)]
728
729 if source not in packages[group]: packages[group][source] = set()
730
731 packages[group][source].add(name)
732
733
734 maints = dict([line.rpartition(" ")[::2] for line in subprocess.check_output(["mgarepo", "maintdb", "get"]).splitlines()])
735
736 def get_output(source, maints, packages):
737 for source in packages.keys():
738 maint = maints.get(source, "?")
739
740 yield "\t".join((maint, source, ",".join(sorted(packages[source]))))
741
742 first = True
743 for group in packages.keys():
744 if first:
745 first = False
746 else:
747 print ""
748 print ""
749 print group
750 print ""
751
752 for line in sorted(get_output(source, maints, packages[group])):
753 print line
754
755 def cmd_ls(options, parser):
756 streams = join_streams(show_version=options.show_version, only_diff_version=options.diff)
757 if options.sort:
758 SORT=dict(zip(options.sort.read().splitlines(), itertools.count()))
759
760 streams = sorted(streams, key=lambda a: (SORT.get(a[1], 9999), a[0]))
761 else:
762 streams = sorted(streams)
763
764 for package, module, package_version, spec_version, downstream_files in streams:
765 sys.stdout.write(package)
766 if options.upstream: sys.stdout.write("\t%s" % module)
767 if options.show_version: sys.stdout.write("\t%s\t%s" % (spec_version, package_version))
768 print
769
770 def cmd_check_latest(options, parser):
771 streams = join_streams(show_version=True)
772
773 for package, module, package_version, spec_version, downstream_files in streams:
774 upgrade=set()
775 sys.stdout.write(package)
776 sys.stdout.write("\t%s\t%s" % (spec_version, package_version))
777
778 safe_max_version = get_safe_max_version(spec_version, module=module)
779
780 versions = Upstream.versions(module)
781 if versions:
782 latest_version = get_latest_version(versions)
783 safe_version = get_latest_version(versions, safe_max_version)
784
785 cmp_latest = version_cmp(latest_version, spec_version)
786 if cmp_latest < 0:
787 latest_version = 'N/A'
788 upgrade.add('l')
789 elif cmp_latest > 0:
790 upgrade.add('L')
791
792 cmp_safe = version_cmp(safe_version, spec_version)
793 if cmp_safe < 0:
794 safe_version = 'N/A'
795 upgrade.add('s')
796 elif cmp_safe > 0:
797 upgrade.add('S')
798
799 sys.stdout.write("\t%s" % latest_version)
800 sys.stdout.write("\t%s" % safe_version)
801 sys.stdout.write("\t%s" % "".join(sorted(upgrade)))
802
803 print
804
805 def cmd_patches(options, parser):
806 root = os.path.expanduser(Downstream.PKGROOT)
807
808 for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
809 for filename in downstream_files:
810 if '.patch' in filename or '.diff' in filename:
811
812 p = Patch(os.path.join(root, package, "SOURCES", filename), show_path=options.path)
813 valid = ""
814 forwarded = ""
815 if p.dep3['headers']:
816 forwarded = p.dep3['headers'].get('Forwarded', "no")
817 if p.dep3['valid']:
818 valid="VALID"
819 print "\t".join((module, package, str(p), forwarded, valid))
820
821 def cmd_dep3(options, parser):
822 p = Patch(options.patch)
823 p.add_dep3()
824
825 def cmd_package_new_version(options, parser):
826 # Determine the package name
827 if options.upstream:
828 try:
829 package = Downstream().get_downstream_from_upstream(options.package, options.version)[0]
830 except ValueError, e:
831 print >>sys.stderr, "ERROR: %s" % e
832 sys.exit(1)
833 else:
834 package = options.package
835
836 # Directories packages are located in
837 root = os.path.expanduser(Downstream.PKGROOT)
838 cwd = os.path.join(root, package)
839
840 # Checkout package to ensure the checkout reflects the latest changes
841 try:
842 Downstream.co(package, cwd=root)
843 except subprocess.CalledProcessError:
844 sys.exit(1)
845
846 # SpecFile class handles the actual version+release change
847 # XXX - module should reflect upstream name, this gives it the package name
848 s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=package)
849 print "%s => %s" % (s.version, options.version)
850 if not s.update(options.version, force=options.force):
851 sys.exit(1)
852
853 # Check hash, if given
854 if options.hexdigest is not None:
855 sources = [name for name, origname in s.sources.iteritems() if '://' in origname]
856 if not len(sources):
857 print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!"
858 sys.stderr(1)
859
860 # If there are multiple sources, try to see if there is a preferred name
861 # --> needed for metacity hash check (multiple tarball sources)
862 if len(sources) > 1:
863 preferred_name = '%s-%s.tar.xz' % (package, options.version)
864 if preferred_name in sources:
865 sources = [preferred_name]
866
867 for filename in sources:
868 path = os.path.join(cwd, "SOURCES", filename)
869 if not is_valid_hash(path, options.algo, options.hexdigest):
870 print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path
871 print >>sys.stderr, "ERROR: Reverting changes!"
872 subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd)
873 sys.exit(1)
874
875 try:
876 # If we made it this far, checkin the changes
877 subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd)
878
879 # Submit is optional
880 if options.submit:
881 cmd = ['mgarepo', 'submit']
882 if Downstream.DISTRO:
883 cmd.extend(('--define', 'section=core/updates_testing', '-t', Downstream.DISTRO))
884 subprocess.check_call(cmd, cwd=cwd)
885 except subprocess.CalledProcessError:
886 sys.exit(1)
887
888 def cmd_parse_ftp_release_list(options, parser):
889 def _send_reply_mail(contents, orig_msg, to, packages=[], error=False):
890 """Send an reply email"""
891 contents.seek(0)
892 msg = MIMEText(contents.read(), _charset='utf-8')
893
894 if error:
895 # XXX - ugly
896 contents.seek(0)
897 lastline = contents.read().rstrip().splitlines()[-1]
898 # Remove things like "ERROR: " and so on from the last line
899 lastline = re.sub(r'^(?:[^ :]+:\s+)+', '', lastline)
900 # Remove things like " - " (youri output from mgarepo submit)
901 lastline = re.sub(r'^\s+-\s+', '', lastline)
902 subjecterror = " (ERROR: %s)" % lastline if lastline else " (ERROR)"
903 else:
904 subjecterror = ""
905
906 if packages:
907 subject = "%s %s%s" % (", ".join(packages), orig_msg['X-Module-Version'], subjecterror)
908 else:
909 subject = "Re: %s%s" % (orig_msg['Subject'], subjecterror)
910
911 msg['Subject'] = subject
912 msg['To'] = to
913 msg["In-Reply-To"] = orig_msg["Message-ID"]
914 msg["References"] = orig_msg["Message-ID"]
915
916 # Call sendmail program directly so it doesn't matter if the service is running
917 cmd = ['/usr/sbin/sendmail', '-oi', '--']
918 cmd.extend([to])
919 p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
920 p.stdin.write(msg.as_string())
921 p.stdin.flush()
922 p.stdin.close()
923 p.wait()
924
925
926 msg = email.email.message_from_file(sys.stdin)
927
928 if options.mail:
929 stdout = tempfile.TemporaryFile()
930 stderr = stdout
931 else:
932 stdout = sys.stdout
933 stderr = sys.stderr
934
935 try:
936 module = msg['X-Module-Name']
937 version = msg['X-Module-Version']
938 hexdigest = msg['X-Module-SHA256-tar.xz']
939 except KeyError, e:
940 print >>stderr, "ERROR: %s" % e
941 if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
942 sys.exit(1)
943
944 try:
945 packages = Downstream().get_downstream_from_upstream(module, version)
946 except ValueError, e:
947 print >>stderr, "ERROR: %s" % e
948 if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
949 sys.exit(1)
950
951 if options.wait:
952 # maildrop aborts and will try to deliver after 5min
953 # fork to avoid this
954 if os.fork() != 0: sys.exit(0)
955 # wait SLEEP_INITIAL after the message was sent
956 secs = SLEEP_INITIAL
957 t = email.utils.parsedate_tz(msg['Date'])
958 if t is not None:
959 msg_time = email.utils.mktime_tz(t)
960 secs = SLEEP_INITIAL - (time.time() - msg_time)
961
962 if secs > 0: time.sleep(secs)
963
964 error = False
965 for package in packages:
966 cmd = ['mga-gnome', 'increase', '--hash', hexdigest]
967 if options.submit:
968 cmd.append('--submit')
969 if options.force:
970 cmd.append('--force')
971 cmd.extend((package, version))
972 if subprocess.call(cmd, stdout=stdout, stderr=stderr):
973 error = True
974
975 if options.mail: _send_reply_mail(stdout, msg, options.mail, packages=packages, error=error)
976
977 def main():
978 description = """Mageia GNOME commands."""
979 epilog="""Report bugs to Olav Vitters"""
980 parser = argparse.ArgumentParser(description=description,epilog=epilog)
981 parser.add_argument("-l", "--limit", type=argparse.FileType('r', 0),
982 dest="limit_upstream", metavar="FILE",
983 help="File containing upstream names")
984 parser.add_argument("-d", "--distro", action="store", dest="distro",
985 help="Distribution release")
986
987 # SUBPARSERS
988 subparsers = parser.add_subparsers(title='subcommands')
989 # install
990 subparser = subparsers.add_parser('co', help='checkout all GNOME modules')
991 subparser.set_defaults(
992 func=cmd_co
993 )
994
995 subparser = subparsers.add_parser('packages', help='list all GNOME packages')
996 subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
997 help="Show upstream module")
998 subparser.add_argument( "--version", action="store_true", dest="show_version",
999 help="Show version numbers")
1000 subparser.add_argument( "--diff", action="store_true", dest="diff",
1001 help="Only show packages with different version")
1002 subparser.add_argument( "--sort", type=argparse.FileType('r', 0),
1003 dest="sort", metavar="FILE",
1004 help="Sort packages according to order in given FILE")
1005
1006 subparser.set_defaults(
1007 func=cmd_ls, upstream=False, show_version=False, diff=False
1008 )
1009
1010 subparser = subparsers.add_parser('group-owner', help='list packages by group')
1011 subparser.add_argument('group', metavar="GROUP", nargs='+')
1012
1013 subparser.set_defaults(
1014 func=cmd_group_owner
1015 )
1016
1017 subparser = subparsers.add_parser('check-latest', help='check for latest version of packages')
1018 subparser.set_defaults(
1019 func=cmd_check_latest
1020 )
1021
1022 subparser = subparsers.add_parser('patches', help='list all GNOME patches')
1023 subparser.add_argument("-p", "--path", action="store_true", dest="path",
1024 help="Show full path to patch")
1025 subparser.set_defaults(
1026 func=cmd_patches, path=False
1027 )
1028
1029 subparser = subparsers.add_parser('dep3', help='Add dep3 headers')
1030 subparser.add_argument("patch", help="Patch")
1031 subparser.set_defaults(
1032 func=cmd_dep3, path=False
1033 )
1034
1035 subparser = subparsers.add_parser('increase', help='Increase version number')
1036 subparser.add_argument("package", help="Package name")
1037 subparser.add_argument("version", help="Version number")
1038 subparser.add_argument("-f", "--force", action="store_true", dest="force",
1039 help="Override warnings, just do it")
1040 subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
1041 help="Package name reflects the upstream name")
1042 subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
1043 help="Commit changes and submit")
1044 subparser.add_argument( "--no-submit", action="store_false", dest="submit",
1045 help="Do not commit changes and submit")
1046 subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo",
1047 help="Hash algorithm")
1048 subparser.add_argument("--hash", dest="hexdigest",
1049 help="Hexdigest of the hash")
1050 subparser.set_defaults(
1051 func=cmd_package_new_version, submit=argparse.SUPPRESS, upstream=False, hexdigest=None, algo="sha256",
1052 force=False
1053 )
1054
1055 subparser = subparsers.add_parser('gnome-release-email', help='Submit packages based on GNOME ftp-release-list email')
1056 subparser.add_argument("-m", "--mail", help="Email address to send the progress to")
1057 subparser.add_argument("-w", "--wait", action="store_true",
1058 help="Wait before trying to retrieve the new version")
1059 subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
1060 help="Commit changes and submit")
1061 subparser.add_argument("-f", "--force", action="store_true",
1062 help="Force submission")
1063 subparser.set_defaults(
1064 func=cmd_parse_ftp_release_list, force=False, wait=False
1065 )
1066
1067 if len(sys.argv) == 1:
1068 parser.print_help()
1069 sys.exit(2)
1070
1071 options = parser.parse_args()
1072 if options.limit_upstream:
1073 Upstream.limit = set(options.limit_upstream.read().strip("\n").splitlines())
1074
1075 if not hasattr(options, 'submit'):
1076 options.submit = not options.distro
1077
1078 if options.distro:
1079 Downstream.PKGROOT = os.path.join('~/pkgs', options.distro)
1080 Downstream.MEDIA = "Core Release {0} Source,Core {0} Updates Source,Core {0} Updates Testing Source".format(options.distro)
1081 Downstream.DISTRO = options.distro
1082
1083 try:
1084 options.func(options, parser)
1085 except KeyboardInterrupt:
1086 print('Interrupted')
1087 sys.exit(1)
1088 except EOFError:
1089 print('EOF')
1090 sys.exit(1)
1091 except IOError, e:
1092 if e.errno != errno.EPIPE:
1093 raise
1094 sys.exit(0)
1095
1096 if __name__ == "__main__":
1097 os.environ['PYTHONUNBUFFERED'] = '1'
1098 main()

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.30