chiark / gitweb /
23321c7052c61460894d324cb0fa75812b26ae57
[stgit] / stgit / lib / transaction.py
1 """The L{StackTransaction} class makes it possible to make complex
2 updates to an StGit stack in a safe and convenient way."""
3
4 from stgit import exception, utils
5 from stgit.utils import any, all
6 from stgit.out import *
7 from stgit.lib import git
8
9 class TransactionException(exception.StgException):
10     """Exception raised when something goes wrong with a
11     L{StackTransaction}."""
12
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."""
17
18 def _print_current_patch(old_applied, new_applied):
19     def now_at(pn):
20         out.info('Now at patch "%s"' % pn)
21     if not old_applied and not new_applied:
22         pass
23     elif not old_applied:
24         now_at(new_applied[-1])
25     elif not new_applied:
26         out.info('No patch applied')
27     elif old_applied[-1] == new_applied[-1]:
28         pass
29     else:
30         now_at(new_applied[-1])
31
32 class _TransPatchMap(dict):
33     """Maps patch names to sha1 strings."""
34     def __init__(self, stack):
35         dict.__init__(self)
36         self.__stack = stack
37     def __getitem__(self, pn):
38         try:
39             return dict.__getitem__(self, pn)
40         except KeyError:
41             return self.__stack.patches.get(pn).commit
42
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
46     cleanly.
47
48     The basic theory of operation is the following:
49
50       1. Create a transaction object.
51
52       2. Inside a::
53
54          try
55            ...
56          except TransactionHalted:
57            pass
58
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
63       required.
64
65       (Some operations may need to touch your index and working tree,
66       though. But they are cleaned up when needed.)
67
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
73       anything."""
74     def __init__(self, stack, msg, allow_conflicts = False):
75         self.__stack = stack
76         self.__msg = msg
77         self.__patches = _TransPatchMap(stack)
78         self.__applied = list(self.__stack.patchorder.applied)
79         self.__unapplied = list(self.__stack.patchorder.unapplied)
80         self.__error = None
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
85         else:
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)
98         self.__base = val
99     base = property(lambda self: self.__base, __set_base)
100     def __checkout(self, tree, iw):
101         if not self.__stack.head_top_equal():
102             out.error(
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.')
106             self.__abort()
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()):
114                 return
115             out.error('Need to resolve conflicts first')
116             self.__abort()
117         assert iw != None
118         iw.checkout(self.__current_tree, tree)
119         self.__current_tree = tree
120     @staticmethod
121     def __abort():
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():
127             if commit == None:
128                 assert self.__stack.patches.exists(pn)
129             else:
130                 assert pn in remaining
131     @property
132     def __head(self):
133         if self.__applied:
134             return self.__patches[self.__applied[-1]]
135         else:
136             return self.__base
137     def abort(self, iw = None):
138         # The only state we need to restore is index+worktree.
139         if iw:
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
146
147         # Set branch head.
148         if set_head:
149             if iw:
150                 try:
151                     self.__checkout(new_head.data.tree, iw)
152                 except git.CheckoutException:
153                     # We have to abort the transaction.
154                     self.abort(iw)
155                     self.__abort()
156             self.__stack.set_head(new_head, self.__msg)
157
158         if self.__error:
159             out.error(self.__error)
160
161         # Write patches.
162         for pn, commit in self.__patches.iteritems():
163             if self.__stack.patches.exists(pn):
164                 p = self.__stack.patches.get(pn)
165                 if commit == None:
166                     p.delete()
167                 else:
168                     p.set_commit(commit, self.__msg)
169             else:
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
174
175         if self.__error:
176             return utils.STGIT_CONFLICT
177         else:
178             return utils.STGIT_SUCCESS
179
180     def __halt(self, msg):
181         self.__error = msg
182         raise TransactionHalted(msg)
183
184     @staticmethod
185     def __print_popped(popped):
186         if len(popped) == 0:
187             pass
188         elif len(popped) == 1:
189             out.info('Popped %s' % popped[0])
190         else:
191             out.info('Popped %s -- %s' % (popped[-1], popped[0]))
192
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
196         succeeds."""
197         popped = []
198         for i in xrange(len(self.applied)):
199             if p(self.applied[i]):
200                 popped = self.applied[i:]
201                 del self.applied[i:]
202                 break
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)
207         return popped1
208
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
212         succeeds."""
213         popped = []
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:]
218                 del self.applied[i:]
219                 break
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:
224             if p(pn):
225                 s = ['', ' (empty)'][self.patches[pn].data.is_nochange()]
226                 self.patches[pn] = None
227                 out.info('Deleted %s%s' % (pn, s))
228         return popped
229
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
241         theirs = cd.tree
242         tree = self.__stack.repository.simple_merge(base, ours, theirs)
243         merge_conflict = False
244         if not tree:
245             if iw == None:
246                 self.__halt('%s does not apply cleanly' % pn)
247             try:
248                 self.__checkout(ours, iw)
249             except git.CheckoutException:
250                 self.__halt('Index/worktree dirty')
251             try:
252                 iw.merge(base, ours, theirs)
253                 tree = iw.index.write_tree()
254                 self.__current_tree = tree
255                 s = ' (modified)'
256             except git.MergeConflictException:
257                 tree = ours
258                 merge_conflict = True
259                 s = ' (conflict)'
260             except git.MergeException, e:
261                 self.__halt(str(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)
266         else:
267             s = ' (unmodified)'
268         del self.unapplied[self.unapplied.index(pn)]
269         self.applied.append(pn)
270         out.info('Pushed %s%s' % (pn, s))
271         if merge_conflict:
272             # We've just caused conflicts, so we must allow them in
273             # the final checkout.
274             self.__allow_conflicts = lambda trans: True
275
276             self.__halt('Merge conflict')