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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.30