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

Legend:
Removed from v.3038  
changed lines
  Added in v.3449

  ViewVC Help
Powered by ViewVC 1.1.30