/[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 3034 by ovitters, Wed Feb 22 20:47:36 2012 UTC revision 3650 by ovitters, Wed Mar 21 19:34:00 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]+)')  re_version = re.compile(r'([-.]|\d+|[^-.\d]+)')
58    
59  def version_cmp(a, b):  def version_cmp(a, b):
# Line 26  def version_cmp(a, b): Line 63  def version_cmp(a, b):
63        -1 if a < b        -1 if a < b
64        0  if a == b        0  if a == b
65        1  if a > b        1  if a > b
66        """
67    
68      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))  
69    
70  def get_latest_version(versions, max_version=None):  def get_latest_version(versions, max_version=None):
71      """Gets the latest version number      """Gets the latest version number
# Line 68  def get_latest_version(versions, max_ver Line 79  def get_latest_version(versions, max_ver
79              latest = version              latest = version
80      return latest      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:
156          if line[-1] == '\n':          if line[-1] == '\n':
# Line 109  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):  class SpecFile(object):
244      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)
245      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 251  class SpecFile(object):
251      @property      @property
252      def version(self):      def version(self):
253          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]
254      def update(self, version):      @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)"""          """Update specfile (increase version)"""
264          cur_version = self.version          cur_version = self.version
265    
266          if version_cmp(version, cur_version) != 1:          (judgement, msg) = judge_version_increase(cur_version, version)
267              print >>sys.stderr, "ERROR: Version %s is older than current version %s!" % (version, cur_version)  
268            if judgement < 0:
269                print >>sys.stderr, "ERROR: %s!" % (msg)
270              return False              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:          with open(self.path, "rw") as f:
292              data = f.read()              data = f.read()
293    
294              if data.count("%mkrel") != 1:              if data.count("%mkrel") != 1:
295                  print "WARNING: Multiple %mkrel found; don't know what to do!"                  print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!"
296                  return False                  return False
297    
298              data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1)              data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1)
299              if nr != 1:              if nr != 1:
300                  print "WARNING: Could not increase version!"                  print >>sys.stderr, "ERROR: Could not increase version!"
301                  return False                  return False
302    
303              data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1)              data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1)
304              if nr != 1:              if nr != 1:
305                  print "WARNING: Could not reset release!"                  print >>sys.stderr, "ERROR: Could not reset release!"
306                  return False                  return False
307    
308              # Overwrite file with new version number              # Overwrite file with new version number
309              write_file(self.path, data)              write_file(self.path, data)
310    
311    
312          # Check RPM also agrees that version number has increased          # Verify that RPM also agrees that version number has changed
313          if self.version != version:          if self.version != version:
314              print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version              print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
315              return False              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:          try:
             # Download new tarball  
             subprocess.check_call(['mgarepo', 'sync', '-d'], cwd=self.cwd)  
337              # Check patches still apply              # Check patches still apply
338              subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd)              subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd)
339          except subprocess.CalledProcessError:          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              return False
344    
345          return True          return True
# Line 286  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 297  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'):          if not hasattr(self, '_svn_author'):
483              return None              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        def __init__(self):
493            urlopen = urllib2.build_opener()
494    
495      # Get the files          good_dir = re.compile('^[-A-Za-z0-9_+.]+/$')
     usock = urlopen.open(URL)  
     parser = urllister()  
     parser.feed(usock.read())  
     usock.close()  
     parser.close()  
     files = parser.urls  
496    
497      tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)])          # 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      return tarballs          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  def get_downstream_names():          self.names = tarballs
510    
511    class Downstream(object):
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)      def __init__(self):
515      contents = p.stdout.read().strip("\n").splitlines()          contents = subprocess.check_output(['urpmf', '--qf', '%name|%version|%files', '.', "--media", MEDIA], close_fds=True).strip("\n").splitlines()
     ecode = p.wait()  
     if ecode != 0:  
         sys.exit(1)  
516    
517      FILES = {}          FILES = {}
518      TARBALLS = {}          TARBALLS = {}
519    
520      for line in  contents:          for line in  contents:
521                try:
522                    srpm, version, filename = line.split("|")
523                except ValueError:
524                    print >>sys.stderr, line
525                    continue
526    
527                if '.tar' in filename:
528                    r = self.re_file.match(filename)
529                    if r:
530                        fileinfo = r.groupdict()
531                        module = fileinfo['module']
532    
533                        if module not in TARBALLS:
534                            TARBALLS[module] = {}
535                        TARBALLS[module][srpm] = version
536    
537                if srpm not in FILES:
538                    FILES[srpm] = set()
539                FILES[srpm].add(filename)
540    
541            self.tarballs = TARBALLS
542            self.files = FILES
543    
544    def get_downstream_from_upstream(upstream, version):
545        # Determine the package name
546        downstream = Downstream()
547    #    downstream, downstream_files = get_downstream_names()
548    
549        if upstream not in downstream:
550            raise ValueError("No packages for upstream name: %s" % upstream)
551    
552        if len(downstream.tarballs[upstream]) == 1:
553            return downstream.tarballs[upstream].keys()
554    
555        # Directories packages are located in
556        root = os.path.expanduser(PKGROOT)
557    
558        packages = {}
559        for package in downstream.tarballs[upstream].keys():
560            cwd = os.path.join(root, package)
561    
562            # Checkout package to ensure the checkout reflects the latest changes
563          try:          try:
564              srpm, filename = line.split(":")              subprocess.check_call(['mgarepo', 'co', package], cwd=root)
565          except ValueError:          except subprocess.CalledProcessError:
566              print >>sys.stderr, line              raise ValueError("Multiple packages found and cannot checkout %s" % package)
             continue  
567    
568          if '.tar' in filename:          # Determine version from spec file
569              r = re_file.match(filename)          try:
570              if r:              packages[package] = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)).version
571                  fileinfo = r.groupdict()          except subprocess.CalledProcessError:
572                  module = fileinfo['module']              raise ValueError("Multiple packages found and cannot determine version of %s" % package)
   
                 if module not in TARBALLS:  
                     TARBALLS[module] = set()  
                 TARBALLS[module].add(srpm)  
   
         if srpm not in FILES:  
             FILES[srpm] = set()  
         FILES[srpm].add(filename)  
573    
574      return TARBALLS, FILES      # Return all packages reflecting the current version
575        matches = [package for package in packages if packages[package] == version]
576        if len(matches):
577            return matches
578    
579        # Return all packages reflecting the version before the current version
580        latest_version = get_latest_version(packages.values(), max_version=version)
581        matches = [package for package in packages if packages[package] == latest_version]
582        if len(matches):
583            return matches
584    
585        # Give up
586        raise ValueError("Multiple packages found and cannot determine package for version %s" % version)
587    
588  def write_file(path, data):  def write_file(path, data):
589      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 363  def write_file(path, data): Line 592  def write_file(path, data):
592          os.rename(fdst.name, path)          os.rename(fdst.name, path)
593    
594  def cmd_co(options, parser):  def cmd_co(options, parser):
595      upstream = get_upstream_names()      root = os.path.expanduser(PKGROOT)
     downstream, downstream_files = get_downstream_names()  
596    
597      cwd = os.path.expanduser(PKGROOT)      for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
598            print "%s => %s" % (module, package)
599            subprocess.call(['mgarepo', 'co', package], cwd=root)
600    
601      matches = upstream & set(downstream.keys())  def join_streams(show_version=False, only_diff_version=False):
602      for module in matches:      root = os.path.expanduser(PKGROOT)
         print module, "\t".join(downstream[module])  
         for package in downstream[module]:  
             subprocess.call(['mgarepo', 'co', package], cwd=cwd)  
603    
604  def cmd_ls(options, parser):      upstream = Upstream().names
605      upstream = get_upstream_names()      downstream = Downstream()
     downstream, downstream_files = get_downstream_names()  
606    
607      matches = upstream & set(downstream.keys())      matches = upstream & set(downstream.tarballs.keys())
608      for module in matches:      for module in matches:
609          print "\n".join(downstream[module])          for package in downstream.tarballs[module].keys():
610                package_version = downstream.tarballs[module][package]
611                spec_version = None
612                if show_version or only_diff_version:
613                    cwd = os.path.join(root, package)
614                    try:
615                        spec_version = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)).version
616                    except subprocess.CalledProcessError:
617                        spec_version = 'N/A'
618    
619  def cmd_patches(options, parser):              if only_diff_version and package_version == spec_version:
620      upstream = get_upstream_names()                  continue
     downstream, downstream_files = get_downstream_names()  
621    
622      path = os.path.expanduser(PKGROOT)              yield (package, module, package_version, spec_version, downstream.files[package])
623    
624      import pprint  def cmd_ls(options, parser):
625        for package, module, package_version, spec_version, downstream_files in sorted(join_streams(show_version=options.show_version, only_diff_version=options.diff)):
626            sys.stdout.write(package)
627            if options.upstream: sys.stdout.write("\t%s" % module)
628            if options.show_version: sys.stdout.write("\t%s\t%s" % (spec_version, package_version))
629            print
630    
631    def cmd_patches(options, parser):
632        root = os.path.expanduser(PKGROOT)
633    
634      matches = upstream & set(downstream.keys())      for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
635      for module in sorted(matches):          for filename in downstream_files:
636          for srpm in downstream[module]:              if '.patch' in filename or '.diff' in filename:
637              for filename in downstream_files[srpm]:  
638                  if '.patch' in filename or '.diff' in filename:                  p = Patch(os.path.join(root, package, "SOURCES", filename), show_path=options.path)
639                    valid = ""
640                      p = Patch(os.path.join(path, srpm, "SOURCES", filename), show_path=options.path)                  forwarded = ""
641                      valid = ""                  if p.dep3['headers']:
642                      forwarded = ""                      forwarded = p.dep3['headers'].get('Forwarded', "no")
643                      if p.dep3['headers']:                      if p.dep3['valid']:
644                          forwarded = p.dep3['headers'].get('Forwarded', "no")                          valid="VALID"
645                          if p.dep3['valid']:                  print "\t".join((module, package, str(p), forwarded, valid))
                             valid="VALID"  
                     print "\t".join((module, srpm, str(p), forwarded, valid))  
646    
647  def cmd_dep3(options, parser):  def cmd_dep3(options, parser):
648      p = Patch(options.patch)      p = Patch(options.patch)
649      p.add_dep3()      p.add_dep3()
650    
651  def cmd_package_new_version(options, parser):  def cmd_package_new_version(options, parser):
652      cwd = os.path.expanduser(PKGROOT)      # Determine the package name
653      package = options.package      if options.upstream:
654            try:
655                package = get_downstream_from_upstream(options.package, options.version)[0]
656            except ValueError, e:
657                print >>sys.stderr, "ERROR: %s" % e
658                sys.exit(1)
659        else:
660            package = options.package
661    
662        # Directories packages are located in
663        root = os.path.expanduser(PKGROOT)
664        cwd = os.path.join(root, package)
665    
666        # Checkout package to ensure the checkout reflects the latest changes
667        try:
668            subprocess.check_call(['mgarepo', 'co', package], cwd=root)
669        except subprocess.CalledProcessError:
670            sys.exit(1)
671    
672      subprocess.call(['mgarepo', 'co', package], cwd=cwd)      # SpecFile class handles the actual version+release change
673      s = SpecFile(os.path.join(cwd, package, "SPECS", "%s.spec" % package))      s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package))
674      print s.version      print "%s => %s" % (s.version, options.version)
675      if not s.update(options.version):      if not s.update(options.version, force=options.force):
676          sys.exit(1)          sys.exit(1)
677    
678        # Check hash, if given
679        if options.hexdigest is not None:
680            sources = [name for name, origname in s.sources.iteritems() if '://' in origname]
681            if not len(sources):
682                print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!"
683                sys.stderr(1)
684    
685            for filename in sources:
686                path = os.path.join(cwd, "SOURCES", filename)
687                if not is_valid_hash(path, options.algo, options.hexdigest):
688                    print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path
689                    print >>sys.stderr, "ERROR: Reverting changes!"
690                    subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd)
691                    sys.exit(1)
692    
693        # We can even checkin and submit :-)
694        if options.submit:
695            try:
696                # checkin changes
697                subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd)
698                # and submit
699                # XXX HACK NOT TO AUTO SUBMIT ATM
700                if options.hexdigest is None:
701                    subprocess.check_call(['mgarepo', 'submit'], cwd=cwd)
702            except subprocess.CalledProcessError:
703                sys.exit(1)
704    
705    def cmd_parse_ftp_release_list(options, parser):
706        def _send_reply_mail(contents, orig_msg, to, packages=[], error=False):
707            """Send an reply email"""
708            contents.seek(0)
709            msg = MIMEText(contents.read(), _charset='utf-8')
710    
711            if error:
712                # XXX - ugly
713                contents.seek(0)
714                lastline = contents.read().rstrip().splitlines()[-1]
715                # Remove things like "ERROR: " and so on from the last line
716                lastline = re.sub(r'^(?:[^ :]+:\s+)+', '', lastline)
717                # Remove things like "   - " (youri output from mgarepo submit)
718                lastline = re.sub(r'^\s+-\s+', '', lastline)
719                subjecterror = " (ERROR: %s)" % lastline if lastline else " (ERROR)"
720            else:
721                subjecterror = ""
722    
723            if packages:
724                subject = "%s %s%s" % (", ".join(packages), orig_msg['X-Module-Version'], subjecterror)
725            else:
726                subject = "Re: %s%s" % (orig_msg['Subject'], subjecterror)
727    
728            msg['Subject'] = subject
729            msg['To'] = to
730            msg["In-Reply-To"] = orig_msg["Message-ID"]
731            msg["References"] = orig_msg["Message-ID"]
732    
733            # Call sendmail program directly so it doesn't matter if the service is running
734            cmd = ['/usr/sbin/sendmail', '-oi', '--']
735            cmd.extend([to])
736            p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
737            p.stdin.write(msg.as_string())
738            p.stdin.flush()
739            p.stdin.close()
740            p.wait()
741    
742    
743        msg = email.email.message_from_file(sys.stdin)
744    
745        if options.mail:
746            stdout = tempfile.TemporaryFile()
747            stderr = stdout
748        else:
749            stdout = sys.stdout
750            stderr = sys.stderr
751    
752        try:
753            module = msg['X-Module-Name']
754            version = msg['X-Module-Version']
755            hexdigest = msg['X-Module-SHA256-tar.xz']
756        except KeyError, e:
757            print >>stderr, "ERROR: %s" % e
758            if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
759            sys.exit(1)
760    
761        try:
762            packages = get_downstream_from_upstream(module, version)
763        except ValueError, e:
764            print >>stderr, "ERROR: %s" % e
765            if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
766            sys.exit(1)
767    
768        if options.wait:
769            # maildrop aborts and will try to deliver after 5min
770            # fork to avoid this
771            if os.fork() != 0: sys.exit(0)
772            # wait SLEEP_INITIAL after the message was sent
773            secs = SLEEP_INITIAL
774            t = email.utils.parsedate_tz(msg['Date'])
775            if t is not None:
776                msg_time = email.utils.mktime_tz(t)
777                secs = SLEEP_INITIAL - (time.time() - msg_time)
778    
779            if secs > 0: time.sleep(secs)
780    
781        error = False
782        for package in packages:
783            cmd = ['mga-gnome', 'increase', '--submit', '--hash', hexdigest]
784            if options.force:
785                cmd.append('--force')
786            cmd.extend((package, version))
787            if subprocess.call(cmd, stdout=stdout, stderr=stderr):
788                error = True
789    
790        if options.mail: _send_reply_mail(stdout, msg, options.mail, packages=packages, error=error)
791    
792  def main():  def main():
793      description = """Mageia GNOME commands."""      description = """Mageia GNOME commands."""
794      epilog="""Report bugs to Olav Vitters"""      epilog="""Report bugs to Olav Vitters"""
795      parser = argparse.ArgumentParser(description=description,epilog=epilog)      parser = argparse.ArgumentParser(description=description,epilog=epilog)
796        parser.add_argument("-l", "--limit", type=argparse.FileType('r', 0),
797                            dest="limit_upstream", metavar="FILE",
798                            help="File containing upstream names")
799    
800      # SUBPARSERS      # SUBPARSERS
801      subparsers = parser.add_subparsers(title='subcommands')      subparsers = parser.add_subparsers(title='subcommands')
# Line 434  def main(): Line 806  def main():
806      )      )
807    
808      subparser = subparsers.add_parser('packages', help='list all GNOME packages')      subparser = subparsers.add_parser('packages', help='list all GNOME packages')
809        subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
810                                           help="Show upstream module")
811        subparser.add_argument(      "--version", action="store_true", dest="show_version",
812                                           help="Show version numbers")
813        subparser.add_argument(      "--diff", action="store_true", dest="diff",
814                                           help="Only show packages with different version")
815      subparser.set_defaults(      subparser.set_defaults(
816          func=cmd_ls          func=cmd_ls, upstream=False, show_version=False, diff=False
817      )      )
818    
819      subparser = subparsers.add_parser('patches', help='list all GNOME patches')      subparser = subparsers.add_parser('patches', help='list all GNOME patches')
# Line 454  def main(): Line 832  def main():
832      subparser = subparsers.add_parser('increase', help='Increase version number')      subparser = subparsers.add_parser('increase', help='Increase version number')
833      subparser.add_argument("package", help="Package name")      subparser.add_argument("package", help="Package name")
834      subparser.add_argument("version", help="Version number")      subparser.add_argument("version", help="Version number")
835        subparser.add_argument("-f", "--force", action="store_true", dest="force",
836                                           help="Override warnings, just do it")
837        subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
838                                           help="Package name reflects the upstream name")
839        subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
840                                           help="Commit changes and submit")
841        subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo",
842                                           help="Hash algorithm")
843        subparser.add_argument("--hash", dest="hexdigest",
844                                           help="Hexdigest of the hash")
845        subparser.set_defaults(
846            func=cmd_package_new_version, submit=False, upstream=False, hexdigest=None, algo="sha256",
847            force=False
848        )
849    
850        subparser = subparsers.add_parser('gnome-release-email', help='Submit packages based on GNOME ftp-release-list email')
851        subparser.add_argument("-m", "--mail", help="Email address to send the progress to")
852        subparser.add_argument("-w", "--wait", action="store_true",
853                                     help="Wait before trying to retrieve the new version")
854        subparser.add_argument("-f", "--force", action="store_true",
855                                     help="Force submission")
856      subparser.set_defaults(      subparser.set_defaults(
857          func=cmd_package_new_version, path=False          func=cmd_parse_ftp_release_list, force=False, wait=False
858      )      )
859    
860      if len(sys.argv) == 1:      if len(sys.argv) == 1:
# Line 463  def main(): Line 862  def main():
862          sys.exit(2)          sys.exit(2)
863    
864      options = parser.parse_args()      options = parser.parse_args()
865        if options.limit_upstream:
866            Upstream.limit = set(options.limit_upstream.read().strip("\n").splitlines())
867    
868      try:      try:
869          options.func(options, parser)          options.func(options, parser)
# Line 478  def main(): Line 879  def main():
879          sys.exit(0)          sys.exit(0)
880    
881  if __name__ == "__main__":  if __name__ == "__main__":
882        os.environ['PYTHONUNBUFFERED'] = '1'
883      main()      main()

Legend:
Removed from v.3034  
changed lines
  Added in v.3650

  ViewVC Help
Powered by ViewVC 1.1.30