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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.30