/[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 2936 by ovitters, Sun Feb 12 12:23:46 2012 UTC revision 3561 by ovitters, Mon Mar 19 09:59:13 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
20    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]+)')
58    
59    def version_cmp(a, b):
60        """Compares two versions
61    
62        Returns
63          -1 if a < b
64          0  if a == b
65          1  if a > b
66        """
67    
68        return rpm.labelCompare(('1', a, '1'), ('1', b, '1'))
69    
70    def get_latest_version(versions, max_version=None):
71        """Gets the latest version number
72    
73        if max_version is specified, gets the latest version number before
74        max_version"""
75        latest = None
76        for version in versions:
77            if ( latest is None or version_cmp(version, latest) > 0 ) \
78               and ( max_version is None or version_cmp(version, max_version) < 0 ):
79                latest = version
80        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:
# Line 22  def line_input (file): Line 158  def line_input (file):
158          else:          else:
159              yield line              yield line
160    
161    def call_editor(filename):
162        """Return a sequence of possible editor binaries for the current platform"""
163    
164        editors = []
165    
166        for varname in 'VISUAL', 'EDITOR':
167            if varname in os.environ:
168                editors.append(os.environ[varname])
169    
170        editors.extend(('/usr/bin/editor', 'vi', 'pico', 'nano', 'joe'))
171    
172        for editor in editors:
173            try:
174                ret = subprocess.call([editor, filename])
175            except OSError, e:
176                if e.errno == 2:
177                    continue
178                raise
179    
180            if ret == 127:
181                continue
182    
183            return True
184    
185  class urllister(SGMLParser):  class urllister(SGMLParser):
186      def reset(self):      def reset(self):
187          SGMLParser.reset(self)          SGMLParser.reset(self)
# Line 32  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):
244        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)
246    
247        def __init__(self, path):
248            self.path = path
249            self.cwd = os.path.dirname(path)
250    
251        @property
252        def version(self):
253            return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0]
254        @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)"""
264            cur_version = self.version
265    
266            (judgement, msg) = judge_version_increase(cur_version, version)
267    
268            if judgement < 0:
269                print >>sys.stderr, "ERROR: %s!" % (msg)
270                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:
292                data = f.read()
293    
294                if data.count("%mkrel") != 1:
295                    print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!"
296                    return False
297    
298                data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1)
299                if nr != 1:
300                    print >>sys.stderr, "ERROR: Could not increase version!"
301                    return False
302    
303                data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1)
304                if nr != 1:
305                    print >>sys.stderr, "ERROR: Could not reset release!"
306                    return False
307    
308                # Overwrite file with new version number
309                write_file(self.path, data)
310    
311    
312            # Verify that RPM also agrees that version number has changed
313            if self.version != version:
314                print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version
315                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:
337                # Check patches still apply
338                subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd)
339            except subprocess.CalledProcessError:
340                # XXX tail -n 15 SPECS/log.$PACKAGE
341                return False
342    
343            return True
344    
345  class Patch(object):  class Patch(object):
346      """Do things with patches"""      """Do things with patches"""
347    
# Line 47  class Patch(object): Line 357  class Patch(object):
357          return self.path if self.show_path else os.path.basename(self.path)          return self.path if self.show_path else os.path.basename(self.path)
358    
359      def add_dep3(self):      def add_dep3(self):
360          pass          """Add DEP-3 headers to a patch file"""
361            if self.dep3['valid']:
362                return False
363    
364            new_headers = (
365                ('Author', self.svn_author),
366                ('Subject', ''),
367                ('Applied-Upstream', ''),
368                ('Forwarded', ''),
369                ('Bug', ''),
370            )
371    
372            with tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False) as fdst:
373                with open(self.path, "r") as fsrc:
374                    # Start with any existing DEP3 headers
375                    for i in range(self.dep3['last_nr']):
376                        fdst.write(fsrc.read())
377    
378                    # After that add the DEP3 headers
379                    add_line = False
380                    for header, data in new_headers:
381                        if header in self.dep3['headers']:
382                            continue
383    
384                        # XXX - wrap this at 80 chars
385                        add_line = True
386                        print >>fdst, "%s: %s" % (header, "" if data is None else data)
387    
388                    if add_line: print >>fdst, ""
389                    # Now copy any other data and the patch
390                    shutil.copyfileobj(fsrc, fdst)
391    
392                fdst.flush()
393                os.rename(fdst.name, self.path)
394    
395            call_editor(self.path)
396    
397      #Author: fwang      #Author: fwang
398      #Subject: Build fix: Fix glib header inclusion      #Subject: Build fix: Fix glib header inclusion
399      #Applied-Upstream: commit:30602      #Applied-Upstream: commit:30602
# Line 55  class Patch(object): Line 401  class Patch(object):
401      #Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247      #Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247
402    
403      def _read_dep3(self):      def _read_dep3(self):
404          """This will also parse git headers"""          """Read DEP-3 headers from an existing patch file
405    
406            This will also parse git headers"""
407          dep3 = {}          dep3 = {}
408            headers = {}
409    
410          last_header = None          last_header = None
411            last_nr = 0
412            nr = 0
413          try:          try:
414              with open(self.path, "r") as f:              with open(self.path, "r") as f:
415                  for line in line_input(f):                  for line in line_input(f):
416                      # Check for start of real patch                      nr += 1
417                        # stop trying to parse when real patch begins
418                      if line == '---':                      if line == '---':
419                          break                          break
420    
421                      r = self.re_dep3.match(line)                      r = self.re_dep3.match(line)
422                      if r:                      if r:
423                          info = r.groupdict()                          info = r.groupdict()
424                          dep3[info['header']] = info['data']  
425                            # Avoid matching URLS
426                            if info['data'].startswith('//') and info['header'].lower () == info['header']:
427                                continue
428    
429                            headers[info['header']] = info['data']
430                          last_header = info['header']                          last_header = info['header']
431                            last_nr = nr
432                          continue                          continue
433    
434                      r = self.re_dep3_cont.match(line)                      r = self.re_dep3_cont.match(line)
435                      if r:                      if r:
436                          info = r.groupdict()                          info = r.groupdict()
437                          if last_header:                          if last_header:
438                              dep3[last_header] = " ".join((dep3[last_header], info['data']))                              headers[last_header] = " ".join((headers[last_header], info['data']))
439                                last_nr = nr
440                          continue                          continue
441    
442                      last_header = None                      last_header = None
443          except IOError:          except IOError:
444              pass              pass
445    
446            dep3['valid'] = \
447                (('Description' in headers and headers['Description'].strip() != '')
448                    or ('Subject' in headers and headers['Subject'].strip() != '')) \
449                and (('Origin' in headers and headers['Origin'].strip() != '') \
450                    or ('Author' in headers and headers['Author'].strip() != '') \
451                    or ('From' in headers and headers['From'].strip() != ''))
452            dep3['last_nr'] = last_nr
453            dep3['headers'] = headers
454    
455          self._dep3 = dep3          self._dep3 = dep3
456    
457      @property      @property
# Line 92  class Patch(object): Line 461  class Patch(object):
461    
462          return self._dep3          return self._dep3
463    
464        @property
465        def svn_author(self):
466            if not hasattr(self, '_svn_author'):
467                try:
468                    contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines()
469    
470                    for line in contents:
471                        if ' | ' not in line:
472                            continue
473    
474                        fields = line.split(' | ')
475                        if len(fields) >= 3:
476                            self._svn_author = fields[1]
477                except subprocess.CalledProcessError:
478                    pass
479    
480            if not hasattr(self, '_svn_author'):
481                return None
482    
483            return self._svn_author
484    
485  def get_upstream_names():  def get_upstream_names():
486      urlopen = urllib2.build_opener()      urlopen = urllib2.build_opener()
# Line 113  def get_upstream_names(): Line 502  def get_upstream_names():
502  def get_downstream_names():  def get_downstream_names():
503      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]*)$')
504    
505      p = subprocess.Popen(['urpmf', '--files', '.', "--media", MEDIA], stdout=subprocess.PIPE, close_fds=True)      contents = subprocess.check_output(['urpmf', '--qf', '%name|%version|%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)  
506    
507      FILES = {}      FILES = {}
508      TARBALLS = {}      TARBALLS = {}
509    
510      for line in  contents:      for line in  contents:
511          try:          try:
512              srpm, filename = line.split(":")              srpm, version, filename = line.split("|")
513          except ValueError:          except ValueError:
514              print >>sys.stderr, line              print >>sys.stderr, line
515              continue              continue
# Line 136  def get_downstream_names(): Line 521  def get_downstream_names():
521                  module = fileinfo['module']                  module = fileinfo['module']
522    
523                  if module not in TARBALLS:                  if module not in TARBALLS:
524                      TARBALLS[module] = set()                      TARBALLS[module] = {}
525                  TARBALLS[module].add(srpm)                  TARBALLS[module][srpm] = version
526    
527          if srpm not in FILES:          if srpm not in FILES:
528              FILES[srpm] = set()              FILES[srpm] = set()
# Line 145  def get_downstream_names(): Line 530  def get_downstream_names():
530    
531      return TARBALLS, FILES      return TARBALLS, FILES
532    
533  def cmd_co(options, parser):  def get_downstream_from_upstream(upstream, version):
534      upstream = get_upstream_names()      # Determine the package name
535      downstream, downstream_files = get_downstream_names()      downstream, downstream_files = get_downstream_names()
536    
537      cwd = os.path.expanduser(PKGROOT)      if upstream not in downstream:
538            raise ValueError("No packages for upstream name: %s" % upstream)
539    
540      matches = upstream & set(downstream.keys())      if len(downstream[upstream]) == 1:
541      for module in matches:          return downstream[upstream].keys()
542          print module, "\t".join(downstream[module])  
543          for package in downstream[module]:      # Directories packages are located in
544              subprocess.call(['mgarepo', 'co', package], cwd=cwd)      root = os.path.expanduser(PKGROOT)
545    
546        packages = {}
547        for package in downstream[upstream].keys():
548            cwd = os.path.join(root, package)
549    
550            # Checkout package to ensure the checkout reflects the latest changes
551            try:
552                subprocess.check_call(['mgarepo', 'co', package], cwd=root)
553            except subprocess.CalledProcessError:
554                raise ValueError("Multiple packages found and cannot checkout %s" % package)
555    
556            # Determine version from spec file
557            try:
558                packages[package] = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)).version
559            except subprocess.CalledProcessError:
560                raise ValueError("Multiple packages found and cannot determine version of %s" % package)
561    
562        # Return all packages reflecting the current version
563        matches = [package for package in packages if packages[package] == version]
564        if len(matches):
565            return matches
566    
567        # Return all packages reflecting the version before the current version
568        latest_version = get_latest_version(packages.values(), max_version=version)
569        matches = [package for package in packages if packages[package] == latest_version]
570        if len(matches):
571            return matches
572    
573        # Give up
574        raise ValueError("Multiple packages found and cannot determine package for version %s" % version)
575    
576    def write_file(path, data):
577        with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst:
578            fdst.write(data)
579            fdst.flush()
580            os.rename(fdst.name, path)
581    
582    def cmd_co(options, parser):
583        root = os.path.expanduser(PKGROOT)
584    
585        for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
586            print "%s => %s" % (module, package)
587            subprocess.call(['mgarepo', 'co', package], cwd=root)
588    
589    def join_streams(show_version=False, only_diff_version=False):
590        root = os.path.expanduser(PKGROOT)
591    
 def cmd_ls(options, parser):  
592      upstream = get_upstream_names()      upstream = get_upstream_names()
593      downstream, downstream_files = get_downstream_names()      downstream, downstream_files = get_downstream_names()
594    
595      matches = upstream & set(downstream.keys())      matches = upstream & set(downstream.keys())
596      for module in matches:      for module in matches:
597          print "\n".join(downstream[module])          for package in downstream[module].keys():
598                package_version = downstream[module][package]
599                spec_version = None
600                if show_version or only_diff_version:
601                    cwd = os.path.join(root, package)
602                    try:
603                        spec_version = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package)).version
604                    except subprocess.CalledProcessError:
605                        spec_version = 'N/A'
606    
607                if only_diff_version and package_version == spec_version:
608                    continue
609    
610                yield (package, module, package_version, spec_version, downstream_files[package])
611    
612    def cmd_ls(options, parser):
613        for package, module, package_version, spec_version, downstream_files in sorted(join_streams(show_version=options.show_version, only_diff_version=options.diff)):
614            print package,"\t",
615            if options.upstream: print module, "\t",
616            if options.show_version: print spec_version, "\t", package_version, "\t",
617            print
618    
619  def cmd_patches(options, parser):  def cmd_patches(options, parser):
620      upstream = get_upstream_names()      root = os.path.expanduser(PKGROOT)
621      downstream, downstream_files = get_downstream_names()  
622        for package, module, package_version, spec_version, downstream_files in sorted(join_streams()):
623            for filename in downstream_files:
624                if '.patch' in filename or '.diff' in filename:
625    
626                    p = Patch(os.path.join(root, package, "SOURCES", filename), show_path=options.path)
627                    valid = ""
628                    forwarded = ""
629                    if p.dep3['headers']:
630                        forwarded = p.dep3['headers'].get('Forwarded', "no")
631                        if p.dep3['valid']:
632                            valid="VALID"
633                    print "\t".join((module, package, str(p), forwarded, valid))
634    
635    def cmd_dep3(options, parser):
636        p = Patch(options.patch)
637        p.add_dep3()
638    
639    def cmd_package_new_version(options, parser):
640        # Determine the package name
641        if options.upstream:
642            try:
643                package = get_downstream_from_upstream(options.package, options.version)[0]
644            except ValueError, e:
645                print >>sys.stderr, "ERROR: %s" % e
646                sys.exit(1)
647        else:
648            package = options.package
649    
650        # Directories packages are located in
651        root = os.path.expanduser(PKGROOT)
652        cwd = os.path.join(root, package)
653    
654        # Checkout package to ensure the checkout reflects the latest changes
655        try:
656            subprocess.check_call(['mgarepo', 'co', package], cwd=root)
657        except subprocess.CalledProcessError:
658            sys.exit(1)
659    
660      path = os.path.expanduser(PKGROOT)      # SpecFile class handles the actual version+release change
661        s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package))
662        print "%s => %s" % (s.version, options.version)
663        if not s.update(options.version, force=options.force):
664            sys.exit(1)
665    
666      import pprint      # Check hash, if given
667        if options.hexdigest is not None:
668            sources = [name for name, origname in s.sources.iteritems() if '://' in origname]
669            if not len(sources):
670                print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!"
671                sys.stderr(1)
672    
673            for filename in sources:
674                if not is_valid_hash(os.path.join(cwd, "SOURCES", filename), options.algo, options.hexdigest):
675                    print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path
676                    print >>sys.stderr, "ERROR: Reverting changes!"
677                    subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd)
678                    sys.exit(1)
679    
680      matches = upstream & set(downstream.keys())      # We can even checkin and submit :-)
681      for module in sorted(matches):      if options.submit:
682          for srpm in downstream[module]:          try:
683              for filename in downstream_files[srpm]:              # checkin changes
684                  if '.patch' in filename or '.diff' in filename:              subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd)
685                      p = Patch(os.path.join(path, srpm, "SOURCES", filename), show_path=options.path)              # and submit
686                      print "\t".join((module, srpm, str(p)))              subprocess.check_call(['mgarepo', 'submit'], cwd=cwd)
687                      if p.dep3:          except subprocess.CalledProcessError:
688                          pprint.pprint(p.dep3)              sys.exit(1)
689    
690    def cmd_parse_ftp_release_list(options, parser):
691        def _send_reply_mail(contents, orig_msg, to, error=False):
692            """Send an reply email"""
693            contents.seek(0)
694            msg = MIMEText(contents.read(), _charset='utf-8')
695            if error:
696                # XXX - ugly
697                contents.seek(0)
698                lastline = contents.read().splitlines()[-1]
699                # Remove things like "ERROR: " and so on from the last line
700                lastline = re.sub(r'^(?:[^ :]+:\s+)+', '', lastline)
701                subjecterror = " (ERROR: %s)" % lastline if lastline else " (ERROR)"
702            else:
703                subjecterror = ""
704            msg['Subject'] = "Re: %s%s" % (orig_msg['Subject'], subjecterror)
705            msg['To'] = to
706            msg["In-Reply-To"] = orig_msg["Message-ID"]
707            msg["References"] = orig_msg["Message-ID"]
708    
709            # Call sendmail program directly so it doesn't matter if the service is running
710            cmd = ['/usr/sbin/sendmail', '-oi', '--']
711            cmd.extend([to])
712            p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
713            p.stdin.write(msg.as_string())
714            p.stdin.flush()
715            p.stdin.close()
716            p.wait()
717    
718    
719        msg = email.email.message_from_file(sys.stdin)
720    
721        if options.mail:
722            stdout = tempfile.TemporaryFile()
723            stderr = stdout
724        else:
725            stdout = sys.stdout
726            stderr = sys.stderr
727    
728        try:
729            module = msg['X-Module-Name']
730            version = msg['X-Module-Version']
731            hexdigest = msg['X-Module-SHA256-tar.xz']
732        except KeyError, e:
733            print >>stderr, "ERROR: %s" % e
734            if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
735            sys.exit(1)
736    
737        try:
738            packages = get_downstream_from_upstream(module, version)
739        except ValueError, e:
740            print >>stderr, "ERROR: %s" % e
741            if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True)
742            sys.exit(1)
743    
744        if options.wait:
745            # maildrop aborts and will try to deliver after 5min
746            # fork to avoid this
747            if os.fork() != 0: sys.exit(0)
748            # wait SLEEP_INITIAL after the message was sent
749            secs = SLEEP_INITIAL
750            t = email.utils.parsedate_tz(msg['Date'])
751            if t is not None:
752                msg_time = email.utils.mktime_tz(t)
753                secs = SLEEP_INITIAL - (time.time() - msg_time)
754    
755            if secs > 0: time.sleep(secs)
756    
757        error = False
758        for package in packages:
759            cmd = ['mga-gnome', 'increase', '--submit', '--hash', hexdigest]
760            if options.force:
761                cmd.append('--force')
762            cmd.extend((package, version))
763            if subprocess.call(cmd, stdout=stdout, stderr=stderr):
764                error = True
765    
766        if options.mail: _send_reply_mail(stdout, msg, options.mail, error=error)
767    
768  def main():  def main():
769      description = """Mageia GNOME commands."""      description = """Mageia GNOME commands."""
# Line 197  def main(): Line 779  def main():
779      )      )
780    
781      subparser = subparsers.add_parser('packages', help='list all GNOME packages')      subparser = subparsers.add_parser('packages', help='list all GNOME packages')
782        subparser.add_argument("-m", "--m", action="store_true", dest="upstream",
783                                           help="Show upstream module")
784        subparser.add_argument(      "--version", action="store_true", dest="show_version",
785                                           help="Show version numbers")
786        subparser.add_argument(      "--diff", action="store_true", dest="diff",
787                                           help="Only show packages with different version")
788      subparser.set_defaults(      subparser.set_defaults(
789          func=cmd_ls          func=cmd_ls, upstream=False, show_version=False, diff=False
790      )      )
791    
792      subparser = subparsers.add_parser('patches', help='list all GNOME patches')      subparser = subparsers.add_parser('patches', help='list all GNOME patches')
793      subparser.add_argument("-p", "--path", action="store_true", dest="path",      subparser.add_argument("-p", "--path", action="store_true", dest="path",
794                                         help="Full path to patch")                                         help="Show full path to patch")
795      subparser.set_defaults(      subparser.set_defaults(
796          func=cmd_patches, path=False          func=cmd_patches, path=False
797      )      )
798    
799        subparser = subparsers.add_parser('dep3', help='Add dep3 headers')
800        subparser.add_argument("patch", help="Patch")
801        subparser.set_defaults(
802            func=cmd_dep3, path=False
803        )
804    
805        subparser = subparsers.add_parser('increase', help='Increase version number')
806        subparser.add_argument("package", help="Package name")
807        subparser.add_argument("version", help="Version number")
808        subparser.add_argument("-f", "--force", action="store_true", dest="force",
809                                           help="Override warnings, just do it")
810        subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream",
811                                           help="Package name reflects the upstream name")
812        subparser.add_argument("-s", "--submit", action="store_true", dest="submit",
813                                           help="Commit changes and submit")
814        subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo",
815                                           help="Hash algorithm")
816        subparser.add_argument("--hash", dest="hexdigest",
817                                           help="Hexdigest of the hash")
818        subparser.set_defaults(
819            func=cmd_package_new_version, submit=False, upstream=False, hexdigest=None, algo="sha256",
820            force=False
821        )
822    
823        subparser = subparsers.add_parser('gnome-release-email', help='Submit packages based on GNOME ftp-release-list email')
824        subparser.add_argument("-m", "--mail", help="Email address to send the progress to")
825        subparser.add_argument("-w", "--wait", action="store_true",
826                                     help="Wait before trying to retrieve the new version")
827        subparser.add_argument("-f", "--force", action="store_true",
828                                     help="Force submission")
829        subparser.set_defaults(
830            func=cmd_parse_ftp_release_list, force=False, wait=False
831        )
832    
833      if len(sys.argv) == 1:      if len(sys.argv) == 1:
834          parser.print_help()          parser.print_help()

Legend:
Removed from v.2936  
changed lines
  Added in v.3561

  ViewVC Help
Powered by ViewVC 1.1.30