1 """Basic quilt-like functionality
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
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.
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.
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
23 from stgit.utils import *
25 from stgit.config import config
28 # stack exception class
29 class StackException(Exception):
34 self.should_print = True
35 def __call__(self, x, until_test, prefix):
37 self.should_print = False
39 return x[0:len(prefix)] != prefix
45 __comment_prefix = 'STG:'
46 __patch_prefix = 'STG_PATCH:'
48 def __clean_comments(f):
49 """Removes lines marked for status in a commit file
53 # remove status-prefixed lines
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)]
60 # remove empty lines at the end
61 while len(lines) != 0 and lines[-1] == '\n':
64 f.seek(0); f.truncate()
67 def edit_file(series, line, comment, show_patch = True):
69 tmpl = os.path.join(git.get_base_dir(), 'patchdescr.tmpl')
74 elif os.path.isfile(tmpl):
75 print >> f, file(tmpl).read().rstrip()
78 print >> f, __comment_prefix, comment
79 print >> f, __comment_prefix, \
80 'Lines prefixed with "%s" will be automatically removed.' \
82 print >> f, __comment_prefix, \
83 'Trailing empty lines will be automatically removed.'
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)
90 #Vim modeline must be near the end.
91 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:'
95 if config.has_option('stgit', 'editor'):
96 editor = config.get('stgit', 'editor')
97 elif 'EDITOR' in os.environ:
98 editor = os.environ['EDITOR']
101 editor += ' %s' % fname
103 print 'Invoking the editor: "%s"...' % editor,
105 print 'done (exit code: %d)' % os.system(editor)
107 f = file(fname, 'r+')
123 """Basic patch implementation
125 def __init__(self, name, series_dir):
126 self.__series_dir = series_dir
128 self.__dir = os.path.join(self.__series_dir, self.__name)
132 create_empty_file(os.path.join(self.__dir, 'bottom'))
133 create_empty_file(os.path.join(self.__dir, 'top'))
136 for f in os.listdir(self.__dir):
137 os.remove(os.path.join(self.__dir, f))
143 def rename(self, newname):
145 self.__name = newname
146 self.__dir = os.path.join(self.__series_dir, self.__name)
148 os.rename(olddir, self.__dir)
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 line = read_string(id_file, multiline)
161 def __set_field(self, name, value, multiline = False):
162 fname = os.path.join(self.__dir, name)
163 if value and value != '':
164 write_string(fname, value, multiline)
165 elif os.path.isfile(fname):
168 def get_old_bottom(self):
169 return self.__get_field('bottom.old')
171 def get_bottom(self):
172 return self.__get_field('bottom')
174 def set_bottom(self, value, backup = False):
176 curr = self.__get_field('bottom')
178 self.__set_field('bottom.old', curr)
180 self.__set_field('bottom.old', None)
181 self.__set_field('bottom', value)
183 def get_old_top(self):
184 return self.__get_field('top.old')
187 return self.__get_field('top')
189 def set_top(self, value, backup = False):
191 curr = self.__get_field('top')
193 self.__set_field('top.old', curr)
195 self.__set_field('top.old', None)
196 self.__set_field('top', value)
198 def restore_old_boundaries(self):
199 bottom = self.__get_field('bottom.old')
200 top = self.__get_field('top.old')
203 self.__set_field('bottom', bottom)
204 self.__set_field('top', top)
209 def get_description(self):
210 return self.__get_field('description', True)
212 def set_description(self, line):
213 self.__set_field('description', line, True)
215 def get_authname(self):
216 return self.__get_field('authname')
218 def set_authname(self, name):
219 if not name and config.has_option('stgit', 'authname'):
220 name = config.get('stgit', 'authname')
221 self.__set_field('authname', name)
223 def get_authemail(self):
224 return self.__get_field('authemail')
226 def set_authemail(self, address):
227 if not address and config.has_option('stgit', 'authemail'):
228 address = config.get('stgit', 'authemail')
229 self.__set_field('authemail', address)
231 def get_authdate(self):
232 return self.__get_field('authdate')
234 def set_authdate(self, authdate):
235 self.__set_field('authdate', authdate)
237 def get_commname(self):
238 return self.__get_field('commname')
240 def set_commname(self, name):
241 if not name and config.has_option('stgit', 'commname'):
242 name = config.get('stgit', 'commname')
243 self.__set_field('commname', name)
245 def get_commemail(self):
246 return self.__get_field('commemail')
248 def set_commemail(self, address):
249 if not address and config.has_option('stgit', 'commemail'):
250 address = config.get('stgit', 'commemail')
251 self.__set_field('commemail', address)
255 """Class including the operations on series
257 def __init__(self, name = None):
258 """Takes a series name as the parameter.
264 self.__name = git.get_head_file()
265 base_dir = git.get_base_dir()
266 except git.GitException, ex:
267 raise StackException, 'GIT tree not initialised: %s' % ex
269 self.__series_dir = os.path.join(base_dir, 'patches',
271 self.__base_file = os.path.join(base_dir, 'refs', 'bases',
274 self.__applied_file = os.path.join(self.__series_dir, 'applied')
275 self.__unapplied_file = os.path.join(self.__series_dir, 'unapplied')
276 self.__current_file = os.path.join(self.__series_dir, 'current')
277 self.__descr_file = os.path.join(self.__series_dir, 'description')
279 # where this series keeps its patches
280 self.__patch_dir = os.path.join(self.__series_dir, 'patches')
281 if not os.path.isdir(self.__patch_dir):
282 self.__patch_dir = self.__series_dir
284 def get_branch(self):
285 """Return the branch name for the Series object
289 def __set_current(self, name):
290 """Sets the topmost patch
293 write_string(self.__current_file, name)
295 create_empty_file(self.__current_file)
297 def get_patch(self, name):
298 """Return a Patch object for the given name
300 return Patch(name, self.__patch_dir)
302 def get_current(self):
303 """Return a Patch object representing the topmost patch
305 if os.path.isfile(self.__current_file):
306 name = read_string(self.__current_file)
314 def get_applied(self):
315 if not os.path.isfile(self.__applied_file):
316 raise StackException, 'Branch "%s" not initialised' % self.__name
317 f = file(self.__applied_file)
318 names = [line.strip() for line in f.readlines()]
322 def get_unapplied(self):
323 if not os.path.isfile(self.__unapplied_file):
324 raise StackException, 'Branch "%s" not initialised' % self.__name
325 f = file(self.__unapplied_file)
326 names = [line.strip() for line in f.readlines()]
330 def get_base_file(self):
331 return self.__base_file
333 def get_protected(self):
334 return os.path.isfile(os.path.join(self.__series_dir, 'protected'))
337 protect_file = os.path.join(self.__series_dir, 'protected')
338 if not os.path.isfile(protect_file):
339 create_empty_file(protect_file)
342 protect_file = os.path.join(self.__series_dir, 'protected')
343 if os.path.isfile(protect_file):
344 os.remove(protect_file)
346 def get_description(self):
347 if os.path.isfile(self.__descr_file):
348 return read_string(self.__descr_file)
352 def __patch_is_current(self, patch):
353 return patch.get_name() == read_string(self.__current_file)
355 def __patch_applied(self, name):
356 """Return true if the patch exists in the applied list
358 return name in self.get_applied()
360 def __patch_unapplied(self, name):
361 """Return true if the patch exists in the unapplied list
363 return name in self.get_unapplied()
365 def __begin_stack_check(self):
366 """Save the current HEAD into .git/refs/heads/base if the stack
369 if len(self.get_applied()) == 0:
370 head = git.get_head()
371 write_string(self.__base_file, head)
373 def __end_stack_check(self):
374 """Remove .git/refs/heads/base if the stack is empty.
375 This warning should never happen
377 if len(self.get_applied()) == 0 \
378 and read_string(self.__base_file) != git.get_head():
379 print 'Warning: stack empty but the HEAD and base are different'
381 def head_top_equal(self):
382 """Return true if the head and the top are the same
384 crt = self.get_current()
386 # we don't care, no patches applied
388 return git.get_head() == Patch(crt, self.__patch_dir).get_top()
390 def is_initialised(self):
391 """Checks if series is already initialised
393 return os.path.isdir(self.__patch_dir)
396 """Initialises the stgit series
398 bases_dir = os.path.join(git.get_base_dir(), 'refs', 'bases')
400 if self.is_initialised():
401 raise StackException, self.__patch_dir + ' already exists'
402 os.makedirs(self.__patch_dir)
404 if not os.path.isdir(bases_dir):
405 os.makedirs(bases_dir)
407 create_empty_file(self.__applied_file)
408 create_empty_file(self.__unapplied_file)
409 create_empty_file(self.__descr_file)
410 os.makedirs(os.path.join(self.__series_dir, 'patches'))
411 self.__begin_stack_check()
414 """Either convert to use a separate patch directory, or
415 unconvert to place the patches in the same directory with
418 if self.__patch_dir == self.__series_dir:
419 print 'Converting old-style to new-style...',
422 self.__patch_dir = os.path.join(self.__series_dir, 'patches')
423 os.makedirs(self.__patch_dir)
425 for p in self.get_applied() + self.get_unapplied():
426 src = os.path.join(self.__series_dir, p)
427 dest = os.path.join(self.__patch_dir, p)
433 print 'Converting new-style to old-style...',
436 for p in self.get_applied() + self.get_unapplied():
437 src = os.path.join(self.__patch_dir, p)
438 dest = os.path.join(self.__series_dir, p)
441 if not os.listdir(self.__patch_dir):
442 os.rmdir(self.__patch_dir)
445 print 'Patch directory %s is not empty.' % self.__name
447 self.__patch_dir = self.__series_dir
449 def rename(self, to_name):
452 to_stack = Series(to_name)
454 if to_stack.is_initialised():
455 raise StackException, '"%s" already exists' % to_stack.get_branch()
456 if os.path.exists(to_stack.__base_file):
457 os.remove(to_stack.__base_file)
459 git.rename_branch(self.__name, to_name)
461 if os.path.isdir(self.__series_dir):
462 os.rename(self.__series_dir, to_stack.__series_dir)
463 if os.path.exists(self.__base_file):
464 os.rename(self.__base_file, to_stack.__base_file)
466 self.__init__(to_name)
468 def clone(self, target_series):
471 base = read_string(self.get_base_file())
472 git.create_branch(target_series, tree_id = base)
473 Series(target_series).init()
474 new_series = Series(target_series)
476 # generate an artificial description file
477 write_string(new_series.__descr_file, 'clone of "%s"' % self.__name)
479 # clone self's entire series as unapplied patches
480 patches = self.get_applied() + self.get_unapplied()
483 patch = self.get_patch(p)
484 new_series.new_patch(p, message = patch.get_description(),
485 can_edit = False, unapplied = True,
486 bottom = patch.get_bottom(),
487 top = patch.get_top(),
488 author_name = patch.get_authname(),
489 author_email = patch.get_authemail(),
490 author_date = patch.get_authdate())
492 # fast forward the cloned series to self's top
493 new_series.forward_patches(self.get_applied())
495 def delete(self, force = False):
496 """Deletes an stgit series
498 if self.is_initialised():
499 patches = self.get_unapplied() + self.get_applied()
500 if not force and patches:
501 raise StackException, \
502 'Cannot delete: the series still contains patches'
504 Patch(p, self.__patch_dir).delete()
506 if os.path.exists(self.__applied_file):
507 os.remove(self.__applied_file)
508 if os.path.exists(self.__unapplied_file):
509 os.remove(self.__unapplied_file)
510 if os.path.exists(self.__current_file):
511 os.remove(self.__current_file)
512 if os.path.exists(self.__descr_file):
513 os.remove(self.__descr_file)
514 if not os.listdir(self.__patch_dir):
515 os.rmdir(self.__patch_dir)
517 print 'Patch directory %s is not empty.' % self.__name
518 if not os.listdir(self.__series_dir):
519 os.rmdir(self.__series_dir)
521 print 'Series directory %s is not empty.' % self.__name
523 if os.path.exists(self.__base_file):
524 os.remove(self.__base_file)
526 def refresh_patch(self, files = None, message = None, edit = False,
529 author_name = None, author_email = None,
531 committer_name = None, committer_email = None):
532 """Generates a new commit for the given patch
534 name = self.get_current()
536 raise StackException, 'No patches applied'
538 patch = Patch(name, self.__patch_dir)
540 descr = patch.get_description()
541 if not (message or descr):
547 if not message and edit:
548 descr = edit_file(self, descr.rstrip(), \
549 'Please edit the description for patch "%s" ' \
550 'above.' % name, show_patch)
553 author_name = patch.get_authname()
555 author_email = patch.get_authemail()
557 author_date = patch.get_authdate()
558 if not committer_name:
559 committer_name = patch.get_commname()
560 if not committer_email:
561 committer_email = patch.get_commemail()
563 commit_id = git.commit(files = files,
564 message = descr, parents = [patch.get_bottom()],
565 cache_update = cache_update,
567 author_name = author_name,
568 author_email = author_email,
569 author_date = author_date,
570 committer_name = committer_name,
571 committer_email = committer_email)
573 patch.set_top(commit_id)
574 patch.set_description(descr)
575 patch.set_authname(author_name)
576 patch.set_authemail(author_email)
577 patch.set_authdate(author_date)
578 patch.set_commname(committer_name)
579 patch.set_commemail(committer_email)
583 def new_patch(self, name, message = None, can_edit = True,
584 unapplied = False, show_patch = False,
585 top = None, bottom = None,
586 author_name = None, author_email = None, author_date = None,
587 committer_name = None, committer_email = None):
588 """Creates a new patch
590 if self.__patch_applied(name) or self.__patch_unapplied(name):
591 raise StackException, 'Patch "%s" already exists' % name
593 if not message and can_edit:
594 descr = edit_file(self, None, \
595 'Please enter the description for patch "%s" ' \
596 'above.' % name, show_patch)
600 head = git.get_head()
602 self.__begin_stack_check()
604 patch = Patch(name, self.__patch_dir)
608 patch.set_bottom(bottom)
610 patch.set_bottom(head)
616 patch.set_description(descr)
617 patch.set_authname(author_name)
618 patch.set_authemail(author_email)
619 patch.set_authdate(author_date)
620 patch.set_commname(committer_name)
621 patch.set_commemail(committer_email)
624 patches = [patch.get_name()] + self.get_unapplied()
626 f = file(self.__unapplied_file, 'w+')
627 f.writelines([line + '\n' for line in patches])
630 append_string(self.__applied_file, patch.get_name())
631 self.__set_current(name)
633 def delete_patch(self, name):
636 patch = Patch(name, self.__patch_dir)
638 if self.__patch_is_current(patch):
640 elif self.__patch_applied(name):
641 raise StackException, 'Cannot remove an applied patch, "%s", ' \
642 'which is not current' % name
643 elif not name in self.get_unapplied():
644 raise StackException, 'Unknown patch "%s"' % name
648 unapplied = self.get_unapplied()
649 unapplied.remove(name)
650 f = file(self.__unapplied_file, 'w+')
651 f.writelines([line + '\n' for line in unapplied])
654 def forward_patches(self, names):
655 """Try to fast-forward an array of patches.
657 On return, patches in names[0:returned_value] have been pushed on the
658 stack. Apply the rest with push_patch
660 unapplied = self.get_unapplied()
661 self.__begin_stack_check()
667 assert(name in unapplied)
669 patch = Patch(name, self.__patch_dir)
672 bottom = patch.get_bottom()
673 top = patch.get_top()
675 # top != bottom always since we have a commit for each patch
677 # reset the backup information
678 patch.set_bottom(head, backup = True)
679 patch.set_top(top, backup = True)
682 head_tree = git.get_commit(head).get_tree()
683 bottom_tree = git.get_commit(bottom).get_tree()
684 if head_tree == bottom_tree:
685 # We must just reparent this patch and create a new commit
687 descr = patch.get_description()
688 author_name = patch.get_authname()
689 author_email = patch.get_authemail()
690 author_date = patch.get_authdate()
691 committer_name = patch.get_commname()
692 committer_email = patch.get_commemail()
694 top_tree = git.get_commit(top).get_tree()
696 top = git.commit(message = descr, parents = [head],
697 cache_update = False,
700 author_name = author_name,
701 author_email = author_email,
702 author_date = author_date,
703 committer_name = committer_name,
704 committer_email = committer_email)
706 patch.set_bottom(head, backup = True)
707 patch.set_top(top, backup = True)
710 # stop the fast-forwarding, must do a real merge
714 unapplied.remove(name)
721 append_strings(self.__applied_file, names[0:forwarded])
723 f = file(self.__unapplied_file, 'w+')
724 f.writelines([line + '\n' for line in unapplied])
727 self.__set_current(name)
731 def push_patch(self, name):
732 """Pushes a patch on the stack
734 unapplied = self.get_unapplied()
735 assert(name in unapplied)
737 self.__begin_stack_check()
739 patch = Patch(name, self.__patch_dir)
741 head = git.get_head()
742 bottom = patch.get_bottom()
743 top = patch.get_top()
748 # top != bottom always since we have a commit for each patch
750 # reset the backup information
751 patch.set_bottom(bottom, backup = True)
752 patch.set_top(top, backup = True)
756 # new patch needs to be refreshed.
757 # The current patch is empty after merge.
758 patch.set_bottom(head, backup = True)
759 patch.set_top(head, backup = True)
761 # Try the fast applying first. If this fails, fall back to the
763 if not git.apply_diff(bottom, top):
764 # if git.apply_diff() fails, the patch requires a diff3
765 # merge and can be reported as modified
768 # merge can fail but the patch needs to be pushed
770 git.merge(bottom, head, top)
771 except git.GitException, ex:
772 print >> sys.stderr, \
773 'The merge failed during "push". ' \
774 'Use "refresh" after fixing the conflicts'
776 append_string(self.__applied_file, name)
778 unapplied.remove(name)
779 f = file(self.__unapplied_file, 'w+')
780 f.writelines([line + '\n' for line in unapplied])
783 self.__set_current(name)
785 # head == bottom case doesn't need to refresh the patch
788 # if the merge was OK and no conflicts, just refresh the patch
789 # The GIT cache was already updated by the merge operation
790 self.refresh_patch(cache_update = False)
792 raise StackException, str(ex)
797 name = self.get_current()
800 patch = Patch(name, self.__patch_dir)
803 return patch.restore_old_boundaries()
805 def pop_patch(self, name):
806 """Pops the top patch from the stack
808 applied = self.get_applied()
810 assert(name in applied)
812 patch = Patch(name, self.__patch_dir)
814 git.switch(patch.get_bottom())
816 # save the new applied list
817 idx = applied.index(name) + 1
819 popped = applied[:idx]
821 unapplied = popped + self.get_unapplied()
823 f = file(self.__unapplied_file, 'w+')
824 f.writelines([line + '\n' for line in unapplied])
830 f = file(self.__applied_file, 'w+')
831 f.writelines([line + '\n' for line in applied])
835 self.__set_current(None)
837 self.__set_current(applied[-1])
839 self.__end_stack_check()
841 def empty_patch(self, name):
842 """Returns True if the patch is empty
844 patch = Patch(name, self.__patch_dir)
845 bottom = patch.get_bottom()
846 top = patch.get_top()
850 elif git.get_commit(top).get_tree() \
851 == git.get_commit(bottom).get_tree():
856 def rename_patch(self, oldname, newname):
857 applied = self.get_applied()
858 unapplied = self.get_unapplied()
860 if oldname == newname:
861 raise StackException, '"To" name and "from" name are the same'
863 if newname in applied or newname in unapplied:
864 raise StackException, 'Patch "%s" already exists' % newname
866 if oldname in unapplied:
867 Patch(oldname, self.__patch_dir).rename(newname)
868 unapplied[unapplied.index(oldname)] = newname
870 f = file(self.__unapplied_file, 'w+')
871 f.writelines([line + '\n' for line in unapplied])
873 elif oldname in applied:
874 Patch(oldname, self.__patch_dir).rename(newname)
875 if oldname == self.get_current():
876 self.__set_current(newname)
878 applied[applied.index(oldname)] = newname
880 f = file(self.__applied_file, 'w+')
881 f.writelines([line + '\n' for line in applied])
884 raise StackException, 'Unknown patch "%s"' % oldname