/[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 3037 by ovitters, Thu Feb 23 19:43:09 2012 UTC revision 3115 by ovitters, Tue Feb 28 10:23:35 2012 UTC
# Line 1  Line 1 
1  #!/usr/bin/python  #!/usr/bin/python
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  MEDIA="Core Release Source"  MEDIA="Core Release Source"
40  URL="http://download.gnome.org/sources/"  URL="http://download.gnome.org/sources/"
41  PKGROOT='~/pkgs'  PKGROOT='~/pkgs'
42    
43    re_majmin = re.compile(r'^([0-9]+\.[0-9]+).*')
44  re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')  re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')
45    
46  def version_cmp(a, b):  def version_cmp(a, b):
# Line 26  def version_cmp(a, b): Line 50  def version_cmp(a, b):
50        -1 if a < b        -1 if a < b
51        0  if a == b        0  if a == b
52        1  if a > b        1  if a > b
53        """
54    
55      Logic from Bugzilla::Install::Util::vers_cmp"""      return rpm.labelCompare(('1', a, '1'), ('1', b, '1'))
     A = re_version.findall(a.lstrip('0'))  
     B = re_version.findall(b.lstrip('0'))  
   
     while A and B:  
         a = A.pop(0)  
         b = B.pop(0)  
   
         if a == b:  
             continue  
         elif a == '-':  
             return -1  
         elif b == '-':  
             return 1  
         elif a == '.':  
             return -1  
         elif b == '.':  
             return 1  
         elif a.isdigit() and b.isdigit():  
             c = cmp(a, b) if (a.startswith('0') or b.startswith('0')) else cmp(int(a, 10), int(b, 10))  
             if c:  
                 return c  
         else:  
             c = cmp(a.upper(), b.upper())  
             if c:  
                 return c  
   
     return cmp(len(A), len(B))  
56    
57  def get_latest_version(versions, max_version=None):  def get_latest_version(versions, max_version=None):
58      """Gets the latest version number      """Gets the latest version number
# Line 68  def get_latest_version(versions, max_ver Line 66  def get_latest_version(versions, max_ver
66              latest = version              latest = version
67      return latest      return latest
68    
69    def judge_version_increase(version_old, version_new):
70            """Judge quality of version increase:
71    
72            Returns a tuple containing judgement and message
73    
74            Judgement:
75            Less than 0: Error
76            0 to 4: Better not
77            5+: Ok"""
78            versions = (version_old, version_new)
79    
80            # First do a basic version comparison to ensure version_new is actually newer
81            compare = version_cmp(version_new, version_old)
82    
83            if compare == 0:
84                return (-2, "Already at version %s!" % (version_old))
85    
86            if compare != 1:
87                return (-3, "Version %s is older than current version %s!" % (version_new, version_old))
88    
89            # Version is newer, but we don't want to see if it follows the GNOME versioning scheme
90            majmins = [re_majmin.sub(r'\1', ver) for ver in versions if re_majmin.match(ver) is not None]
91    
92            if len(majmins) == 1:
93                return (-1, "Version number scheme changes: %s" % (", ".join(versions)))
94    
95            if len(majmins) == 0:
96                return (0, "Unsupported version numbers: %s" % (", ".join(versions)))
97    
98            # Follows GNOME versioning scheme
99            # Meaning: x.y.z
100            #          x = major
101            #          y = minor  : even if stable
102            #          z = micro
103    
104            # Major+minor the same? Then go ahead and upgrade!
105            if majmins[0] == majmins[1]:
106                # Majmin of both versions are the same, looks good!
107                return (10, None)
108    
109            # More detailed analysis needed, so figure out the numbers
110            majmin_nrs = [map(long, ver.split('.')) for ver in majmins]
111    
112            # Check/ensure major version number is the same
113            if majmin_nrs[0][0] != majmin_nrs[1][0]:
114                return (1, "Major version number increase")
115    
116            # Minor indicates stable/unstable
117            devstate = (majmin_nrs[0][1] % 2 == 0, majmin_nrs[1][1] % 2 == 0)
118    
119            # Upgrading to unstable is weird
120            if not devstate[1]:
121                if devstate[0]:
122                    return (1, "Stable to unstable increase")
123    
124                return (4, "Unstable to unstable version increase")
125    
126            # Unstable => stable is always ok
127            if not devstate[0]:
128                return (5, "Unstable to stable")
129    
130            # Can only be increase of minors from one stable to the next
131            return (6, "Stable version increase")
132    
133  def line_input (file):  def line_input (file):
134      for line in file:      for line in file:
135          if line[-1] == '\n':          if line[-1] == '\n':
# Line 109  class urllister(SGMLParser): Line 171  class urllister(SGMLParser):
171          if href:          if href:
172              self.urls.extend(href)              self.urls.extend(href)
173    
174    class XzTarFile(tarfile.TarFile):
175    
176        OPEN_METH = tarfile.TarFile.OPEN_METH.copy()
177        OPEN_METH["xz"] = "xzopen"
178    
179        @classmethod
180        def xzopen(cls, name, mode="r", fileobj=None, **kwargs):
181            """Open gzip compressed tar archive name for reading or writing.
182               Appending is not allowed.
183            """
184            if len(mode) > 1 or mode not in "rw":
185                raise ValueError("mode must be 'r' or 'w'")
186    
187            if fileobj is not None:
188                fileobj = _LMZAProxy(fileobj, mode)
189            else:
190                fileobj = lzma.LZMAFile(name, mode)
191    
192            try:
193                # lzma doesn't immediately return an error
194                # try and read a bit of data to determine if it is a valid xz file
195                fileobj.read(_LZMAProxy.blocksize)
196                fileobj.seek(0)
197                t = cls.taropen(name, mode, fileobj, **kwargs)
198            except IOError:
199                raise tarfile.ReadError("not a xz file")
200            except lzma.error:
201                raise tarfile.ReadError("not a xz file")
202            t._extfileobj = False
203            return t
204    
205    if not hasattr(tarfile.TarFile, 'xzopen'):
206        tarfile.open = XzTarFile.open
207    
208    def is_valid_hash(path, algo, hexdigest):
209        if algo not in hashlib.algorithms:
210            raise ValueError("Unknown hash algorithm: %s" % algo)
211    
212        local_hash = getattr(hashlib, algo)()
213    
214        with open(path, 'rb') as fp:
215            data = fp.read(32768)
216            while data:
217                local_hash.update(data)
218                data = fp.read(32768)
219    
220        return local_hash.hexdigest() == hexdigest
221    
222  class SpecFile(object):  class SpecFile(object):
223      re_update_version = re.compile(r'^(?P<pre>Version:\s*)(?P<version>.+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)      re_update_version = re.compile(r'^(?P<pre>Version:\s*)(?P<version>.+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)
224      re_update_release = re.compile(r'^(?P<pre>Release:\s*)(?P<release>%mkrel \d+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)      re_update_release = re.compile(r'^(?P<pre>Release:\s*)(?P<release>%mkrel \d+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE)
# Line 120  class SpecFile(object): Line 230  class SpecFile(object):
230      @property      @property
231      def version(self):      def version(self):
232          return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0]          return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0]
233        @property
234        def sources(self):
235            ts = rpm.ts()
236            spec = ts.parseSpec(self.path)
237            srclist = spec.sources if isinstance(spec.sources, (list, tuple)) \
238                            else spec.sources()
239            return dict((os.path.basename(name), name) for name, no, flags in srclist)
240    
241      def update(self, version):      def update(self, version):
242          """Update specfile (increase version)"""          """Update specfile (increase version)"""
243          cur_version = self.version          cur_version = self.version
244    
245          compare = version_cmp(version, cur_version)          (judgement, msg) = judge_version_increase(cur_version, version)
246    
247          if compare == 0:          if judgement < 0:
248              print >>sys.stderr, "ERROR: Already at version %s!" % (cur_version)              print >>sys.stderr, "ERROR: %s!" % (msg)
249              return False              return False
250    
251          if compare != 1:          if judgement < 5:
252              print >>sys.stderr, "ERROR: Version %s is older than current version %s!" % (version, cur_version)              print "WARNING: %s!" % (msg)
253                return False
254    
255            # XXX - os.path.join is hackish
256            if subprocess.check_output(["svn", "diff", os.path.join(self.path, '..')]) != '':
257                print >>sys.stderr, "ERROR: Package has uncommitted changes!"
258              return False              return False
259    
260          with open(self.path, "rw") as f:          with open(self.path, "rw") as f:
# Line 156  class SpecFile(object): Line 278  class SpecFile(object):
278              write_file(self.path, data)              write_file(self.path, data)
279    
280    
281          # Check RPM also agrees that version number has increased          # Verify that RPM also agrees that version number has changed
282          if self.version != version:          if self.version != version:
283              print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version              print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
284              return False              return False
# Line 293  class Patch(object): Line 415  class Patch(object):
415      @property      @property
416      def svn_author(self):      def svn_author(self):
417          if not hasattr(self, '_svn_author'):          if not hasattr(self, '_svn_author'):
418              p = subprocess.Popen(['svn', 'log', '-q', "--", self.path], stdout=subprocess.PIPE, close_fds=True)              try:
419              contents = p.stdout.read().strip("\n").splitlines()                  contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines()
420              ecode = p.wait()  
             if ecode == 0:  
421                  for line in contents:                  for line in contents:
422                      if ' | ' not in line:                      if ' | ' not in line:
423                          continue                          continue
# Line 304  class Patch(object): Line 425  class Patch(object):
425                      fields = line.split(' | ')                      fields = line.split(' | ')
426                      if len(fields) >= 3:                      if len(fields) >= 3:
427                          self._svn_author = fields[1]                          self._svn_author = fields[1]
428                except subprocess.CalledProcessError:
429                    pass
430    
431          if not hasattr(self, '_svn_author'):          if not hasattr(self, '_svn_author'):
432              return None              return None
# Line 330  def get_upstream_names(): Line 453  def get_upstream_names():
453  def get_downstream_names():  def get_downstream_names():
454      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]*)$')
455    
456      p = subprocess.Popen(['urpmf', '--files', '.', "--media", MEDIA], stdout=subprocess.PIPE, close_fds=True)      contents = subprocess.check_output(['urpmf', '--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)  
457    
458      FILES = {}      FILES = {}
459      TARBALLS = {}      TARBALLS = {}
# Line 381  def cmd_co(options, parser): Line 500  def cmd_co(options, parser):
500          for package in downstream[module]:          for package in downstream[module]:
501              subprocess.call(['mgarepo', 'co', package], cwd=cwd)              subprocess.call(['mgarepo', 'co', package], cwd=cwd)
502    
503  def cmd_ls(options, parser):  def join_streams():
504      upstream = get_upstream_names()      upstream = get_upstream_names()
505      downstream, downstream_files = get_downstream_names()      downstream, downstream_files = get_downstream_names()
506    
507      matches = upstream & set(downstream.keys())      matches = upstream & set(downstream.keys())
508      for module in matches:      for module in matches:
509          print "\n".join(downstream[module])          for package in downstream[module]:
510                yield (package, module)
511    
512    def cmd_ls(options, parser):
513        for package, module in sorted(join_streams()):
514            print "\t".join((package, module)) if options.upstream else package
515    
516  def cmd_patches(options, parser):  def cmd_patches(options, parser):
517      upstream = get_upstream_names()      upstream = get_upstream_names()
# Line 417  def cmd_dep3(options, parser): Line 541  def cmd_dep3(options, parser):
541      p.add_dep3()      p.add_dep3()
542    
543  def cmd_package_new_version(options, parser):  def cmd_package_new_version(options, parser):
544      cwd = os.path.expanduser(PKGROOT)      # Determine the package name
545      package = options.package      if options.upstream:
546            downstream, downstream_files = get_downstream_names()
547    
548            if options.package not in downstream:
549                print >>sys.stderr, "ERROR: No packages for upstream name: %s" % options.package
550                sys.exit(1)
551    
552            if len(downstream[options.package]) != 1:
553                # XXX - Make it more intelligent
554                print >>sys.stderr, "ERROR: Multiple packages found for %s: %s" % (options.package, ", ".join(downstream[options.package]))
555                sys.exit(1)
556    
557            package = list(downstream[options.package])[0]
558        else:
559            package = options.package
560    
561        # Directories packages are located in
562        root = os.path.expanduser(PKGROOT)
563        cwd = os.path.join(root, package)
564    
565        # Checkout package to ensure the checkout reflects the latest changes
566        try:
567            subprocess.check_call(['mgarepo', 'co', package], cwd=root)
568        except subprocess.CalledProcessError:
569            sys.exit(1)
570    
571      subprocess.call(['mgarepo', 'co', package], cwd=cwd)      # SpecFile class handles the actual version+release change
572      s = SpecFile(os.path.join(cwd, package, "SPECS", "%s.spec" % package))      s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package))
573      print "%s => %s" % (s.version, options.version)      print "%s => %s" % (s.version, options.version)
574      if not s.update(options.version):      if not s.update(options.version):
575          sys.exit(1)          sys.exit(1)
576    
577        # Check hash, if given
578        if options.hexdigest is not None:
579            sources = [name for name, origname in s.sources.iteritems() if '://' in origname]
580            if not len(sources):
581                print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!"
582                sys.stderr(1)
583    
584            for filename in sources:
585                if not is_valid_hash(os.path.join(cwd, "SOURCES", filename), options.algo, options.hexdigest):
586                    print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path
587                    print >>sys.stderr, "ERROR: Reverting changes!"
588                    subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd)
589                    sys.exit(1)
590    
591        # We can even checkin and submit :-)
592        if options.submit:
593            try:
594                # checkin changes
595                subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd)
596                # and submit
597                subprocess.check_call(['mgarepo', 'submit'], cwd=cwd)
598            except subprocess.CalledProcessError:
599                sys.exit(1)
600    
601    
602  def main():  def main():
603      description = """Mageia GNOME commands."""      description = """Mageia GNOME commands."""
# Line 441  def main(): Line 613  def main():
613      )      )
614    
615      subparser = subparsers.add_parser('packages', help='list all GNOME packages')      subparser = subparsers.add_parser('packages', help='list all GNOME packages')
616        subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
617                                           help="Show upstream module")
618      subparser.set_defaults(      subparser.set_defaults(
619          func=cmd_ls          func=cmd_ls, upstream=False
620      )      )
621    
622      subparser = subparsers.add_parser('patches', help='list all GNOME patches')      subparser = subparsers.add_parser('patches', help='list all GNOME patches')
# Line 461  def main(): Line 635  def main():
635      subparser = subparsers.add_parser('increase', help='Increase version number')      subparser = subparsers.add_parser('increase', help='Increase version number')
636      subparser.add_argument("package", help="Package name")      subparser.add_argument("package", help="Package name")
637      subparser.add_argument("version", help="Version number")      subparser.add_argument("version", help="Version number")
638        subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
639                                           help="Package name reflects the upstream name")
640        subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
641                                           help="Commit changes and submit")
642        subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo",
643                                           help="Hash algorithm")
644        subparser.add_argument("--hash", dest="hexdigest",
645                                           help="Hexdigest of the hash")
646      subparser.set_defaults(      subparser.set_defaults(
647          func=cmd_package_new_version, path=False          func=cmd_package_new_version, submit=False, upstream=False, hexdigest=None, algo="sha256"
648      )      )
649    
650      if len(sys.argv) == 1:      if len(sys.argv) == 1:

Legend:
Removed from v.3037  
changed lines
  Added in v.3115

  ViewVC Help
Powered by ViewVC 1.1.30