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

Diff of /mga-gnome/trunk/mga-gnome

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2944 by ovitters, Tue Feb 14 10:38:56 2012 UTC revision 3649 by ovitters, Wed Mar 21 19:17:35 2012 UTC
# Line 1  Line 1 
1  #!/usr/bin/python  #!/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  import os
9  import os.path  import os.path
10  import sys  import sys
11  import re  import re
12  import subprocess  import subprocess
13  import urllib2  
14  import urlparse  # command line parsing, error handling:
15  import argparse  import argparse
16  import errno  import errno
17    
18    # overwriting files by moving them (safer):
19  import tempfile  import tempfile
20  import shutil  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  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  MEDIA="Core Release Source"  MEDIA="Core Release Source"
50  URL="http://download.gnome.org/sources/"  URL="http://download.gnome.org/sources/"
51  PKGROOT='~/pkgs'  PKGROOT='~/pkgs'
52    SLEEP_INITIAL=180
53    SLEEP_REPEAT=30
54    SLEEP_TIMES=20
55    
56    re_majmin = re.compile(r'^([0-9]+\.[0-9]+).*')
57    re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')
58    
59    def version_cmp(a, b):
60        """Compares two versions
61    
62        Returns
63          -1 if a < b
64          0  if a == b
65          1  if a > b
66        """
67    
68        return rpm.labelCompare(('1', a, '1'), ('1', b, '1'))
69    
70    def get_latest_version(versions, max_version=None):
71        """Gets the latest version number
72    
73        if max_version is specified, gets the latest version number before
74        max_version"""
75        latest = None
76        for version in versions:
77            if ( latest is None or version_cmp(version, latest) > 0 ) \
78               and ( max_version is None or version_cmp(version, max_version) < 0 ):
79                latest = version
80        return latest
81    
82    def judge_version_increase(version_old, version_new):
83            """Judge quality of version increase:
84    
85            Returns a tuple containing judgement and message
86    
87            Judgement:
88            Less than 0: Error
89            0 to 4: Better not
90            5+: Ok"""
91            versions = (version_old, version_new)
92    
93            # First do a basic version comparison to ensure version_new is actually newer
94            compare = version_cmp(version_new, version_old)
95    
96            if compare == 0:
97                # 1.0.0 -> 1.0.1
98                return (-2, "Already at version %s!" % (version_old))
99    
100            if compare != 1:
101                # 1.0.1 -> 1.0.0
102                return (-3, "Version %s is older than current version %s!" % (version_new, version_old))
103    
104            # Version is newer, but we don't want to see if it follows the GNOME versioning scheme
105            majmins = [re_majmin.sub(r'\1', ver) for ver in versions if re_majmin.match(ver) is not None]
106    
107            if len(majmins) == 1:
108                return (-1, "Version number scheme changes: %s" % (", ".join(versions)))
109    
110            if len(majmins) == 0:
111                return (0, "Unsupported version numbers: %s" % (", ".join(versions)))
112    
113            # Follows GNOME versioning scheme
114            # Meaning: x.y.z
115            #          x = major
116            #          y = minor  : even if stable
117            #          z = micro
118    
119            # Major+minor the same? Then go ahead and upgrade!
120            if majmins[0] == majmins[1]:
121                # Majmin of both versions are the same, looks good!
122                # 1.1.x -> 1.1.x or 1.0.x -> 1.0.x
123                return (10, None)
124    
125            # More detailed analysis needed, so figure out the numbers
126            majmin_nrs = [map(long, ver.split('.')) for ver in majmins]
127    
128            # Check/ensure major version number is the same
129            if majmin_nrs[0][0] != majmin_nrs[1][0]:
130                # 1.0.x -> 2.0.x
131                return (1, "Major version number increase")
132    
133            # Minor indicates stable/unstable
134            devstate = (majmin_nrs[0][1] % 2 == 0, majmin_nrs[1][1] % 2 == 0)
135    
136            # Upgrading to unstable is weird
137            if not devstate[1]:
138                if devstate[0]:
139                    # 1.2.x -> 1.3.x
140                    return (1, "Stable to unstable increase")
141    
142                # 1.3.x -> 1.5.x
143                return (4, "Unstable to unstable version increase")
144    
145            # Unstable => stable is always ok
146            if not devstate[0]:
147                # 1.1.x -> 1.2.x
148                return (5, "Unstable to stable")
149    
150            # Can only be increase of minors from one stable to the next
151            # 1.0.x -> 1.2.x
152            return (6, "Stable version increase")
153    
154  def line_input (file):  def line_input (file):
155      for line in file:      for line in file:
# Line 24  def line_input (file): Line 158  def line_input (file):
158          else:          else:
159              yield line              yield line
160    
161    def call_editor(filename):
162        """Return a sequence of possible editor binaries for the current platform"""
163    
164        editors = []
165    
166        for varname in 'VISUAL', 'EDITOR':
167            if varname in os.environ:
168                editors.append(os.environ[varname])
169    
170        editors.extend(('/usr/bin/editor', 'vi', 'pico', 'nano', 'joe'))
171    
172        for editor in editors:
173            try:
174                ret = subprocess.call([editor, filename])
175            except OSError, e:
176                if e.errno == 2:
177                    continue
178                raise
179    
180            if ret == 127:
181                continue
182    
183            return True
184    
185  class urllister(SGMLParser):  class urllister(SGMLParser):
186      def reset(self):      def reset(self):
187          SGMLParser.reset(self)          SGMLParser.reset(self)
# Line 34  class urllister(SGMLParser): Line 192  class urllister(SGMLParser):
192          if href:          if href:
193              self.urls.extend(href)              self.urls.extend(href)
194    
195    class XzTarFile(tarfile.TarFile):
196    
197        OPEN_METH = tarfile.TarFile.OPEN_METH.copy()
198        OPEN_METH["xz"] = "xzopen"
199    
200        @classmethod
201        def xzopen(cls, name, mode="r", fileobj=None, **kwargs):
202            """Open gzip compressed tar archive name for reading or writing.
203               Appending is not allowed.
204            """
205            if len(mode) > 1 or mode not in "rw":
206                raise ValueError("mode must be 'r' or 'w'")
207    
208            if fileobj is not None:
209                fileobj = _LMZAProxy(fileobj, mode)
210            else:
211                fileobj = lzma.LZMAFile(name, mode)
212    
213            try:
214                # lzma doesn't immediately return an error
215                # try and read a bit of data to determine if it is a valid xz file
216                fileobj.read(_LZMAProxy.blocksize)
217                fileobj.seek(0)
218                t = cls.taropen(name, mode, fileobj, **kwargs)
219            except IOError:
220                raise tarfile.ReadError("not a xz file")
221            except lzma.error:
222                raise tarfile.ReadError("not a xz file")
223            t._extfileobj = False
224            return t
225    
226    if not hasattr(tarfile.TarFile, 'xzopen'):
227        tarfile.open = XzTarFile.open
228    
229    def is_valid_hash(path, algo, hexdigest):
230        if algo not in hashlib.algorithms:
231            raise ValueError("Unknown hash algorithm: %s" % algo)
232    
233        local_hash = getattr(hashlib, algo)()
234    
235        with open(path, 'rb') as fp:
236            data = fp.read(32768)
237            while data:
238                local_hash.update(data)
239                data = fp.read(32768)
240    
241        return local_hash.hexdigest() == hexdigest
242    
243    class SpecFile(object):
244        re_update_version = re.compile(r'^(?P<pre>Version:\s*)(?P<version>.+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)
245        re_update_release = re.compile(r'^(?P<pre>Release:\s*)(?P<release>%mkrel \d+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)
246    
247        def __init__(self, path):
248            self.path = path
249            self.cwd = os.path.dirname(path)
250    
251        @property
252        def version(self):
253            return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0]
254        @property
255        def sources(self):
256            ts = rpm.ts()
257            spec = ts.parseSpec(self.path)
258            srclist = spec.sources if isinstance(spec.sources, (list, tuple)) \
259                            else spec.sources()
260            return dict((os.path.basename(name), name) for name, no, flags in srclist)
261    
262        def update(self, version, force=False):
263            """Update specfile (increase version)"""
264            cur_version = self.version
265    
266            (judgement, msg) = judge_version_increase(cur_version, version)
267    
268            if judgement < 0:
269                print >>sys.stderr, "ERROR: %s!" % (msg)
270                return False
271    
272            if judgement < 5:
273                print "WARNING: %s!" % (msg)
274                if not force: return False
275    
276            # XXX - os.path.join is hackish
277            svn_diff_output = subprocess.check_output(["svn", "diff", os.path.join(self.path, '..')])
278            if svn_diff_output != '':
279                print svn_diff_output
280                print >>sys.stderr, "ERROR: Package has uncommitted changes!"
281                if not force:
282                    return False
283    
284                # Forcing package submission: revert changes
285                try:
286                    print >>sys.stderr, "WARNING: Force used; reverting svn changes"
287                    subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')])
288                except subprocess.CalledProcessError:
289                    return False
290    
291            with open(self.path, "rw") as f:
292                data = f.read()
293    
294                if data.count("%mkrel") != 1:
295                    print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!"
296                    return False
297    
298                data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1)
299                if nr != 1:
300                    print >>sys.stderr, "ERROR: Could not increase version!"
301                    return False
302    
303                data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1)
304                if nr != 1:
305                    print >>sys.stderr, "ERROR: Could not reset release!"
306                    return False
307    
308                # Overwrite file with new version number
309                write_file(self.path, data)
310    
311    
312            # Verify that RPM also agrees that version number has changed
313            if self.version != version:
314                print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
315                return False
316    
317    
318            # Try to download the new tarball various times and wait between attempts
319            tries = 0
320            while tries < SLEEP_TIMES:
321                tries += 1
322                if tries > 1: time.sleep(SLEEP_REPEAT)
323                try:
324                    # Download new tarball
325                    subprocess.check_call(['mgarepo', 'sync', '-d'], cwd=self.cwd)
326                    # success, so exit loop
327                    break
328                except subprocess.CalledProcessError, e:
329                    # mgarepo sync returns 1 if the tarball cannot be downloaded
330                    if e.returncode != 1:
331                        return False
332            else:
333                return False
334    
335    
336            try:
337                # Check patches still apply
338                subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd)
339            except subprocess.CalledProcessError:
340                logfile = os.path.join(os.path.dirname(self.path), 'log.%s' % os.path.splitext(os.path.basename(self.path))[0])
341                if os.path.exists(logfile):
342                    subprocess.call(['tail', '-n', '15', logfile])
343                return False
344    
345            return True
346    
347  class Patch(object):  class Patch(object):
348      """Do things with patches"""      """Do things with patches"""
349    
# Line 49  class Patch(object): Line 359  class Patch(object):
359          return self.path if self.show_path else os.path.basename(self.path)          return self.path if self.show_path else os.path.basename(self.path)
360    
361      def add_dep3(self):      def add_dep3(self):
362            """Add DEP-3 headers to a patch file"""
363          if self.dep3['valid']:          if self.dep3['valid']:
364              return False              return False
365    
# Line 74  class Patch(object): Line 385  class Patch(object):
385    
386                      # XXX - wrap this at 80 chars                      # XXX - wrap this at 80 chars
387                      add_line = True                      add_line = True
388                      print >>fdst, "%s: %s" % (header, data)                      print >>fdst, "%s: %s" % (header, "" if data is None else data)
389    
390                  if add_line: print >>fdst, ""                  if add_line: print >>fdst, ""
391                  # Now copy any other data and the patch                  # Now copy any other data and the patch
# Line 83  class Patch(object): Line 394  class Patch(object):
394              fdst.flush()              fdst.flush()
395              os.rename(fdst.name, self.path)              os.rename(fdst.name, self.path)
396    
397            call_editor(self.path)
398    
399      #Author: fwang      #Author: fwang
400      #Subject: Build fix: Fix glib header inclusion      #Subject: Build fix: Fix glib header inclusion
401      #Applied-Upstream: commit:30602      #Applied-Upstream: commit:30602
# Line 90  class Patch(object): Line 403  class Patch(object):
403      #Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247      #Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247
404    
405      def _read_dep3(self):      def _read_dep3(self):
406          """This will also parse git headers"""          """Read DEP-3 headers from an existing patch file
407    
408            This will also parse git headers"""
409          dep3 = {}          dep3 = {}
410          headers = {}          headers = {}
411    
# Line 108  class Patch(object): Line 423  class Patch(object):
423                      r = self.re_dep3.match(line)                      r = self.re_dep3.match(line)
424                      if r:                      if r:
425                          info = r.groupdict()                          info = r.groupdict()
426    
427                            # Avoid matching URLS
428                            if info['data'].startswith('//') and info['header'].lower () == info['header']:
429                                continue
430    
431                          headers[info['header']] = info['data']                          headers[info['header']] = info['data']
432                          last_header = info['header']                          last_header = info['header']
433                          last_nr = nr                          last_nr = nr
# Line 146  class Patch(object): Line 466  class Patch(object):
466      @property      @property
467      def svn_author(self):      def svn_author(self):
468          if not hasattr(self, '_svn_author'):          if not hasattr(self, '_svn_author'):
469              p = subprocess.Popen(['svn', 'log', '-q', "--", self.path], stdout=subprocess.PIPE, close_fds=True)              try:
470              contents = p.stdout.read().strip("\n").splitlines()                  contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines()
471              ecode = p.wait()  
             if ecode == 0:  
472                  for line in contents:                  for line in contents:
473                      if ' | ' not in line:                      if ' | ' not in line:
474                          continue                          continue
# Line 157  class Patch(object): Line 476  class Patch(object):
476                      fields = line.split(' | ')                      fields = line.split(' | ')
477                      if len(fields) >= 3:                      if len(fields) >= 3:
478                          self._svn_author = fields[1]                          self._svn_author = fields[1]
479                except subprocess.CalledProcessError:
480                    pass
481    
482            if not hasattr(self, '_svn_author'):
483                return None
484    
485          return self._svn_author          return self._svn_author
486    
 def get_upstream_names():  
     urlopen = urllib2.build_opener()  
487    
488      good_dir = re.compile('^[-A-Za-z0-9_+.]+/$')  class Upstream(object):
489    
490        limit = None
491    
492      # Get the files      def __init__(self):
493      usock = urlopen.open(URL)          urlopen = urllib2.build_opener()
     parser = urllister()  
     parser.feed(usock.read())  
     usock.close()  
     parser.close()  
     files = parser.urls  
494    
495      tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)])          good_dir = re.compile('^[-A-Za-z0-9_+.]+/$')
496    
497      return tarballs          # Get the files
498            usock = urlopen.open(URL)
499            parser = urllister()
500            parser.feed(usock.read())
501            usock.close()
502            parser.close()
503            files = parser.urls
504    
505            tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)])
506            if self.limit is not None:
507                tarballs.intersection_update(self.limit)
508    
509            self.names = tarballs
510    
511  def get_downstream_names():  def get_downstream_names():
512      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]*)$')      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]*)$')
513    
514      p = subprocess.Popen(['urpmf', '--files', '.', "--media", MEDIA], stdout=subprocess.PIPE, close_fds=True)      contents = subprocess.check_output(['urpmf', '--qf', '%name|%version|%files', '.', "--media", MEDIA], close_fds=True).strip("\n").splitlines()
     contents = p.stdout.read().strip("\n").splitlines()  
     ecode = p.wait()  
     if ecode != 0:  
         sys.exit(1)  
515    
516      FILES = {}      FILES = {}
517      TARBALLS = {}      TARBALLS = {}
518    
519      for line in  contents:      for line in  contents:
520          try:          try:
521              srpm, filename = line.split(":")              srpm, version, filename = line.split("|")
522          except ValueError:          except ValueError:
523              print >>sys.stderr, line              print >>sys.stderr, line
524              continue              continue
# Line 203  def get_downstream_names(): Line 530  def get_downstream_names():
530                  module = fileinfo['module']                  module = fileinfo['module']
531    
532                  if module not in TARBALLS:                  if module not in TARBALLS:
533                      TARBALLS[module] = set()                      TARBALLS[module] = {}
534                  TARBALLS[module].add(srpm)                  TARBALLS[module][srpm] = version
535    
536          if srpm not in FILES:          if srpm not in FILES:
537              FILES[srpm] = set()              FILES[srpm] = set()
# Line 212  def get_downstream_names(): Line 539  def get_downstream_names():
539    
540      return TARBALLS, FILES      return TARBALLS, FILES
541    
542  def cmd_co(options, parser):  def get_downstream_from_upstream(upstream, version):
543      upstream = get_upstream_names()      # Determine the package name
544      downstream, downstream_files = get_downstream_names()      downstream, downstream_files = get_downstream_names()
545    
546      cwd = os.path.expanduser(PKGROOT)      if upstream not in downstream:
547            raise ValueError("No packages for upstream name: %s" % upstream)
548    
549      matches = upstream & set(downstream.keys())      if len(downstream[upstream]) == 1:
550      for module in matches:          return downstream[upstream].keys()
         print module, "\t".join(downstream[module])  
         for package in downstream[module]:  
             subprocess.call(['mgarepo', 'co', package], cwd=cwd)  
551    
552  def cmd_ls(options, parser):      # Directories packages are located in
553      upstream = get_upstream_names()      root = os.path.expanduser(PKGROOT)
554    
555        packages = {}
556        for package in downstream[upstream].keys():
557            cwd = os.path.join(root, package)
558    
559            # Checkout package to ensure the checkout reflects the latest changes
560            try:
561                subprocess.check_call(['mgarepo', 'co', package], cwd=root)
562            except subprocess.CalledProcessError:
563                raise ValueError("Multiple packages found and cannot checkout %s" % package)
564    
565            # Determine version from spec file
566            try:
567                packages[package] = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)).version
568            except subprocess.CalledProcessError:
569                raise ValueError("Multiple packages found and cannot determine version of %s" % package)
570    
571        # Return all packages reflecting the current version
572        matches = [package for package in packages if packages[package] == version]
573        if len(matches):
574            return matches
575    
576        # Return all packages reflecting the version before the current version
577        latest_version = get_latest_version(packages.values(), max_version=version)
578        matches = [package for package in packages if packages[package] == latest_version]
579        if len(matches):
580            return matches
581    
582        # Give up
583        raise ValueError("Multiple packages found and cannot determine package for version %s" % version)
584    
585    def write_file(path, data):
586        with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst:
587            fdst.write(data)
588            fdst.flush()
589            os.rename(fdst.name, path)
590    
591    def cmd_co(options, parser):
592        root = os.path.expanduser(PKGROOT)
593    
594        for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
595            print "%s => %s" % (module, package)
596            subprocess.call(['mgarepo', 'co', package], cwd=root)
597    
598    def join_streams(show_version=False, only_diff_version=False):
599        root = os.path.expanduser(PKGROOT)
600    
601        upstream = Upstream().names
602      downstream, downstream_files = get_downstream_names()      downstream, downstream_files = get_downstream_names()
603    
604      matches = upstream & set(downstream.keys())      matches = upstream & set(downstream.keys())
605      for module in matches:      for module in matches:
606          print "\n".join(downstream[module])          for package in downstream[module].keys():
607                package_version = downstream[module][package]
608                spec_version = None
609                if show_version or only_diff_version:
610                    cwd = os.path.join(root, package)
611                    try:
612                        spec_version = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)).version
613                    except subprocess.CalledProcessError:
614                        spec_version = 'N/A'
615    
616  def cmd_patches(options, parser):              if only_diff_version and package_version == spec_version:
617      upstream = get_upstream_names()                  continue
     downstream, downstream_files = get_downstream_names()  
618    
619      path = os.path.expanduser(PKGROOT)              yield (package, module, package_version, spec_version, downstream_files[package])
620    
621      import pprint  def cmd_ls(options, parser):
622        for package, module, package_version, spec_version, downstream_files in sorted(join_streams(show_version=options.show_version, only_diff_version=options.diff)):
623            sys.stdout.write(package)
624            if options.upstream: sys.stdout.write("\t%s" % module)
625            if options.show_version: sys.stdout.write("\t%s\t%s" % (spec_version, package_version))
626            print
627    
628      matches = upstream & set(downstream.keys())  def cmd_patches(options, parser):
629      for module in sorted(matches):      root = os.path.expanduser(PKGROOT)
630          for srpm in downstream[module]:  
631              for filename in downstream_files[srpm]:      for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
632                  if '.patch' in filename or '.diff' in filename:          for filename in downstream_files:
633                      p = Patch(os.path.join(path, srpm, "SOURCES", filename), show_path=options.path)              if '.patch' in filename or '.diff' in filename:
634                      print "\t".join((module, srpm, str(p)))  
635                      if p.dep3['headers']:                  p = Patch(os.path.join(root, package, "SOURCES", filename), show_path=options.path)
636                          pprint.pprint(p.dep3['headers'])                  valid = ""
637                          if p.dep3['valid']:                  forwarded = ""
638                              print "VALID"                  if p.dep3['headers']:
639                        forwarded = p.dep3['headers'].get('Forwarded', "no")
640                        if p.dep3['valid']:
641                            valid="VALID"
642                    print "\t".join((module, package, str(p), forwarded, valid))
643    
644  def cmd_dep3(options, parser):  def cmd_dep3(options, parser):
645      p = Patch(options.patch)      p = Patch(options.patch)
646      p.add_dep3()      p.add_dep3()
647    
648    def cmd_package_new_version(options, parser):
649        # Determine the package name
650        if options.upstream:
651            try:
652                package = get_downstream_from_upstream(options.package, options.version)[0]
653            except ValueError, e:
654                print >>sys.stderr, "ERROR: %s" % e
655                sys.exit(1)
656        else:
657            package = options.package
658    
659        # Directories packages are located in
660        root = os.path.expanduser(PKGROOT)
661        cwd = os.path.join(root, package)
662    
663        # Checkout package to ensure the checkout reflects the latest changes
664        try:
665            subprocess.check_call(['mgarepo', 'co', package], cwd=root)
666        except subprocess.CalledProcessError:
667            sys.exit(1)
668    
669        # SpecFile class handles the actual version+release change
670        s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package))
671        print "%s => %s" % (s.version, options.version)
672        if not s.update(options.version, force=options.force):
673            sys.exit(1)
674    
675        # Check hash, if given
676        if options.hexdigest is not None:
677            sources = [name for name, origname in s.sources.iteritems() if '://' in origname]
678            if not len(sources):
679                print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!"
680                sys.stderr(1)
681    
682            for filename in sources:
683                path = os.path.join(cwd, "SOURCES", filename)
684                if not is_valid_hash(path, options.algo, options.hexdigest):
685                    print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path
686                    print >>sys.stderr, "ERROR: Reverting changes!"
687                    subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd)
688                    sys.exit(1)
689    
690        # We can even checkin and submit :-)
691        if options.submit:
692            try:
693                # checkin changes
694                subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd)
695                # and submit
696                # XXX HACK NOT TO AUTO SUBMIT ATM
697                if options.hexdigest is None:
698                    subprocess.check_call(['mgarepo', 'submit'], cwd=cwd)
699            except subprocess.CalledProcessError:
700                sys.exit(1)
701    
702    def cmd_parse_ftp_release_list(options, parser):
703        def _send_reply_mail(contents, orig_msg, to, packages=[], error=False):
704            """Send an reply email"""
705            contents.seek(0)
706            msg = MIMEText(contents.read(), _charset='utf-8')
707    
708            if error:
709                # XXX - ugly
710                contents.seek(0)
711                lastline = contents.read().rstrip().splitlines()[-1]
712                # Remove things like "ERROR: " and so on from the last line
713                lastline = re.sub(r'^(?:[^ :]+:\s+)+', '', lastline)
714                # Remove things like "   - " (youri output from mgarepo submit)
715                lastline = re.sub(r'^\s+-\s+', '', lastline)
716                subjecterror = " (ERROR: %s)" % lastline if lastline else " (ERROR)"
717            else:
718                subjecterror = ""
719    
720            if packages:
721                subject = "%s %s%s" % (", ".join(packages), orig_msg['X-Module-Version'], subjecterror)
722            else:
723                subject = "Re: %s%s" % (orig_msg['Subject'], subjecterror)
724    
725            msg['Subject'] = subject
726            msg['To'] = to
727            msg["In-Reply-To"] = orig_msg["Message-ID"]
728            msg["References"] = orig_msg["Message-ID"]
729    
730            # Call sendmail program directly so it doesn't matter if the service is running
731            cmd = ['/usr/sbin/sendmail', '-oi', '--']
732            cmd.extend([to])
733            p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
734            p.stdin.write(msg.as_string())
735            p.stdin.flush()
736            p.stdin.close()
737            p.wait()
738    
739    
740        msg = email.email.message_from_file(sys.stdin)
741    
742        if options.mail:
743            stdout = tempfile.TemporaryFile()
744            stderr = stdout
745        else:
746            stdout = sys.stdout
747            stderr = sys.stderr
748    
749        try:
750            module = msg['X-Module-Name']
751            version = msg['X-Module-Version']
752            hexdigest = msg['X-Module-SHA256-tar.xz']
753        except KeyError, e:
754            print >>stderr, "ERROR: %s" % e
755            if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
756            sys.exit(1)
757    
758        try:
759            packages = get_downstream_from_upstream(module, version)
760        except ValueError, e:
761            print >>stderr, "ERROR: %s" % e
762            if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
763            sys.exit(1)
764    
765        if options.wait:
766            # maildrop aborts and will try to deliver after 5min
767            # fork to avoid this
768            if os.fork() != 0: sys.exit(0)
769            # wait SLEEP_INITIAL after the message was sent
770            secs = SLEEP_INITIAL
771            t = email.utils.parsedate_tz(msg['Date'])
772            if t is not None:
773                msg_time = email.utils.mktime_tz(t)
774                secs = SLEEP_INITIAL - (time.time() - msg_time)
775    
776            if secs > 0: time.sleep(secs)
777    
778        error = False
779        for package in packages:
780            cmd = ['mga-gnome', 'increase', '--submit', '--hash', hexdigest]
781            if options.force:
782                cmd.append('--force')
783            cmd.extend((package, version))
784            if subprocess.call(cmd, stdout=stdout, stderr=stderr):
785                error = True
786    
787        if options.mail: _send_reply_mail(stdout, msg, options.mail, packages=packages, error=error)
788    
789  def main():  def main():
790      description = """Mageia GNOME commands."""      description = """Mageia GNOME commands."""
791      epilog="""Report bugs to Olav Vitters"""      epilog="""Report bugs to Olav Vitters"""
792      parser = argparse.ArgumentParser(description=description,epilog=epilog)      parser = argparse.ArgumentParser(description=description,epilog=epilog)
793        parser.add_argument("-l", "--limit", type=argparse.FileType('r', 0),
794                            dest="limit_upstream", metavar="FILE",
795                            help="File containing upstream names")
796    
797      # SUBPARSERS      # SUBPARSERS
798      subparsers = parser.add_subparsers(title='subcommands')      subparsers = parser.add_subparsers(title='subcommands')
# Line 270  def main(): Line 803  def main():
803      )      )
804    
805      subparser = subparsers.add_parser('packages', help='list all GNOME packages')      subparser = subparsers.add_parser('packages', help='list all GNOME packages')
806        subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
807                                           help="Show upstream module")
808        subparser.add_argument(      "--version", action="store_true", dest="show_version",
809                                           help="Show version numbers")
810        subparser.add_argument(      "--diff", action="store_true", dest="diff",
811                                           help="Only show packages with different version")
812      subparser.set_defaults(      subparser.set_defaults(
813          func=cmd_ls          func=cmd_ls, upstream=False, show_version=False, diff=False
814      )      )
815    
816      subparser = subparsers.add_parser('patches', help='list all GNOME patches')      subparser = subparsers.add_parser('patches', help='list all GNOME patches')
# Line 287  def main(): Line 826  def main():
826          func=cmd_dep3, path=False          func=cmd_dep3, path=False
827      )      )
828    
829        subparser = subparsers.add_parser('increase', help='Increase version number')
830        subparser.add_argument("package", help="Package name")
831        subparser.add_argument("version", help="Version number")
832        subparser.add_argument("-f", "--force", action="store_true", dest="force",
833                                           help="Override warnings, just do it")
834        subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
835                                           help="Package name reflects the upstream name")
836        subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
837                                           help="Commit changes and submit")
838        subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo",
839                                           help="Hash algorithm")
840        subparser.add_argument("--hash", dest="hexdigest",
841                                           help="Hexdigest of the hash")
842        subparser.set_defaults(
843            func=cmd_package_new_version, submit=False, upstream=False, hexdigest=None, algo="sha256",
844            force=False
845        )
846    
847        subparser = subparsers.add_parser('gnome-release-email', help='Submit packages based on GNOME ftp-release-list email')
848        subparser.add_argument("-m", "--mail", help="Email address to send the progress to")
849        subparser.add_argument("-w", "--wait", action="store_true",
850                                     help="Wait before trying to retrieve the new version")
851        subparser.add_argument("-f", "--force", action="store_true",
852                                     help="Force submission")
853        subparser.set_defaults(
854            func=cmd_parse_ftp_release_list, force=False, wait=False
855        )
856    
857      if len(sys.argv) == 1:      if len(sys.argv) == 1:
858          parser.print_help()          parser.print_help()
859          sys.exit(2)          sys.exit(2)
860    
861      options = parser.parse_args()      options = parser.parse_args()
862        if options.limit_upstream:
863            Upstream.limit = set(options.limit_upstream.read().strip("\n").splitlines())
864    
865      try:      try:
866          options.func(options, parser)          options.func(options, parser)
# Line 307  def main(): Line 876  def main():
876          sys.exit(0)          sys.exit(0)
877    
878  if __name__ == "__main__":  if __name__ == "__main__":
879        os.environ['PYTHONUNBUFFERED'] = '1'
880      main()      main()

Legend:
Removed from v.2944  
changed lines
  Added in v.3649

  ViewVC Help
Powered by ViewVC 1.1.30