chiark / gitweb /
a7c4f7e890aaa4d85023b5e1a3e17c8f360e8781
[stgit] / stgit / lib / transaction.py
1 from stgit import exception, utils
2 from stgit.out import *
3 from stgit.lib import git
4
5 class TransactionException(exception.StgException):
6     pass
7
8 class TransactionHalted(TransactionException):
9     pass
10
11 def _print_current_patch(old_applied, new_applied):
12     def now_at(pn):
13         out.info('Now at patch "%s"' % pn)
14     if not old_applied and not new_applied:
15         pass
16     elif not old_applied:
17         now_at(new_applied[-1])
18     elif not new_applied:
19         out.info('No patch applied')
20     elif old_applied[-1] == new_applied[-1]:
21         pass
22     else:
23         now_at(new_applied[-1])
24
25 class _TransPatchMap(dict):
26     def __init__(self, stack):
27         dict.__init__(self)
28         self.__stack = stack
29     def __getitem__(self, pn):
30         try:
31             return dict.__getitem__(self, pn)
32         except KeyError:
33             return self.__stack.patches.get(pn).commit
34
35 class StackTransaction(object):
36     def __init__(self, stack, msg):
37         self.__stack = stack
38         self.__msg = msg
39         self.__patches = _TransPatchMap(stack)
40         self.__applied = list(self.__stack.patchorder.applied)
41         self.__unapplied = list(self.__stack.patchorder.unapplied)
42         self.__error = None
43         self.__current_tree = self.__stack.head.data.tree
44         self.__base = self.__stack.base
45     stack = property(lambda self: self.__stack)
46     patches = property(lambda self: self.__patches)
47     def __set_applied(self, val):
48         self.__applied = list(val)
49     applied = property(lambda self: self.__applied, __set_applied)
50     def __set_unapplied(self, val):
51         self.__unapplied = list(val)
52     unapplied = property(lambda self: self.__unapplied, __set_unapplied)
53     def __set_base(self, val):
54         assert not self.__applied
55         self.__base = val
56     base = property(lambda self: self.__base, __set_base)
57     def __checkout(self, tree, iw):
58         if not self.__stack.head_top_equal():
59             out.error(
60                 'HEAD and top are not the same.',
61                 'This can happen if you modify a branch with git.',
62                 '"stg repair --help" explains more about what to do next.')
63             self.__abort()
64         if self.__current_tree != tree:
65             assert iw != None
66             iw.checkout(self.__current_tree, tree)
67             self.__current_tree = tree
68     @staticmethod
69     def __abort():
70         raise TransactionException(
71             'Command aborted (all changes rolled back)')
72     def __check_consistency(self):
73         remaining = set(self.__applied + self.__unapplied)
74         for pn, commit in self.__patches.iteritems():
75             if commit == None:
76                 assert self.__stack.patches.exists(pn)
77             else:
78                 assert pn in remaining
79     @property
80     def __head(self):
81         if self.__applied:
82             return self.__patches[self.__applied[-1]]
83         else:
84             return self.__base
85     def abort(self, iw = None):
86         # The only state we need to restore is index+worktree.
87         if iw:
88             self.__checkout(self.__stack.head.data.tree, iw)
89     def run(self, iw = None):
90         self.__check_consistency()
91         new_head = self.__head
92
93         # Set branch head.
94         try:
95             self.__checkout(new_head.data.tree, iw)
96         except git.CheckoutException:
97             # We have to abort the transaction.
98             self.abort(iw)
99             self.__abort()
100         self.__stack.set_head(new_head, self.__msg)
101
102         if self.__error:
103             out.error(self.__error)
104
105         # Write patches.
106         for pn, commit in self.__patches.iteritems():
107             if self.__stack.patches.exists(pn):
108                 p = self.__stack.patches.get(pn)
109                 if commit == None:
110                     p.delete()
111                 else:
112                     p.set_commit(commit, self.__msg)
113             else:
114                 self.__stack.patches.new(pn, commit, self.__msg)
115         _print_current_patch(self.__stack.patchorder.applied, self.__applied)
116         self.__stack.patchorder.applied = self.__applied
117         self.__stack.patchorder.unapplied = self.__unapplied
118
119         if self.__error:
120             return utils.STGIT_CONFLICT
121         else:
122             return utils.STGIT_SUCCESS
123
124     def __halt(self, msg):
125         self.__error = msg
126         raise TransactionHalted(msg)
127
128     @staticmethod
129     def __print_popped(popped):
130         if len(popped) == 0:
131             pass
132         elif len(popped) == 1:
133             out.info('Popped %s' % popped[0])
134         else:
135             out.info('Popped %s -- %s' % (popped[-1], popped[0]))
136
137     def pop_patches(self, p):
138         """Pop all patches pn for which p(pn) is true. Return the list of
139         other patches that had to be popped to accomplish this."""
140         popped = []
141         for i in xrange(len(self.applied)):
142             if p(self.applied[i]):
143                 popped = self.applied[i:]
144                 del self.applied[i:]
145                 break
146         popped1 = [pn for pn in popped if not p(pn)]
147         popped2 = [pn for pn in popped if p(pn)]
148         self.unapplied = popped1 + popped2 + self.unapplied
149         self.__print_popped(popped)
150         return popped1
151
152     def delete_patches(self, p):
153         """Delete all patches pn for which p(pn) is true. Return the list of
154         other patches that had to be popped to accomplish this."""
155         popped = []
156         all_patches = self.applied + self.unapplied
157         for i in xrange(len(self.applied)):
158             if p(self.applied[i]):
159                 popped = self.applied[i:]
160                 del self.applied[i:]
161                 break
162         popped = [pn for pn in popped if not p(pn)]
163         self.unapplied = popped + [pn for pn in self.unapplied if not p(pn)]
164         self.__print_popped(popped)
165         for pn in all_patches:
166             if p(pn):
167                 s = ['', ' (empty)'][self.patches[pn].data.is_nochange()]
168                 self.patches[pn] = None
169                 out.info('Deleted %s%s' % (pn, s))
170         return popped
171
172     def push_patch(self, pn, iw = None):
173         """Attempt to push the named patch. If this results in conflicts,
174         halts the transaction. If index+worktree are given, spill any
175         conflicts to them."""
176         i = self.unapplied.index(pn)
177         cd = self.patches[pn].data
178         s = ['', ' (empty)'][cd.is_nochange()]
179         oldparent = cd.parent
180         cd = cd.set_parent(self.__head)
181         base = oldparent.data.tree
182         ours = cd.parent.data.tree
183         theirs = cd.tree
184         tree = self.__stack.repository.simple_merge(base, ours, theirs)
185         merge_conflict = False
186         if not tree:
187             if iw == None:
188                 self.__halt('%s does not apply cleanly' % pn)
189             try:
190                 self.__checkout(ours, iw)
191             except git.CheckoutException:
192                 self.__halt('Index/worktree dirty')
193             try:
194                 iw.merge(base, ours, theirs)
195                 tree = iw.index.write_tree()
196                 self.__current_tree = tree
197                 s = ' (modified)'
198             except git.MergeException:
199                 tree = ours
200                 merge_conflict = True
201                 s = ' (conflict)'
202         cd = cd.set_tree(tree)
203         self.patches[pn] = self.__stack.repository.commit(cd)
204         del self.unapplied[i]
205         self.applied.append(pn)
206         out.info('Pushed %s%s' % (pn, s))
207         if merge_conflict:
208             self.__halt('Merge conflict')