chiark / gitweb /
cef4ae5d22ba3e9273bfb6c0f06736e338751f41
[stgit] / stgit / stack.py
1 """Basic quilt-like functionality
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os
22
23 from stgit.utils import *
24 from stgit import git
25 from stgit.config import config
26
27
28 # stack exception class
29 class StackException(Exception):
30     pass
31
32 #
33 # Functions
34 #
35 __comment_prefix = 'STG:'
36
37 def __clean_comments(f):
38     """Removes lines marked for status in a commit file
39     """
40     f.seek(0)
41
42     # remove status-prefixed lines
43     lines = filter(lambda x: x[0:len(__comment_prefix)] != __comment_prefix,
44                    f.readlines())
45     # remove empty lines at the end
46     while len(lines) != 0 and lines[-1] == '\n':
47         del lines[-1]
48
49     f.seek(0); f.truncate()
50     f.writelines(lines)
51
52 def edit_file(string, comment):
53     fname = '.stgit.msg'
54     tmpl = os.path.join(git.base_dir, 'patchdescr.tmpl')
55
56     f = file(fname, 'w+')
57     if string:
58         print >> f, string
59     elif os.path.isfile(tmpl):
60         print >> f, file(tmpl).read().rstrip()
61     else:
62         print >> f
63     print >> f, __comment_prefix, comment
64     print >> f, __comment_prefix, \
65           'Lines prefixed with "%s" will be automatically removed.' \
66           % __comment_prefix
67     print >> f, __comment_prefix, \
68           'Trailing empty lines will be automatically removed.'
69     f.close()
70
71     # the editor
72     if 'EDITOR' in os.environ:
73         editor = os.environ['EDITOR']
74     else:
75         editor = 'vi'
76     editor += ' %s' % fname
77
78     print 'Invoking the editor: "%s"...' % editor,
79     sys.stdout.flush()
80     print 'done (exit code: %d)' % os.system(editor)
81
82     f = file(fname, 'r+')
83
84     __clean_comments(f)
85     f.seek(0)
86     string = f.read()
87
88     f.close()
89     os.remove(fname)
90
91     return string
92
93 #
94 # Classes
95 #
96
97 class Patch:
98     """Basic patch implementation
99     """
100     def __init__(self, name, patch_dir):
101         self.__patch_dir = patch_dir
102         self.__name = name
103         self.__dir = os.path.join(self.__patch_dir, self.__name)
104
105     def create(self):
106         os.mkdir(self.__dir)
107         create_empty_file(os.path.join(self.__dir, 'bottom'))
108         create_empty_file(os.path.join(self.__dir, 'top'))
109
110     def delete(self):
111         for f in os.listdir(self.__dir):
112             os.remove(os.path.join(self.__dir, f))
113         os.rmdir(self.__dir)
114
115     def get_name(self):
116         return self.__name
117
118     def __get_field(self, name, multiline = False):
119         id_file = os.path.join(self.__dir, name)
120         if os.path.isfile(id_file):
121             string = read_string(id_file, multiline)
122             if string == '':
123                 return None
124             else:
125                 return string
126         else:
127             return None
128
129     def __set_field(self, name, string, multiline = False):
130         fname = os.path.join(self.__dir, name)
131         if string and string != '':
132             write_string(fname, string, multiline)
133         elif os.path.isfile(fname):
134             os.remove(fname)
135
136     def get_bottom(self):
137         return self.__get_field('bottom')
138
139     def set_bottom(self, string, backup = False):
140         if backup:
141             self.__set_field('bottom.old', self.__get_field('bottom'))
142         self.__set_field('bottom', string)
143
144     def get_top(self):
145         return self.__get_field('top')
146
147     def set_top(self, string, backup = False):
148         if backup:
149             self.__set_field('top.old', self.__get_field('top'))
150         self.__set_field('top', string)
151
152     def restore_old_boundaries(self):
153         bottom = self.__get_field('bottom.old')
154         top = self.__get_field('top.old')
155
156         if top and bottom:
157             self.__set_field('bottom', bottom)
158             self.__set_field('top', top)
159         else:
160             raise StackException, 'No patch undo information'
161
162     def get_description(self):
163         return self.__get_field('description', True)
164
165     def set_description(self, string):
166         self.__set_field('description', string, True)
167
168     def get_authname(self):
169         return self.__get_field('authname')
170
171     def set_authname(self, string):
172         if not string and config.has_option('stgit', 'authname'):
173             string = config.get('stgit', 'authname')
174         self.__set_field('authname', string)
175
176     def get_authemail(self):
177         return self.__get_field('authemail')
178
179     def set_authemail(self, string):
180         if not string and config.has_option('stgit', 'authemail'):
181             string = config.get('stgit', 'authemail')
182         self.__set_field('authemail', string)
183
184     def get_authdate(self):
185         return self.__get_field('authdate')
186
187     def set_authdate(self, string):
188         self.__set_field('authdate', string)
189
190     def get_commname(self):
191         return self.__get_field('commname')
192
193     def set_commname(self, string):
194         if not string and config.has_option('stgit', 'commname'):
195             string = config.get('stgit', 'commname')
196         self.__set_field('commname', string)
197
198     def get_commemail(self):
199         return self.__get_field('commemail')
200
201     def set_commemail(self, string):
202         if not string and config.has_option('stgit', 'commemail'):
203             string = config.get('stgit', 'commemail')
204         self.__set_field('commemail', string)
205
206
207 class Series:
208     """Class including the operations on series
209     """
210     def __init__(self, name = None):
211         """Takes a series name as the parameter. A valid .git/patches/name
212         directory should exist
213         """
214         if name:
215             self.__name = name
216         else:
217             self.__name = git.get_head_file()
218
219         if self.__name:
220             self.__patch_dir = os.path.join(git.base_dir, 'patches',
221                                             self.__name)
222             self.__base_file = os.path.join(git.base_dir, 'refs', 'bases',
223                                             self.__name)
224             self.__applied_file = os.path.join(self.__patch_dir, 'applied')
225             self.__unapplied_file = os.path.join(self.__patch_dir, 'unapplied')
226             self.__current_file = os.path.join(self.__patch_dir, 'current')
227
228     def __set_current(self, name):
229         """Sets the topmost patch
230         """
231         if name:
232             write_string(self.__current_file, name)
233         else:
234             create_empty_file(self.__current_file)
235
236     def get_patch(self, name):
237         """Return a Patch object for the given name
238         """
239         return Patch(name, self.__patch_dir)
240
241     def get_current(self):
242         """Return a Patch object representing the topmost patch
243         """
244         if os.path.isfile(self.__current_file):
245             name = read_string(self.__current_file)
246         else:
247             return None
248         if name == '':
249             return None
250         else:
251             return name
252
253     def get_applied(self):
254         f = file(self.__applied_file)
255         names = [line.strip() for line in f.readlines()]
256         f.close()
257         return names
258
259     def get_unapplied(self):
260         f = file(self.__unapplied_file)
261         names = [line.strip() for line in f.readlines()]
262         f.close()
263         return names
264
265     def get_base_file(self):
266         return self.__base_file
267
268     def __patch_is_current(self, patch):
269         return patch.get_name() == read_string(self.__current_file)
270
271     def __patch_applied(self, name):
272         """Return true if the patch exists in the applied list
273         """
274         return name in self.get_applied()
275
276     def __patch_unapplied(self, name):
277         """Return true if the patch exists in the unapplied list
278         """
279         return name in self.get_unapplied()
280
281     def __begin_stack_check(self):
282         """Save the current HEAD into .git/refs/heads/base if the stack
283         is empty
284         """
285         if len(self.get_applied()) == 0:
286             head = git.get_head()
287             write_string(self.__base_file, head)
288
289     def __end_stack_check(self):
290         """Remove .git/refs/heads/base if the stack is empty.
291         This warning should never happen
292         """
293         if len(self.get_applied()) == 0 \
294            and read_string(self.__base_file) != git.get_head():
295             print 'Warning: stack empty but the HEAD and base are different'
296
297     def head_top_equal(self):
298         """Return true if the head and the top are the same
299         """
300         crt = self.get_current()
301         if not crt:
302             # we don't care, no patches applied
303             return True
304         return git.get_head() == Patch(crt, self.__patch_dir).get_top()
305
306     def init(self):
307         """Initialises the stgit series
308         """
309         bases_dir = os.path.join(git.base_dir, 'refs', 'bases')
310
311         if os.path.isdir(self.__patch_dir):
312             raise StackException, self.__patch_dir + ' already exists'
313         os.makedirs(self.__patch_dir)
314
315         if not os.path.isdir(bases_dir):
316             os.makedirs(bases_dir)
317
318         create_empty_file(self.__applied_file)
319         create_empty_file(self.__unapplied_file)
320
321     def refresh_patch(self, message = None, edit = False,
322                       author_name = None, author_email = None,
323                       author_date = None,
324                       committer_name = None, committer_email = None):
325         """Generates a new commit for the given patch
326         """
327         name = self.get_current()
328         if not name:
329             raise StackException, 'No patches applied'
330
331         patch = Patch(name, self.__patch_dir)
332
333         descr = patch.get_description()
334         if not (message or descr):
335             edit = True
336             descr = ''
337         elif message:
338             descr = message
339
340         if not message and edit:
341             descr = edit_file(descr.rstrip(), \
342                               'Please edit the description for patch "%s" ' \
343                               'above.' % name)
344
345         if not author_name:
346             author_name = patch.get_authname()
347         if not author_email:
348             author_email = patch.get_authemail()
349         if not author_date:
350             author_date = patch.get_authdate()
351         if not committer_name:
352             committer_name = patch.get_commname()
353         if not committer_email:
354             committer_email = patch.get_commemail()
355
356         commit_id = git.commit(message = descr, parents = [patch.get_bottom()],
357                                allowempty = True,
358                                author_name = author_name,
359                                author_email = author_email,
360                                author_date = author_date,
361                                committer_name = committer_name,
362                                committer_email = committer_email)
363
364         patch.set_top(commit_id)
365         patch.set_description(descr)
366         patch.set_authname(author_name)
367         patch.set_authemail(author_email)
368         patch.set_authdate(author_date)
369         patch.set_commname(committer_name)
370         patch.set_commemail(committer_email)
371
372     def new_patch(self, name, message = None, edit = False,
373                   author_name = None, author_email = None, author_date = None,
374                   committer_name = None, committer_email = None):
375         """Creates a new patch
376         """
377         if self.__patch_applied(name) or self.__patch_unapplied(name):
378             raise StackException, 'Patch "%s" already exists' % name
379
380         if not message:
381             descr = edit_file(None, \
382                               'Please enter the description for patch "%s" ' \
383                               'above.' % name)
384         else:
385             descr = message
386
387         head = git.get_head()
388
389         self.__begin_stack_check()
390
391         patch = Patch(name, self.__patch_dir)
392         patch.create()
393         patch.set_bottom(head)
394         patch.set_top(head)
395         patch.set_description(descr)
396         patch.set_authname(author_name)
397         patch.set_authemail(author_email)
398         patch.set_authdate(author_date)
399         patch.set_commname(committer_name)
400         patch.set_commemail(committer_email)
401
402         append_string(self.__applied_file, patch.get_name())
403         self.__set_current(name)
404
405     def delete_patch(self, name):
406         """Deletes a patch
407         """
408         patch = Patch(name, self.__patch_dir)
409
410         if self.__patch_is_current(patch):
411             self.pop_patch(name)
412         elif self.__patch_applied(name):
413             raise StackException, 'Cannot remove an applied patch, "%s", ' \
414                   'which is not current' % name
415         elif not name in self.get_unapplied():
416             raise StackException, 'Unknown patch "%s"' % name
417
418         patch.delete()
419
420         unapplied = self.get_unapplied()
421         unapplied.remove(name)
422         f = file(self.__unapplied_file, 'w+')
423         f.writelines([line + '\n' for line in unapplied])
424         f.close()
425
426     def push_patch(self, name):
427         """Pushes a patch on the stack
428         """
429         unapplied = self.get_unapplied()
430         assert(name in unapplied)
431
432         self.__begin_stack_check()
433
434         patch = Patch(name, self.__patch_dir)
435
436         head = git.get_head()
437         bottom = patch.get_bottom()
438         top = patch.get_top()
439
440         ex = None
441
442         # top != bottom always since we have a commit for each patch
443         if head == bottom:
444             # reset the backup information
445             patch.set_bottom(bottom, backup = True)
446             patch.set_top(top, backup = True)
447
448             git.switch(top)
449         else:
450             # new patch needs to be refreshed.
451             # The current patch is empty after merge.
452             patch.set_bottom(head, backup = True)
453             patch.set_top(head, backup = True)
454             # merge/refresh can fail but the patch needs to be pushed
455             try:
456                 git.merge(bottom, head, top)
457             except git.GitException, ex:
458                 print >> sys.stderr, \
459                       'The merge failed during "push". ' \
460                       'Use "refresh" after fixing the conflicts'
461                 pass
462
463         append_string(self.__applied_file, name)
464
465         unapplied.remove(name)
466         f = file(self.__unapplied_file, 'w+')
467         f.writelines([line + '\n' for line in unapplied])
468         f.close()
469
470         self.__set_current(name)
471
472         if not ex:
473             # if the merge was OK and no conflicts, just refresh the patch
474             self.refresh_patch()
475         else:
476             raise StackException, str(ex)
477
478     def undo_push(self):
479         name = self.get_current()
480         assert(name)
481
482         patch = Patch(name, self.__patch_dir)
483         self.pop_patch(name)
484         patch.restore_old_boundaries()
485
486     def pop_patch(self, name):
487         """Pops the top patch from the stack
488         """
489         applied = self.get_applied()
490         applied.reverse()
491         assert(name in applied)
492
493         patch = Patch(name, self.__patch_dir)
494
495         git.switch(patch.get_bottom())
496
497         # save the new applied list
498         idx = applied.index(name) + 1
499
500         popped = applied[:idx]
501         popped.reverse()
502         unapplied = popped + self.get_unapplied()
503
504         f = file(self.__unapplied_file, 'w+')
505         f.writelines([line + '\n' for line in unapplied])
506         f.close()
507
508         del applied[:idx]
509         applied.reverse()
510
511         f = file(self.__applied_file, 'w+')
512         f.writelines([line + '\n' for line in applied])
513         f.close()
514
515         if applied == []:
516             self.__set_current(None)
517         else:
518             self.__set_current(applied[-1])
519
520         self.__end_stack_check()
521
522     def empty_patch(self, name):
523         """Returns True if the patch is empty
524         """
525         patch = Patch(name, self.__patch_dir)
526         bottom = patch.get_bottom()
527         top = patch.get_top()
528
529         if bottom == top:
530             return True
531         elif git.Commit(top).get_tree() == git.Commit(bottom).get_tree():
532             return True
533
534         return False