Updated "stg reset" series
cover Updated "stg reset" series
The patch stack log / stg reset series has matured over the weekend. The major highlights are
1. When a command fails to push a patch due to conflicts, it will log two entries -- one for the part of the command that succeeded, and one just for the conflicting push. This makes it possible to undo just the last part, and not the whole command.
2. I've tightened the checks so that conflicts will prevent most commands from working unless they actively claim to make sense in the face of conflicts. Basically, only commands that don't touch the topmost patch should be able to run when there are conflicts.
3. stg reset now understands --hard, which makes it zonk any local changes, including conflicts.
(1) and (3) means that
$ stg reset --hard <branchname>.stgit^~1
can be used instead of stg push --undo when you want to undo a conflicting push. Now I just have to make that available as
$ stg undo
so that it actually becomes usable ...
These patches are available at
git://repo.or.cz/stgit/kha.git experimental
---
Karl Hasselström (10):
Don't write a log entry if there were no changes Add a --hard flag to stg reset
Log conflicts separately for all commands
Log conflicts separately
New command: stg reset
Add utility function for reordering patches
Write to a stack log when stack is modified Library functions for tree and blob manipulation Add property with a list of all patch names Prevent most commands from running when there are conflicts
stgit/commands/branch.py | 20 ++++- stgit/commands/clean.py | 3 + stgit/commands/coalesce.py | 6 +- stgit/commands/commit.py | 13 ++-- stgit/commands/common.py | 8 ++ stgit/commands/delete.py | 14 +++- stgit/commands/diff.py | 2 - stgit/commands/edit.py | 3 + stgit/commands/export.py | 2 - stgit/commands/files.py | 2 - stgit/commands/id.py | 2 - stgit/commands/log.py | 2 - stgit/commands/mail.py | 2 - stgit/commands/patches.py | 2 - stgit/commands/reset.py | 118 ++++++++++++++++++++++++++++++++ stgit/commands/series.py | 2 - stgit/commands/show.py | 2 - stgit/commands/status.py | 3 + stgit/commands/top.py | 2 - stgit/commands/uncommit.py | 5 + stgit/lib/git.py | 143 +++++++++++++++++++++++++++++++++------ stgit/lib/log.py | 161 ++++++++++++++++++++++++++++++++++++++++++++ stgit/lib/stack.py | 8 ++ stgit/lib/transaction.py | 92 ++++++++++++++++++++----- stgit/main.py | 4 + t/t3100-reset.sh | 151 +++++++++++++++++++++++++++++++++++++++++ t/t3101-reset-hard.sh | 56 +++++++++++++++ 27 files changed, 754 insertions(+), 74 deletions(-) create mode 100644 stgit/commands/reset.py create mode 100644 stgit/lib/log.py create mode 100755 t/t3100-reset.sh create mode 100755 t/t3101-reset-hard.sh
Signature · 2 lines
Karl Hasselström, [email protected] www.treskal.com/kalle
PATCH 1/10 Prevent most commands from running when there are conflicts
When there are conflicts, we want most commands to fail, since the conflicts conceptually belong to the topmost patch. git read-tree already checks this for us when we check out a new tree, but there are operations where the top tree stays the same, e.g. stg new.
This patch inserts a conflict check when the tree to check out is the same. By default, conflicts will prevent the checkout from succeeding, but commands can choose to override this if the same patch stays on top (for some definition of "same").
This change only affects the new-infrastructure commands; the others always refuse to run when there are local changes of any kind.
---
stgit/commands/clean.py | 3 ++- stgit/commands/coalesce.py | 3 ++- stgit/commands/commit.py | 7 ++++++- stgit/commands/delete.py | 10 +++++++++- stgit/commands/edit.py | 3 ++- stgit/commands/uncommit.py | 3 ++- stgit/lib/transaction.py | 27 ++++++++++++++++++++++----- 7 files changed, 45 insertions(+), 11 deletions(-)
stgit/commands/clean.py +2 -1
@@ -37,7 +37,8 @@ options = [make_option('-a', '--applied', def _clean(stack, clean_applied, clean_unapplied): - trans = transaction.StackTransaction(stack, 'stg clean') + trans = transaction.StackTransaction(stack, 'stg clean', + allow_conflicts = True) def del_patch(pn): if pn in stack.patchorder.applied: if pn == stack.patchorder.applied[-1]:
stgit/commands/coalesce.py +2 -1
@@ -79,7 +79,8 @@ def _coalesce(stack, iw, name, msg, save_template, patches): trans.patches[name] = stack.repository.commit(new_commit_data) trans.unapplied.insert(0, name) - trans = transaction.StackTransaction(stack, 'stg coalesce') + trans = transaction.StackTransaction(stack, 'stg coalesce', + allow_conflicts = True) push_new_patch = bool(set(patches) & set(trans.applied)) try: new_commit_data = _coalesce_patches(trans, patches, msg, save_template)
stgit/commands/commit.py +6 -1
@@ -69,7 +69,12 @@ def func(parser, options, args): raise common.CmdException('No patches to commit') iw = stack.repository.default_iw - trans = transaction.StackTransaction(stack, 'stg commit') + def allow_conflicts(trans): + # As long as the topmost patch stays where it is, it's OK to + # run "stg commit" with conflicts in the index. + return len(trans.applied) >= 1 + trans = transaction.StackTransaction(stack, 'stg commit', + allow_conflicts = allow_conflicts) try: common_prefix = 0 for i in xrange(min(len(stack.patchorder.applied), len(patches))):
stgit/commands/delete.py +9 -1
@@ -46,7 +46,15 @@ def func(parser, options, args): + list(stack.patchorder.unapplied)))) else: parser.error('No patches specified') - trans = transaction.StackTransaction(stack, 'stg delete') + def allow_conflicts(trans): + # Allow conflicts if the topmost patch stays the same. + if stack.patchorder.applied: + return (trans.applied + and trans.applied[-1] == stack.patchorder.applied[-1]) + else: + return not trans.applied + trans = transaction.StackTransaction(stack, 'stg delete', + allow_conflicts = allow_conflicts) try: to_push = trans.delete_patches(lambda pn: pn in patches) for pn in to_push:
stgit/commands/edit.py +2 -1
@@ -173,7 +173,8 @@ def func(parser, options, args): # The patch applied, so now we have to rewrite the StGit patch # (and any patches on top of it). iw = stack.repository.default_iw - trans = transaction.StackTransaction(stack, 'stg edit') + trans = transaction.StackTransaction(stack, 'stg edit', + allow_conflicts = True) if patchname in trans.applied: popped = trans.applied[trans.applied.index(patchname)+1:] assert not trans.pop_patches(lambda pn: pn in popped)
stgit/commands/uncommit.py +2 -1
@@ -131,7 +131,8 @@ def func(parser, options, args): taken_names.add(pn) patchnames.reverse() - trans = transaction.StackTransaction(stack, 'stg uncommit') + trans = transaction.StackTransaction(stack, 'stg uncommit', + allow_conflicts = True) for commit, pn in zip(commits, patchnames): trans.patches[pn] = commit trans.applied = list(reversed(patchnames)) + trans.applied
stgit/lib/transaction.py +22 -5
@@ -34,7 +34,7 @@ class _TransPatchMap(dict): return self.__stack.patches.get(pn).commit class StackTransaction(object): - def __init__(self, stack, msg): + def __init__(self, stack, msg, allow_conflicts = False): self.__stack = stack self.__msg = msg self.__patches = _TransPatchMap(stack)
@@ -43,6 +43,10 @@ class StackTransaction(object): self.__error = None self.__current_tree = self.__stack.head.data.tree self.__base = self.__stack.base + if isinstance(allow_conflicts, bool): + self.__allow_conflicts = lambda trans: allow_conflicts + else: + self.__allow_conflicts = allow_conflicts stack = property(lambda self: self.__stack) patches = property(lambda self: self.__patches) def __set_applied(self, val):
@@ -63,10 +67,19 @@ class StackTransaction(object): 'This can happen if you modify a branch with git.', '"stg repair --help" explains more about what to do next.') self.__abort() - if self.__current_tree != tree: - assert iw != None - iw.checkout(self.__current_tree, tree) - self.__current_tree = tree + if self.__current_tree == tree: + # No tree change, but we still want to make sure that + # there are no unresolved conflicts. Conflicts + # conceptually "belong" to the topmost patch, and just + # carrying them along to another patch is confusing. + if (self.__allow_conflicts(self) or iw == None + or not iw.index.conflicts()): + return + out.error('Need to resolve conflicts first') + self.__abort() + assert iw != None + iw.checkout(self.__current_tree, tree) + self.__current_tree = tree @staticmethod def __abort(): raise TransactionException(
@@ -214,4 +227,8 @@ class StackTransaction(object): self.applied.append(pn) out.info('Pushed %s%s' % (pn, s)) if merge_conflict: + # We've just caused conflicts, so we must allow them in + # the final checkout. + self.__allow_conflicts = lambda trans: True + self.__halt('Merge conflict')
PATCH 2/10 Add property with a list of all patch names
In reply to Karl HasselströmThis simplifies the code in a number of places.
---
stgit/commands/coalesce.py | 3 +-- stgit/commands/commit.py | 6 ++---- stgit/commands/delete.py | 4 +--- stgit/commands/uncommit.py | 2 +- stgit/lib/stack.py | 1 + 5 files changed, 6 insertions(+), 10 deletions(-)
stgit/commands/coalesce.py +1 -2
@@ -115,8 +115,7 @@ def _coalesce(stack, iw, name, msg, save_template, patches): def func(parser, options, args): stack = directory.repository.current_stack - patches = common.parse_patches(args, (list(stack.patchorder.applied) - + list(stack.patchorder.unapplied))) + patches = common.parse_patches(args, list(stack.patchorder.all)) if len(patches) < 2: raise common.CmdException('Need at least two patches') return _coalesce(stack, stack.repository.default_iw, options.name,
stgit/commands/commit.py +2 -4
@@ -45,13 +45,11 @@ options = [make_option('-n', '--number', type = 'int', def func(parser, options, args): """Commit a number of patches.""" stack = directory.repository.current_stack - args = common.parse_patches(args, (list(stack.patchorder.applied) - + list(stack.patchorder.unapplied))) + args = common.parse_patches(args, list(stack.patchorder.all)) if len([x for x in [args, options.number != None, options.all] if x]) > 1: parser.error('too many options') if args: - patches = [pn for pn in (stack.patchorder.applied - + stack.patchorder.unapplied) if pn in args] + patches = [pn for pn in stack.patchorder.all if pn in args] bad = set(args) - set(patches) if bad: raise common.CmdException('Bad patch names: %s'
stgit/commands/delete.py +1 -3
@@ -41,9 +41,7 @@ def func(parser, options, args): stack = directory.repository.current_stack iw = stack.repository.default_iw if args: - patches = set(common.parse_patches( - args, (list(stack.patchorder.applied) - + list(stack.patchorder.unapplied)))) + patches = set(common.parse_patches(args, list(stack.patchorder.all))) else: parser.error('No patches specified') def allow_conflicts(trans):
stgit/commands/uncommit.py +1 -1
@@ -116,7 +116,7 @@ def func(parser, options, args): next_commit = get_parent(next_commit) patch_nr = len(commits) - taken_names = set(stack.patchorder.applied + stack.patchorder.unapplied) + taken_names = set(stack.patchorder.all) if patchnames: for pn in patchnames: if pn in taken_names:
stgit/lib/stack.py +1 -0
@@ -96,6 +96,7 @@ class PatchOrder(object): lambda self, val: self.__set_list('applied', val)) unapplied = property(lambda self: self.__get_list('unapplied'), lambda self, val: self.__set_list('unapplied', val)) + all = property(lambda self: self.applied + self.unapplied) class Patches(object): """Creates Patch objects."""
PATCH 3/10 Library functions for tree and blob manipulation
In reply to Karl HasselströmWrap trees and blobs in Python objects (just like commits were already wrapped), so that StGit code can read and write them.
---
stgit/lib/git.py | 139 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 files changed, 118 insertions(+), 21 deletions(-)
stgit/lib/git.py +118 -21
@@ -146,13 +146,100 @@ class Person(Repr): defaults = cls.user()) return cls.__committer -class Tree(Repr): +class GitObject(Repr): + """Base class for all git objects.""" + +class Blobdata(Repr): + def __init__(self, string): + self.__string = str(string) + str = property(lambda self: self.__string) + def commit(self, repository): + sha1 = repository.run(['git', 'hash-object', '-w', '--stdin'] + ).raw_input(self.str).output_one_line() + return repository.get_blob(sha1) + +class Blob(GitObject): """Immutable.""" - def __init__(self, sha1): + typename = 'blob' + default_perm = '100644' + def __init__(self, repository, sha1): + self.__repository = repository self.__sha1 = sha1 sha1 = property(lambda self: self.__sha1) def __str__(self): - return 'Tree<%s>' % self.sha1 + return 'Blob<%s>' % self.sha1 + @property + def data(self): + return Blobdata(self.__repository.cat_object(self.sha1)) + +class ImmutableDict(dict): + def error(*args, **kwargs): + raise TypeError('Cannot modify immutable dict') + __delitem__ = error + __setitem__ = error + clear = error + pop = error + popitem = error + setdefault = error + update = error + +class Treedata(Repr): + """Immutable.""" + @staticmethod + def __x(po): + if isinstance(po, GitObject): + perm, object = po.default_perm, po + else: + perm, object = po + return perm, object + def __init__(self, entries): + self.__entries = ImmutableDict((name, self.__x(po)) + for (name, po) in entries.iteritems()) + entries = property(lambda self: self.__entries) + def set_entry(self, name, po): + e = dict(self.entries) + e[name] = self.__x(po) + return type(self)(e) + def del_entry(self, name): + e = dict(self.entries) + del e[name] + return type(self)(e) + def commit(self, repository): + listing = ''.join( + '%s %s %s\t%s\0' % (mode, obj.typename, obj.sha1, name) + for (name, (mode, obj)) in self.entries.iteritems()) + sha1 = repository.run(['git', 'mktree', '-z'] + ).raw_input(listing).output_one_line() + return repository.get_tree(sha1) + @classmethod + def parse(cls, repository, s): + entries = {} + for line in s.split('\0')[:-1]: + m = re.match(r'^([0-7]{6}) ([a-z]+) ([0-9a-f]{40})\t(.*)$', line) + assert m + perm, type, sha1, name = m.groups() + entries[name] = (perm, repository.get_object(type, sha1)) + return cls(entries) + +class Tree(GitObject): + """Immutable.""" + typename = 'tree' + default_perm = '040000' + def __init__(self, repository, sha1): + self.__sha1 = sha1 + self.__repository = repository + self.__data = None + sha1 = property(lambda self: self.__sha1) + @property + def data(self): + if self.__data == None: + self.__data = Treedata.parse( + self.__repository, + self.__repository.run(['git', 'ls-tree', '-z', self.sha1] + ).raw_output()) + return self.__data + def __str__(self): + return 'Tree<sha1: %s>' % self.sha1 class Commitdata(Repr): """Immutable."""
@@ -202,6 +289,22 @@ class Commitdata(Repr): return ('Commitdata<tree: %s, parents: %s, author: %s,' ' committer: %s, message: "%s">' ) % (tree, parents, self.author, self.committer, self.message) + def commit(self, repository): + c = ['git', 'commit-tree', self.tree.sha1] + for p in self.parents: + c.append('-p') + c.append(p.sha1) + env = {} + for p, v1 in ((self.author, 'AUTHOR'), + (self.committer, 'COMMITTER')): + if p != None: + for attr, v2 in (('name', 'NAME'), ('email', 'EMAIL'), + ('date', 'DATE')): + if getattr(p, attr) != None: + env['GIT_%s_%s' % (v1, v2)] = str(getattr(p, attr)) + sha1 = repository.run(c, env = env).raw_input(self.message + ).output_one_line() + return repository.get_commit(sha1) @classmethod def parse(cls, repository, s): cd = cls(parents = [])
@@ -223,8 +326,9 @@ class Commitdata(Repr): assert False assert False -class Commit(Repr): +class Commit(GitObject): """Immutable.""" + typename = 'commit' def __init__(self, repository, sha1): self.__sha1 = sha1 self.__repository = repository
@@ -306,7 +410,8 @@ class Repository(RunWithEnv): def __init__(self, directory): self.__git_dir = directory self.__refs = Refs(self) - self.__trees = ObjectCache(lambda sha1: Tree(sha1)) + self.__blobs = ObjectCache(lambda sha1: Blob(self, sha1)) + self.__trees = ObjectCache(lambda sha1: Tree(self, sha1)) self.__commits = ObjectCache(lambda sha1: Commit(self, sha1)) self.__default_index = None self.__default_worktree = None
@@ -357,26 +462,18 @@ class Repository(RunWithEnv): ).output_one_line()) except run.RunException: raise RepositoryException('%s: No such revision' % rev) + def get_blob(self, sha1): + return self.__blobs[sha1] def get_tree(self, sha1): return self.__trees[sha1] def get_commit(self, sha1): return self.__commits[sha1] - def commit(self, commitdata): - c = ['git', 'commit-tree', commitdata.tree.sha1] - for p in commitdata.parents: - c.append('-p') - c.append(p.sha1) - env = {} - for p, v1 in ((commitdata.author, 'AUTHOR'), - (commitdata.committer, 'COMMITTER')): - if p != None: - for attr, v2 in (('name', 'NAME'), ('email', 'EMAIL'), - ('date', 'DATE')): - if getattr(p, attr) != None: - env['GIT_%s_%s' % (v1, v2)] = str(getattr(p, attr)) - sha1 = self.run(c, env = env).raw_input(commitdata.message - ).output_one_line() - return self.get_commit(sha1) + def get_object(self, type, sha1): + return { Blob.typename: self.get_blob, + Tree.typename: self.get_tree, + Commit.typename: self.get_commit }[type](sha1) + def commit(self, objectdata): + return objectdata.commit(self) @property def head(self): try:
PATCH 4/10 Write to a stack log when stack is modified
In reply to Karl HasselströmCreate a log branch (called <branchname>.stgit) for each StGit branch, and write to it whenever the stack is modified.
Commands using the new infrastructure write to the log when they commit a transaction. Commands using the old infrastructure get a log entry write written for them when they exit, unless they explicitly ask for this not to happen.
As of yet, nothing can be done with this log.
---
stgit/commands/branch.py | 20 +++++-- stgit/commands/common.py | 8 ++- stgit/commands/diff.py | 2 - stgit/commands/export.py | 2 - stgit/commands/files.py | 2 - stgit/commands/id.py | 2 - stgit/commands/log.py | 2 - stgit/commands/mail.py | 2 - stgit/commands/patches.py | 2 - stgit/commands/series.py | 2 - stgit/commands/show.py | 2 - stgit/commands/status.py | 3 + stgit/commands/top.py | 2 - stgit/lib/log.py | 131 +++++++++++++++++++++++++++++++++++++++++++++ stgit/lib/transaction.py | 3 + stgit/main.py | 2 + 16 files changed, 168 insertions(+), 19 deletions(-) create mode 100644 stgit/lib/log.py
stgit/commands/branch.py +14 -6
@@ -25,7 +25,7 @@ from stgit.commands.common import * from stgit.utils import * from stgit.out import * from stgit import stack, git, basedir - +from stgit.lib import log help = 'manage patch stacks' usage = """%prog [options] branch-name [commit-id]
@@ -40,7 +40,7 @@ When displaying the branches, the names can be prefixed with If not given any options, switch to the named branch.""" -directory = DirectoryGotoToplevel() +directory = DirectoryGotoToplevel(log = False) options = [make_option('-c', '--create', help = 'create a new development branch', action = 'store_true'),
@@ -161,6 +161,7 @@ def func(parser, options, args): parent_branch = parentbranch) out.info('Branch "%s" created' % args[0]) + log.compat_log_entry('stg branch --create') return elif options.clone:
@@ -181,6 +182,8 @@ def func(parser, options, args): crt_series.clone(clone) out.done() + log.copy_log(log.default_repo(), crt_series.get_name(), clone, + 'stg branch --clone') return elif options.delete:
@@ -188,6 +191,7 @@ def func(parser, options, args): if len(args) != 1: parser.error('incorrect number of arguments') __delete_branch(args[0], options.force) + log.delete_log(log.default_repo(), args[0]) return elif options.list:
@@ -195,13 +199,16 @@ def func(parser, options, args): if len(args) != 0: parser.error('incorrect number of arguments') - branches = git.get_heads() - branches.sort() + branches = set(git.get_heads()) + for br in set(branches): + m = re.match(r'^(.*)\.stgit$', br) + if m and m.group(1) in branches: + branches.remove(br) if branches: out.info('Available branches:') max_len = max([len(i) for i in branches]) - for i in branches: + for i in sorted(branches): __print_branch(i, max_len) else: out.info('No branches')
@@ -238,7 +245,8 @@ def func(parser, options, args): stack.Series(args[0]).rename(args[1]) out.info('Renamed branch "%s" to "%s"' % (args[0], args[1])) - + log.rename_log(log.default_repo(), args[0], args[1], + 'stg branch --rename') return elif options.unprotect:
stgit/commands/common.py +7 -1
@@ -28,6 +28,7 @@ from stgit.run import * from stgit import stack, git, basedir from stgit.config import config, file_extensions from stgit.lib import stack as libstack +from stgit.lib import log # Command exception class class CmdException(StgException):
@@ -478,8 +479,9 @@ class DirectoryException(StgException): pass class _Directory(object): - def __init__(self, needs_current_series = True): + def __init__(self, needs_current_series = True, log = True): self.needs_current_series = needs_current_series + self.log = log @readonly_constant_property def git_dir(self): try:
@@ -512,6 +514,9 @@ class _Directory(object): ).output_one_line()] def cd_to_topdir(self): os.chdir(self.__topdir_path) + def write_log(self, msg): + if self.log: + log.compat_log_entry(msg) class DirectoryAnywhere(_Directory): def setup(self):
@@ -536,6 +541,7 @@ class DirectoryHasRepositoryLib(_Directory): """For commands that use the new infrastructure in stgit.lib.*.""" def __init__(self): self.needs_current_series = False + self.log = False # stgit.lib.transaction handles logging def setup(self): # This will throw an exception if we don't have a repository. self.repository = libstack.Repository.default()
stgit/commands/diff.py +1 -1
@@ -42,7 +42,7 @@ rev = '([patch][//[bottom | top]]) | <tree-ish> | base' If neither bottom nor top are given but a '//' is present, the command shows the specified patch (defaulting to the current one).""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-r', '--range', metavar = 'rev1[..[rev2]]', dest = 'revs', help = 'show the diff between revisions'),
stgit/commands/export.py +1 -1
@@ -49,7 +49,7 @@ file: %(commemail)s - committer's e-mail """ -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-d', '--dir', help = 'export patches to DIR instead of the default'), make_option('-p', '--patch',
stgit/commands/files.py +1 -1
@@ -34,7 +34,7 @@ given patch. Note that this command doesn't show the files modified in the working tree and not yet included in the patch by a 'refresh' command. Use the 'diff' or 'status' commands for these files.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-s', '--stat', help = 'show the diff stat', action = 'store_true'),
stgit/commands/id.py +1 -1
@@ -33,7 +33,7 @@ the standard GIT id's like heads and tags, this command also accepts 'top' or 'bottom' are passed and <patch> is a valid patch name, 'top' will be used by default.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-b', '--branch', help = 'use BRANCH instead of the default one')]
stgit/commands/log.py +1 -1
@@ -44,7 +44,7 @@ represent the changes to the entire base of the current patch. Conflicts reset the patch content and a subsequent 'refresh' will show the entire patch.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-b', '--branch', help = 'use BRANCH instead of the default one'), make_option('-p', '--patch',
stgit/commands/mail.py +1 -1
@@ -90,7 +90,7 @@ the following: %(prefix)s - 'prefix ' string passed on the command line %(shortdescr)s - the first line of the patch description""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-a', '--all', help = 'e-mail all the applied patches', action = 'store_true'),
stgit/commands/patches.py +1 -1
@@ -33,7 +33,7 @@ it shows the patches affected by the local tree modifications. The '--diff' option also lists the patch log and the diff for the given files.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-d', '--diff', help = 'show the diff for the given files', action = 'store_true'),
stgit/commands/series.py +1 -1
@@ -34,7 +34,7 @@ range. The applied patches are prefixed with a '+', the unapplied ones with a '-' and the hidden ones with a '!'. The current patch is prefixed with a '>'. Empty patches are prefixed with a '0'.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-b', '--branch', help = 'use BRANCH instead of the default one'), make_option('-a', '--all',
stgit/commands/show.py +1 -1
@@ -30,7 +30,7 @@ Show the commit log and the diff corresponding to the given patches. The output is similar to that generated by the 'git show' command.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-b', '--branch', help = 'use BRANCH instead of the default one'), make_option('-a', '--applied',
stgit/commands/status.py +2 -1
@@ -40,7 +40,7 @@ under revision control. The files are prefixed as follows: A 'refresh' command clears the status of the modified, new and deleted files.""" -directory = DirectoryHasRepository(needs_current_series = False) +directory = DirectoryHasRepository(needs_current_series = False, log = False) options = [make_option('-m', '--modified', help = 'show modified files only', action = 'store_true'),
@@ -106,6 +106,7 @@ def func(parser, options, args): directory.cd_to_topdir() if options.reset: + directory.log = True if args: conflicts = git.get_conflicts() git.resolved(fn for fn in args if fn in conflicts)
stgit/commands/top.py +1 -1
@@ -30,7 +30,7 @@ usage = """%prog [options] Print the name of the current (topmost) patch.""" -directory = DirectoryHasRepository() +directory = DirectoryHasRepository(log = False) options = [make_option('-b', '--branch', help = 'use BRANCH instead of the default one')]
stgit/lib/log.py new file +131 -0
131 lines not on this page · raw message
stgit/lib/transaction.py +2 -1
@@ -1,7 +1,7 @@ from stgit import exception, utils from stgit.utils import any, all from stgit.out import * -from stgit.lib import git +from stgit.lib import git, log class TransactionException(exception.StgException): pass
@@ -131,6 +131,7 @@ class StackTransaction(object): _print_current_patch(self.__stack.patchorder.applied, self.__applied) self.__stack.patchorder.applied = self.__applied self.__stack.patchorder.unapplied = self.__unapplied + log.log_entry(self.__stack, self.__msg) if self.__error: return utils.STGIT_CONFLICT
stgit/main.py +2 -0
@@ -277,6 +277,7 @@ def main(): ret = command.func(parser, options, args) except (StgException, IOError, ParsingError, NoSectionError), err: + directory.write_log('%s %s' % (prog, cmd)) out.error(str(err), title = '%s %s' % (prog, cmd)) if debug_level > 0: traceback.print_exc()
@@ -292,4 +293,5 @@ def main(): traceback.print_exc() sys.exit(utils.STGIT_BUG_ERROR) + directory.write_log('%s %s' % (prog, cmd)) sys.exit(ret or utils.STGIT_SUCCESS)
PATCH 5/10 Add utility function for reordering patches
In reply to Karl Hasselström---
stgit/lib/transaction.py | 14 ++++++++++++++ 1 files changed, 14 insertions(+), 0 deletions(-)
stgit/lib/transaction.py +14 -0
@@ -1,3 +1,5 @@ +import itertools as it + from stgit import exception, utils from stgit.utils import any, all from stgit.out import *
@@ -233,3 +235,15 @@ class StackTransaction(object): self.__allow_conflicts = lambda trans: True self.__halt('Merge conflict') + + def reorder_patches(self, applied, unapplied, iw = None): + """Push and pop patches to attain the given ordering.""" + common = len(list(it.takewhile(lambda (a, b): a == b, + zip(self.applied, applied)))) + to_pop = set(self.applied[common:]) + self.pop_patches(lambda pn: pn in to_pop) + for pn in applied[common:]: + self.push_patch(pn, iw) + assert self.applied == applied + assert set(self.unapplied) == set(unapplied) + self.unapplied = unapplied
PATCH 6/10 New command: stg reset
In reply to Karl HasselströmGiven a commit object from the log, resets the stack (or just the named patches) to the state given by that log entry.
---
stgit/commands/reset.py | 114 +++++++++++++++++++++++++++++++++++ stgit/main.py | 2 + t/t3100-reset.sh | 151 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 267 insertions(+), 0 deletions(-) create mode 100644 stgit/commands/reset.py create mode 100755 t/t3100-reset.sh
stgit/commands/reset.py new file +114 -0
@@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +__copyright__ = """ +Copyright (C) 2008, 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 +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" + +from stgit.commands import common +from stgit.lib import git, log, transaction +from stgit.out import out + +help = 'reset the patch stack to an earlier state' +usage = """%prog <state> [<patchnames>] + +Reset the patch stack to an earlier state. The state is specified with +a commit from a stack log; for a branch foo, StGit stores the stack +log in foo.stgit^. So to undo the last N StGit commands, you would say + + stg reset foo.stgit^~N + +or, if you are not sure how many steps to undo, you can view the log +with "git log" or gitk + + gitk foo.stgit^ + +and then reset to any sha1 you see in the log. + +If one or more patch names are given, reset only those patches, and +leave the rest alone.""" + +directory = common.DirectoryHasRepositoryLib() +options = [] + +def reset_stack(stack, iw, state, only_patches): + only_patches = set(only_patches) + def mask(s): + if only_patches: + return s & only_patches + else: + return s + patches_to_reset = mask(set(state.applied + state.unapplied)) + existing_patches = set(stack.patchorder.all) + to_delete = mask(existing_patches - patches_to_reset) + trans = transaction.StackTransaction(stack, 'stg reset') + + # If we have to change the stack base, we need to pop all patches + # first. + if not only_patches and trans.base != state.base: + trans.pop_patches(lambda pn: True) + out.info('Setting stack base to %s' % state.base.sha1) + trans.base = state.base + + # In one go, do all the popping we have to in order to pop the + # patches we're going to delete or modify. + def mod(pn): + if only_patches and not pn in only_patches: + return False + if pn in to_delete: + return True + if stack.patches.get(pn).commit != state.patches.get(pn, None): + return True + return False + trans.pop_patches(mod) + + # Delete and modify/create patches. We've previously popped all + # patches that we touch in this step. + trans.delete_patches(lambda pn: pn in to_delete) + for pn in patches_to_reset: + if pn in existing_patches: + if trans.patches[pn] == state.patches[pn]: + continue + else: + out.info('Resetting %s' % pn) + else: + trans.unapplied.append(pn) + out.info('Resurrecting %s' % pn) + trans.patches[pn] = state.patches[pn] + + # Push/pop patches as necessary. + try: + if only_patches: + # Push all the patches that we've popped, if they still + # exist. + pushable = set(trans.unapplied) + for pn in stack.patchorder.applied: + if pn in pushable: + trans.push_patch(pn, iw) + else: + # Recreate the exact order specified by the goal state. + trans.reorder_patches(state.applied, state.unapplied, iw) + except transaction.TransactionHalted: + pass + return trans.run(iw) + +def func(parser, options, args): + stack = directory.repository.current_stack + if len(args) >= 1: + ref, patches = args[0], args[1:] + state = log.Log(stack.repository, ref, stack.repository.rev_parse(ref)) + else: + raise common.CmdException('Wrong number of arguments') + return reset_stack(stack, stack.repository.default_iw, state, patches)
stgit/main.py +2 -0
@@ -89,6 +89,7 @@ commands = Commands({ 'refresh': 'refresh', 'rename': 'rename', 'repair': 'repair', + 'reset': 'reset', 'resolved': 'resolved', 'series': 'series', 'show': 'show',
@@ -122,6 +123,7 @@ stackcommands = ( 'push', 'rebase', 'repair', + 'reset', 'series', 'sink', 'top',
t/t3100-reset.sh new file +151 -0
151 lines not on this page · raw message
PATCH 7/10 Log conflicts separately
In reply to Karl HasselströmThis patch makes commands that produce a conflict log that final conflicting push separately from the rest of the command's effects. This makes it possible for the user to roll back just the final conflicting push if she desires. (Rolling back the whole operation is of course still possible, by resetting to the state yet another step back in the log.)
This change only applies to the new-infrastructure commands.
---
stgit/lib/transaction.py | 47 +++++++++++++++++++++++++++++++--------------- 1 files changed, 32 insertions(+), 15 deletions(-)
stgit/lib/transaction.py +32 -15
@@ -42,6 +42,7 @@ class StackTransaction(object): self.__patches = _TransPatchMap(stack) self.__applied = list(self.__stack.patchorder.applied) self.__unapplied = list(self.__stack.patchorder.unapplied) + self.__conflicting_push = None self.__error = None self.__current_tree = self.__stack.head.data.tree self.__base = self.__stack.base
@@ -121,19 +122,26 @@ class StackTransaction(object): out.error(self.__error) # Write patches. - for pn, commit in self.__patches.iteritems(): - if self.__stack.patches.exists(pn): - p = self.__stack.patches.get(pn) - if commit == None: - p.delete() + def write(msg): + for pn, commit in self.__patches.iteritems(): + if self.__stack.patches.exists(pn): + p = self.__stack.patches.get(pn) + if commit == None: + p.delete() + else: + p.set_commit(commit, msg) else: - p.set_commit(commit, self.__msg) - else: - self.__stack.patches.new(pn, commit, self.__msg) - _print_current_patch(self.__stack.patchorder.applied, self.__applied) - self.__stack.patchorder.applied = self.__applied - self.__stack.patchorder.unapplied = self.__unapplied - log.log_entry(self.__stack, self.__msg) + self.__stack.patches.new(pn, commit, msg) + self.__stack.patchorder.applied = self.__applied + self.__stack.patchorder.unapplied = self.__unapplied + log.log_entry(self.__stack, msg) + old_applied = self.__stack.patchorder.applied + write(self.__msg) + if self.__conflicting_push != None: + self.__patches = _TransPatchMap(self.__stack) + self.__conflicting_push() + write(self.__msg + ' (CONFLICT)') + _print_current_patch(old_applied, self.__applied) if self.__error: return utils.STGIT_CONFLICT
@@ -223,18 +231,27 @@ class StackTransaction(object): cd = cd.set_tree(tree) if any(getattr(cd, a) != getattr(orig_cd, a) for a in ['parent', 'tree', 'author', 'message']): - self.patches[pn] = self.__stack.repository.commit(cd) + comm = self.__stack.repository.commit(cd) else: + comm = None s = ' (unmodified)' - del self.unapplied[self.unapplied.index(pn)] - self.applied.append(pn) out.info('Pushed %s%s' % (pn, s)) + def update(): + if comm: + self.patches[pn] = comm + del self.unapplied[self.unapplied.index(pn)] + self.applied.append(pn) if merge_conflict: # We've just caused conflicts, so we must allow them in # the final checkout. self.__allow_conflicts = lambda trans: True + # Save this update so that we can run it a little later. + self.__conflicting_push = update self.__halt('Merge conflict') + else: + # Update immediately. + update() def reorder_patches(self, applied, unapplied, iw = None): """Push and pop patches to attain the given ordering."""
PATCH 8/10 Log conflicts separately for all commands
In reply to Karl HasselströmThis takes care of the old-infrastructure commands as well. They'll all be converted to the new infrastructure eventually, but until then this patch is necessary to make all the commands behave consistently.
---
stgit/lib/log.py | 29 ++++++++++++++++++++++++++++- stgit/lib/stack.py | 7 +++++++ 2 files changed, 35 insertions(+), 1 deletions(-)
stgit/lib/log.py +28 -1
@@ -58,10 +58,37 @@ def log_entry(stack, msg): + [ll.full_log for ll in last_log]))) stack.repository.refs.set(ref, full_log, msg) +class Fakestack(object): + """Imitates a real Stack, but with the topmost patch popped.""" + def __init__(self, stack): + appl = list(stack.patchorder.applied) + unappl = list(stack.patchorder.unapplied) + class patchorder(object): + applied = appl[:-1] + unapplied = [appl[-1]] + unappl + all = appl + unappl + self.patchorder = patchorder + class patches(object): + @staticmethod + def get(pn): + if pn == appl[-1]: + class patch(object): + commit = stack.patches.get(pn).old_commit + return patch + else: + return stack.patches.get(pn) + self.patches = patches + self.head = stack.head.data.parent + self.name = stack.name + self.repository = stack.repository def compat_log_entry(msg): repo = default_repo() stack = repo.get_stack(repo.current_branch) - log_entry(stack, msg) + if repo.default_index.conflicts(): + log_entry(Fakestack(stack), msg) + log_entry(stack, msg + ' (CONFLICT)') + else: + log_entry(stack, msg) class Log(object): """Read a log entry."""
stgit/lib/stack.py +7 -0
@@ -17,6 +17,13 @@ class Patch(object): def commit(self): return self.__stack.repository.refs.get(self.__ref) @property + def old_commit(self): + """Return the previous commit for this patch.""" + fn = os.path.join(self.__compat_dir, 'top.old') + if not os.path.isfile(fn): + return None + return self.__stack.repository.get_commit(utils.read_string(fn)) + @property def __compat_dir(self): return os.path.join(self.__stack.directory, 'patches', self.__name) def __write_compat_files(self, new_commit, msg):
PATCH 9/10 Add a --hard flag to stg reset
In reply to Karl HasselströmWith this flag, reset will overwrite any local changes. Useful e.g. when undoing a push that's polluted the index+worktree with a heap of conflicts.
---
stgit/commands/reset.py | 14 +++++++----- stgit/lib/git.py | 4 +++ stgit/lib/transaction.py | 11 +++++++-- t/t3101-reset-hard.sh | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 8 deletions(-) create mode 100755 t/t3101-reset-hard.sh
stgit/commands/reset.py +9 -5
@@ -17,12 +17,13 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ +from optparse import make_option from stgit.commands import common from stgit.lib import git, log, transaction from stgit.out import out help = 'reset the patch stack to an earlier state' -usage = """%prog <state> [<patchnames>] +usage = """%prog [options] <state> [<patchnames>] Reset the patch stack to an earlier state. The state is specified with a commit from a stack log; for a branch foo, StGit stores the stack
@@ -41,9 +42,10 @@ If one or more patch names are given, reset only those patches, and leave the rest alone.""" directory = common.DirectoryHasRepositoryLib() -options = [] +options = [make_option('--hard', action = 'store_true', + help = 'discard changes in your index/worktree')] -def reset_stack(stack, iw, state, only_patches): +def reset_stack(stack, iw, state, only_patches, hard): only_patches = set(only_patches) def mask(s): if only_patches:
@@ -53,7 +55,8 @@ def reset_stack(stack, iw, state, only_patches): patches_to_reset = mask(set(state.applied + state.unapplied)) existing_patches = set(stack.patchorder.all) to_delete = mask(existing_patches - patches_to_reset) - trans = transaction.StackTransaction(stack, 'stg reset') + trans = transaction.StackTransaction(stack, 'stg reset', + discard_changes = hard) # If we have to change the stack base, we need to pop all patches # first.
@@ -111,4 +114,5 @@ def func(parser, options, args): state = log.Log(stack.repository, ref, stack.repository.rev_parse(ref)) else: raise common.CmdException('Wrong number of arguments') - return reset_stack(stack, stack.repository.default_iw, state, patches) + return reset_stack(stack, stack.repository.default_iw, state, patches, + options.hard)
stgit/lib/git.py +4 -0
@@ -605,6 +605,10 @@ class IndexAndWorktree(RunWithEnvCwd): env = property(lambda self: utils.add_dict(self.__index.env, self.__worktree.env)) cwd = property(lambda self: self.__worktree.directory) + def checkout_hard(self, tree): + assert isinstance(tree, Tree) + self.run(['git', 'read-tree', '--reset', '-u', tree.sha1] + ).discard_output() def checkout(self, old_tree, new_tree): # TODO: Optionally do a 3-way instead of doing nothing when we # have a problem. Or maybe we should stash changes in a patch?
stgit/lib/transaction.py +8 -3
@@ -36,7 +36,8 @@ class _TransPatchMap(dict): return self.__stack.patches.get(pn).commit class StackTransaction(object): - def __init__(self, stack, msg, allow_conflicts = False): + def __init__(self, stack, msg, discard_changes = False, + allow_conflicts = False): self.__stack = stack self.__msg = msg self.__patches = _TransPatchMap(stack)
@@ -46,6 +47,7 @@ class StackTransaction(object): self.__error = None self.__current_tree = self.__stack.head.data.tree self.__base = self.__stack.base + self.__discard_changes = discard_changes if isinstance(allow_conflicts, bool): self.__allow_conflicts = lambda trans: allow_conflicts else:
@@ -70,7 +72,7 @@ class StackTransaction(object): 'This can happen if you modify a branch with git.', '"stg repair --help" explains more about what to do next.') self.__abort() - if self.__current_tree == tree: + if self.__current_tree == tree and not self.__discard_changes: # No tree change, but we still want to make sure that # there are no unresolved conflicts. Conflicts # conceptually "belong" to the topmost patch, and just
@@ -81,7 +83,10 @@ class StackTransaction(object): out.error('Need to resolve conflicts first') self.__abort() assert iw != None - iw.checkout(self.__current_tree, tree) + if self.__discard_changes: + iw.checkout_hard(tree) + else: + iw.checkout(self.__current_tree, tree) self.__current_tree = tree @staticmethod def __abort():
t/t3101-reset-hard.sh new file +56 -0
56 lines not on this page · raw message
PATCH 10/10 Don't write a log entry if there were no changes
In reply to Karl HasselströmSome commands end up calling log_entry() without verifying that they did in fact change anything. (One example of this is a conflicting push, which will log two entries, everything else and the conflicting push, with the "everything else" part being empty if there was only one patch to push.) So before appending to the log, make sure that the entry we're appending isn't a no-op.
---
stgit/lib/log.py | 3 +++ 1 files changed, 3 insertions(+), 0 deletions(-)
stgit/lib/log.py +3 -0
@@ -49,6 +49,9 @@ def log_entry(stack, msg): out.warn(str(e), 'No log entry written.') return log_tree = log_entry_tree(stack.repository, stack) + if len(last_log) == 1 and log_tree == last_log[0].full_log.data.tree: + # No changes, so there's no point writing a new log entry. + return stack_log = stack.repository.commit( git.Commitdata(tree = log_tree, message = msg, parents = [ll.stack_log for ll in last_log]))