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 *
24 from stgit import git, basedir, templates
25 from stgit.config import config
26 from shutil import copyfile
29 # stack exception class
30 class StackException(Exception):
35 self.should_print = True
36 def __call__(self, x, until_test, prefix):
38 self.should_print = False
40 return x[0:len(prefix)] != prefix
46 __comment_prefix = 'STG:'
47 __patch_prefix = 'STG_PATCH:'
49 def __clean_comments(f):
50 """Removes lines marked for status in a commit file
54 # remove status-prefixed lines
57 patch_filter = FilterUntil()
58 until_test = lambda t: t == (__patch_prefix + '\n')
59 lines = [l for l in lines if patch_filter(l, until_test, __comment_prefix)]
61 # remove empty lines at the end
62 while len(lines) != 0 and lines[-1] == '\n':
65 f.seek(0); f.truncate()
68 def edit_file(series, line, comment, show_patch = True):
69 fname = '.stgitmsg.txt'
70 tmpl = templates.get_template('patchdescr.tmpl')
79 print >> f, __comment_prefix, comment
80 print >> f, __comment_prefix, \
81 'Lines prefixed with "%s" will be automatically removed.' \
83 print >> f, __comment_prefix, \
84 'Trailing empty lines will be automatically removed.'
87 print >> f, __patch_prefix
88 # series.get_patch(series.get_current()).get_top()
89 git.diff([], series.get_patch(series.get_current()).get_bottom(), None, f)
91 #Vim modeline must be near the end.
92 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:'
113 """An object with stgit-like properties stored as files in a directory
115 def _set_dir(self, dir):
120 def create_empty_field(self, name):
121 create_empty_file(os.path.join(self.__dir, name))
123 def _get_field(self, name, multiline = False):
124 id_file = os.path.join(self.__dir, name)
125 if os.path.isfile(id_file):
126 line = read_string(id_file, multiline)
134 def _set_field(self, name, value, multiline = False):
135 fname = os.path.join(self.__dir, name)
136 if value and value != '':
137 write_string(fname, value, multiline)
138 elif os.path.isfile(fname):
142 class Patch(StgitObject):
143 """Basic patch implementation
145 def __init__(self, name, series_dir, refs_dir):
146 self.__series_dir = series_dir
148 self._set_dir(os.path.join(self.__series_dir, self.__name))
149 self.__refs_dir = refs_dir
150 self.__top_ref_file = os.path.join(self.__refs_dir, self.__name)
151 self.__log_ref_file = os.path.join(self.__refs_dir,
152 self.__name + '.log')
155 os.mkdir(self._dir())
156 self.create_empty_field('bottom')
157 self.create_empty_field('top')
160 for f in os.listdir(self._dir()):
161 os.remove(os.path.join(self._dir(), f))
162 os.rmdir(self._dir())
163 os.remove(self.__top_ref_file)
164 if os.path.exists(self.__log_ref_file):
165 os.remove(self.__log_ref_file)
170 def rename(self, newname):
172 old_top_ref_file = self.__top_ref_file
173 old_log_ref_file = self.__log_ref_file
174 self.__name = newname
175 self._set_dir(os.path.join(self.__series_dir, self.__name))
176 self.__top_ref_file = os.path.join(self.__refs_dir, self.__name)
177 self.__log_ref_file = os.path.join(self.__refs_dir,
178 self.__name + '.log')
180 os.rename(olddir, self._dir())
181 os.rename(old_top_ref_file, self.__top_ref_file)
182 if os.path.exists(old_log_ref_file):
183 os.rename(old_log_ref_file, self.__log_ref_file)
185 def __update_top_ref(self, ref):
186 write_string(self.__top_ref_file, ref)
188 def __update_log_ref(self, ref):
189 write_string(self.__log_ref_file, ref)
191 def update_top_ref(self):
194 self.__update_top_ref(top)
196 def get_old_bottom(self):
197 return self._get_field('bottom.old')
199 def get_bottom(self):
200 return self._get_field('bottom')
202 def set_bottom(self, value, backup = False):
204 curr = self._get_field('bottom')
205 self._set_field('bottom.old', curr)
206 self._set_field('bottom', value)
208 def get_old_top(self):
209 return self._get_field('top.old')
212 return self._get_field('top')
214 def set_top(self, value, backup = False):
216 curr = self._get_field('top')
217 self._set_field('top.old', curr)
218 self._set_field('top', value)
219 self.__update_top_ref(value)
221 def restore_old_boundaries(self):
222 bottom = self._get_field('bottom.old')
223 top = self._get_field('top.old')
226 self._set_field('bottom', bottom)
227 self._set_field('top', top)
228 self.__update_top_ref(top)
233 def get_description(self):
234 return self._get_field('description', True)
236 def set_description(self, line):
237 self._set_field('description', line, True)
239 def get_authname(self):
240 return self._get_field('authname')
242 def set_authname(self, name):
243 self._set_field('authname', name or git.author().name)
245 def get_authemail(self):
246 return self._get_field('authemail')
248 def set_authemail(self, email):
249 self._set_field('authemail', email or git.author().email)
251 def get_authdate(self):
252 return self._get_field('authdate')
254 def set_authdate(self, date):
255 self._set_field('authdate', date or git.author().date)
257 def get_commname(self):
258 return self._get_field('commname')
260 def set_commname(self, name):
261 self._set_field('commname', name or git.committer().name)
263 def get_commemail(self):
264 return self._get_field('commemail')
266 def set_commemail(self, email):
267 self._set_field('commemail', email or git.committer().email)
270 return self._get_field('log')
272 def set_log(self, value, backup = False):
273 self._set_field('log', value)
274 self.__update_log_ref(value)
276 # The current StGIT metadata format version.
279 def format_version_key(branch):
280 return 'branch.%s.stgitformatversion' % branch
282 def update_to_current_format_version(branch, git_dir):
283 """Update a potentially older StGIT directory structure to the
284 latest version. Note: This function should depend as little as
285 possible on external functions that may change during a format
286 version bump, since it must remain able to process older formats."""
288 branch_dir = os.path.join(git_dir, 'patches', branch)
289 def get_format_version():
290 """Return the integer format version number, or None if the
291 branch doesn't have any StGIT metadata at all, of any version."""
292 fv = config.get(format_version_key(branch))
294 # Great, there's an explicitly recorded format version
295 # number, which means that the branch is initialized and
296 # of that exact version.
298 elif os.path.isdir(os.path.join(branch_dir, 'patches')):
299 # There's a .git/patches/<branch>/patches dirctory, which
300 # means this is an initialized version 1 branch.
302 elif os.path.isdir(branch_dir):
303 # There's a .git/patches/<branch> directory, which means
304 # this is an initialized version 0 branch.
307 # The branch doesn't seem to be initialized at all.
309 def set_format_version(v):
310 config.set(format_version_key(branch), '%d' % v)
312 if not os.path.isdir(d):
315 if os.path.exists(f):
319 if get_format_version() == 0:
320 mkdir(os.path.join(branch_dir, 'trash'))
321 patch_dir = os.path.join(branch_dir, 'patches')
323 refs_dir = os.path.join(git_dir, 'refs', 'patches', branch)
325 for patch in (file(os.path.join(branch_dir, 'unapplied')).readlines()
326 + file(os.path.join(branch_dir, 'applied')).readlines()):
327 patch = patch.strip()
328 os.rename(os.path.join(branch_dir, patch),
329 os.path.join(patch_dir, patch))
330 Patch(patch, patch_dir, refs_dir).update_top_ref()
331 set_format_version(1)
334 if get_format_version() == 1:
335 desc_file = os.path.join(branch_dir, 'description')
336 if os.path.isfile(desc_file):
337 desc = read_string(desc_file)
339 config.set('branch.%s.description' % branch, desc)
341 rm(os.path.join(branch_dir, 'current'))
342 rm(os.path.join(git_dir, 'refs', 'bases', branch))
343 set_format_version(2)
345 # Make sure we're at the latest version.
346 if not get_format_version() in [None, FORMAT_VERSION]:
347 raise StackException('Branch %s is at format version %d, expected %d'
348 % (branch, get_format_version(), FORMAT_VERSION))
350 class Series(StgitObject):
351 """Class including the operations on series
353 def __init__(self, name = None):
354 """Takes a series name as the parameter.
360 self.__name = git.get_head_file()
361 self.__base_dir = basedir.get()
362 except git.GitException, ex:
363 raise StackException, 'GIT tree not initialised: %s' % ex
365 self._set_dir(os.path.join(self.__base_dir, 'patches', self.__name))
367 # Update the branch to the latest format version if it is
368 # initialized, but don't touch it if it isn't.
369 update_to_current_format_version(self.__name, self.__base_dir)
371 self.__refs_dir = os.path.join(self.__base_dir, 'refs', 'patches',
374 self.__applied_file = os.path.join(self._dir(), 'applied')
375 self.__unapplied_file = os.path.join(self._dir(), 'unapplied')
376 self.__hidden_file = os.path.join(self._dir(), 'hidden')
378 # where this series keeps its patches
379 self.__patch_dir = os.path.join(self._dir(), 'patches')
382 self.__trash_dir = os.path.join(self._dir(), 'trash')
384 def __patch_name_valid(self, name):
385 """Raise an exception if the patch name is not valid.
387 if not name or re.search('[^\w.-]', name):
388 raise StackException, 'Invalid patch name: "%s"' % name
390 def get_branch(self):
391 """Return the branch name for the Series object
395 def get_patch(self, name):
396 """Return a Patch object for the given name
398 return Patch(name, self.__patch_dir, self.__refs_dir)
400 def get_current_patch(self):
401 """Return a Patch object representing the topmost patch, or
402 None if there is no such patch."""
403 crt = self.get_current()
406 return Patch(crt, self.__patch_dir, self.__refs_dir)
408 def get_current(self):
409 """Return the name of the topmost patch, or None if there is
412 applied = self.get_applied()
413 except StackException:
414 # No "applied" file: branch is not initialized.
419 # No patches applied.
422 def get_applied(self):
423 if not os.path.isfile(self.__applied_file):
424 raise StackException, 'Branch "%s" not initialised' % self.__name
425 f = file(self.__applied_file)
426 names = [line.strip() for line in f.readlines()]
430 def get_unapplied(self):
431 if not os.path.isfile(self.__unapplied_file):
432 raise StackException, 'Branch "%s" not initialised' % self.__name
433 f = file(self.__unapplied_file)
434 names = [line.strip() for line in f.readlines()]
438 def get_hidden(self):
439 if not os.path.isfile(self.__hidden_file):
441 f = file(self.__hidden_file)
442 names = [line.strip() for line in f.readlines()]
447 # Return the parent of the bottommost patch, if there is one.
448 if os.path.isfile(self.__applied_file):
449 bottommost = file(self.__applied_file).readline().strip()
451 return self.get_patch(bottommost).get_bottom()
452 # No bottommost patch, so just return HEAD
453 return git.get_head()
456 """Return the head of the branch
458 crt = self.get_current_patch()
462 return self.get_base()
464 def get_protected(self):
465 return os.path.isfile(os.path.join(self._dir(), 'protected'))
468 protect_file = os.path.join(self._dir(), 'protected')
469 if not os.path.isfile(protect_file):
470 create_empty_file(protect_file)
473 protect_file = os.path.join(self._dir(), 'protected')
474 if os.path.isfile(protect_file):
475 os.remove(protect_file)
477 def __branch_descr(self):
478 return 'branch.%s.description' % self.get_branch()
480 def get_description(self):
481 return config.get(self.__branch_descr()) or ''
483 def set_description(self, line):
485 config.set(self.__branch_descr(), line)
487 config.unset(self.__branch_descr())
489 def get_parent_remote(self):
490 value = config.get('branch.%s.remote' % self.__name)
493 elif 'origin' in git.remotes_list():
494 print 'Notice: no parent remote declared for stack "%s", ' \
495 'defaulting to "origin". Consider setting "branch.%s.remote" ' \
496 'and "branch.%s.merge" with "git repo-config".' \
497 % (self.__name, self.__name, self.__name)
500 raise StackException, 'Cannot find a parent remote for "%s"' % self.__name
502 def __set_parent_remote(self, remote):
503 value = config.set('branch.%s.remote' % self.__name, remote)
505 def get_parent_branch(self):
506 value = config.get('branch.%s.stgit.parentbranch' % self.__name)
509 elif git.rev_parse('heads/origin'):
510 print 'Notice: no parent branch declared for stack "%s", ' \
511 'defaulting to "heads/origin". Consider setting ' \
512 '"branch.%s.stgit.parentbranch" with "git repo-config".' \
513 % (self.__name, self.__name)
514 return 'heads/origin'
516 raise StackException, 'Cannot find a parent branch for "%s"' % self.__name
518 def __set_parent_branch(self, name):
519 if config.get('branch.%s.remote' % self.__name):
520 # Never set merge if remote is not set to avoid
521 # possibly-erroneous lookups into 'origin'
522 config.set('branch.%s.merge' % self.__name, name)
523 config.set('branch.%s.stgit.parentbranch' % self.__name, name)
525 def set_parent(self, remote, localbranch):
527 self.__set_parent_remote(remote)
528 self.__set_parent_branch(localbranch)
529 # We'll enforce this later
531 # raise StackException, 'Parent branch (%s) should be specified for %s' % localbranch, self.__name
533 def __patch_is_current(self, patch):
534 return patch.get_name() == self.get_current()
536 def patch_applied(self, name):
537 """Return true if the patch exists in the applied list
539 return name in self.get_applied()
541 def patch_unapplied(self, name):
542 """Return true if the patch exists in the unapplied list
544 return name in self.get_unapplied()
546 def patch_hidden(self, name):
547 """Return true if the patch is hidden.
549 return name in self.get_hidden()
551 def patch_exists(self, name):
552 """Return true if there is a patch with the given name, false
554 return self.patch_applied(name) or self.patch_unapplied(name)
556 def head_top_equal(self):
557 """Return true if the head and the top are the same
559 crt = self.get_current_patch()
561 # we don't care, no patches applied
563 return git.get_head() == crt.get_top()
565 def is_initialised(self):
566 """Checks if series is already initialised
568 return bool(config.get(format_version_key(self.get_branch())))
570 def init(self, create_at=False, parent_remote=None, parent_branch=None):
571 """Initialises the stgit series
573 if self.is_initialised():
574 raise StackException, '%s already initialized' % self.get_branch()
575 for d in [self._dir(), self.__refs_dir]:
576 if os.path.exists(d):
577 raise StackException, '%s already exists' % d
579 if (create_at!=False):
580 git.create_branch(self.__name, create_at)
582 os.makedirs(self.__patch_dir)
584 self.set_parent(parent_remote, parent_branch)
586 self.create_empty_field('applied')
587 self.create_empty_field('unapplied')
588 os.makedirs(self.__refs_dir)
589 self._set_field('orig-base', git.get_head())
591 config.set(format_version_key(self.get_branch()), str(FORMAT_VERSION))
593 def rename(self, to_name):
596 to_stack = Series(to_name)
598 if to_stack.is_initialised():
599 raise StackException, '"%s" already exists' % to_stack.get_branch()
601 git.rename_branch(self.__name, to_name)
603 if os.path.isdir(self._dir()):
604 rename(os.path.join(self.__base_dir, 'patches'),
605 self.__name, to_stack.__name)
606 if os.path.exists(self.__refs_dir):
607 rename(os.path.join(self.__base_dir, 'refs', 'patches'),
608 self.__name, to_stack.__name)
610 # Rename the config section
611 config.rename_section("branch.%s" % self.__name,
612 "branch.%s" % to_name)
614 self.__init__(to_name)
616 def clone(self, target_series):
620 # allow cloning of branches not under StGIT control
621 base = self.get_base()
623 base = git.get_head()
624 Series(target_series).init(create_at = base)
625 new_series = Series(target_series)
627 # generate an artificial description file
628 new_series.set_description('clone of "%s"' % self.__name)
630 # clone self's entire series as unapplied patches
632 # allow cloning of branches not under StGIT control
633 applied = self.get_applied()
634 unapplied = self.get_unapplied()
635 patches = applied + unapplied
638 patches = applied = unapplied = []
640 patch = self.get_patch(p)
641 newpatch = new_series.new_patch(p, message = patch.get_description(),
642 can_edit = False, unapplied = True,
643 bottom = patch.get_bottom(),
644 top = patch.get_top(),
645 author_name = patch.get_authname(),
646 author_email = patch.get_authemail(),
647 author_date = patch.get_authdate())
649 print "setting log to %s" % patch.get_log()
650 newpatch.set_log(patch.get_log())
652 print "no log for %s" % p
654 # fast forward the cloned series to self's top
655 new_series.forward_patches(applied)
657 # Clone parent informations
658 value = config.get('branch.%s.remote' % self.__name)
660 config.set('branch.%s.remote' % target_series, value)
662 value = config.get('branch.%s.merge' % self.__name)
664 config.set('branch.%s.merge' % target_series, value)
666 value = config.get('branch.%s.stgit.parentbranch' % self.__name)
668 config.set('branch.%s.stgit.parentbranch' % target_series, value)
670 def delete(self, force = False):
671 """Deletes an stgit series
673 if self.is_initialised():
674 patches = self.get_unapplied() + self.get_applied()
675 if not force and patches:
676 raise StackException, \
677 'Cannot delete: the series still contains patches'
679 Patch(p, self.__patch_dir, self.__refs_dir).delete()
681 # remove the trash directory
682 for fname in os.listdir(self.__trash_dir):
683 os.remove(os.path.join(self.__trash_dir, fname))
684 os.rmdir(self.__trash_dir)
686 # FIXME: find a way to get rid of those manual removals
687 # (move functionality to StgitObject ?)
688 if os.path.exists(self.__applied_file):
689 os.remove(self.__applied_file)
690 if os.path.exists(self.__unapplied_file):
691 os.remove(self.__unapplied_file)
692 if os.path.exists(self.__hidden_file):
693 os.remove(self.__hidden_file)
694 if os.path.exists(self._dir()+'/orig-base'):
695 os.remove(self._dir()+'/orig-base')
697 if not os.listdir(self.__patch_dir):
698 os.rmdir(self.__patch_dir)
700 print 'Patch directory %s is not empty.' % self.__patch_dir
703 os.removedirs(self._dir())
705 raise StackException, 'Series directory %s is not empty.' % self._dir()
708 os.removedirs(self.__refs_dir)
710 print 'Refs directory %s is not empty.' % self.__refs_dir
712 # Cleanup parent informations
713 # FIXME: should one day make use of git-config --section-remove,
714 # scheduled for 1.5.1
715 config.unset('branch.%s.remote' % self.__name)
716 config.unset('branch.%s.merge' % self.__name)
717 config.unset('branch.%s.stgit.parentbranch' % self.__name)
719 def refresh_patch(self, files = None, message = None, edit = False,
722 author_name = None, author_email = None,
724 committer_name = None, committer_email = None,
725 backup = False, sign_str = None, log = 'refresh'):
726 """Generates a new commit for the given patch
728 name = self.get_current()
730 raise StackException, 'No patches applied'
732 patch = Patch(name, self.__patch_dir, self.__refs_dir)
734 descr = patch.get_description()
735 if not (message or descr):
741 if not message and edit:
742 descr = edit_file(self, descr.rstrip(), \
743 'Please edit the description for patch "%s" ' \
744 'above.' % name, show_patch)
747 author_name = patch.get_authname()
749 author_email = patch.get_authemail()
751 author_date = patch.get_authdate()
752 if not committer_name:
753 committer_name = patch.get_commname()
754 if not committer_email:
755 committer_email = patch.get_commemail()
758 descr = descr.rstrip()
759 if descr.find("\nSigned-off-by:") < 0 \
760 and descr.find("\nAcked-by:") < 0:
763 descr = '%s\n%s: %s <%s>\n' % (descr, sign_str,
764 committer_name, committer_email)
766 bottom = patch.get_bottom()
768 commit_id = git.commit(files = files,
769 message = descr, parents = [bottom],
770 cache_update = cache_update,
772 author_name = author_name,
773 author_email = author_email,
774 author_date = author_date,
775 committer_name = committer_name,
776 committer_email = committer_email)
778 patch.set_bottom(bottom, backup = backup)
779 patch.set_top(commit_id, backup = backup)
780 patch.set_description(descr)
781 patch.set_authname(author_name)
782 patch.set_authemail(author_email)
783 patch.set_authdate(author_date)
784 patch.set_commname(committer_name)
785 patch.set_commemail(committer_email)
788 self.log_patch(patch, log)
792 def undo_refresh(self):
793 """Undo the patch boundaries changes caused by 'refresh'
795 name = self.get_current()
798 patch = Patch(name, self.__patch_dir, self.__refs_dir)
799 old_bottom = patch.get_old_bottom()
800 old_top = patch.get_old_top()
802 # the bottom of the patch is not changed by refresh. If the
803 # old_bottom is different, there wasn't any previous 'refresh'
804 # command (probably only a 'push')
805 if old_bottom != patch.get_bottom() or old_top == patch.get_top():
806 raise StackException, 'No undo information available'
808 git.reset(tree_id = old_top, check_out = False)
809 if patch.restore_old_boundaries():
810 self.log_patch(patch, 'undo')
812 def new_patch(self, name, message = None, can_edit = True,
813 unapplied = False, show_patch = False,
814 top = None, bottom = None,
815 author_name = None, author_email = None, author_date = None,
816 committer_name = None, committer_email = None,
817 before_existing = False, refresh = True):
818 """Creates a new patch
822 self.__patch_name_valid(name)
823 if self.patch_applied(name) or self.patch_unapplied(name):
824 raise StackException, 'Patch "%s" already exists' % name
826 if not message and can_edit:
829 'Please enter the description for the patch above.',
834 head = git.get_head()
837 name = make_patch_name(descr, self.patch_exists)
839 patch = Patch(name, self.__patch_dir, self.__refs_dir)
843 patch.set_bottom(bottom)
845 patch.set_bottom(head)
851 patch.set_description(descr)
852 patch.set_authname(author_name)
853 patch.set_authemail(author_email)
854 patch.set_authdate(author_date)
855 patch.set_commname(committer_name)
856 patch.set_commemail(committer_email)
859 self.log_patch(patch, 'new')
861 patches = [patch.get_name()] + self.get_unapplied()
863 f = file(self.__unapplied_file, 'w+')
864 f.writelines([line + '\n' for line in patches])
866 elif before_existing:
867 self.log_patch(patch, 'new')
869 insert_string(self.__applied_file, patch.get_name())
871 append_string(self.__applied_file, patch.get_name())
873 self.refresh_patch(cache_update = False, log = 'new')
877 def delete_patch(self, name):
880 self.__patch_name_valid(name)
881 patch = Patch(name, self.__patch_dir, self.__refs_dir)
883 if self.__patch_is_current(patch):
885 elif self.patch_applied(name):
886 raise StackException, 'Cannot remove an applied patch, "%s", ' \
887 'which is not current' % name
888 elif not name in self.get_unapplied():
889 raise StackException, 'Unknown patch "%s"' % name
891 # save the commit id to a trash file
892 write_string(os.path.join(self.__trash_dir, name), patch.get_top())
896 unapplied = self.get_unapplied()
897 unapplied.remove(name)
898 f = file(self.__unapplied_file, 'w+')
899 f.writelines([line + '\n' for line in unapplied])
902 if self.patch_hidden(name):
903 self.unhide_patch(name)
905 def forward_patches(self, names):
906 """Try to fast-forward an array of patches.
908 On return, patches in names[0:returned_value] have been pushed on the
909 stack. Apply the rest with push_patch
911 unapplied = self.get_unapplied()
917 assert(name in unapplied)
919 patch = Patch(name, self.__patch_dir, self.__refs_dir)
922 bottom = patch.get_bottom()
923 top = patch.get_top()
925 # top != bottom always since we have a commit for each patch
927 # reset the backup information. No logging since the
928 # patch hasn't changed
929 patch.set_bottom(head, backup = True)
930 patch.set_top(top, backup = True)
933 head_tree = git.get_commit(head).get_tree()
934 bottom_tree = git.get_commit(bottom).get_tree()
935 if head_tree == bottom_tree:
936 # We must just reparent this patch and create a new commit
938 descr = patch.get_description()
939 author_name = patch.get_authname()
940 author_email = patch.get_authemail()
941 author_date = patch.get_authdate()
942 committer_name = patch.get_commname()
943 committer_email = patch.get_commemail()
945 top_tree = git.get_commit(top).get_tree()
947 top = git.commit(message = descr, parents = [head],
948 cache_update = False,
951 author_name = author_name,
952 author_email = author_email,
953 author_date = author_date,
954 committer_name = committer_name,
955 committer_email = committer_email)
957 patch.set_bottom(head, backup = True)
958 patch.set_top(top, backup = True)
960 self.log_patch(patch, 'push(f)')
963 # stop the fast-forwarding, must do a real merge
967 unapplied.remove(name)
974 append_strings(self.__applied_file, names[0:forwarded])
976 f = file(self.__unapplied_file, 'w+')
977 f.writelines([line + '\n' for line in unapplied])
982 def merged_patches(self, names):
983 """Test which patches were merged upstream by reverse-applying
984 them in reverse order. The function returns the list of
985 patches detected to have been applied. The state of the tree
986 is restored to the original one
988 patches = [Patch(name, self.__patch_dir, self.__refs_dir)
994 if git.apply_diff(p.get_top(), p.get_bottom()):
995 merged.append(p.get_name())
1002 def push_patch(self, name, empty = False):
1003 """Pushes a patch on the stack
1005 unapplied = self.get_unapplied()
1006 assert(name in unapplied)
1008 patch = Patch(name, self.__patch_dir, self.__refs_dir)
1010 head = git.get_head()
1011 bottom = patch.get_bottom()
1012 top = patch.get_top()
1017 # top != bottom always since we have a commit for each patch
1019 # just make an empty patch (top = bottom = HEAD). This
1020 # option is useful to allow undoing already merged
1021 # patches. The top is updated by refresh_patch since we
1022 # need an empty commit
1023 patch.set_bottom(head, backup = True)
1024 patch.set_top(head, backup = True)
1026 elif head == bottom:
1027 # reset the backup information. No need for logging
1028 patch.set_bottom(bottom, backup = True)
1029 patch.set_top(top, backup = True)
1033 # new patch needs to be refreshed.
1034 # The current patch is empty after merge.
1035 patch.set_bottom(head, backup = True)
1036 patch.set_top(head, backup = True)
1038 # Try the fast applying first. If this fails, fall back to the
1040 if not git.apply_diff(bottom, top):
1041 # if git.apply_diff() fails, the patch requires a diff3
1042 # merge and can be reported as modified
1045 # merge can fail but the patch needs to be pushed
1047 git.merge(bottom, head, top, recursive = True)
1048 except git.GitException, ex:
1049 print >> sys.stderr, \
1050 'The merge failed during "push". ' \
1051 'Use "refresh" after fixing the conflicts or ' \
1052 'revert the operation with "push --undo".'
1054 append_string(self.__applied_file, name)
1056 unapplied.remove(name)
1057 f = file(self.__unapplied_file, 'w+')
1058 f.writelines([line + '\n' for line in unapplied])
1061 # head == bottom case doesn't need to refresh the patch
1062 if empty or head != bottom:
1064 # if the merge was OK and no conflicts, just refresh the patch
1065 # The GIT cache was already updated by the merge operation
1070 self.refresh_patch(cache_update = False, log = log)
1072 # we store the correctly merged files only for
1073 # tracking the conflict history. Note that the
1074 # git.merge() operations should always leave the index
1075 # in a valid state (i.e. only stage 0 files)
1076 self.refresh_patch(cache_update = False, log = 'push(c)')
1077 raise StackException, str(ex)
1081 def undo_push(self):
1082 name = self.get_current()
1085 patch = Patch(name, self.__patch_dir, self.__refs_dir)
1086 old_bottom = patch.get_old_bottom()
1087 old_top = patch.get_old_top()
1089 # the top of the patch is changed by a push operation only
1090 # together with the bottom (otherwise the top was probably
1091 # modified by 'refresh'). If they are both unchanged, there
1092 # was a fast forward
1093 if old_bottom == patch.get_bottom() and old_top != patch.get_top():
1094 raise StackException, 'No undo information available'
1097 self.pop_patch(name)
1098 ret = patch.restore_old_boundaries()
1100 self.log_patch(patch, 'undo')
1104 def pop_patch(self, name, keep = False):
1105 """Pops the top patch from the stack
1107 applied = self.get_applied()
1109 assert(name in applied)
1111 patch = Patch(name, self.__patch_dir, self.__refs_dir)
1113 if git.get_head_file() == self.get_branch():
1114 if keep and not git.apply_diff(git.get_head(), patch.get_bottom()):
1115 raise StackException(
1116 'Failed to pop patches while preserving the local changes')
1117 git.switch(patch.get_bottom(), keep)
1119 git.set_branch(self.get_branch(), patch.get_bottom())
1121 # save the new applied list
1122 idx = applied.index(name) + 1
1124 popped = applied[:idx]
1126 unapplied = popped + self.get_unapplied()
1128 f = file(self.__unapplied_file, 'w+')
1129 f.writelines([line + '\n' for line in unapplied])
1135 f = file(self.__applied_file, 'w+')
1136 f.writelines([line + '\n' for line in applied])
1139 def empty_patch(self, name):
1140 """Returns True if the patch is empty
1142 self.__patch_name_valid(name)
1143 patch = Patch(name, self.__patch_dir, self.__refs_dir)
1144 bottom = patch.get_bottom()
1145 top = patch.get_top()
1149 elif git.get_commit(top).get_tree() \
1150 == git.get_commit(bottom).get_tree():
1155 def rename_patch(self, oldname, newname):
1156 self.__patch_name_valid(newname)
1158 applied = self.get_applied()
1159 unapplied = self.get_unapplied()
1161 if oldname == newname:
1162 raise StackException, '"To" name and "from" name are the same'
1164 if newname in applied or newname in unapplied:
1165 raise StackException, 'Patch "%s" already exists' % newname
1167 if self.patch_hidden(oldname):
1168 self.unhide_patch(oldname)
1169 self.hide_patch(newname)
1171 if oldname in unapplied:
1172 Patch(oldname, self.__patch_dir, self.__refs_dir).rename(newname)
1173 unapplied[unapplied.index(oldname)] = newname
1175 f = file(self.__unapplied_file, 'w+')
1176 f.writelines([line + '\n' for line in unapplied])
1178 elif oldname in applied:
1179 Patch(oldname, self.__patch_dir, self.__refs_dir).rename(newname)
1181 applied[applied.index(oldname)] = newname
1183 f = file(self.__applied_file, 'w+')
1184 f.writelines([line + '\n' for line in applied])
1187 raise StackException, 'Unknown patch "%s"' % oldname
1189 def log_patch(self, patch, message):
1190 """Generate a log commit for a patch
1192 top = git.get_commit(patch.get_top())
1193 msg = '%s\t%s' % (message, top.get_id_hash())
1195 old_log = patch.get_log()
1201 log = git.commit(message = msg, parents = parents,
1202 cache_update = False, tree_id = top.get_tree(),
1206 def hide_patch(self, name):
1207 """Add the patch to the hidden list.
1209 if not self.patch_exists(name):
1210 raise StackException, 'Unknown patch "%s"' % name
1211 elif self.patch_hidden(name):
1212 raise StackException, 'Patch "%s" already hidden' % name
1214 append_string(self.__hidden_file, name)
1216 def unhide_patch(self, name):
1217 """Add the patch to the hidden list.
1219 if not self.patch_exists(name):
1220 raise StackException, 'Unknown patch "%s"' % name
1221 hidden = self.get_hidden()
1222 if not name in hidden:
1223 raise StackException, 'Patch "%s" not hidden' % name
1227 f = file(self.__hidden_file, 'w+')
1228 f.writelines([line + '\n' for line in hidden])