/[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 3039 by ovitters, Thu Feb 23 20:10:41 2012 UTC revision 3125 by ovitters, Wed Feb 29 15:30:34 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  MEDIA="Core Release Source"  MEDIA="Core Release Source"
47  URL="http://download.gnome.org/sources/"  URL="http://download.gnome.org/sources/"
48  PKGROOT='~/pkgs'  PKGROOT='~/pkgs'
49    SLEEP_INITIAL=300
50    
51    re_majmin = re.compile(r'^([0-9]+\.[0-9]+).*')
52  re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')  re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')
53    
54  def version_cmp(a, b):  def version_cmp(a, b):
# Line 26  def version_cmp(a, b): Line 58  def version_cmp(a, b):
58        -1 if a < b        -1 if a < b
59        0  if a == b        0  if a == b
60        1  if a > b        1  if a > b
61        """
62    
63      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))  
64    
65  def get_latest_version(versions, max_version=None):  def get_latest_version(versions, max_version=None):
66      """Gets the latest version number      """Gets the latest version number
# Line 68  def get_latest_version(versions, max_ver Line 74  def get_latest_version(versions, max_ver
74              latest = version              latest = version
75      return latest      return latest
76    
77    def judge_version_increase(version_old, version_new):
78            """Judge quality of version increase:
79    
80            Returns a tuple containing judgement and message
81    
82            Judgement:
83            Less than 0: Error
84            0 to 4: Better not
85            5+: Ok"""
86            versions = (version_old, version_new)
87    
88            # First do a basic version comparison to ensure version_new is actually newer
89            compare = version_cmp(version_new, version_old)
90    
91            if compare == 0:
92                # 1.0.0 -> 1.0.1
93                return (-2, "Already at version %s!" % (version_old))
94    
95            if compare != 1:
96                # 1.0.1 -> 1.0.0
97                return (-3, "Version %s is older than current version %s!" % (version_new, version_old))
98    
99            # Version is newer, but we don't want to see if it follows the GNOME versioning scheme
100            majmins = [re_majmin.sub(r'\1', ver) for ver in versions if re_majmin.match(ver) is not None]
101    
102            if len(majmins) == 1:
103                return (-1, "Version number scheme changes: %s" % (", ".join(versions)))
104    
105            if len(majmins) == 0:
106                return (0, "Unsupported version numbers: %s" % (", ".join(versions)))
107    
108            # Follows GNOME versioning scheme
109            # Meaning: x.y.z
110            #          x = major
111            #          y = minor  : even if stable
112            #          z = micro
113    
114            # Major+minor the same? Then go ahead and upgrade!
115            if majmins[0] == majmins[1]:
116                # Majmin of both versions are the same, looks good!
117                # 1.1.x -> 1.1.x or 1.0.x -> 1.0.x
118                return (10, None)
119    
120            # More detailed analysis needed, so figure out the numbers
121            majmin_nrs = [map(long, ver.split('.')) for ver in majmins]
122    
123            # Check/ensure major version number is the same
124            if majmin_nrs[0][0] != majmin_nrs[1][0]:
125                # 1.0.x -> 2.0.x
126                return (1, "Major version number increase")
127    
128            # Minor indicates stable/unstable
129            devstate = (majmin_nrs[0][1] % 2 == 0, majmin_nrs[1][1] % 2 == 0)
130    
131            # Upgrading to unstable is weird
132            if not devstate[1]:
133                if devstate[0]:
134                    # 1.2.x -> 1.3.x
135                    return (1, "Stable to unstable increase")
136    
137                # 1.3.x -> 1.5.x
138                return (4, "Unstable to unstable version increase")
139    
140            # Unstable => stable is always ok
141            if not devstate[0]:
142                # 1.1.x -> 1.2.x
143                return (5, "Unstable to stable")
144    
145            # Can only be increase of minors from one stable to the next
146            # 1.0.x -> 1.2.x
147            return (6, "Stable version increase")
148    
149  def line_input (file):  def line_input (file):
150      for line in file:      for line in file:
151          if line[-1] == '\n':          if line[-1] == '\n':
# Line 109  class urllister(SGMLParser): Line 187  class urllister(SGMLParser):
187          if href:          if href:
188              self.urls.extend(href)              self.urls.extend(href)
189    
190    class XzTarFile(tarfile.TarFile):
191    
192        OPEN_METH = tarfile.TarFile.OPEN_METH.copy()
193        OPEN_METH["xz"] = "xzopen"
194    
195        @classmethod
196        def xzopen(cls, name, mode="r", fileobj=None, **kwargs):
197            """Open gzip compressed tar archive name for reading or writing.
198               Appending is not allowed.
199            """
200            if len(mode) > 1 or mode not in "rw":
201                raise ValueError("mode must be 'r' or 'w'")
202    
203            if fileobj is not None:
204                fileobj = _LMZAProxy(fileobj, mode)
205            else:
206                fileobj = lzma.LZMAFile(name, mode)
207    
208            try:
209                # lzma doesn't immediately return an error
210                # try and read a bit of data to determine if it is a valid xz file
211                fileobj.read(_LZMAProxy.blocksize)
212                fileobj.seek(0)
213                t = cls.taropen(name, mode, fileobj, **kwargs)
214            except IOError:
215                raise tarfile.ReadError("not a xz file")
216            except lzma.error:
217                raise tarfile.ReadError("not a xz file")
218            t._extfileobj = False
219            return t
220    
221    if not hasattr(tarfile.TarFile, 'xzopen'):
222        tarfile.open = XzTarFile.open
223    
224    def is_valid_hash(path, algo, hexdigest):
225        if algo not in hashlib.algorithms:
226            raise ValueError("Unknown hash algorithm: %s" % algo)
227    
228        local_hash = getattr(hashlib, algo)()
229    
230        with open(path, 'rb') as fp:
231            data = fp.read(32768)
232            while data:
233                local_hash.update(data)
234                data = fp.read(32768)
235    
236        return local_hash.hexdigest() == hexdigest
237    
238  class SpecFile(object):  class SpecFile(object):
239      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)
240      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 246  class SpecFile(object):
246      @property      @property
247      def version(self):      def version(self):
248          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]
249        @property
250        def sources(self):
251            ts = rpm.ts()
252            spec = ts.parseSpec(self.path)
253            srclist = spec.sources if isinstance(spec.sources, (list, tuple)) \
254                            else spec.sources()
255            return dict((os.path.basename(name), name) for name, no, flags in srclist)
256    
257      def update(self, version):      def update(self, version):
258          """Update specfile (increase version)"""          """Update specfile (increase version)"""
259          cur_version = self.version          cur_version = self.version
260    
261          compare = version_cmp(version, cur_version)          (judgement, msg) = judge_version_increase(cur_version, version)
262    
263          if compare == 0:          if judgement < 0:
264              print >>sys.stderr, "ERROR: Already at version %s!" % (cur_version)              print >>sys.stderr, "ERROR: %s!" % (msg)
265              return False              return False
266    
267          if compare != 1:          if judgement < 5:
268              print >>sys.stderr, "ERROR: Version %s is older than current version %s!" % (version, cur_version)              print "WARNING: %s!" % (msg)
269              return False              return False
270    
271          # XXX - os.path.join is hackish          # XXX - os.path.join is hackish
# Line 161  class SpecFile(object): Line 294  class SpecFile(object):
294              write_file(self.path, data)              write_file(self.path, data)
295    
296    
297          # Check RPM also agrees that version number has increased          # Verify that RPM also agrees that version number has changed
298          if self.version != version:          if self.version != version:
299              print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version              print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
300              return False              return False
# Line 298  class Patch(object): Line 431  class Patch(object):
431      @property      @property
432      def svn_author(self):      def svn_author(self):
433          if not hasattr(self, '_svn_author'):          if not hasattr(self, '_svn_author'):
434              p = subprocess.Popen(['svn', 'log', '-q', "--", self.path], stdout=subprocess.PIPE, close_fds=True)              try:
435              contents = p.stdout.read().strip("\n").splitlines()                  contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines()
436              ecode = p.wait()  
             if ecode == 0:  
437                  for line in contents:                  for line in contents:
438                      if ' | ' not in line:                      if ' | ' not in line:
439                          continue                          continue
# Line 309  class Patch(object): Line 441  class Patch(object):
441                      fields = line.split(' | ')                      fields = line.split(' | ')
442                      if len(fields) >= 3:                      if len(fields) >= 3:
443                          self._svn_author = fields[1]                          self._svn_author = fields[1]
444                except subprocess.CalledProcessError:
445                    pass
446    
447          if not hasattr(self, '_svn_author'):          if not hasattr(self, '_svn_author'):
448              return None              return None
# Line 335  def get_upstream_names(): Line 469  def get_upstream_names():
469  def get_downstream_names():  def get_downstream_names():
470      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]*)$')
471    
472      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)  
473    
474      FILES = {}      FILES = {}
475      TARBALLS = {}      TARBALLS = {}
# Line 367  def get_downstream_names(): Line 497  def get_downstream_names():
497    
498      return TARBALLS, FILES      return TARBALLS, FILES
499    
500    def get_downstream_from_upstream(upstream, version):
501        # Determine the package name
502        downstream, downstream_files = get_downstream_names()
503    
504        if upstream not in downstream:
505            raise ValueError("No packages for upstream name: %s" % upstream)
506    
507        if len(downstream[upstream]) != 1:
508            # XXX - Make it more intelligent
509            raise ValueError("Multiple packages found for %s: %s" % (upstream, ", ".join(downstream[upstream])))
510    
511        return list(downstream[upstream])
512    
513  def write_file(path, data):  def write_file(path, data):
514      with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst:      with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst:
# Line 386  def cmd_co(options, parser): Line 528  def cmd_co(options, parser):
528          for package in downstream[module]:          for package in downstream[module]:
529              subprocess.call(['mgarepo', 'co', package], cwd=cwd)              subprocess.call(['mgarepo', 'co', package], cwd=cwd)
530    
531  def cmd_ls(options, parser):  def join_streams():
532      upstream = get_upstream_names()      upstream = get_upstream_names()
533      downstream, downstream_files = get_downstream_names()      downstream, downstream_files = get_downstream_names()
534    
535      matches = upstream & set(downstream.keys())      matches = upstream & set(downstream.keys())
536      for module in matches:      for module in matches:
537          print "\n".join(downstream[module])          for package in downstream[module]:
538                yield (package, module)
539    
540    def cmd_ls(options, parser):
541        for package, module in sorted(join_streams()):
542            print "\t".join((package, module)) if options.upstream else package
543    
544  def cmd_patches(options, parser):  def cmd_patches(options, parser):
545      upstream = get_upstream_names()      upstream = get_upstream_names()
# Line 422  def cmd_dep3(options, parser): Line 569  def cmd_dep3(options, parser):
569      p.add_dep3()      p.add_dep3()
570    
571  def cmd_package_new_version(options, parser):  def cmd_package_new_version(options, parser):
572      package = options.package      # Determine the package name
573        if options.upstream:
574            try:
575                package = get_downstream_from_upstream(options.package, options.version)[0]
576            except ValueError, e:
577                print >>sys.stderr, "ERROR: %s" % e
578                sys.exit(1)
579        else:
580            package = options.package
581    
582      cwd = os.path.join(os.path.expanduser(PKGROOT), package)      # Directories packages are located in
583        root = os.path.expanduser(PKGROOT)
584        cwd = os.path.join(root, package)
585    
586        # Checkout package to ensure the checkout reflects the latest changes
587        try:
588            subprocess.check_call(['mgarepo', 'co', package], cwd=root)
589        except subprocess.CalledProcessError:
590            sys.exit(1)
591    
592      subprocess.call(['mgarepo', 'co', package], cwd=cwd)      # SpecFile class handles the actual version+release change
593      s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package))      s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package))
594      print "%s => %s" % (s.version, options.version)      print "%s => %s" % (s.version, options.version)
595      if not s.update(options.version):      if not s.update(options.version):
596          sys.exit(1)          sys.exit(1)
597    
598        # Check hash, if given
599        if options.hexdigest is not None:
600            sources = [name for name, origname in s.sources.iteritems() if '://' in origname]
601            if not len(sources):
602                print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!"
603                sys.stderr(1)
604    
605            for filename in sources:
606                if not is_valid_hash(os.path.join(cwd, "SOURCES", filename), options.algo, options.hexdigest):
607                    print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path
608                    print >>sys.stderr, "ERROR: Reverting changes!"
609                    subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd)
610                    sys.exit(1)
611    
612        # We can even checkin and submit :-)
613      if options.submit:      if options.submit:
614          try:          try:
615              # checkin changes              # checkin changes
616              subprocess.check_call(['mgarepo', 'ci', '-m', 'new version'], cwd=cwd)              subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd)
617              # and submit              # and submit
618              subprocess.check_call(['mgarepo', 'submit'], cwd=cwd)              subprocess.check_call(['mgarepo', 'submit'], cwd=cwd)
619          except subprocess.CalledProcessError:          except subprocess.CalledProcessError:
620              sys.exit(1)              sys.exit(1)
621    
622    def cmd_parse_ftp_release_list(options, parser):
623        # XXX - not working yet
624        def _send_reply_mail(contents, orig_msg, to):
625            """Send an reply email"""
626            contents.seek(0)
627            msg = MIMEText(contents.read(), _charset='utf-8')
628            msg['Subject'] = "Re: %s" % orig_msg['Subject']
629            msg['To'] = to
630            msg["In-Reply-To"] = orig_msg["Message-ID"]
631            msg["References"] = orig_msg["Message-ID"]
632    
633            # Call sendmail program directly so it doesn't matter if the service is running
634            cmd = ['/usr/sbin/sendmail', '-oi', '--']
635            cmd.extend([to])
636            p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
637            p.stdin.write(msg.as_string())
638            p.stdin.flush()
639            p.stdin.close()
640            p.wait()
641    
642    
643        msg = email.email.message_from_file(sys.stdin)
644    
645        if options.mail:
646            stdout = tempfile.NamedTemporaryFile()
647            stderr = stdout
648        else:
649            stdout = sys.stdout
650            stderr = sys.stderr
651    
652        try:
653            module = msg['X-Module-Name']
654            version = msg['X-Module-Version']
655            hexdigest = msg['X-Module-SHA256-tar.xz']
656        except KeyError, e:
657            print >>stderr, "ERROR: %s" % e
658            if options.mail: _send_reply_mail(stdout, msg, options.mail)
659            sys.exit(1)
660    
661        try:
662            packages = get_downstream_from_upstream(module, version)
663        except ValueError, e:
664            print >>stderr, "ERROR: %s" % e
665            if options.mail: _send_reply_mail(stdout, msg, options.mail)
666            sys.exit(1)
667    
668        if options.wait:
669            # maildrop aborts and will try to deliver after 5min
670            # fork to avoid this
671            if os.fork() != 0: sys.exit(0)
672            time.sleep(SLEEP_INITIAL)
673    
674        for package in packages:
675            subprocess.call(['mga-gnome', 'increase', '--submit', '--hash', hexdigest, package, version], stdout=stdout, stderr=stderr)
676    
677        if options.mail: _send_reply_mail(stdout, msg, options.mail)
678    
679  def main():  def main():
680      description = """Mageia GNOME commands."""      description = """Mageia GNOME commands."""
# Line 456  def main(): Line 690  def main():
690      )      )
691    
692      subparser = subparsers.add_parser('packages', help='list all GNOME packages')      subparser = subparsers.add_parser('packages', help='list all GNOME packages')
693        subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
694                                           help="Show upstream module")
695      subparser.set_defaults(      subparser.set_defaults(
696          func=cmd_ls          func=cmd_ls, upstream=False
697      )      )
698    
699      subparser = subparsers.add_parser('patches', help='list all GNOME patches')      subparser = subparsers.add_parser('patches', help='list all GNOME patches')
# Line 476  def main(): Line 712  def main():
712      subparser = subparsers.add_parser('increase', help='Increase version number')      subparser = subparsers.add_parser('increase', help='Increase version number')
713      subparser.add_argument("package", help="Package name")      subparser.add_argument("package", help="Package name")
714      subparser.add_argument("version", help="Version number")      subparser.add_argument("version", help="Version number")
715        subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
716                                           help="Package name reflects the upstream name")
717      subparser.add_argument("-s", "--submit", action="store_true", dest="submit",      subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
718                                         help="Commit changes and submit")                                         help="Commit changes and submit")
719        subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo",
720                                           help="Hash algorithm")
721        subparser.add_argument("--hash", dest="hexdigest",
722                                           help="Hexdigest of the hash")
723        subparser.set_defaults(
724            func=cmd_package_new_version, submit=False, upstream=False, hexdigest=None, algo="sha256"
725        )
726    
727        subparser = subparsers.add_parser('gnome-release-email', help='Submit packages based on GNOME ftp-release-list email')
728        subparser.add_argument("-m", "--mail", help="Email address to send the progress to")
729        subparser.add_argument("-w", "--wait", action="store_true",
730                                     help="Wait before trying to retrieve the new version")
731      subparser.set_defaults(      subparser.set_defaults(
732          func=cmd_package_new_version, submit=False          func=cmd_parse_ftp_release_list
733      )      )
734    
735      if len(sys.argv) == 1:      if len(sys.argv) == 1:

Legend:
Removed from v.3039  
changed lines
  Added in v.3125

  ViewVC Help
Powered by ViewVC 1.1.30