Allow user to protect some branches against "stg pull"
[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 class FilterUntil:
33 def __init__(self):
34 self.should_print = True
35 def __call__(self, x, until_test, prefix):
36 if until_test(x):
37 self.should_print = False
38 if self.should_print:
39 return x[0:len(prefix)] != prefix
40 return False
41
42 #
43 # Functions
44 #
45 __comment_prefix = 'STG:'
46 __patch_prefix = 'STG_PATCH:'
47
48 def __clean_comments(f):
49 """Removes lines marked for status in a commit file
50 """
51 f.seek(0)
52
53 # remove status-prefixed lines
54 lines = f.readlines()
55
56 patch_filter = FilterUntil()
57 until_test = lambda t: t == (__patch_prefix + '\n')
58 lines = [l for l in lines if patch_filter(l, until_test, __comment_prefix)]
59
60 # remove empty lines at the end
61 while len(lines) != 0 and lines[-1] == '\n':
62 del lines[-1]
63
64 f.seek(0); f.truncate()
65 f.writelines(lines)
66
67 def edit_file(series, string, comment, show_patch = True):
68 fname = '.stgit.msg'
69 tmpl = os.path.join(git.base_dir, 'patchdescr.tmpl')
70
71 f = file(fname, 'w+')
72 if string:
73 print >> f, string
74 elif os.path.isfile(tmpl):
75 print >> f, file(tmpl).read().rstrip()
76 else:
77 print >> f
78 print >> f, __comment_prefix, comment
79 print >> f, __comment_prefix, \
80 'Lines prefixed with "%s" will be automatically removed.' \
81 % __comment_prefix
82 print >> f, __comment_prefix, \
83 'Trailing empty lines will be automatically removed.'
84
85 if show_patch:
86 print >> f, __patch_prefix
87 # series.get_patch(series.get_current()).get_top()
88 git.diff([], series.get_patch(series.get_current()).get_bottom(), None, f)
89
90 #Vim modeline must be near the end.
91 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff:'
92 f.close()
93
94 # the editor
95 if config.has_option('stgit', 'editor'):
96 editor = config.get('stgit', 'editor')
97 elif 'EDITOR' in os.environ:
98 editor = os.environ['EDITOR']
99 else:
100 editor = 'vi'
101 editor += ' %s' % fname
102
103 print 'Invoking the editor: "%s"...' % editor,
104 sys.stdout.flush()
105 print 'done (exit code: %d)' % os.system(editor)
106
107 f = file(fname, 'r+')
108
109 __clean_comments(f)
110 f.seek(0)
111 string = f.read()
112
113 f.close()
114 os.remove(fname)
115
116 return string
117
118 #
119 # Classes
120 #
121
122 class Patch:
123 """Basic patch implementation
124 """
125 def __init__(self, name, patch_dir):
126 self.__patch_dir = patch_dir
127 self.__name = name
128 self.__dir = os.path.join(self.__patch_dir, self.__name)
129
130 def create(self):
131 os.mkdir(self.__dir)
132 create_empty_file(os.path.join(self.__dir, 'bottom'))
133 create_empty_file(os.path.join(self.__dir, 'top'))
134
135 def delete(self):
136 for f in os.listdir(self.__dir):
137 os.remove(os.path.join(self.__dir, f))
138 os.rmdir(self.__dir)
139
140 def get_name(self):
141 return self.__name
142
143 def rename(self, newname):
144 olddir = self.__dir
145 self.__name = newname
146 self.__dir = os.path.join(self.__patch_dir, self.__name)
147
148 os.rename(olddir, self.__dir)
149
150 def __get_field(self, name, multiline = False):
151 id_file = os.path.join(self.__dir, name)
152 if os.path.isfile(id_file):
153 string = read_string(id_file, multiline)
154 if string == '':
155 return None
156 else:
157 return string
158 else:
159 return None
160
161 def __set_field(self, name, string, multiline = False):
162 fname = os.path.join(self.__dir, name)
163 if string and string != '':
164 write_string(fname, string, multiline)
165 elif os.path.isfile(fname):
166 os.remove(fname)
167
168 def get_bottom(self):
169 return self.__get_field('bottom')
170
171 def set_bottom(self, string, backup = False):
172 if backup:
173 curr = self.__get_field('bottom')
174 if curr != string:
175 self.__set_field('bottom.old', curr)
176 else:
177 self.__set_field('bottom.old', None)
178 self.__set_field('bottom', string)
179
180 def get_top(self):
181 return self.__get_field('top')
182
183 def set_top(self, string, backup = False):
184 if backup:
185 curr = self.__get_field('top')
186 if curr != string:
187 self.__set_field('top.old', curr)
188 else:
189 self.__set_field('top.old', None)
190 self.__set_field('top', string)
191
192 def restore_old_boundaries(self):
193 bottom = self.__get_field('bottom.old')
194 top = self.__get_field('top.old')
195
196 if top and bottom:
197 self.__set_field('bottom', bottom)
198 self.__set_field('top', top)
199 return True
200 else:
201 return False
202
203 def get_description(self):
204 return self.__get_field('description', True)
205
206 def set_description(self, string):
207 self.__set_field('description', string, True)
208
209 def get_authname(self):
210 return self.__get_field('authname')
211
212 def set_authname(self, string):
213 if not string and config.has_option('stgit', 'authname'):
214 string = config.get('stgit', 'authname')
215 self.__set_field('authname', string)
216
217 def get_authemail(self):
218 return self.__get_field('authemail')
219
220 def set_authemail(self, string):
221 if not string and config.has_option('stgit', 'authemail'):
222 string = config.get('stgit', 'authemail')
223 self.__set_field('authemail', string)
224
225 def get_authdate(self):
226 return self.__get_field('authdate')
227
228 def set_authdate(self, string):
229 self.__set_field('authdate', string)
230
231 def get_commname(self):
232 return self.__get_field('commname')
233
234 def set_commname(self, string):
235 if not string and config.has_option('stgit', 'commname'):
236 string = config.get('stgit', 'commname')
237 self.__set_field('commname', string)
238
239 def get_commemail(self):
240 return self.__get_field('commemail')
241
242 def set_commemail(self, string):
243 if not string and config.has_option('stgit', 'commemail'):
244 string = config.get('stgit', 'commemail')
245 self.__set_field('commemail', string)
246
247
248 class Series:
249 """Class including the operations on series
250 """
251 def __init__(self, name = None):
252 """Takes a series name as the parameter.
253 """
254 if name:
255 self.__name = name
256 else:
257 self.__name = git.get_head_file()
258
259 if self.__name:
260 self.__patch_dir = os.path.join(git.base_dir, 'patches',
261 self.__name)
262 self.__base_file = os.path.join(git.base_dir, 'refs', 'bases',
263 self.__name)
264 self.__applied_file = os.path.join(self.__patch_dir, 'applied')
265 self.__unapplied_file = os.path.join(self.__patch_dir, 'unapplied')
266 self.__current_file = os.path.join(self.__patch_dir, 'current')
267
268 def get_branch(self):
269 """Return the branch name for the Series object
270 """
271 return self.__name
272
273 def __set_current(self, name):
274 """Sets the topmost patch
275 """
276 if name:
277 write_string(self.__current_file, name)
278 else:
279 create_empty_file(self.__current_file)
280
281 def get_patch(self, name):
282 """Return a Patch object for the given name
283 """
284 return Patch(name, self.__patch_dir)
285
286 def get_current(self):
287 """Return a Patch object representing the topmost patch
288 """
289 if os.path.isfile(self.__current_file):
290 name = read_string(self.__current_file)
291 else:
292 return None
293 if name == '':
294 return None
295 else:
296 return name
297
298 def get_applied(self):
299 if not os.path.isfile(self.__applied_file):
300 raise StackException, 'Branch "%s" not initialised' % self.__name
301 f = file(self.__applied_file)
302 names = [line.strip() for line in f.readlines()]
303 f.close()
304 return names
305
306 def get_unapplied(self):
307 if not os.path.isfile(self.__unapplied_file):
308 raise StackException, 'Branch "%s" not initialised' % self.__name
309 f = file(self.__unapplied_file)
310 names = [line.strip() for line in f.readlines()]
311 f.close()
312 return names
313
314 def get_base_file(self):
315 return self.__base_file
316
317 def get_protected(self):
318 return os.path.isfile(os.path.join(self.__patch_dir, 'protected'))
319
320 def protect(self):
321 protect_file = os.path.join(self.__patch_dir, 'protected')
322 if not os.path.isfile(protect_file):
323 create_empty_file(protect_file)
324
325 def unprotect(self):
326 protect_file = os.path.join(self.__patch_dir, 'protected')
327 if os.path.isfile(protect_file):
328 os.remove(protect_file)
329
330 def __patch_is_current(self, patch):
331 return patch.get_name() == read_string(self.__current_file)
332
333 def __patch_applied(self, name):
334 """Return true if the patch exists in the applied list
335 """
336 return name in self.get_applied()
337
338 def __patch_unapplied(self, name):
339 """Return true if the patch exists in the unapplied list
340 """
341 return name in self.get_unapplied()
342
343 def __begin_stack_check(self):
344 """Save the current HEAD into .git/refs/heads/base if the stack
345 is empty
346 """
347 if len(self.get_applied()) == 0:
348 head = git.get_head()
349 write_string(self.__base_file, head)
350
351 def __end_stack_check(self):
352 """Remove .git/refs/heads/base if the stack is empty.
353 This warning should never happen
354 """
355 if len(self.get_applied()) == 0 \
356 and read_string(self.__base_file) != git.get_head():
357 print 'Warning: stack empty but the HEAD and base are different'
358
359 def head_top_equal(self):
360 """Return true if the head and the top are the same
361 """
362 crt = self.get_current()
363 if not crt:
364 # we don't care, no patches applied
365 return True
366 return git.get_head() == Patch(crt, self.__patch_dir).get_top()
367
368 def init(self):
369 """Initialises the stgit series
370 """
371 bases_dir = os.path.join(git.base_dir, 'refs', 'bases')
372
373 if os.path.isdir(self.__patch_dir):
374 raise StackException, self.__patch_dir + ' already exists'
375 os.makedirs(self.__patch_dir)
376
377 if not os.path.isdir(bases_dir):
378 os.makedirs(bases_dir)
379
380 create_empty_file(self.__applied_file)
381 create_empty_file(self.__unapplied_file)
382 self.__begin_stack_check()
383
384 def delete(self, force = False):
385 """Deletes an stgit series
386 """
387 if os.path.isdir(self.__patch_dir):
388 patches = self.get_unapplied() + self.get_applied()
389 if not force and patches:
390 raise StackException, \
391 'Cannot delete: the series still contains patches'
392 patches.reverse()
393 for p in patches:
394 self.delete_patch(p)
395
396 if os.path.isfile(self.__applied_file):
397 os.remove(self.__applied_file)
398 if os.path.isfile(self.__unapplied_file):
399 os.remove(self.__unapplied_file)
400 if os.path.isfile(self.__current_file):
401 os.remove(self.__current_file)
402 if not os.listdir(self.__patch_dir):
403 os.rmdir(self.__patch_dir)
404 else:
405 print 'Series directory %s is not empty.' % self.__name
406
407 if os.path.isfile(self.__base_file):
408 os.remove(self.__base_file)
409
410 def refresh_patch(self, message = None, edit = False, show_patch = False,
411 cache_update = True,
412 author_name = None, author_email = None,
413 author_date = None,
414 committer_name = None, committer_email = None):
415 """Generates a new commit for the given patch
416 """
417 name = self.get_current()
418 if not name:
419 raise StackException, 'No patches applied'
420
421 patch = Patch(name, self.__patch_dir)
422
423 descr = patch.get_description()
424 if not (message or descr):
425 edit = True
426 descr = ''
427 elif message:
428 descr = message
429
430 if not message and edit:
431 descr = edit_file(self, descr.rstrip(), \
432 'Please edit the description for patch "%s" ' \
433 'above.' % name, show_patch)
434
435 if not author_name:
436 author_name = patch.get_authname()
437 if not author_email:
438 author_email = patch.get_authemail()
439 if not author_date:
440 author_date = patch.get_authdate()
441 if not committer_name:
442 committer_name = patch.get_commname()
443 if not committer_email:
444 committer_email = patch.get_commemail()
445
446 commit_id = git.commit(message = descr, parents = [patch.get_bottom()],
447 cache_update = cache_update,
448 allowempty = True,
449 author_name = author_name,
450 author_email = author_email,
451 author_date = author_date,
452 committer_name = committer_name,
453 committer_email = committer_email)
454
455 patch.set_top(commit_id)
456 patch.set_description(descr)
457 patch.set_authname(author_name)
458 patch.set_authemail(author_email)
459 patch.set_authdate(author_date)
460 patch.set_commname(committer_name)
461 patch.set_commemail(committer_email)
462
463 return commit_id
464
465 def new_patch(self, name, message = None, can_edit = True,
466 unapplied = False, show_patch = False,
467 top = None, bottom = None,
468 author_name = None, author_email = None, author_date = None,
469 committer_name = None, committer_email = None):
470 """Creates a new patch
471 """
472 if self.__patch_applied(name) or self.__patch_unapplied(name):
473 raise StackException, 'Patch "%s" already exists' % name
474
475 if not message and can_edit:
476 descr = edit_file(self, None, \
477 'Please enter the description for patch "%s" ' \
478 'above.' % name, show_patch)
479 else:
480 descr = message
481
482 head = git.get_head()
483
484 self.__begin_stack_check()
485
486 patch = Patch(name, self.__patch_dir)
487 patch.create()
488
489 if bottom:
490 patch.set_bottom(bottom)
491 else:
492 patch.set_bottom(head)
493 if top:
494 patch.set_top(top)
495 else:
496 patch.set_top(head)
497
498 patch.set_description(descr)
499 patch.set_authname(author_name)
500 patch.set_authemail(author_email)
501 patch.set_authdate(author_date)
502 patch.set_commname(committer_name)
503 patch.set_commemail(committer_email)
504
505 if unapplied:
506 patches = [patch.get_name()] + self.get_unapplied()
507
508 f = file(self.__unapplied_file, 'w+')
509 f.writelines([line + '\n' for line in patches])
510 f.close()
511 else:
512 append_string(self.__applied_file, patch.get_name())
513 self.__set_current(name)
514
515 def delete_patch(self, name):
516 """Deletes a patch
517 """
518 patch = Patch(name, self.__patch_dir)
519
520 if self.__patch_is_current(patch):
521 self.pop_patch(name)
522 elif self.__patch_applied(name):
523 raise StackException, 'Cannot remove an applied patch, "%s", ' \
524 'which is not current' % name
525 elif not name in self.get_unapplied():
526 raise StackException, 'Unknown patch "%s"' % name
527
528 patch.delete()
529
530 unapplied = self.get_unapplied()
531 unapplied.remove(name)
532 f = file(self.__unapplied_file, 'w+')
533 f.writelines([line + '\n' for line in unapplied])
534 f.close()
535
536 def forward_patches(self, names):
537 """Try to fast-forward an array of patches.
538
539 On return, patches in names[0:returned_value] have been pushed on the
540 stack. Apply the rest with push_patch
541 """
542 unapplied = self.get_unapplied()
543 self.__begin_stack_check()
544
545 forwarded = 0
546 top = git.get_head()
547
548 for name in names:
549 assert(name in unapplied)
550
551 patch = Patch(name, self.__patch_dir)
552
553 head = top
554 bottom = patch.get_bottom()
555 top = patch.get_top()
556
557 # top != bottom always since we have a commit for each patch
558 if head == bottom:
559 # reset the backup information
560 patch.set_bottom(head, backup = True)
561 patch.set_top(top, backup = True)
562
563 else:
564 head_tree = git.get_commit(head).get_tree()
565 bottom_tree = git.get_commit(bottom).get_tree()
566 if head_tree == bottom_tree:
567 # We must just reparent this patch and create a new commit
568 # for it
569 descr = patch.get_description()
570 author_name = patch.get_authname()
571 author_email = patch.get_authemail()
572 author_date = patch.get_authdate()
573 committer_name = patch.get_commname()
574 committer_email = patch.get_commemail()
575
576 top_tree = git.get_commit(top).get_tree()
577
578 top = git.commit(message = descr, parents = [head],
579 cache_update = False,
580 tree_id = top_tree,
581 allowempty = True,
582 author_name = author_name,
583 author_email = author_email,
584 author_date = author_date,
585 committer_name = committer_name,
586 committer_email = committer_email)
587
588 patch.set_bottom(head, backup = True)
589 patch.set_top(top, backup = True)
590 else:
591 top = head
592 # stop the fast-forwarding, must do a real merge
593 break
594
595 forwarded+=1
596 unapplied.remove(name)
597
598 git.switch(top)
599
600 append_strings(self.__applied_file, names[0:forwarded])
601
602 f = file(self.__unapplied_file, 'w+')
603 f.writelines([line + '\n' for line in unapplied])
604 f.close()
605
606 self.__set_current(name)
607
608 return forwarded
609
610 def push_patch(self, name):
611 """Pushes a patch on the stack
612 """
613 unapplied = self.get_unapplied()
614 assert(name in unapplied)
615
616 self.__begin_stack_check()
617
618 patch = Patch(name, self.__patch_dir)
619
620 head = git.get_head()
621 bottom = patch.get_bottom()
622 top = patch.get_top()
623
624 ex = None
625
626 # top != bottom always since we have a commit for each patch
627 if head == bottom:
628 # reset the backup information
629 patch.set_bottom(bottom, backup = True)
630 patch.set_top(top, backup = True)
631
632 git.switch(top)
633 else:
634 # new patch needs to be refreshed.
635 # The current patch is empty after merge.
636 patch.set_bottom(head, backup = True)
637 patch.set_top(head, backup = True)
638
639 # Try the fast applying first. If this fails, fall back to the
640 # three-way merge
641 if not git.apply_diff(bottom, top):
642 # merge can fail but the patch needs to be pushed
643 try:
644 git.merge(bottom, head, top)
645 except git.GitException, ex:
646 print >> sys.stderr, \
647 'The merge failed during "push". ' \
648 'Use "refresh" after fixing the conflicts'
649
650 append_string(self.__applied_file, name)
651
652 unapplied.remove(name)
653 f = file(self.__unapplied_file, 'w+')
654 f.writelines([line + '\n' for line in unapplied])
655 f.close()
656
657 self.__set_current(name)
658
659 # head == bottom case doesn't need to refresh the patch
660 if head != bottom:
661 if not ex:
662 # if the merge was OK and no conflicts, just refresh the patch
663 # The GIT cache was already updated by the merge operation
664 self.refresh_patch(cache_update = False)
665 else:
666 raise StackException, str(ex)
667
668 def undo_push(self):
669 name = self.get_current()
670 assert(name)
671
672 patch = Patch(name, self.__patch_dir)
673 git.reset()
674 self.pop_patch(name)
675 return patch.restore_old_boundaries()
676
677 def pop_patch(self, name):
678 """Pops the top patch from the stack
679 """
680 applied = self.get_applied()
681 applied.reverse()
682 assert(name in applied)
683
684 patch = Patch(name, self.__patch_dir)
685
686 git.switch(patch.get_bottom())
687
688 # save the new applied list
689 idx = applied.index(name) + 1
690
691 popped = applied[:idx]
692 popped.reverse()
693 unapplied = popped + self.get_unapplied()
694
695 f = file(self.__unapplied_file, 'w+')
696 f.writelines([line + '\n' for line in unapplied])
697 f.close()
698
699 del applied[:idx]
700 applied.reverse()
701
702 f = file(self.__applied_file, 'w+')
703 f.writelines([line + '\n' for line in applied])
704 f.close()
705
706 if applied == []:
707 self.__set_current(None)
708 else:
709 self.__set_current(applied[-1])
710
711 self.__end_stack_check()
712
713 def empty_patch(self, name):
714 """Returns True if the patch is empty
715 """
716 patch = Patch(name, self.__patch_dir)
717 bottom = patch.get_bottom()
718 top = patch.get_top()
719
720 if bottom == top:
721 return True
722 elif git.get_commit(top).get_tree() \
723 == git.get_commit(bottom).get_tree():
724 return True
725
726 return False
727
728 def rename_patch(self, oldname, newname):
729 applied = self.get_applied()
730 unapplied = self.get_unapplied()
731
732 if newname in applied or newname in unapplied:
733 raise StackException, 'Patch "%s" already exists' % newname
734
735 if oldname in unapplied:
736 Patch(oldname, self.__patch_dir).rename(newname)
737 unapplied[unapplied.index(oldname)] = newname
738
739 f = file(self.__unapplied_file, 'w+')
740 f.writelines([line + '\n' for line in unapplied])
741 f.close()
742 elif oldname in applied:
743 Patch(oldname, self.__patch_dir).rename(newname)
744 if oldname == self.get_current():
745 self.__set_current(newname)
746
747 applied[applied.index(oldname)] = newname
748
749 f = file(self.__applied_file, 'w+')
750 f.writelines([line + '\n' for line in applied])
751 f.close()
752 else:
753 raise StackException, 'Unknown patch "%s"' % oldname