/[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 3086 by ovitters, Mon Feb 27 09:32:36 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  # A lot of the code comes from ftpadmin, see
4  #   http://git.gnome.org/browse/sysadmin-bin/tree/ftpadmin  #   http://git.gnome.org/browse/sysadmin-bin/tree/ftpadmin
# Line 33  from sgmllib import SGMLParser Line 33  from sgmllib import SGMLParser
33  import urllib2  import urllib2
34  import urlparse  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 62  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 137  class XzTarFile(tarfile.TarFile): Line 221  class XzTarFile(tarfile.TarFile):
221  if not hasattr(tarfile.TarFile, 'xzopen'):  if not hasattr(tarfile.TarFile, 'xzopen'):
222      tarfile.open = XzTarFile.open      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 148  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 392  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 411  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(sorted(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 447  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        # Determine the package name
573      if options.upstream:      if options.upstream:
574          downstream, downstream_files = get_downstream_names()          try:
575                package = get_downstream_from_upstream(options.package, options.version)[0]
576          if options.package not in downstream:          except ValueError, e:
577              print >>sys.stderr, "ERROR: No packages for upstream name: %s" % options.package              print >>sys.stderr, "ERROR: %s" % e
             sys.exit(1)  
   
         if len(downstream[options.package]) != 1:  
             # XXX - Make it more intelligent  
             print >>sys.stderr, "ERROR: Multiple packages for upstream name: %s" % options.package  
578              sys.exit(1)              sys.exit(1)
   
         package = list(downstream[options.package])[0]  
579      else:      else:
580          package = options.package          package = options.package
581    
582        # Directories packages are located in
   
583      root = os.path.expanduser(PKGROOT)      root = os.path.expanduser(PKGROOT)
584      cwd = os.path.join(root, package)      cwd = os.path.join(root, package)
585    
586        # Checkout package to ensure the checkout reflects the latest changes
587      try:      try:
588          subprocess.check_call(['mgarepo', 'co', package], cwd=root)          subprocess.check_call(['mgarepo', 'co', package], cwd=root)
589      except subprocess.CalledProcessError:      except subprocess.CalledProcessError:
590          sys.exit(1)          sys.exit(1)
591    
592        # 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 501  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 525  def main(): Line 716  def main():
716                                         help="Package name reflects the upstream name")                                         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, upstream=False          func=cmd_parse_ftp_release_list
733      )      )
734    
735      if len(sys.argv) == 1:      if len(sys.argv) == 1:

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

  ViewVC Help
Powered by ViewVC 1.1.30