1 """The L{StackTransaction} class makes it possible to make complex
2 updates to an StGit stack in a safe and convenient way."""
4 from stgit import exception, utils
5 from stgit.utils import any, all
6 from stgit.out import *
7 from stgit.lib import git
9 class TransactionException(exception.StgException):
10 """Exception raised when something goes wrong with a
11 L{StackTransaction}."""
13 class TransactionHalted(TransactionException):
14 """Exception raised when a L{StackTransaction} stops part-way through.
15 Used to make a non-local jump from the transaction setup to the
16 part of the transaction code where the transaction is run."""
18 def _print_current_patch(old_applied, new_applied):
20 out.info('Now at patch "%s"' % pn)
21 if not old_applied and not new_applied:
24 now_at(new_applied[-1])
26 out.info('No patch applied')
27 elif old_applied[-1] == new_applied[-1]:
30 now_at(new_applied[-1])
32 class _TransPatchMap(dict):
33 """Maps patch names to sha1 strings."""
34 def __init__(self, stack):
37 def __getitem__(self, pn):
39 return dict.__getitem__(self, pn)
41 return self.__stack.patches.get(pn).commit
43 class StackTransaction(object):
44 """A stack transaction, used for making complex updates to an StGit
45 stack in one single operation that will either succeed or fail
48 The basic theory of operation is the following:
50 1. Create a transaction object.
56 except TransactionHalted:
59 block, update the transaction with e.g. methods like
60 L{pop_patches} and L{push_patch}. This may create new git
61 objects such as commits, but will not write any refs; this means
62 that in case of a fatal error we can just walk away, no clean-up
65 (Some operations may need to touch your index and working tree,
66 though. But they are cleaned up when needed.)
68 3. After the C{try} block -- wheher or not the setup ran to
69 completion or halted part-way through by raising a
70 L{TransactionHalted} exception -- call the transaction's L{run}
71 method. This will either succeed in writing the updated state to
72 your refs and index+worktree, or fail without having done
74 def __init__(self, stack, msg, allow_conflicts = False):
77 self.__patches = _TransPatchMap(stack)
78 self.__applied = list(self.__stack.patchorder.applied)
79 self.__unapplied = list(self.__stack.patchorder.unapplied)
81 self.__current_tree = self.__stack.head.data.tree
82 self.__base = self.__stack.base
83 if isinstance(allow_conflicts, bool):
84 self.__allow_conflicts = lambda trans: allow_conflicts
86 self.__allow_conflicts = allow_conflicts
87 stack = property(lambda self: self.__stack)
88 patches = property(lambda self: self.__patches)
89 def __set_applied(self, val):
90 self.__applied = list(val)
91 applied = property(lambda self: self.__applied, __set_applied)
92 def __set_unapplied(self, val):
93 self.__unapplied = list(val)
94 unapplied = property(lambda self: self.__unapplied, __set_unapplied)
95 def __set_base(self, val):
96 assert (not self.__applied
97 or self.patches[self.applied[0]].data.parent == val)
99 base = property(lambda self: self.__base, __set_base)
100 def __checkout(self, tree, iw):
101 if not self.__stack.head_top_equal():
103 'HEAD and top are not the same.',
104 'This can happen if you modify a branch with git.',
105 '"stg repair --help" explains more about what to do next.')
107 if self.__current_tree == tree:
108 # No tree change, but we still want to make sure that
109 # there are no unresolved conflicts. Conflicts
110 # conceptually "belong" to the topmost patch, and just
111 # carrying them along to another patch is confusing.
112 if (self.__allow_conflicts(self) or iw == None
113 or not iw.index.conflicts()):
115 out.error('Need to resolve conflicts first')
118 iw.checkout(self.__current_tree, tree)
119 self.__current_tree = tree
122 raise TransactionException(
123 'Command aborted (all changes rolled back)')
124 def __check_consistency(self):
125 remaining = set(self.__applied + self.__unapplied)
126 for pn, commit in self.__patches.iteritems():
128 assert self.__stack.patches.exists(pn)
130 assert pn in remaining
134 return self.__patches[self.__applied[-1]]
137 def abort(self, iw = None):
138 # The only state we need to restore is index+worktree.
140 self.__checkout(self.__stack.head.data.tree, iw)
141 def run(self, iw = None, set_head = True):
142 """Execute the transaction. Will either succeed, or fail (with an
143 exception) and do nothing."""
144 self.__check_consistency()
145 new_head = self.__head
151 self.__checkout(new_head.data.tree, iw)
152 except git.CheckoutException:
153 # We have to abort the transaction.
156 self.__stack.set_head(new_head, self.__msg)
159 out.error(self.__error)
162 for pn, commit in self.__patches.iteritems():
163 if self.__stack.patches.exists(pn):
164 p = self.__stack.patches.get(pn)
168 p.set_commit(commit, self.__msg)
170 self.__stack.patches.new(pn, commit, self.__msg)
171 _print_current_patch(self.__stack.patchorder.applied, self.__applied)
172 self.__stack.patchorder.applied = self.__applied
173 self.__stack.patchorder.unapplied = self.__unapplied
176 return utils.STGIT_CONFLICT
178 return utils.STGIT_SUCCESS
180 def __halt(self, msg):
182 raise TransactionHalted(msg)
185 def __print_popped(popped):
188 elif len(popped) == 1:
189 out.info('Popped %s' % popped[0])
191 out.info('Popped %s -- %s' % (popped[-1], popped[0]))
193 def pop_patches(self, p):
194 """Pop all patches pn for which p(pn) is true. Return the list of
195 other patches that had to be popped to accomplish this. Always
198 for i in xrange(len(self.applied)):
199 if p(self.applied[i]):
200 popped = self.applied[i:]
203 popped1 = [pn for pn in popped if not p(pn)]
204 popped2 = [pn for pn in popped if p(pn)]
205 self.unapplied = popped1 + popped2 + self.unapplied
206 self.__print_popped(popped)
209 def delete_patches(self, p):
210 """Delete all patches pn for which p(pn) is true. Return the list of
211 other patches that had to be popped to accomplish this. Always
214 all_patches = self.applied + self.unapplied
215 for i in xrange(len(self.applied)):
216 if p(self.applied[i]):
217 popped = self.applied[i:]
220 popped = [pn for pn in popped if not p(pn)]
221 self.unapplied = popped + [pn for pn in self.unapplied if not p(pn)]
222 self.__print_popped(popped)
223 for pn in all_patches:
225 s = ['', ' (empty)'][self.patches[pn].data.is_nochange()]
226 self.patches[pn] = None
227 out.info('Deleted %s%s' % (pn, s))
230 def push_patch(self, pn, iw = None):
231 """Attempt to push the named patch. If this results in conflicts,
232 halts the transaction. If index+worktree are given, spill any
233 conflicts to them."""
234 orig_cd = self.patches[pn].data
235 cd = orig_cd.set_committer(None)
236 s = ['', ' (empty)'][cd.is_nochange()]
237 oldparent = cd.parent
238 cd = cd.set_parent(self.__head)
239 base = oldparent.data.tree
240 ours = cd.parent.data.tree
242 tree = self.__stack.repository.simple_merge(base, ours, theirs)
243 merge_conflict = False
246 self.__halt('%s does not apply cleanly' % pn)
248 self.__checkout(ours, iw)
249 except git.CheckoutException:
250 self.__halt('Index/worktree dirty')
252 iw.merge(base, ours, theirs)
253 tree = iw.index.write_tree()
254 self.__current_tree = tree
256 except git.MergeConflictException:
258 merge_conflict = True
260 except git.MergeException, e:
262 cd = cd.set_tree(tree)
263 if any(getattr(cd, a) != getattr(orig_cd, a) for a in
264 ['parent', 'tree', 'author', 'message']):
265 self.patches[pn] = self.__stack.repository.commit(cd)
268 del self.unapplied[self.unapplied.index(pn)]
269 self.applied.append(pn)
270 out.info('Pushed %s%s' % (pn, s))
272 # We've just caused conflicts, so we must allow them in
273 # the final checkout.
274 self.__allow_conflicts = lambda trans: True
276 self.__halt('Merge conflict')