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

Annotation of /mga-gnome/trunk/mga-gnome

Parent Directory Parent Directory | Revision Log Revision Log


Revision 7105 - (hide annotations) (download)
Wed Jan 16 09:35:26 2013 UTC (11 years, 7 months ago) by ovitters
File size: 37916 byte(s)
handle networkmanager version numbering
1 ovitters 3121 #!/usr/bin/python -u
2 ovitters 2932
3 ovitters 3057 # 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 ovitters 2932 import os
9     import os.path
10     import sys
11     import re
12     import subprocess
13 ovitters 3057
14     # command line parsing, error handling:
15 ovitters 2932 import argparse
16 ovitters 2936 import errno
17 ovitters 3057
18     # overwriting files by moving them (safer):
19 ovitters 2944 import tempfile
20     import shutil
21 ovitters 3057
22     # version comparison:
23 ovitters 3045 import rpm
24 ovitters 3057
25     # opening tarballs:
26     import tarfile
27     import gzip
28     import bz2
29     import lzma # pyliblzma
30    
31     # getting links from HTML document:
32 ovitters 2932 from sgmllib import SGMLParser
33 ovitters 3057 import urllib2
34     import urlparse
35 ovitters 2932
36 ovitters 3115 # for checking hashes
37     import hashlib
38    
39 ovitters 3119 # for parsing ftp-release-list emails
40     import email
41     from email.mime.text import MIMEText
42    
43 ovitters 3120 # to be able to sleep for a while
44     import time
45 ovitters 3119
46 ovitters 3180 # version freeze
47     import datetime
48    
49 ovitters 3653 # packages --sort
50     import itertools
51    
52 ovitters 5288 # check-latest
53     import requests
54    
55 ovitters 3557 SLEEP_INITIAL=180
56 ovitters 3555 SLEEP_REPEAT=30
57 ovitters 6248 SLEEP_TIMES=30
58 ovitters 2932
59 ovitters 3090 re_majmin = re.compile(r'^([0-9]+\.[0-9]+).*')
60 ovitters 3012 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 ovitters 3045 """
70 ovitters 3012
71 ovitters 3045 return rpm.labelCompare(('1', a, '1'), ('1', b, '1'))
72 ovitters 3012
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 ovitters 7105 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 ovitters 5288 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 ovitters 7105 def judge_version_increase(version_old, version_new, module=None):
119 ovitters 3088 """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 ovitters 3125 # 1.0.0 -> 1.0.1
134 ovitters 3088 return (-2, "Already at version %s!" % (version_old))
135    
136     if compare != 1:
137 ovitters 3125 # 1.0.1 -> 1.0.0
138 ovitters 3088 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 ovitters 7105 majmins = [get_majmin(ver, module) for ver in versions if re_majmin.match(ver) is not None]
142 ovitters 3088
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 ovitters 3125 # 1.1.x -> 1.1.x or 1.0.x -> 1.0.x
159 ovitters 3088 return (10, None)
160    
161     # Check/ensure major version number is the same
162 ovitters 7105 if majmins[0][0] != majmins[1][0]:
163 ovitters 3125 # 1.0.x -> 2.0.x
164 ovitters 3088 return (1, "Major version number increase")
165    
166     # Minor indicates stable/unstable
167 ovitters 7105 devstate = (long(majmins[0][1]) % 2 == 0, long(majmins[1][1]) % 2 == 0)
168 ovitters 3088
169     # Upgrading to unstable is weird
170     if not devstate[1]:
171     if devstate[0]:
172 ovitters 3125 # 1.2.x -> 1.3.x
173 ovitters 3088 return (1, "Stable to unstable increase")
174    
175 ovitters 3125 # 1.3.x -> 1.5.x
176 ovitters 3088 return (4, "Unstable to unstable version increase")
177    
178     # Unstable => stable is always ok
179     if not devstate[0]:
180 ovitters 3125 # 1.1.x -> 1.2.x
181 ovitters 3088 return (5, "Unstable to stable")
182    
183     # Can only be increase of minors from one stable to the next
184 ovitters 3125 # 1.0.x -> 1.2.x
185 ovitters 3088 return (6, "Stable version increase")
186    
187 ovitters 2936 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 ovitters 2955 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 ovitters 2932 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 ovitters 3057 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 ovitters 3082 if not hasattr(tarfile.TarFile, 'xzopen'):
260 ovitters 3057 tarfile.open = XzTarFile.open
261    
262 ovitters 3115 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 ovitters 3012 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 ovitters 7105 def __init__(self, path, module=None):
281 ovitters 3012 self.path = path
282     self.cwd = os.path.dirname(path)
283 ovitters 7105 self.module = module
284 ovitters 3012
285     @property
286     def version(self):
287     return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0]
288 ovitters 3115 @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 ovitters 3037
296 ovitters 3555 def update(self, version, force=False):
297 ovitters 3012 """Update specfile (increase version)"""
298     cur_version = self.version
299    
300 ovitters 3088 (judgement, msg) = judge_version_increase(cur_version, version)
301 ovitters 3037
302 ovitters 3088 if judgement < 0:
303     print >>sys.stderr, "ERROR: %s!" % (msg)
304 ovitters 3037 return False
305    
306 ovitters 3088 if judgement < 5:
307 ovitters 3089 print "WARNING: %s!" % (msg)
308 ovitters 3555 if not force: return False
309 ovitters 3012
310 ovitters 3039 # XXX - os.path.join is hackish
311 ovitters 3560 svn_diff_output = subprocess.check_output(["svn", "diff", os.path.join(self.path, '..')])
312     if svn_diff_output != '':
313     print svn_diff_output
314 ovitters 3039 print >>sys.stderr, "ERROR: Package has uncommitted changes!"
315 ovitters 3560 if not force:
316     return False
317 ovitters 3039
318 ovitters 3560 # 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 ovitters 3012 with open(self.path, "rw") as f:
326     data = f.read()
327    
328 ovitters 6243 if data.count("%subrel") != 0:
329     print >>sys.stderr, "ERROR: %subrel found; don't know what to do!"
330     return False
331    
332 ovitters 3012 if data.count("%mkrel") != 1:
333 ovitters 3037 print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!"
334 ovitters 3012 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 ovitters 3037 print >>sys.stderr, "ERROR: Could not increase version!"
339 ovitters 3012 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 ovitters 3037 print >>sys.stderr, "ERROR: Could not reset release!"
344 ovitters 3012 return False
345    
346     # Overwrite file with new version number
347     write_file(self.path, data)
348    
349    
350 ovitters 3045 # Verify that RPM also agrees that version number has changed
351 ovitters 3012 if self.version != version:
352     print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
353     return False
354    
355 ovitters 3555
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 ovitters 6248 if tries > 1: time.sleep(SLEEP_REPEAT * 2 ** (tries // 10))
361 ovitters 3555 try:
362     # Download new tarball
363     subprocess.check_call(['mgarepo', 'sync', '-d'], cwd=self.cwd)
364 ovitters 3558 # success, so exit loop
365 ovitters 3555 break
366     except subprocess.CalledProcessError, e:
367     # mgarepo sync returns 1 if the tarball cannot be downloaded
368     if e.returncode != 1:
369 ovitters 6243 subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')])
370 ovitters 3555 return False
371 ovitters 3558 else:
372 ovitters 6243 # failed to download tarball
373     subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')])
374 ovitters 3558 return False
375 ovitters 3555
376    
377 ovitters 3034 try:
378     # Check patches still apply
379     subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd)
380     except subprocess.CalledProcessError:
381 ovitters 3568 logfile = os.path.join(os.path.dirname(self.path), 'log.%s' % os.path.splitext(os.path.basename(self.path))[0])
382 ovitters 3569 if os.path.exists(logfile):
383 ovitters 3568 subprocess.call(['tail', '-n', '15', logfile])
384 ovitters 3034 return False
385 ovitters 3012
386     return True
387    
388 ovitters 2936 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 ovitters 2955 """Add DEP-3 headers to a patch file"""
404 ovitters 2944 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 ovitters 2955 print >>fdst, "%s: %s" % (header, "" if data is None else data)
430 ovitters 2944
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 ovitters 2955 call_editor(self.path)
439    
440 ovitters 2936 #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 ovitters 2955 """Read DEP-3 headers from an existing patch file
448    
449     This will also parse git headers"""
450 ovitters 2936 dep3 = {}
451 ovitters 2944 headers = {}
452 ovitters 2936
453     last_header = None
454 ovitters 2944 last_nr = 0
455     nr = 0
456 ovitters 2936 try:
457     with open(self.path, "r") as f:
458     for line in line_input(f):
459 ovitters 2944 nr += 1
460     # stop trying to parse when real patch begins
461 ovitters 2936 if line == '---':
462     break
463    
464     r = self.re_dep3.match(line)
465     if r:
466     info = r.groupdict()
467 ovitters 3012
468     # Avoid matching URLS
469     if info['data'].startswith('//') and info['header'].lower () == info['header']:
470     continue
471    
472 ovitters 2944 headers[info['header']] = info['data']
473 ovitters 2936 last_header = info['header']
474 ovitters 2944 last_nr = nr
475 ovitters 2936 continue
476    
477     r = self.re_dep3_cont.match(line)
478     if r:
479     info = r.groupdict()
480     if last_header:
481 ovitters 2944 headers[last_header] = " ".join((headers[last_header], info['data']))
482     last_nr = nr
483 ovitters 2936 continue
484    
485     last_header = None
486     except IOError:
487     pass
488 ovitters 2944
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 ovitters 2936 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 ovitters 2944 @property
508     def svn_author(self):
509     if not hasattr(self, '_svn_author'):
510 ovitters 3083 try:
511     contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines()
512    
513 ovitters 2944 for line in contents:
514     if ' | ' not in line:
515     continue
516 ovitters 2936
517 ovitters 2944 fields = line.split(' | ')
518     if len(fields) >= 3:
519     self._svn_author = fields[1]
520 ovitters 3083 except subprocess.CalledProcessError:
521     pass
522 ovitters 2944
523 ovitters 2955 if not hasattr(self, '_svn_author'):
524     return None
525    
526 ovitters 2944 return self._svn_author
527    
528 ovitters 2932
529 ovitters 3649 class Upstream(object):
530 ovitters 2932
531 ovitters 5287 URL="http://download.gnome.org/sources/"
532 ovitters 3649 limit = None
533 ovitters 5288 _cache_versions = {}
534 ovitters 2932
535 ovitters 3649 def __init__(self):
536     urlopen = urllib2.build_opener()
537 ovitters 2932
538 ovitters 3649 good_dir = re.compile('^[-A-Za-z0-9_+.]+/$')
539 ovitters 2932
540 ovitters 3649 # Get the files
541 ovitters 5287 usock = urlopen.open(self.URL)
542 ovitters 3649 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 ovitters 5288 @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 ovitters 3650 class Downstream(object):
571 ovitters 2932 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 ovitters 5287 MEDIA="Core Release Source"
574     PKGROOT='~/pkgs'
575     DISTRO=None
576    
577 ovitters 3650 def __init__(self):
578 ovitters 5287 contents = subprocess.check_output(['urpmf', '--qf', '%name|%version|%files', '.', "--media", self.MEDIA], close_fds=True).strip("\n").splitlines()
579 ovitters 2932
580 ovitters 3650 FILES = {}
581     TARBALLS = {}
582 ovitters 2932
583 ovitters 3650 for line in contents:
584     try:
585     srpm, version, filename = line.split("|")
586     except ValueError:
587     print >>sys.stderr, line
588     continue
589 ovitters 2932
590 ovitters 3650 if '.tar' in filename:
591     r = self.re_file.match(filename)
592     if r:
593     fileinfo = r.groupdict()
594     module = fileinfo['module']
595 ovitters 2932
596 ovitters 3650 if module not in TARBALLS:
597     TARBALLS[module] = {}
598 ovitters 2932
599 ovitters 6243 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 ovitters 3650 if srpm not in FILES:
607     FILES[srpm] = set()
608     FILES[srpm].add(filename)
609 ovitters 2932
610 ovitters 3650 self.tarballs = TARBALLS
611     self.files = FILES
612 ovitters 2932
613 ovitters 5287 @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 ovitters 3652 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 ovitters 3012
628 ovitters 3652 if len(self.tarballs[upstream]) == 1:
629     return self.tarballs[upstream].keys()
630 ovitters 3119
631 ovitters 3652 # Directories packages are located in
632 ovitters 5287 root = os.path.expanduser(self.PKGROOT)
633 ovitters 3119
634 ovitters 3652 packages = {}
635     for package in self.tarballs[upstream].keys():
636     cwd = os.path.join(root, package)
637 ovitters 3119
638 ovitters 3652 # Checkout package to ensure the checkout reflects the latest changes
639     try:
640 ovitters 5287 self.co(package, cwd=root)
641 ovitters 3652 except subprocess.CalledProcessError:
642     raise ValueError("Multiple packages found and cannot checkout %s" % package)
643 ovitters 3559
644 ovitters 3652 # Determine version from spec file
645     try:
646 ovitters 7105 packages[package] = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=upstream).version
647 ovitters 3652 except subprocess.CalledProcessError:
648     raise ValueError("Multiple packages found and cannot determine version of %s" % package)
649 ovitters 3559
650 ovitters 3652 # 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 ovitters 3559
655 ovitters 3652 # 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 ovitters 3559
661 ovitters 3652 # Give up
662     raise ValueError("Multiple packages found and cannot determine package for version %s" % version)
663 ovitters 3559
664 ovitters 3012 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 ovitters 2932 def cmd_co(options, parser):
671 ovitters 3502 for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
672 ovitters 3501 print "%s => %s" % (module, package)
673 ovitters 5287 try:
674     Downstream.co(package)
675     except subprocess.CalledProcessError:
676     pass
677 ovitters 2932
678 ovitters 3501 def join_streams(show_version=False, only_diff_version=False):
679 ovitters 5287 root = os.path.expanduser(Downstream.PKGROOT)
680 ovitters 2932
681 ovitters 3649 upstream = Upstream().names
682 ovitters 3650 downstream = Downstream()
683 ovitters 2932
684 ovitters 3650 matches = upstream & set(downstream.tarballs.keys())
685 ovitters 2932 for module in matches:
686 ovitters 3650 for package in downstream.tarballs[module].keys():
687     package_version = downstream.tarballs[module][package]
688 ovitters 3501 spec_version = None
689     if show_version or only_diff_version:
690     cwd = os.path.join(root, package)
691     try:
692 ovitters 7105 spec_version = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=module).version
693 ovitters 3501 except subprocess.CalledProcessError:
694     spec_version = 'N/A'
695 ovitters 2932
696 ovitters 3501 if only_diff_version and package_version == spec_version:
697     continue
698    
699 ovitters 3650 yield (package, module, package_version, spec_version, downstream.files[package])
700 ovitters 3501
701 ovitters 6522 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 ovitters 6523 yield "\t".join((maint, source, ",".join(sorted(packages[source]))))
734 ovitters 6522
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 ovitters 3114 def cmd_ls(options, parser):
749 ovitters 3653 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 ovitters 3648 sys.stdout.write(package)
759     if options.upstream: sys.stdout.write("\t%s" % module)
760 ovitters 3649 if options.show_version: sys.stdout.write("\t%s\t%s" % (spec_version, package_version))
761 ovitters 3501 print
762 ovitters 3114
763 ovitters 5288 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 ovitters 6243 upgrade=set()
768 ovitters 5288 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 ovitters 6243 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 ovitters 5288
785 ovitters 6243 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 ovitters 5288 sys.stdout.write("\t%s" % latest_version)
793     sys.stdout.write("\t%s" % safe_version)
794 ovitters 6243 sys.stdout.write("\t%s" % "".join(sorted(upgrade)))
795    
796 ovitters 5288 print
797    
798 ovitters 2932 def cmd_patches(options, parser):
799 ovitters 5287 root = os.path.expanduser(Downstream.PKGROOT)
800 ovitters 2932
801 ovitters 3502 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 ovitters 2932
805 ovitters 3502 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 ovitters 2936
814 ovitters 2944 def cmd_dep3(options, parser):
815     p = Patch(options.patch)
816     p.add_dep3()
817    
818 ovitters 3012 def cmd_package_new_version(options, parser):
819 ovitters 3087 # Determine the package name
820 ovitters 3086 if options.upstream:
821 ovitters 3119 try:
822 ovitters 3652 package = Downstream().get_downstream_from_upstream(options.package, options.version)[0]
823 ovitters 3119 except ValueError, e:
824     print >>sys.stderr, "ERROR: %s" % e
825 ovitters 3086 sys.exit(1)
826     else:
827     package = options.package
828    
829 ovitters 3087 # Directories packages are located in
830 ovitters 5287 root = os.path.expanduser(Downstream.PKGROOT)
831 ovitters 3044 cwd = os.path.join(root, package)
832 ovitters 3038
833 ovitters 3087 # Checkout package to ensure the checkout reflects the latest changes
834 ovitters 3044 try:
835 ovitters 5287 Downstream.co(package, cwd=root)
836 ovitters 3044 except subprocess.CalledProcessError:
837     sys.exit(1)
838 ovitters 3087
839     # SpecFile class handles the actual version+release change
840 ovitters 7105 # 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 ovitters 3037 print "%s => %s" % (s.version, options.version)
843 ovitters 3555 if not s.update(options.version, force=options.force):
844 ovitters 3012 sys.exit(1)
845    
846 ovitters 3115 # 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 ovitters 6244 # 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 ovitters 3115 for filename in sources:
861 ovitters 3597 path = os.path.join(cwd, "SOURCES", filename)
862     if not is_valid_hash(path, options.algo, options.hexdigest):
863 ovitters 3115 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 ovitters 3654 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 ovitters 3012
872 ovitters 3654 # Submit is optional
873     if options.submit:
874 ovitters 5289 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 ovitters 3654 except subprocess.CalledProcessError:
879     sys.exit(1)
880    
881 ovitters 3119 def cmd_parse_ftp_release_list(options, parser):
882 ovitters 3596 def _send_reply_mail(contents, orig_msg, to, packages=[], error=False):
883 ovitters 3119 """Send an reply email"""
884     contents.seek(0)
885     msg = MIMEText(contents.read(), _charset='utf-8')
886 ovitters 3596
887 ovitters 3384 if error:
888     # XXX - ugly
889     contents.seek(0)
890 ovitters 3567 lastline = contents.read().rstrip().splitlines()[-1]
891 ovitters 3384 # Remove things like "ERROR: " and so on from the last line
892     lastline = re.sub(r'^(?:[^ :]+:\s+)+', '', lastline)
893 ovitters 3570 # Remove things like " - " (youri output from mgarepo submit)
894     lastline = re.sub(r'^\s+-\s+', '', lastline)
895 ovitters 3397 subjecterror = " (ERROR: %s)" % lastline if lastline else " (ERROR)"
896 ovitters 3384 else:
897     subjecterror = ""
898 ovitters 3596
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 ovitters 3119 msg['To'] = to
906     msg["In-Reply-To"] = orig_msg["Message-ID"]
907     msg["References"] = orig_msg["Message-ID"]
908 ovitters 3038
909 ovitters 3119 # 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 ovitters 3176 stdout = tempfile.TemporaryFile()
923 ovitters 3119 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 ovitters 3180 if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
935 ovitters 3119 sys.exit(1)
936    
937     try:
938 ovitters 3652 packages = Downstream().get_downstream_from_upstream(module, version)
939 ovitters 3119 except ValueError, e:
940     print >>stderr, "ERROR: %s" % e
941 ovitters 3180 if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
942 ovitters 3119 sys.exit(1)
943    
944 ovitters 3120 if options.wait:
945 ovitters 3122 # maildrop aborts and will try to deliver after 5min
946     # fork to avoid this
947     if os.fork() != 0: sys.exit(0)
948 ovitters 3556 # 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 ovitters 3120
955 ovitters 3556 if secs > 0: time.sleep(secs)
956    
957 ovitters 3180 error = False
958 ovitters 3119 for package in packages:
959 ovitters 3654 cmd = ['mga-gnome', 'increase', '--hash', hexdigest]
960     if options.submit:
961     cmd.append('--submit')
962 ovitters 3561 if options.force:
963     cmd.append('--force')
964     cmd.extend((package, version))
965     if subprocess.call(cmd, stdout=stdout, stderr=stderr):
966 ovitters 3180 error = True
967 ovitters 3119
968 ovitters 3596 if options.mail: _send_reply_mail(stdout, msg, options.mail, packages=packages, error=error)
969 ovitters 3119
970 ovitters 2932 def main():
971     description = """Mageia GNOME commands."""
972     epilog="""Report bugs to Olav Vitters"""
973     parser = argparse.ArgumentParser(description=description,epilog=epilog)
974 ovitters 3649 parser.add_argument("-l", "--limit", type=argparse.FileType('r', 0),
975     dest="limit_upstream", metavar="FILE",
976     help="File containing upstream names")
977 ovitters 5287 parser.add_argument("-d", "--distro", action="store", dest="distro",
978     help="Distribution release")
979 ovitters 2932
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 ovitters 3114 subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
990     help="Show upstream module")
991 ovitters 3501 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 ovitters 3653 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 ovitters 2932 subparser.set_defaults(
1000 ovitters 3501 func=cmd_ls, upstream=False, show_version=False, diff=False
1001 ovitters 2932 )
1002    
1003 ovitters 6522 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 ovitters 5288 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 ovitters 2932 subparser = subparsers.add_parser('patches', help='list all GNOME patches')
1016     subparser.add_argument("-p", "--path", action="store_true", dest="path",
1017 ovitters 2944 help="Show full path to patch")
1018 ovitters 2932 subparser.set_defaults(
1019     func=cmd_patches, path=False
1020     )
1021    
1022 ovitters 2944 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 ovitters 2932
1028 ovitters 3012 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 ovitters 3555 subparser.add_argument("-f", "--force", action="store_true", dest="force",
1032     help="Override warnings, just do it")
1033 ovitters 3086 subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
1034     help="Package name reflects the upstream name")
1035 ovitters 3038 subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
1036     help="Commit changes and submit")
1037 ovitters 6243 subparser.add_argument( "--no-submit", action="store_false", dest="submit",
1038     help="Do not commit changes and submit")
1039 ovitters 3115 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 ovitters 3012 subparser.set_defaults(
1044 ovitters 6243 func=cmd_package_new_version, submit=argparse.SUPPRESS, upstream=False, hexdigest=None, algo="sha256",
1045 ovitters 3555 force=False
1046 ovitters 3012 )
1047    
1048 ovitters 3119 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 ovitters 3120 subparser.add_argument("-w", "--wait", action="store_true",
1051     help="Wait before trying to retrieve the new version")
1052 ovitters 3654 subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
1053     help="Commit changes and submit")
1054 ovitters 3561 subparser.add_argument("-f", "--force", action="store_true",
1055     help="Force submission")
1056 ovitters 3119 subparser.set_defaults(
1057 ovitters 3561 func=cmd_parse_ftp_release_list, force=False, wait=False
1058 ovitters 3119 )
1059    
1060 ovitters 2932 if len(sys.argv) == 1:
1061     parser.print_help()
1062     sys.exit(2)
1063    
1064     options = parser.parse_args()
1065 ovitters 3649 if options.limit_upstream:
1066     Upstream.limit = set(options.limit_upstream.read().strip("\n").splitlines())
1067 ovitters 2932
1068 ovitters 6243 if not hasattr(options, 'submit'):
1069     options.submit = not options.distro
1070    
1071 ovitters 5287 if options.distro:
1072     Downstream.PKGROOT = os.path.join('~/pkgs', options.distro)
1073 ovitters 6243 Downstream.MEDIA = "Core Release {0} Source,Core {0} Updates Source,Core {0} Updates Testing Source".format(options.distro)
1074 ovitters 5287 Downstream.DISTRO = options.distro
1075    
1076 ovitters 2932 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 ovitters 3567 os.environ['PYTHONUNBUFFERED'] = '1'
1091 ovitters 2932 main()

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.30