Package: git-buildpackage
Version: 0.6.0~git20120419
Severity: wishlist

Dear Maintainer,

Here is my first proposal of moving some gbp.scripts.dch functions to
reusable places.

Included is a pull request and a patch for review.

Regards.

The following changes since commit c57d4af675910ec151cf982532db0f877aef413f:

  gbp.git.repository: Add a "git merge-base" wrapper (2012-05-14 13:16:15 +0200)

are available in the git repository at:

  git://git.baby-gnu.org/git-buildpackage tags/dad/move-spawn_dch-to-ChangeLog

for you to fetch changes up to a141d79488cc5b24d295d864a2f0c164e3933ace:

  Move spawn_dch, add_changelog_entry and add_changelog_section from 
gbp.scripts.dch to gbp.deb.changelog.ChangeLog. (2012-05-15 00:27:07 +0200)

----------------------------------------------------------------
First proposal for review based on actual experimental.

----------------------------------------------------------------
Daniel Dehennin (1):
      Move spawn_dch, add_changelog_entry and add_changelog_section from 
gbp.scripts.dch to gbp.deb.changelog.ChangeLog.

 gbp/deb/changelog.py               |   70 ++++++++++++++++++
 gbp/deb/git.py                     |   17 +++++
 gbp/scripts/dch.py                 |  138 ++++++------------------------------
 tests/03_test_dch_guess_version.py |   11 +--
 4 files changed, 110 insertions(+), 126 deletions(-)


From a141d79488cc5b24d295d864a2f0c164e3933ace Mon Sep 17 00:00:00 2001
From: Daniel Dehennin <daniel.dehen...@baby-gnu.org>
Date: Mon, 14 May 2012 18:15:06 +0200
Subject: [PATCH] Move spawn_dch, add_changelog_entry and
 add_changelog_section from gbp.scripts.dch to
 gbp.deb.changelog.ChangeLog.

This require the move of gbp.scripts.guess_version_from_upstream to
gbp.deb.git.DebianGitRepository.

spawn_dch use gbp.command.wrappers.Command, this require the change of
dch_options from string to list.

* tests/03_test_dch_guess_version.py: Make MockGitRepository inherits
  from DebianGitRepository since guess_version_from_upstream became a
  method of DebianGitRepository.
  Update calls to guess_version_from_upstream accordingly.

* gbp/deb/changelog.py (ChangeLog.spawn_dch): static method imported from
  gbp.scripts.dch and converted to gbp.command_wrappers.Command.
  (add_entry): New method imported from
  gbp.scripts.dch.add_changelog_entry.
  (add_section): New method imported from
  gbp.scripts.dch.add_changelog_entry.

* gbp/deb/git.py: Update imports.
  (guess_version_from_upstream): New method imported from
  gbp.scripts.dch. Remove the logging. Caller is responsible of handling
  possible GitRepositoryError exception.

* gbp/scripts/dch.py: Remove useless import.
  Remove unused functions.
  (process_options): dch_options is now a list.
  (main): Update calls to spawn_dch() to ChangeLog.spawn_dch().
  Update calls to add_changelog_entry() to ChangeLog.add_entry().
  Update calls to add_changelog_section() to ChangeLog.add_section().
  Catch CommandExecFailed exception.
---
 gbp/deb/changelog.py               |   70 ++++++++++++++++++
 gbp/deb/git.py                     |   17 +++++
 gbp/scripts/dch.py                 |  138 ++++++------------------------------
 tests/03_test_dch_guess_version.py |   11 +--
 4 files changed, 110 insertions(+), 126 deletions(-)

diff --git a/gbp/deb/changelog.py b/gbp/deb/changelog.py
index b8c10b8..3ab259d 100644
--- a/gbp/deb/changelog.py
+++ b/gbp/deb/changelog.py
@@ -19,6 +19,7 @@
 import email
 import os
 import subprocess
+from gbp.command_wrappers import Command
 
 class NoChangeLogError(Exception):
     """No changelog found"""
@@ -148,3 +149,72 @@ class ChangeLog(object):
         """
         return self._cp['Date']
 
+    @staticmethod
+    def spawn_dch(msg=[], author=None, email=None, newversion=False, 
version=None,
+                  release=False, distribution=None, dch_options=[]):
+        """
+        Spawn dch
+    
+        @param author: committers name
+        @param email: committers email
+        @param newversion: start a new version
+        @param version: the verion to use
+        @param release: finalize changelog for releaze
+        @param distribution: distribution to use
+        @param dch_options: options passed verbatim to dch
+        """
+        distopt = ""
+        versionopt = ""
+        env = ""
+        args = ['--no-auto-nmu']
+        if newversion:
+            if version:
+                try:
+                    args.append(version['increment'])
+                except KeyError:
+                    args.append('--newversion=%s' % version['version'])
+            else:
+                args.append('-i')
+        elif release:
+            args.append("--release --no-force-save-on-release")
+            msg = None
+    
+        if author and email:
+            env = {'DEBFULLNAME': author, 'DEBEMAIL': email}
+    
+        if distribution:
+            args.append("--distribution=%s" % distribution)
+
+        args.extend(dch_options)
+        args.append('--')
+        if msg:
+            args.append('"[[[insert-git-dch-commit-message-here]]]"')
+        else:
+            args.append('""')
+        dch = Command('dch', args, shell=True, extra_env=env)
+        dch.call([])
+        if msg:
+            old_cl = open("debian/changelog", "r")
+            new_cl = open("debian/changelog.bak", "w")
+            for line in old_cl:
+                if line == "  * [[[insert-git-dch-commit-message-here]]]\n":
+                    print >> new_cl, "  * " + msg[0]
+                    for line in msg[1:]:
+                        print >> new_cl, "    " + line
+                else:
+                    print >> new_cl, line,
+            os.rename("debian/changelog.bak", "debian/changelog")
+
+    def add_entry(self, msg, author, email, dch_options):
+        """Add a single changelog entry"""
+        self.spawn_dch(msg=msg, author=author, email=email, 
dch_options=dch_options)
+
+    def add_section(self, msg, distribution, repo, options,
+                    author=None, email=None, version={}, dch_options=''):
+        """Add a new section to the changelog"""
+        if not version and not self.is_native():
+            v = repo.guess_version_from_upstream(options.upstream_tag, self)
+            if v:
+                version['version'] = v
+        self.spawn_dch(msg=msg, newversion=True, version=version, 
author=author,
+                       email=email, distribution=distribution, 
dch_options=dch_options)
diff --git a/gbp/deb/git.py b/gbp/deb/git.py
index 3f99805..b7acff5 100644
--- a/gbp/deb/git.py
+++ b/gbp/deb/git.py
@@ -19,6 +19,7 @@
 import re
 from gbp.git import GitRepository, GitRepositoryError
 from gbp.deb.pristinetar import PristineTar
+from gbp.deb import compare_versions
 
 class DebianGitRepository(GitRepository):
     """A git repository that holds the source of a Debian package"""
@@ -117,6 +118,22 @@ class DebianGitRepository(GitRepository):
             return version
         return None
 
+    def guess_version_from_upstream(self, upstream_tag_format, cp):
+        """
+        Guess the version based on the latest version on the upstream branch
+        """
+        pattern = upstream_tag_format % dict(version='*')
+        tag = self.find_tag('HEAD', pattern=pattern)
+        version = self.tag_to_version(tag, upstream_tag_format)
+        if version:
+            if cp == None:
+                return "%s-1" % version
+            if cp.has_epoch():
+                version = "%s:%s" % (cp.epoch, version)
+            if compare_versions(version, cp.version) > 0:
+                return "%s-1" % version
+        return None
+    
     @property
     def pristine_tar_branch(self):
         """
diff --git a/gbp/scripts/dch.py b/gbp/scripts/dch.py
index 14dff29..4eb32ed 100644
--- a/gbp/scripts/dch.py
+++ b/gbp/scripts/dch.py
@@ -28,7 +28,6 @@ import gbp.dch as dch
 import gbp.log
 from gbp.config import GbpOptionParserDebian, GbpOptionGroup
 from gbp.errors import GbpError
-from gbp.deb import compare_versions
 from gbp.deb.git import GitRepositoryError, DebianGitRepository
 from gbp.deb.changelog import ChangeLog, NoChangeLogError
 
@@ -36,102 +35,6 @@ user_customizations = {}
 snapshot_re = re.compile("\s*\*\* SNAPSHOT build 
@(?P<commit>[a-z0-9]+)\s+\*\*")
 
 
-def system(cmd):
-    try:
-        gbpc.Command(cmd, shell=True)()
-    except gbpc.CommandExecFailed:
-        raise GbpError
-
-
-def spawn_dch(msg=[], author=None, email=None, newversion=False, version=None,
-              release=False, distribution=None, dch_options=''):
-    """
-    Spawn dch
-
-    @param author: committers name
-    @param email: committers email
-    @param newversion: start a new version
-    @param version: the verion to use
-    @param release: finalize changelog for releaze
-    @param distribution: distribution to use
-    @param dch_options: options passed verbatim to dch
-    """
-    distopt = ""
-    versionopt = ""
-    env = ""
-
-    if newversion:
-        if version:
-            try:
-                versionopt = version['increment']
-            except KeyError:
-                versionopt = '--newversion=%s' % version['version']
-        else:
-            versionopt = '-i'
-    elif release:
-        versionopt = "--release --no-force-save-on-release"
-        msg = None
-
-    if author and email:
-        env = """DEBFULLNAME="%s" DEBEMAIL="%s" """ % (author, email)
-
-    if distribution:
-        distopt = "--distribution=%s" % distribution
-
-    cmd = '%(env)s dch --no-auto-nmu  %(distopt)s %(versionopt)s 
%(dch_options)s ' % locals()
-    if msg:
-        cmd += '-- "[[[insert-git-dch-commit-message-here]]]"'
-    else:
-        cmd += '-- ""'
-    system(cmd)
-    if msg:
-        old_cl = open("debian/changelog", "r")
-        new_cl = open("debian/changelog.bak", "w")
-        for line in old_cl:
-            if line == "  * [[[insert-git-dch-commit-message-here]]]\n":
-                print >> new_cl, "  * " + msg[0]
-                for line in msg[1:]:
-                    print >> new_cl, "    " + line
-            else:
-                print >> new_cl, line,
-        os.rename("debian/changelog.bak", "debian/changelog")
-
-
-def add_changelog_entry(msg, author, email, dch_options):
-    """Add a single changelog entry"""
-    spawn_dch(msg=msg, author=author, email=email, dch_options=dch_options)
-
-
-def guess_version_from_upstream(repo, upstream_tag_format, cp):
-    """
-    Guess the version based on the latest version on the upstream branch
-    """
-    pattern = upstream_tag_format % dict(version='*')
-    try:
-        tag = repo.find_tag('HEAD', pattern=pattern)
-        version = repo.tag_to_version(tag, upstream_tag_format)
-        if version:
-            gbp.log.debug("Found upstream version %s." % version)
-            if cp.has_epoch():
-                version = "%s:%s" % (cp.epoch, version)
-            if compare_versions(version, cp.version) > 0:
-                return "%s-1" % version
-    except GitRepositoryError:
-        gbp.log.debug("No tag found matching pattern %s." % pattern)
-    return None
-
-
-def add_changelog_section(msg, distribution, repo, options, cp,
-                          author=None, email=None, version={}, dch_options=''):
-    """Add a new section to the changelog"""
-    if not version and not cp.is_native():
-        v = guess_version_from_upstream(repo, options.upstream_tag, cp)
-        if v:
-            version['version'] = v
-    spawn_dch(msg=msg, newversion=True, version=version, author=author,
-              email=email, distribution=distribution, dch_options=dch_options)
-
-
 def get_author_email(repo, use_git_config):
     """Get author and email from git configuration"""
     author = email = None
@@ -153,7 +56,7 @@ def fixup_trailer(repo, git_author, dch_options):
     creating the changelog
     """
     author, email = get_author_email(repo, git_author)
-    spawn_dch(msg='', author=author, email=email, dch_options=dch_options)
+    ChangeLog.spawn_dch(msg='', author=author, email=email, 
dch_options=dch_options)
 
 
 def snapshot_version(version):
@@ -294,15 +197,16 @@ def process_options(options, parser):
     if options.since and options.auto:
         parser.error("'--since' and '--auto' are incompatible options")
 
+    dch_options = []
     if options.multimaint_merge:
-        dch_options = "--multimaint-merge"
+        dch_options.append("--multimaint-merge")
     else:
-        dch_options = "--nomultimaint-merge"
+        dch_options.append("--nomultimaint-merge")
 
     if options.multimaint:
-        dch_options += " --multimaint"
+        dch_options.append(" --multimaint")
     else:
-        dch_options += " --nomultimaint"
+        dch_options.append(" --nomultimaint")
 
     get_customizations(options.customization_file)
     return dch_options
@@ -481,18 +385,17 @@ def main(argv):
             if add_section:
                 # Add a section containing just this message (we can't
                 # add an empty section with dch)
-                add_changelog_section(distribution="UNRELEASED", 
msg=commit_msg,
-                                      version=version_change,
-                                      author=commit_author,
-                                      email=commit_email,
-                                      dch_options=dch_options,
-                                      repo=repo,
-                                      options=options,
-                                      cp=cp)
+                cp.add_section(distribution="UNRELEASED", msg=commit_msg,
+                               version=version_change,
+                               author=commit_author,
+                               email=commit_email,
+                               dch_options=dch_options,
+                               repo=repo,
+                               options=options)
                 # Adding a section only needs to happen once.
                 add_section = False
             else:
-                add_changelog_entry(commit_msg, commit_author, commit_email, 
dch_options)
+                cp.add_entry(commit_msg, commit_author, commit_email, 
dch_options)
 
 
         # Show a message if there were no commits (not even ignored
@@ -503,12 +406,11 @@ def main(argv):
         if add_section:
             # If we end up here, then there were no commits to include,
             # so we put a dummy message in the new section.
-            add_changelog_section(distribution="UNRELEASED", 
msg=["UNRELEASED"],
-                                  version=version_change,
-                                  dch_options=dch_options,
-                                  repo=repo,
-                                  options=options,
-                                  cp=cp)
+            cp.add_section(distribution="UNRELEASED", msg=["UNRELEASED"],
+                           version=version_change,
+                           dch_options=dch_options,
+                           repo=repo,
+                           options=options)
 
         fixup_trailer(repo, git_author=options.git_author,
                       dch_options=dch_options)
@@ -533,7 +435,7 @@ def main(argv):
             repo.commit_files([changelog], msg)
             gbp.log.info("Changelog has been committed for version %s" % 
version)
 
-    except (GbpError, GitRepositoryError, NoChangeLogError), err:
+    except (CommandExecFailed, GbpError, GitRepositoryError, 
NoChangeLogError), err:
         if len(err.__str__()):
             gbp.log.err(err)
         ret = 1
diff --git a/tests/03_test_dch_guess_version.py 
b/tests/03_test_dch_guess_version.py
index d954459..ba80a3b 100644
--- a/tests/03_test_dch_guess_version.py
+++ b/tests/03_test_dch_guess_version.py
@@ -4,12 +4,11 @@
 
 import unittest
 
-from gbp.scripts import dch
 from gbp.errors import GbpError
 from gbp.deb.changelog import ChangeLog
 from gbp.deb.git import DebianGitRepository
 
-class MockGitRepository(object):
+class MockGitRepository(DebianGitRepository):
     def __init__(self, upstream_tag):
         self.upstream_tag = upstream_tag
 
@@ -37,18 +36,14 @@ class TestGuessVersionFromUpstream(unittest.TestCase):
         """Guess the new version from the upstream tag"""
         repo = MockGitRepository(upstream_tag='upstream/1.1')
         cp = MockedChangeLog('1.0-1')
-        guessed = dch.guess_version_from_upstream(repo,
-                                                  'upstream/%(version)s',
-                                                  cp)
+        guessed = repo.guess_version_from_upstream('upstream/%(version)s', cp)
         self.assertEqual('1.1-1', guessed)
 
     def test_guess_epoch(self):
         """Check if we picked up the epoch correctly (#652366)"""
         repo = MockGitRepository(upstream_tag='upstream/1.1')
         cp = MockedChangeLog('1:1.0-1')
-        guessed = dch.guess_version_from_upstream(repo,
-                                                  'upstream/%(version)s',
-                                                  cp)
+        guessed = repo.guess_version_from_upstream('upstream/%(version)s', cp)
         self.assertEqual('1:1.1-1', guessed)
 
 
-- 
1.7.10


-- System Information:
Debian Release: wheezy/sid
  APT prefers unstable
  APT policy: (500, 'unstable'), (500, 'testing'), (90, 'experimental')
Architecture: amd64 (x86_64)

Kernel: Linux 3.2.4+hati.1+ (SMP w/2 CPU cores; PREEMPT)
Locale: LANG=fr_FR.UTF-8, LC_CTYPE=fr_FR.UTF-8 (charmap=UTF-8)
Shell: /bin/sh linked to /bin/bash

Versions of packages git-buildpackage depends on:
ii  devscripts       2.11.6
ii  git              1:1.7.10-1
ii  python           2.7.2-10
ii  python-dateutil  1.5-1
ii  python2.6        2.6.7-4
ii  python2.7        2.7.3~rc2-2.1

Versions of packages git-buildpackage recommends:
ii  cowbuilder    <none>
ii  pristine-tar  1.24

Versions of packages git-buildpackage suggests:
ii  python-notify  0.1.1-3
ii  unzip          6.0-6

-- no debconf information

-- debsums errors found:
debsums: changed file /usr/share/pyshared/gbp/deb/changelog.py (from 
git-buildpackage package)
debsums: changed file /usr/share/pyshared/gbp/scripts/dch.py (from 
git-buildpackage package)

-- 
Daniel Dehennin
Récupérer ma clef GPG:
gpg --keyserver pgp.mit.edu --recv-keys 0x7A6FE2DF

Attachment: pgprFIY14roRG.pgp
Description: PGP signature

Reply via email to