Skip to contentSkip to conversation

Infrastructure rewrite series

PATCH In review Karl Hasselström 2 participants 14 messages Jun 15, 2016

lore
Share & tools
lore
#0 lore raw

cover Infrastructure rewrite series

I've expanded on the infrastructure rewrite series. As of now, clean, applied, unapplied, goto, uncommit, and the new command coalesce have been converted.

The main new development is support for index and worktree operations, so that it can do conflicting merges. This made it possible to convert "stg goto", but the main practical attraction is the vastly improved "stg coalesce", which can now take an arbitrary list of patches and reorder them so that they can be joined to one big patch. It will do so entirely automatically if the merges resolve automatically, and if they don't it will pretend to have done a series of pops, pushes, and deletes, and leave the user to manually resolve the first conflicting push.

The implementation of coalesce -- particularly the ability to fail gracefully on conflicts at any intermediate step -- is helped a lot by some new cool transaction stuff.

Available from

git://repo.or.cz/stgit/kha.git experimental

---

Karl Hasselström (10):
Convert "stg uncommit" to the new infrastructure
Let "stg goto" use the new infrastructure
Let "stg clean" use the new transaction primitives Teach the new infrastructure about the index and worktree Let "stg applied" and "stg unapplied" use the new infrastructure Add "stg coalesce"
Let "stg clean" use the new infrastructure
Upgrade older stacks to newest version
Write metadata files used by the old infrastructure New StGit core infrastructure: repository operations

 contrib/stgit-completion.bash |    2 
 setup.py                      |    2 
 stgit/commands/applied.py     |   27 +--
 stgit/commands/clean.py       |   49 ++---
 stgit/commands/coalesce.py    |  109 ++++++++++++
 stgit/commands/common.py      |   10 +
 stgit/commands/goto.py        |   52 ++----
 stgit/commands/unapplied.py   |   23 +-
 stgit/commands/uncommit.py    |   79 ++++----
 stgit/lib/__init__.py         |   18 ++
 stgit/lib/git.py              |  383 +++++++++++++++++++++++++++++++++++++++++
 stgit/lib/stack.py            |  168 ++++++++++++++++++
 stgit/lib/stackupgrade.py     |   96 ++++++++++
 stgit/lib/transaction.py      |  194 +++++++++++++++++++++
 stgit/main.py                 |    2 
 stgit/stack.py                |  100 +----------
 stgit/utils.py                |   24 +++
 t/t2600-coalesce.sh           |   31 +++
 18 files changed, 1136 insertions(+), 233 deletions(-)
 create mode 100644 stgit/commands/coalesce.py
 create mode 100644 stgit/lib/__init__.py
 create mode 100644 stgit/lib/git.py
 create mode 100644 stgit/lib/stack.py
 create mode 100644 stgit/lib/stackupgrade.py
 create mode 100644 stgit/lib/transaction.py
 create mode 100755 t/t2600-coalesce.sh
Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#1 lore raw

PATCH 1/10 New StGit core infrastructure: repository operations

This is the first part of the New and Improved StGit core infrastructure. It has functions for manipulating the git repository (commits, refs, and so on), but doesn't yet touch the index or worktree.

Currently not used by anything.

---

 setup.py                 |    2 
 stgit/lib/__init__.py    |   18 +++
 stgit/lib/git.py         |  253 ++++++++++++++++++++++++++++++++++++++++++++++
 stgit/lib/stack.py       |  120 ++++++++++++++++++++++
 stgit/lib/transaction.py |   79 ++++++++++++++
 stgit/utils.py           |   13 ++
 6 files changed, 484 insertions(+), 1 deletions(-)
 create mode 100644 stgit/lib/__init__.py
 create mode 100644 stgit/lib/git.py
 create mode 100644 stgit/lib/stack.py
 create mode 100644 stgit/lib/transaction.py
setup.py +1 -1
index cf5b1da..cad8f7e 100755
@@ -14,7 +14,7 @@ setup(name = 'stgit',
       description = 'Stacked GIT',
       long_description = 'Push/pop utility on top of GIT',
       scripts = ['stg'],
-      packages = ['stgit', 'stgit.commands'],
+      packages = ['stgit', 'stgit.commands', 'stgit.lib'],
       data_files = [('share/stgit/templates', glob.glob('templates/*.tmpl')),
                     ('share/stgit/examples', glob.glob('examples/*.tmpl')),
                     ('share/stgit/examples', ['examples/gitconfig']),
stgit/lib/__init__.py renamed from stgit/__init__.py +3 -1
similarity index 88%
copy from stgit/__init__.py
copy to stgit/lib/__init__.py
index 4b03e3a..45eb307 100644
@@ -1,5 +1,7 @@
+# -*- coding: utf-8 -*-
+
 __copyright__ = """
-Copyright (C) 2005, Catalin Marinas <[email protected]>
+Copyright (C) 2007, Karl Hasselström <[email protected]>
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License version 2 as
stgit/lib/git.py new file +253 -0

253 lines not on this page · raw message

stgit/lib/stack.py new file +120 -0

120 lines not on this page · raw message

stgit/lib/transaction.py new file +79 -0

79 lines not on this page · raw message

stgit/utils.py +13 -0
index 3a480c0..b3f6232 100644
@@ -256,3 +256,16 @@ def add_sign_line(desc, sign_str, name, email):
     if not any(s in desc for s in ['\nSigned-off-by:', '\nAcked-by:']):
         desc = desc + '\n'
     return '%s\n%s\n' % (desc, sign_str)
+
+def strip_leading(prefix, s):
+    """Strip leading prefix from a string. Blow up if the prefix isn't
+    there."""
+    assert s.startswith(prefix)
+    return s[len(prefix):]
+
+def add_dict(d1, d2):
+    """Return a new dict with the contents of both d1 and d2. In case of
+    conflicting mappings, d2 takes precedence."""
+    d = dict(d1)
+    d.update(d2)
+    return d
#2 lore raw

PATCH 2/10 Write metadata files used by the old infrastructure

In reply to Karl Hasselström

The new infrastructure doesn't use them, but they're needed to support the old infrastructure during the transition when both of them are in use.

---

 stgit/lib/stack.py |   52 +++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 49 insertions(+), 3 deletions(-)
stgit/lib/stack.py +49 -3
index d5bd488..5a34592 100644
@@ -7,15 +7,61 @@ class Patch(object):
         self.__stack = stack
         self.__name = name
     name = property(lambda self: self.__name)
+    @property
     def __ref(self):
         return 'refs/patches/%s/%s' % (self.__stack.name, self.__name)
     @property
+    def __log_ref(self):
+        return self.__ref + '.log'
+    @property
     def commit(self):
-        return self.__stack.repository.refs.get(self.__ref())
+        return self.__stack.repository.refs.get(self.__ref)
+    @property
+    def __compat_dir(self):
+        return os.path.join(self.__stack.directory, 'patches', self.__name)
+    def __write_compat_files(self, new_commit, msg):
+        """Write files used by the old infrastructure."""
+        def write(name, val, multiline = False):
+            fn = os.path.join(self.__compat_dir, name)
+            if val:
+                utils.write_string(fn, val, multiline)
+            elif os.path.isfile(fn):
+                os.remove(fn)
+        def write_patchlog():
+            try:
+                old_log = [self.__stack.repository.refs.get(self.__log_ref)]
+            except KeyError:
+                old_log = []
+            cd = git.Commitdata(tree = new_commit.data.tree, parents = old_log,
+                                message = '%s\t%s' % (msg, new_commit.sha1))
+            c = self.__stack.repository.commit(cd)
+            self.__stack.repository.refs.set(self.__log_ref, c, msg)
+            return c
+        d = new_commit.data
+        write('authname', d.author.name)
+        write('authemail', d.author.email)
+        write('authdate', d.author.date)
+        write('commname', d.committer.name)
+        write('commemail', d.committer.email)
+        write('description', d.message)
+        write('log', write_patchlog().sha1)
+        try:
+            old_commit_sha1 = self.commit
+        except KeyError:
+            old_commit_sha1 = None
+        write('top.old', old_commit_sha1)
+    def __delete_compat_files(self):
+        if os.path.isdir(self.__compat_dir):
+            for f in os.listdir(self.__compat_dir):
+                os.remove(os.path.join(self.__compat_dir, f))
+            os.rmdir(self.__compat_dir)
+        self.__stack.repository.refs.delete(self.__log_ref)
     def set_commit(self, commit, msg):
-        self.__stack.repository.refs.set(self.__ref(), commit, msg)
+        self.__write_compat_files(commit, msg)
+        self.__stack.repository.refs.set(self.__ref, commit, msg)
     def delete(self):
-        self.__stack.repository.refs.delete(self.__ref())
+        self.__delete_compat_files()
+        self.__stack.repository.refs.delete(self.__ref)
     def is_applied(self):
         return self.name in self.__stack.patchorder.applied
     def is_empty(self):
#3 lore raw

PATCH 3/10 Upgrade older stacks to newest version

In reply to Karl Hasselström

This is of course needed by the new infrastructure as well. So break it out into its own file, where it can be used by both new and old infrastructure. This has the added benefit of making it easy to see that the upgrade code doesn't depend on anything it shouldn't.

---

 stgit/lib/git.py          |    7 +++
 stgit/lib/stack.py        |    3 +
 stgit/lib/stackupgrade.py |   96 +++++++++++++++++++++++++++++++++++++++++++
 stgit/stack.py            |  100 +++------------------------------------------
 4 files changed, 112 insertions(+), 94 deletions(-)
 create mode 100644 stgit/lib/stackupgrade.py
stgit/lib/git.py +7 -0
index 120ea35..c4011f9 100644
@@ -160,6 +160,13 @@ class Refs(object):
         if self.__refs == None:
             self.__cache_refs()
         return self.__repository.get_commit(self.__refs[ref])
+    def exists(self, ref):
+        try:
+            self.get(ref)
+        except KeyError:
+            return False
+        else:
+            return True
     def set(self, ref, commit, msg):
         if self.__refs == None:
             self.__cache_refs()
stgit/lib/stack.py +2 -1
index 5a34592..8fc8b08 100644
@@ -1,6 +1,6 @@
 import os.path
 from stgit import exception, utils
-from stgit.lib import git
+from stgit.lib import git, stackupgrade
 
 class Patch(object):
     def __init__(self, stack, name):
@@ -128,6 +128,7 @@ class Stack(object):
             raise exception.StgException('%s: no such branch' % name)
         self.__patchorder = PatchOrder(self)
         self.__patches = Patches(self)
+        stackupgrade.update_to_current_format_version(repository, name)
     name = property(lambda self: self.__name)
     repository = property(lambda self: self.__repository)
     patchorder = property(lambda self: self.__patchorder)
stgit/lib/stackupgrade.py new file +96 -0

96 lines not on this page · raw message

stgit/stack.py +7 -93

136 lines not on this page · raw message

#4 lore raw

PATCH 4/10 Let "stg clean" use the new infrastructure

In reply to Karl Hasselström

---

 stgit/commands/clean.py  |   68 ++++++++++++++++++++++++----------------------
 stgit/commands/common.py |   10 ++++++-
 2 files changed, 44 insertions(+), 34 deletions(-)
stgit/commands/clean.py +35 -33
index c703418..bbea253 100644
@@ -15,14 +15,10 @@ along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 """
 
-import sys, os
-from optparse import OptionParser, make_option
-
-from stgit.commands.common import *
-from stgit.utils import *
+from optparse import make_option
 from stgit.out import *
-from stgit import stack, git
-
+from stgit.commands import common
+from stgit.lib import transaction
 
 help = 'delete the empty patches in the series'
 usage = """%prog [options]
@@ -31,7 +27,7 @@ Delete the empty patches in the whole series or only those applied or
 unapplied. A patch is considered empty if the two commit objects
 representing its boundaries refer to the same tree object."""
 
-directory = DirectoryGotoToplevel()
+directory = common.DirectoryHasRepositoryLib()
 options = [make_option('-a', '--applied',
                        help = 'delete the empty applied patches',
                        action = 'store_true'),
@@ -40,18 +36,35 @@ options = [make_option('-a', '--applied',
                        action = 'store_true')]
 
 
-def __delete_empty(patches, applied):
-    """Delete the empty patches
-    """
-    for p in patches:
-        if crt_series.empty_patch(p):
-            out.start('Deleting patch "%s"' % p)
-            if applied and crt_series.patch_applied(p):
-                crt_series.pop_patch(p)
-            crt_series.delete_patch(p)
-            out.done()
-        elif applied and crt_series.patch_unapplied(p):
-            crt_series.push_patch(p)
+def _clean(stack, clean_applied, clean_unapplied):
+    def deleting(pn):
+        out.info('Deleting empty patch %s' % pn)
+    trans = transaction.StackTransaction(stack, 'clean')
+    if clean_unapplied:
+        trans.unapplied = []
+        for pn in stack.patchorder.unapplied:
+            p = stack.patches.get(pn)
+            if p.is_empty():
+                trans.patches[pn] = None
+                deleting(pn)
+            else:
+                trans.unapplied.append(pn)
+    if clean_applied:
+        trans.applied = []
+        parent = stack.base
+        for pn in stack.patchorder.applied:
+            p = stack.patches.get(pn)
+            if p.is_empty():
+                trans.patches[pn] = None
+                deleting(pn)
+            else:
+                if parent != p.commit.data.parent:
+                    parent = trans.patches[pn] = stack.repository.commit(
+                        p.commit.data.set_parent(parent))
+                else:
+                    parent = p.commit
+                trans.applied.append(pn)
+    trans.run()
 
 def func(parser, options, args):
     """Delete the empty patches in the series
@@ -59,19 +72,8 @@ def func(parser, options, args):
     if len(args) != 0:
         parser.error('incorrect number of arguments')
 
-    check_local_changes()
-    check_conflicts()
-    check_head_top_equal(crt_series)
-
     if not (options.applied or options.unapplied):
         options.applied = options.unapplied = True
 
-    if options.applied:
-        applied = crt_series.get_applied()
-        __delete_empty(applied, True)
-
-    if options.unapplied:
-        unapplied = crt_series.get_unapplied()
-        __delete_empty(unapplied, False)
-
-    print_crt_patch(crt_series)
+    _clean(directory.repository.current_stack,
+           options.applied, options.unapplied)
stgit/commands/common.py +9 -1
index 36202dd..6271572 100644
@@ -27,7 +27,7 @@ from stgit.out import *
 from stgit.run import *
 from stgit import stack, git, basedir
 from stgit.config import config, file_extensions
-
+from stgit.lib import stack as libstack
 
 # Command exception class
 class CmdException(StgException):
@@ -537,3 +537,11 @@ class DirectoryGotoToplevel(DirectoryInWorktree):
     def setup(self):
         DirectoryInWorktree.setup(self)
         self.cd_to_topdir()
+
+class DirectoryHasRepositoryLib(_Directory):
+    """For commands that use the new infrastructure in stgit.lib.*."""
+    def __init__(self):
+        self.needs_current_series = False
+    def setup(self):
+        # This will throw an exception if we don't have a repository.
+        self.repository = libstack.Repository.default()
#5 lore raw

PATCH 5/10 Add "stg coalesce"

In reply to Karl Hasselström

It coalesces two or more consecutive applied patches, with no need to touch index/worktree, and no possibiliy of conflicts.

Future improvements could relax the "consecutive" and "applied" restrictions, by building a new chain of commits just like "stg push" will do once it's been converted to the new infrastructure.

---

 contrib/stgit-completion.bash |    2 +
 stgit/commands/coalesce.py    |   84 +++++++++++++++++++++++++++++++++++++++++
 stgit/main.py                 |    2 +
 stgit/utils.py                |   11 +++++
 t/t2600-coalesce.sh           |   31 +++++++++++++++
 5 files changed, 130 insertions(+), 0 deletions(-)
 create mode 100644 stgit/commands/coalesce.py
 create mode 100755 t/t2600-coalesce.sh
contrib/stgit-completion.bash +2 -0
index b3b23d4..b02eb64 100644
@@ -18,6 +18,7 @@ _stg_commands="
     diff
     clean
     clone
+    coalesce
     commit
     cp
     edit
@@ -238,6 +239,7 @@ _stg ()
         # repository commands
         id)     _stg_patches $command _all_patches ;;
         # stack commands
+        coalesce) _stg_patches $command _applied_patches ;;
         float)  _stg_patches $command _all_patches ;;
         goto)   _stg_patches $command _all_other_patches ;;
         hide)   _stg_patches $command _unapplied_patches ;;
stgit/commands/coalesce.py new file +84 -0

84 lines not on this page · raw message

stgit/main.py +2 -0
index deaac91..384803b 100644
@@ -64,6 +64,7 @@ commands = Commands({
     'diff':             'diff',
     'clean':            'clean',
     'clone':            'clone',
+    'coalesce':         'coalesce',
     'commit':           'commit',
     'edit':             'edit',
     'export':           'export',
@@ -108,6 +109,7 @@ stackcommands = (
     'applied',
     'branch',
     'clean',
+    'coalesce',
     'commit',
     'float',
     'goto',
stgit/utils.py +11 -0
index b3f6232..688276c 100644
@@ -189,6 +189,17 @@ def call_editor(filename):
         raise EditorException, 'editor failed, exit code: %d' % err
     out.done()
 
+def edit_string(s, filename):
+    f = file(filename, 'w')
+    f.write(s)
+    f.close()
+    call_editor(filename)
+    f = file(filename)
+    s = f.read()
+    f.close()
+    os.remove(filename)
+    return s
+
 def patch_name_from_msg(msg):
     """Return a string to be used as a patch name. This is generated
     from the top line of the string passed as argument."""
t/t2600-coalesce.sh new file +31 -0
new file mode 100755
index 0000000..f13a309
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+test_description='Run "stg coalesce"'
+
+. ./test-lib.sh
+
+test_expect_success 'Initialize StGit stack' '
+    stg init &&
+    for i in 0 1 2 3; do
+        stg new p$i -m "foo $i" &&
+        echo "foo $i" >> foo.txt &&
+        git add foo.txt &&
+        stg refresh
+    done
+'
+
+test_expect_success 'Coalesce some patches' '
+    [ "$(echo $(stg applied))" = "p0 p1 p2 p3" ] &&
+    [ "$(echo $(stg unapplied))" = "" ] &&
+    stg coalesce --name=q0 --message="wee woo" p1 p2 &&
+    [ "$(echo $(stg applied))" = "p0 q0 p3" ] &&
+    [ "$(echo $(stg unapplied))" = "" ]
+'
+
+test_expect_success 'Coalesce at stack top' '
+    stg coalesce --name=q1 --message="wee woo wham" q0 p3 &&
+    [ "$(echo $(stg applied))" = "p0 q1" ] &&
+    [ "$(echo $(stg unapplied))" = "" ]
+'
+
+test_done
#6 lore raw

PATCH 6/10 Let "stg applied" and "stg unapplied" use the new infrastructure

In reply to Karl Hasselström

This is a trivial change since these commands are so simple, but because these are the commands used by t4000-upgrade, we now test that the new infrastructure can upgrade old stacks.

---

 stgit/commands/applied.py   |   27 +++++++++++++--------------
 stgit/commands/unapplied.py |   23 +++++++++++------------
 2 files changed, 24 insertions(+), 26 deletions(-)
stgit/commands/applied.py +13 -14
index 45d0926..522425b 100644
@@ -16,25 +16,21 @@ along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 """
 
-import sys, os
-from optparse import OptionParser, make_option
-
-from stgit.commands.common import *
-from stgit.utils import *
+from optparse import make_option
 from stgit.out import *
-from stgit import stack, git
+from stgit.commands import common
 
 
 help = 'print the applied patches'
 usage = """%prog [options]
 
-List the patches from the series which were already pushed onto the
-stack.  They are listed in the order in which they were pushed, the
+List the patches from the series which have already been pushed onto
+the stack. They are listed in the order in which they were pushed, the
 last one being the current (topmost) patch."""
 
-directory = DirectoryHasRepository()
+directory = common.DirectoryHasRepositoryLib()
 options = [make_option('-b', '--branch',
-                       help = 'use BRANCH instead of the default one'),
+                       help = 'use BRANCH instead of the default branch'),
            make_option('-c', '--count',
                        help = 'print the number of applied patches',
                        action = 'store_true')]
@@ -46,10 +42,13 @@ def func(parser, options, args):
     if len(args) != 0:
         parser.error('incorrect number of arguments')
 
-    applied = crt_series.get_applied()
+    if options.branch:
+        s = directory.repository.get_stack(options.branch)
+    else:
+        s = directory.repository.current_stack
 
     if options.count:
-        out.stdout(len(applied))
+        out.stdout(len(s.patchorder.applied))
     else:
-        for p in applied:
-            out.stdout(p)
+        for pn in s.patchorder.applied:
+            out.stdout(pn)
stgit/commands/unapplied.py +11 -12
index d5bb43e..7702207 100644
@@ -16,13 +16,9 @@ along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 """
 
-import sys, os
-from optparse import OptionParser, make_option
-
-from stgit.commands.common import *
-from stgit.utils import *
+from optparse import make_option
 from stgit.out import *
-from stgit import stack, git
+from stgit.commands import common
 
 
 help = 'print the unapplied patches'
@@ -31,9 +27,9 @@ usage = """%prog [options]
 List the patches from the series which are not pushed onto the stack.
 They are listed in the reverse order in which they were popped."""
 
-directory = DirectoryHasRepository()
+directory = common.DirectoryHasRepositoryLib()
 options = [make_option('-b', '--branch',
-                       help = 'use BRANCH instead of the default one'),
+                       help = 'use BRANCH instead of the default branch'),
            make_option('-c', '--count',
                        help = 'print the number of unapplied patches',
                        action = 'store_true')]
@@ -45,10 +41,13 @@ def func(parser, options, args):
     if len(args) != 0:
         parser.error('incorrect number of arguments')
 
-    unapplied = crt_series.get_unapplied()
+    if options.branch:
+        s = directory.repository.get_stack(options.branch)
+    else:
+        s = directory.repository.current_stack
 
     if options.count:
-        out.stdout(len(unapplied))
+        out.stdout(len(s.patchorder.unapplied))
     else:
-        for p in unapplied:
-            out.stdout(p)
+        for pn in s.patchorder.unapplied:
+            out.stdout(pn)
#7 lore raw

PATCH 7/10 Teach the new infrastructure about the index and worktree

In reply to Karl Hasselström

And use the new powers to make "stg coalesce" able to handle arbitrary patches, not just consecutive applied patches.

---

 stgit/commands/clean.py    |    4 +
 stgit/commands/coalesce.py |   93 ++++++++++++++++---------
 stgit/lib/git.py           |  123 ++++++++++++++++++++++++++++++++++
 stgit/lib/stack.py         |    7 +-
 stgit/lib/transaction.py   |  161 ++++++++++++++++++++++++++++++++++++++------
 5 files changed, 326 insertions(+), 62 deletions(-)
stgit/commands/clean.py +2 -2
index bbea253..e2d1678 100644
@@ -44,7 +44,7 @@ def _clean(stack, clean_applied, clean_unapplied):
         trans.unapplied = []
         for pn in stack.patchorder.unapplied:
             p = stack.patches.get(pn)
-            if p.is_empty():
+            if p.commit.data.is_empty():
                 trans.patches[pn] = None
                 deleting(pn)
             else:
@@ -54,7 +54,7 @@ def _clean(stack, clean_applied, clean_unapplied):
         parent = stack.base
         for pn in stack.patchorder.applied:
             p = stack.patches.get(pn)
-            if p.is_empty():
+            if p.commit.data.is_empty():
                 trans.patches[pn] = None
                 deleting(pn)
             else:
stgit/commands/coalesce.py +59 -34

109 lines not on this page · raw message

stgit/lib/git.py +123 -0

138 lines not on this page · raw message

stgit/lib/stack.py +4 -3
index 8fc8b08..b4512b1 100644
@@ -64,9 +64,6 @@ class Patch(object):
         self.__stack.repository.refs.delete(self.__ref)
     def is_applied(self):
         return self.name in self.__stack.patchorder.applied
-    def is_empty(self):
-        c = self.commit
-        return c.data.tree == c.data.parent.data.tree
 
 class PatchOrder(object):
     """Keeps track of patch order, and which patches are applied.
@@ -150,6 +147,10 @@ class Stack(object):
                                     ).commit.data.parent
         else:
             return self.head
+    def head_top_equal(self):
+        if not self.patchorder.applied:
+            return True
+        return self.head == self.patches.get(self.patchorder.applied[-1]).commit
 
 class Repository(git.Repository):
     def __init__(self, *args, **kwargs):
stgit/lib/transaction.py +138 -23

205 lines not on this page · raw message

#8 lore raw

Re: [StGit PATCH 07/10] Teach the new infrastructure about the index and worktree

Quoted 2 lines · Karl Hasselström

And use the new powers to make "stg coalesce" able to handle arbitrary patches, not just consecutive applied patches.

Obviously, this should come with an updated help text for "stg coalesce". Will amend the patch.

stgit/commands/coalesce.py +5 -2
index 2b121a9..6c0ae6d 100644
@@ -27,8 +27,11 @@ help = 'coalesce two or more patches into one'
 usage = """%prog [options] <patches>
 
 Coalesce two or more patches, creating one big patch that contains all
-their changes. The patches must all be applied, and must be
-consecutive."""
+their changes.
+
+If there are conflicts when reordering the patches to match the order
+you specify, you will have to resolve them manually just as if you had
+done a sequence of pushes and pops yourself."""
 
 directory = common.DirectoryHasRepositoryLib()
 options = [make_option('-n', '--name', help = 'name of coalesced patch'),
Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#9 lore raw

Re: [StGit PATCH 07/10] Teach the new infrastructure about the index and worktree

In reply to Karl Hasselström

stgit/lib/git.py class Commitdata(Repr): · line 102

Quoted 11 lines · Karl Hasselström
stgit/lib/git.py +2 -0
@@ -95,6 +95,8 @@ class Commitdata(Repr):
         return type(self)(committer = committer, defaults = self)
     def set_message(self, message):
         return type(self)(message = message, defaults = self)
+    def is_empty(self):
+        return self.tree == self.parent.data.tree
     def __str__(self):
         if self.tree == None:
             tree = None

But a Commitdata describes a Git commit, right? And not an StGit patch. So what does it mean to say that a commit is empty? I could just as well mean that the tree is the null tree.

I think I would have called this "is_nochange" or something.

Signature · 1 line
David Kågedal
#10 lore raw

Re: [StGit PATCH 07/10] Teach the new infrastructure about the index and worktree

Quoted 16 lines · David Kågedal

stgit/lib/git.py class Commitdata(Repr): · line 102

Quoted 11 lines · Karl Hasselström
stgit/lib/git.py +2 -0
@@ -95,6 +95,8 @@ class Commitdata(Repr):
         return type(self)(committer = committer, defaults = self)
     def set_message(self, message):
         return type(self)(message = message, defaults = self)
+    def is_empty(self):
+        return self.tree == self.parent.data.tree
     def __str__(self):
         if self.tree == None:
             tree = None

But a Commitdata describes a Git commit, right? And not an StGit patch.

Yes.

Quoted 3 lines

So what does it mean to say that a commit is empty? I could just as well mean that the tree is the null tree. I think I would have called this "is_nochange" or something.

Good point.

Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#11 lore raw

PATCH 8/10 Let "stg clean" use the new transaction primitives

In reply to Karl Hasselström

---

 stgit/commands/clean.py |   33 +++++++--------------------------
 1 files changed, 7 insertions(+), 26 deletions(-)
stgit/commands/clean.py +7 -26
index e2d1678..cfcc004 100644
@@ -37,33 +37,14 @@ options = [make_option('-a', '--applied',
 
 
 def _clean(stack, clean_applied, clean_unapplied):
-    def deleting(pn):
-        out.info('Deleting empty patch %s' % pn)
     trans = transaction.StackTransaction(stack, 'clean')
-    if clean_unapplied:
-        trans.unapplied = []
-        for pn in stack.patchorder.unapplied:
-            p = stack.patches.get(pn)
-            if p.commit.data.is_empty():
-                trans.patches[pn] = None
-                deleting(pn)
-            else:
-                trans.unapplied.append(pn)
-    if clean_applied:
-        trans.applied = []
-        parent = stack.base
-        for pn in stack.patchorder.applied:
-            p = stack.patches.get(pn)
-            if p.commit.data.is_empty():
-                trans.patches[pn] = None
-                deleting(pn)
-            else:
-                if parent != p.commit.data.parent:
-                    parent = trans.patches[pn] = stack.repository.commit(
-                        p.commit.data.set_parent(parent))
-                else:
-                    parent = p.commit
-                trans.applied.append(pn)
+    def del_patch(pn):
+        if pn in stack.patchorder.applied:
+            return clean_applied and trans.patches[pn].data.is_empty()
+        elif pn in stack.patchorder.unapplied:
+            return clean_unapplied and trans.patches[pn].data.is_empty()
+    for pn in trans.delete_patches(del_patch):
+        trans.push_patch(pn)
     trans.run()
 
 def func(parser, options, args):
#12 lore raw

PATCH 9/10 Let "stg goto" use the new infrastructure

In reply to Karl Hasselström

In the process, it loses the --keep option, since the new infrastructure always keeps local changes (and aborts cleanly if they are in the way).

---

 stgit/commands/clean.py |    2 +-
 stgit/commands/goto.py  |   52 ++++++++++++++++-------------------------------
 2 files changed, 19 insertions(+), 35 deletions(-)
stgit/commands/clean.py +1 -1
index cfcc004..55ab858 100644
@@ -37,7 +37,7 @@ options = [make_option('-a', '--applied',
 
 
 def _clean(stack, clean_applied, clean_unapplied):
-    trans = transaction.StackTransaction(stack, 'clean')
+    trans = transaction.StackTransaction(stack, 'stg clean')
     def del_patch(pn):
         if pn in stack.patchorder.applied:
             return clean_applied and trans.patches[pn].data.is_empty()
stgit/commands/goto.py +18 -34

69 lines not on this page · raw message

#13 lore raw

PATCH 10/10 Convert "stg uncommit" to the new infrastructure

In reply to Karl Hasselström

---

 stgit/commands/uncommit.py |   79 +++++++++++++++++++-------------------------
 1 files changed, 34 insertions(+), 45 deletions(-)
stgit/commands/uncommit.py +34 -45
index ba3448f..8422952 100644
@@ -17,13 +17,11 @@ along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 """
 
-import sys, os
-from optparse import OptionParser, make_option
-
-from stgit.commands.common import *
-from stgit.utils import *
+from optparse import make_option
+from stgit.commands import common
+from stgit.lib import transaction
 from stgit.out import *
-from stgit import stack, git
+from stgit import utils
 
 help = 'turn regular GIT commits into StGIT patches'
 usage = """%prog [<patchnames>] | -n NUM [<prefix>]] | -t <committish> [-x]
@@ -48,7 +46,7 @@ given commit should be uncommitted.
 Only commits with exactly one parent can be uncommitted; in other
 words, you can't uncommit a merge."""
 
-directory = DirectoryGotoToplevel()
+directory = common.DirectoryHasRepositoryLib()
 options = [make_option('-n', '--number', type = 'int',
                        help = 'uncommit the specified number of commits'),
            make_option('-t', '--to',
@@ -60,19 +58,18 @@ options = [make_option('-n', '--number', type = 'int',
 def func(parser, options, args):
     """Uncommit a number of patches.
     """
+    stack = directory.repository.current_stack
     if options.to:
         if options.number:
             parser.error('cannot give both --to and --number')
         if len(args) != 0:
             parser.error('cannot specify patch name with --to')
         patch_nr = patchnames = None
-        to_commit = git_id(crt_series, options.to)
+        to_commit = stack.repository.rev_parse(options.to)
     elif options.number:
         if options.number <= 0:
             parser.error('invalid value passed to --number')
-
         patch_nr = options.number
-
         if len(args) == 0:
             patchnames = None
         elif len(args) == 1:
@@ -88,53 +85,45 @@ def func(parser, options, args):
         patchnames = args
         patch_nr = len(patchnames)
 
-    if crt_series.get_protected():
-        raise CmdException, \
-              'This branch is protected. Uncommit is not permitted'
-
-    def get_commit(commit_id):
-        commit = git.Commit(commit_id)
-        try:
-            parent, = commit.get_parents()
-        except ValueError:
-            raise CmdException('Commit %s does not have exactly one parent'
-                               % commit_id)
-        return (commit, commit_id, parent)
-
     commits = []
-    next_commit = crt_series.get_base()
+    next_commit = stack.base
     if patch_nr:
         out.start('Uncommitting %d patches' % patch_nr)
         for i in xrange(patch_nr):
-            commit, commit_id, parent = get_commit(next_commit)
-            commits.append((commit, commit_id, parent))
-            next_commit = parent
+            commits.append(next_commit)
+            next_commit = next_commit.data.parent
     else:
         if options.exclusive:
             out.start('Uncommitting to %s (exclusive)' % to_commit)
         else:
             out.start('Uncommitting to %s' % to_commit)
         while True:
-            commit, commit_id, parent = get_commit(next_commit)
-            if commit_id == to_commit:
+            if next_commit == to_commit:
                 if not options.exclusive:
-                    commits.append((commit, commit_id, parent))
+                    commits.append(next_commit)
                 break
-            commits.append((commit, commit_id, parent))
-            next_commit = parent
+            commits.append(next_commit)
+            next_commit = next_commit.data.parent
         patch_nr = len(commits)
 
-    for (commit, commit_id, parent), patchname in \
-        zip(commits, patchnames or [None for i in xrange(len(commits))]):
-        author_name, author_email, author_date = \
-                     name_email_date(commit.get_author())
-        crt_series.new_patch(patchname,
-                             can_edit = False, before_existing = True,
-                             commit = False,
-                             top = commit_id, bottom = parent,
-                             message = commit.get_log(),
-                             author_name = author_name,
-                             author_email = author_email,
-                             author_date = author_date)
-
+    taken_names = set(stack.patchorder.applied + stack.patchorder.unapplied)
+    if patchnames:
+        for pn in patchnames:
+            if pn in taken_names:
+                raise common.CmdException('Patch name "%s" already taken' % pn)
+            taken_names.add(pn)
+    else:
+        patchnames = []
+        for c in reversed(commits):
+            pn = utils.make_patch_name(c.data.message,
+                                       lambda pn: pn in taken_names)
+            patchnames.append(pn)
+            taken_names.add(pn)
+        patchnames.reverse()
+
+    trans = transaction.StackTransaction(stack, 'stg uncommit')
+    for commit, pn in zip(commits, patchnames):
+        trans.patches[pn] = commit
+    trans.applied = list(reversed(patchnames)) + trans.applied
+    trans.run()
     out.done()