import re
import subprocess
from tambo import Transport
# import rhcephpkg.log as log
import rhcephpkg.util as util


class Patch(object):
    help_menu = 'apply patches from patch-queue branch'
    _help = """
Generate patches from a patch-queue branch.

"""
    name = 'patch'

    def __init__(self, argv):
        self.argv = argv
        self.options = []

    def main(self):
        self.parser = Transport(self.argv, options=self.options)
        self.parser.catch_help = self.help()
        self.parser.parse_args()
        self._run()

    def help(self):
        return self._help

    def _run(self):
        """ Generate quilt patch series with gbp pq, and update d/rules """

        patches_branch = util.current_branch()
        if not patches_branch.startswith('patch-queue/'):
            raise SystemExit('%s is not a patch-queue branch' % patches_branch)

        # TODO: default to fetching from upstream, the way rdopkg patch does.

        # Get the new sha1 to insert into the $COMMIT variable in d/rules
        cmd = ['git', 'rev-parse', patches_branch]
        patches_sha1 = subprocess.check_output(cmd).rstrip()

        # Git-buildpackage pq operation
        cmd = ['gbp', 'pq', 'export']
        subprocess.check_call(cmd)

        # Add all patch files to Git's index
        cmd = ['git', 'add', '--all', 'debian/patches']
        subprocess.check_call(cmd)

        # Replace $COMMIT sha1 in d/rules
        with open('debian/rules') as rules:
            rules_file = rules.read()
        old = r'export COMMIT=[0-9a-f]{40}'
        new = 'export COMMIT=%s' % patches_sha1
        with open('debian/rules', 'w') as fileh:
            fileh.write(re.sub(old, new, rules_file))

        # TODO: add patch entries to d/changelog

        # TODO: commit everything with a standard commit message
        # cmd = ['git', 'commit', 'debian/changelog', 'debian/patches',
        #        'debian/rules', '-m', 'add patches from %s' % patches_branch]
        # subprocess.check_call(cmd)

@@ -49,18 +49,16 @@
 ansport%0A
-# 
 import r
@@ -108,16 +108,42 @@
 s util%0A%0A
+BZ_REGEX = r'rhbz#(%5Cd+)'%0A%0A
 %0Aclass P
@@ -1155,24 +1155,309 @@
 ).rstrip()%0A%0A
+        # Switch to %22debian%22 branch%0A        cmd = %5B'gbp', 'pq', 'switch'%5D%0A        subprocess.check_call(cmd)%0A%0A        # Get the original (old) patch series%0A        old_series = self.read_series_file('debian/patches/series')%0A        old_subjects = map(lambda x: x.subject, old_series)%0A%0A
         # Gi
@@ -2029,297 +2029,1315 @@
   # 
-TODO: add patch entries to d/changelog%0A%0A        # TODO: commit everything with a standard commit message%0A        # cmd = %5B'git', 'commit', 'debian/changelog', 'debian/patches',%0A        #        'debian/rules', '-m', 'add patches from %25s' %25 patches_branch%5D%0A        # subprocess.check_call(cmd
+Get the new patch series%0A        new_series = self.read_series_file('debian/patches/series')%0A%0A        # Add patch entries to d/changelog%0A        changelog = %5B%5D%0A        for p in new_series:%0A            if p.subject in old_subjects:%0A                continue%0A            change = p.subject%0A            bzs = self.get_rhbzs(p)%0A            bzstr = ' '.join(map(lambda x: 'rhbz#%25s' %25 x, bzs))%0A            if bzstr != '':%0A                change += ' (%25s)' %25 bzstr%0A            changelog.append(change)%0A        util.bump_changelog(changelog)%0A%0A        # TODO: commit everything with a standard commit message%0A        # cmd = %5B'git', 'commit', 'debian/changelog', 'debian/patches',%0A        #        'debian/rules', '-m', 'add patches from %25s' %25 patches_branch%5D%0A        # subprocess.check_call(cmd)%0A%0A    def get_rhbzs(self, patch):%0A        bzs = re.findall(BZ_REGEX, patch.subject)%0A        bzs.extend(re.findall(BZ_REGEX, patch.long_desc))%0A        return bzs%0A%0A    def read_series_file(self, file_):%0A        try:%0A            from gbp.patch_series import PatchSeries%0A            return PatchSeries.read_series_file(file_)%0A        except ImportError:%0A            log.warning('Please run %22sudo apt-get install '%0A                        'git-buildpackage%22 to write the patches to '%0A                        './debian/changelog'
 )%0A

write changelog with rhbz numbers