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 class PatchSet(StgitObject
):
282 def set_name(self
, name
):
286 """Return the head of the branch
288 crt
= self
.get_current_patch()
292 return self
.get_base()
294 def get_protected(self
):
295 return os
.path
.isfile(os
.path
.join(self
._dir
(), 'protected'))
298 protect_file
= os
.path
.join(self
._dir
(), 'protected')
299 if not os
.path
.isfile(protect_file
):
300 create_empty_file(protect_file
)
303 protect_file
= os
.path
.join(self
._dir
(), 'protected')
304 if os
.path
.isfile(protect_file
):
305 os
.remove(protect_file
)
307 def __branch_descr(self
):
308 return 'branch.%s.description' % self
.get_name()
310 def get_description(self
):
311 return config
.get(self
.__branch
_descr
()) or ''
313 def set_description(self
, line
):
315 config
.set(self
.__branch
_descr
(), line
)
317 config
.unset(self
.__branch
_descr
())
319 def head_top_equal(self
):
320 """Return true if the head and the top are the same
322 crt
= self
.get_current_patch()
324 # we don't care, no patches applied
326 return git
.get_head() == crt
.get_top()
328 def is_initialised(self
):
329 """Checks if series is already initialised
331 return bool(config
.get(self
.format_version_key()))
334 class Series(PatchSet
):
335 """Class including the operations on series
337 def __init__(self
, name
= None):
338 """Takes a series name as the parameter.
344 self
.set_name (git
.get_head_file())
345 self
.__base
_dir
= basedir
.get()
346 except git
.GitException
, ex
:
347 raise StackException
, 'GIT tree not initialised: %s' % ex
349 self
._set
_dir
(os
.path
.join(self
.__base
_dir
, 'patches', self
.get_name()))
351 # Update the branch to the latest format version if it is
352 # initialized, but don't touch it if it isn't.
353 self
.update_to_current_format_version()
355 self
.__refs
_dir
= os
.path
.join(self
.__base
_dir
, 'refs', 'patches',
358 self
.__applied
_file
= os
.path
.join(self
._dir
(), 'applied')
359 self
.__unapplied
_file
= os
.path
.join(self
._dir
(), 'unapplied')
360 self
.__hidden
_file
= os
.path
.join(self
._dir
(), 'hidden')
362 # where this series keeps its patches
363 self
.__patch
_dir
= os
.path
.join(self
._dir
(), 'patches')
366 self
.__trash
_dir
= os
.path
.join(self
._dir
(), 'trash')
368 def format_version_key(self
):
369 return 'branch.%s.stgit.stackformatversion' % self
.get_name()
371 def update_to_current_format_version(self
):
372 """Update a potentially older StGIT directory structure to the
373 latest version. Note: This function should depend as little as
374 possible on external functions that may change during a format
375 version bump, since it must remain able to process older formats."""
377 branch_dir
= os
.path
.join(self
.__base
_dir
, 'patches', self
.get_name())
378 def get_format_version():
379 """Return the integer format version number, or None if the
380 branch doesn't have any StGIT metadata at all, of any version."""
381 fv
= config
.get(self
.format_version_key())
382 ofv
= config
.get('branch.%s.stgitformatversion' % self
.get_name())
384 # Great, there's an explicitly recorded format version
385 # number, which means that the branch is initialized and
386 # of that exact version.
389 # Old name for the version info, upgrade it
390 config
.set(self
.format_version_key(), ofv
)
391 config
.unset('branch.%s.stgitformatversion' % self
.get_name())
393 elif os
.path
.isdir(os
.path
.join(branch_dir
, 'patches')):
394 # There's a .git/patches/<branch>/patches dirctory, which
395 # means this is an initialized version 1 branch.
397 elif os
.path
.isdir(branch_dir
):
398 # There's a .git/patches/<branch> directory, which means
399 # this is an initialized version 0 branch.
402 # The branch doesn't seem to be initialized at all.
404 def set_format_version(v
):
405 out
.info('Upgraded branch %s to format version %d' % (self
.get_name(), v
))
406 config
.set(self
.format_version_key(), '%d' % v
)
408 if not os
.path
.isdir(d
):
411 if os
.path
.exists(f
):
415 if get_format_version() == 0:
416 mkdir(os
.path
.join(branch_dir
, 'trash'))
417 patch_dir
= os
.path
.join(branch_dir
, 'patches')
419 refs_dir
= os
.path
.join(self
.__base
_dir
, 'refs', 'patches', self
.get_name())
421 for patch
in (file(os
.path
.join(branch_dir
, 'unapplied')).readlines()
422 + file(os
.path
.join(branch_dir
, 'applied')).readlines()):
423 patch
= patch
.strip()
424 os
.rename(os
.path
.join(branch_dir
, patch
),
425 os
.path
.join(patch_dir
, patch
))
426 Patch(patch
, patch_dir
, refs_dir
).update_top_ref()
427 set_format_version(1)
430 if get_format_version() == 1:
431 desc_file
= os
.path
.join(branch_dir
, 'description')
432 if os
.path
.isfile(desc_file
):
433 desc
= read_string(desc_file
)
435 config
.set('branch.%s.description' % self
.get_name(), desc
)
437 rm(os
.path
.join(branch_dir
, 'current'))
438 rm(os
.path
.join(self
.__base
_dir
, 'refs', 'bases', self
.get_name()))
439 set_format_version(2)
441 # Make sure we're at the latest version.
442 if not get_format_version() in [None, FORMAT_VERSION
]:
443 raise StackException('Branch %s is at format version %d, expected %d'
444 % (self
.get_name(), get_format_version(), FORMAT_VERSION
))
446 def __patch_name_valid(self
, name
):
447 """Raise an exception if the patch name is not valid.
449 if not name
or re
.search('[^\w.-]', name
):
450 raise StackException
, 'Invalid patch name: "%s"' % name
452 def get_patch(self
, name
):
453 """Return a Patch object for the given name
455 return Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
457 def get_current_patch(self
):
458 """Return a Patch object representing the topmost patch, or
459 None if there is no such patch."""
460 crt
= self
.get_current()
463 return Patch(crt
, self
.__patch
_dir
, self
.__refs
_dir
)
465 def get_current(self
):
466 """Return the name of the topmost patch, or None if there is
469 applied
= self
.get_applied()
470 except StackException
:
471 # No "applied" file: branch is not initialized.
476 # No patches applied.
479 def get_applied(self
):
480 if not os
.path
.isfile(self
.__applied
_file
):
481 raise StackException
, 'Branch "%s" not initialised' % self
.get_name()
482 return read_strings(self
.__applied
_file
)
484 def get_unapplied(self
):
485 if not os
.path
.isfile(self
.__unapplied
_file
):
486 raise StackException
, 'Branch "%s" not initialised' % self
.get_name()
487 return read_strings(self
.__unapplied
_file
)
489 def get_hidden(self
):
490 if not os
.path
.isfile(self
.__hidden
_file
):
492 return read_strings(self
.__hidden
_file
)
495 # Return the parent of the bottommost patch, if there is one.
496 if os
.path
.isfile(self
.__applied
_file
):
497 bottommost
= file(self
.__applied
_file
).readline().strip()
499 return self
.get_patch(bottommost
).get_bottom()
500 # No bottommost patch, so just return HEAD
501 return git
.get_head()
503 def get_parent_remote(self
):
504 value
= config
.get('branch.%s.remote' % self
.get_name())
507 elif 'origin' in git
.remotes_list():
508 out
.note(('No parent remote declared for stack "%s",'
509 ' defaulting to "origin".' % self
.get_name()),
510 ('Consider setting "branch.%s.remote" and'
511 ' "branch.%s.merge" with "git repo-config".'
512 % (self
.get_name(), self
.get_name())))
515 raise StackException
, 'Cannot find a parent remote for "%s"' % self
.get_name()
517 def __set_parent_remote(self
, remote
):
518 value
= config
.set('branch.%s.remote' % self
.get_name(), remote
)
520 def get_parent_branch(self
):
521 value
= config
.get('branch.%s.stgit.parentbranch' % self
.get_name())
524 elif git
.rev_parse('heads/origin'):
525 out
.note(('No parent branch declared for stack "%s",'
526 ' defaulting to "heads/origin".' % self
.get_name()),
527 ('Consider setting "branch.%s.stgit.parentbranch"'
528 ' with "git repo-config".' % self
.get_name()))
529 return 'heads/origin'
531 raise StackException
, 'Cannot find a parent branch for "%s"' % self
.get_name()
533 def __set_parent_branch(self
, name
):
534 if config
.get('branch.%s.remote' % self
.get_name()):
535 # Never set merge if remote is not set to avoid
536 # possibly-erroneous lookups into 'origin'
537 config
.set('branch.%s.merge' % self
.get_name(), name
)
538 config
.set('branch.%s.stgit.parentbranch' % self
.get_name(), name
)
540 def set_parent(self
, remote
, localbranch
):
542 self
.__set
_parent
_remote
(remote
)
543 self
.__set
_parent
_branch
(localbranch
)
544 # We'll enforce this later
546 # raise StackException, 'Parent branch (%s) should be specified for %s' % localbranch, self.get_name()
548 def __patch_is_current(self
, patch
):
549 return patch
.get_name() == self
.get_current()
551 def patch_applied(self
, name
):
552 """Return true if the patch exists in the applied list
554 return name
in self
.get_applied()
556 def patch_unapplied(self
, name
):
557 """Return true if the patch exists in the unapplied list
559 return name
in self
.get_unapplied()
561 def patch_hidden(self
, name
):
562 """Return true if the patch is hidden.
564 return name
in self
.get_hidden()
566 def patch_exists(self
, name
):
567 """Return true if there is a patch with the given name, false
569 return self
.patch_applied(name
) or self
.patch_unapplied(name
) \
570 or self
.patch_hidden(name
)
572 def init(self
, create_at
=False, parent_remote
=None, parent_branch
=None):
573 """Initialises the stgit series
575 if self
.is_initialised():
576 raise StackException
, '%s already initialized' % self
.get_name()
577 for d
in [self
._dir
(), self
.__refs
_dir
]:
578 if os
.path
.exists(d
):
579 raise StackException
, '%s already exists' % d
581 if (create_at
!=False):
582 git
.create_branch(self
.get_name(), create_at
)
584 os
.makedirs(self
.__patch
_dir
)
586 self
.set_parent(parent_remote
, parent_branch
)
588 self
.create_empty_field('applied')
589 self
.create_empty_field('unapplied')
590 os
.makedirs(self
.__refs
_dir
)
591 self
._set
_field
('orig-base', git
.get_head())
593 config
.set(self
.format_version_key(), str(FORMAT_VERSION
))
595 def rename(self
, to_name
):
598 to_stack
= Series(to_name
)
600 if to_stack
.is_initialised():
601 raise StackException
, '"%s" already exists' % to_stack
.get_name()
603 git
.rename_branch(self
.get_name(), to_name
)
605 if os
.path
.isdir(self
._dir
()):
606 rename(os
.path
.join(self
.__base
_dir
, 'patches'),
607 self
.get_name(), to_stack
.get_name())
608 if os
.path
.exists(self
.__refs
_dir
):
609 rename(os
.path
.join(self
.__base
_dir
, 'refs', 'patches'),
610 self
.get_name(), to_stack
.get_name())
612 # Rename the config section
613 config
.rename_section("branch.%s" % self
.get_name(),
614 "branch.%s" % to_name
)
616 self
.__init
__(to_name
)
618 def clone(self
, target_series
):
622 # allow cloning of branches not under StGIT control
623 base
= self
.get_base()
625 base
= git
.get_head()
626 Series(target_series
).init(create_at
= base
)
627 new_series
= Series(target_series
)
629 # generate an artificial description file
630 new_series
.set_description('clone of "%s"' % self
.get_name())
632 # clone self's entire series as unapplied patches
634 # allow cloning of branches not under StGIT control
635 applied
= self
.get_applied()
636 unapplied
= self
.get_unapplied()
637 patches
= applied
+ unapplied
640 patches
= applied
= unapplied
= []
642 patch
= self
.get_patch(p
)
643 newpatch
= new_series
.new_patch(p
, message
= patch
.get_description(),
644 can_edit
= False, unapplied
= True,
645 bottom
= patch
.get_bottom(),
646 top
= patch
.get_top(),
647 author_name
= patch
.get_authname(),
648 author_email
= patch
.get_authemail(),
649 author_date
= patch
.get_authdate())
651 out
.info('Setting log to %s' % patch
.get_log())
652 newpatch
.set_log(patch
.get_log())
654 out
.info('No log for %s' % p
)
656 # fast forward the cloned series to self's top
657 new_series
.forward_patches(applied
)
659 # Clone parent informations
660 value
= config
.get('branch.%s.remote' % self
.get_name())
662 config
.set('branch.%s.remote' % target_series
, value
)
664 value
= config
.get('branch.%s.merge' % self
.get_name())
666 config
.set('branch.%s.merge' % target_series
, value
)
668 value
= config
.get('branch.%s.stgit.parentbranch' % self
.get_name())
670 config
.set('branch.%s.stgit.parentbranch' % target_series
, value
)
672 def delete(self
, force
= False):
673 """Deletes an stgit series
675 if self
.is_initialised():
676 patches
= self
.get_unapplied() + self
.get_applied()
677 if not force
and patches
:
678 raise StackException
, \
679 'Cannot delete: the series still contains patches'
681 Patch(p
, self
.__patch
_dir
, self
.__refs
_dir
).delete()
683 # remove the trash directory if any
684 if os
.path
.exists(self
.__trash
_dir
):
685 for fname
in os
.listdir(self
.__trash
_dir
):
686 os
.remove(os
.path
.join(self
.__trash
_dir
, fname
))
687 os
.rmdir(self
.__trash
_dir
)
689 # FIXME: find a way to get rid of those manual removals
690 # (move functionality to StgitObject ?)
691 if os
.path
.exists(self
.__applied
_file
):
692 os
.remove(self
.__applied
_file
)
693 if os
.path
.exists(self
.__unapplied
_file
):
694 os
.remove(self
.__unapplied
_file
)
695 if os
.path
.exists(self
.__hidden
_file
):
696 os
.remove(self
.__hidden
_file
)
697 if os
.path
.exists(self
._dir
()+'/orig-base'):
698 os
.remove(self
._dir
()+'/orig-base')
700 if not os
.listdir(self
.__patch
_dir
):
701 os
.rmdir(self
.__patch
_dir
)
703 out
.warn('Patch directory %s is not empty' % self
.__patch
_dir
)
706 os
.removedirs(self
._dir
())
708 raise StackException('Series directory %s is not empty'
712 os
.removedirs(self
.__refs
_dir
)
714 out
.warn('Refs directory %s is not empty' % self
.__refs
_dir
)
716 # Cleanup parent informations
717 # FIXME: should one day make use of git-config --section-remove,
718 # scheduled for 1.5.1
719 config
.unset('branch.%s.remote' % self
.get_name())
720 config
.unset('branch.%s.merge' % self
.get_name())
721 config
.unset('branch.%s.stgit.parentbranch' % self
.get_name())
722 config
.unset(self
.format_version_key())
724 def refresh_patch(self
, files
= None, message
= None, edit
= False,
727 author_name
= None, author_email
= None,
729 committer_name
= None, committer_email
= None,
730 backup
= False, sign_str
= None, log
= 'refresh'):
731 """Generates a new commit for the given patch
733 name
= self
.get_current()
735 raise StackException
, 'No patches applied'
737 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
739 descr
= patch
.get_description()
740 if not (message
or descr
):
746 if not message
and edit
:
747 descr
= edit_file(self
, descr
.rstrip(), \
748 'Please edit the description for patch "%s" ' \
749 'above.' % name
, show_patch
)
752 author_name
= patch
.get_authname()
754 author_email
= patch
.get_authemail()
756 author_date
= patch
.get_authdate()
757 if not committer_name
:
758 committer_name
= patch
.get_commname()
759 if not committer_email
:
760 committer_email
= patch
.get_commemail()
763 descr
= descr
.rstrip()
764 if descr
.find("\nSigned-off-by:") < 0 \
765 and descr
.find("\nAcked-by:") < 0:
768 descr
= '%s\n%s: %s <%s>\n' % (descr
, sign_str
,
769 committer_name
, committer_email
)
771 bottom
= patch
.get_bottom()
773 commit_id
= git
.commit(files
= files
,
774 message
= descr
, parents
= [bottom
],
775 cache_update
= cache_update
,
777 author_name
= author_name
,
778 author_email
= author_email
,
779 author_date
= author_date
,
780 committer_name
= committer_name
,
781 committer_email
= committer_email
)
783 patch
.set_bottom(bottom
, backup
= backup
)
784 patch
.set_top(commit_id
, backup
= backup
)
785 patch
.set_description(descr
)
786 patch
.set_authname(author_name
)
787 patch
.set_authemail(author_email
)
788 patch
.set_authdate(author_date
)
789 patch
.set_commname(committer_name
)
790 patch
.set_commemail(committer_email
)
793 self
.log_patch(patch
, log
)
797 def undo_refresh(self
):
798 """Undo the patch boundaries changes caused by 'refresh'
800 name
= self
.get_current()
803 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
804 old_bottom
= patch
.get_old_bottom()
805 old_top
= patch
.get_old_top()
807 # the bottom of the patch is not changed by refresh. If the
808 # old_bottom is different, there wasn't any previous 'refresh'
809 # command (probably only a 'push')
810 if old_bottom
!= patch
.get_bottom() or old_top
== patch
.get_top():
811 raise StackException
, 'No undo information available'
813 git
.reset(tree_id
= old_top
, check_out
= False)
814 if patch
.restore_old_boundaries():
815 self
.log_patch(patch
, 'undo')
817 def new_patch(self
, name
, message
= None, can_edit
= True,
818 unapplied
= False, show_patch
= False,
819 top
= None, bottom
= None,
820 author_name
= None, author_email
= None, author_date
= None,
821 committer_name
= None, committer_email
= None,
822 before_existing
= False, refresh
= True):
823 """Creates a new patch
827 self
.__patch
_name
_valid
(name
)
828 if self
.patch_exists(name
):
829 raise StackException
, 'Patch "%s" already exists' % name
831 if not message
and can_edit
:
834 'Please enter the description for the patch above.',
839 head
= git
.get_head()
842 name
= make_patch_name(descr
, self
.patch_exists
)
844 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
848 patch
.set_bottom(bottom
)
850 patch
.set_bottom(head
)
856 patch
.set_description(descr
)
857 patch
.set_authname(author_name
)
858 patch
.set_authemail(author_email
)
859 patch
.set_authdate(author_date
)
860 patch
.set_commname(committer_name
)
861 patch
.set_commemail(committer_email
)
864 self
.log_patch(patch
, 'new')
866 patches
= [patch
.get_name()] + self
.get_unapplied()
867 write_strings(self
.__unapplied
_file
, patches
)
868 elif before_existing
:
869 self
.log_patch(patch
, 'new')
871 insert_string(self
.__applied
_file
, patch
.get_name())
873 append_string(self
.__applied
_file
, patch
.get_name())
875 self
.refresh_patch(cache_update
= False, log
= 'new')
879 def delete_patch(self
, name
):
882 self
.__patch
_name
_valid
(name
)
883 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
885 if self
.__patch
_is
_current
(patch
):
887 elif self
.patch_applied(name
):
888 raise StackException
, 'Cannot remove an applied patch, "%s", ' \
889 'which is not current' % name
890 elif not name
in self
.get_unapplied():
891 raise StackException
, 'Unknown patch "%s"' % name
893 # save the commit id to a trash file
894 write_string(os
.path
.join(self
.__trash
_dir
, name
), patch
.get_top())
898 unapplied
= self
.get_unapplied()
899 unapplied
.remove(name
)
900 write_strings(self
.__unapplied
_file
, unapplied
)
902 def forward_patches(self
, names
):
903 """Try to fast-forward an array of patches.
905 On return, patches in names[0:returned_value] have been pushed on the
906 stack. Apply the rest with push_patch
908 unapplied
= self
.get_unapplied()
914 assert(name
in unapplied
)
916 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
919 bottom
= patch
.get_bottom()
920 top
= patch
.get_top()
922 # top != bottom always since we have a commit for each patch
924 # reset the backup information. No logging since the
925 # patch hasn't changed
926 patch
.set_bottom(head
, backup
= True)
927 patch
.set_top(top
, backup
= True)
930 head_tree
= git
.get_commit(head
).get_tree()
931 bottom_tree
= git
.get_commit(bottom
).get_tree()
932 if head_tree
== bottom_tree
:
933 # We must just reparent this patch and create a new commit
935 descr
= patch
.get_description()
936 author_name
= patch
.get_authname()
937 author_email
= patch
.get_authemail()
938 author_date
= patch
.get_authdate()
939 committer_name
= patch
.get_commname()
940 committer_email
= patch
.get_commemail()
942 top_tree
= git
.get_commit(top
).get_tree()
944 top
= git
.commit(message
= descr
, parents
= [head
],
945 cache_update
= False,
948 author_name
= author_name
,
949 author_email
= author_email
,
950 author_date
= author_date
,
951 committer_name
= committer_name
,
952 committer_email
= committer_email
)
954 patch
.set_bottom(head
, backup
= True)
955 patch
.set_top(top
, backup
= True)
957 self
.log_patch(patch
, 'push(f)')
960 # stop the fast-forwarding, must do a real merge
964 unapplied
.remove(name
)
971 append_strings(self
.__applied
_file
, names
[0:forwarded
])
972 write_strings(self
.__unapplied
_file
, unapplied
)
976 def merged_patches(self
, names
):
977 """Test which patches were merged upstream by reverse-applying
978 them in reverse order. The function returns the list of
979 patches detected to have been applied. The state of the tree
980 is restored to the original one
982 patches
= [Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
988 if git
.apply_diff(p
.get_top(), p
.get_bottom()):
989 merged
.append(p
.get_name())
996 def push_patch(self
, name
, empty
= False):
997 """Pushes a patch on the stack
999 unapplied
= self
.get_unapplied()
1000 assert(name
in unapplied
)
1002 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
1004 head
= git
.get_head()
1005 bottom
= patch
.get_bottom()
1006 top
= patch
.get_top()
1011 # top != bottom always since we have a commit for each patch
1013 # just make an empty patch (top = bottom = HEAD). This
1014 # option is useful to allow undoing already merged
1015 # patches. The top is updated by refresh_patch since we
1016 # need an empty commit
1017 patch
.set_bottom(head
, backup
= True)
1018 patch
.set_top(head
, backup
= True)
1020 elif head
== bottom
:
1021 # reset the backup information. No need for logging
1022 patch
.set_bottom(bottom
, backup
= True)
1023 patch
.set_top(top
, backup
= True)
1027 # new patch needs to be refreshed.
1028 # The current patch is empty after merge.
1029 patch
.set_bottom(head
, backup
= True)
1030 patch
.set_top(head
, backup
= True)
1032 # Try the fast applying first. If this fails, fall back to the
1034 if not git
.apply_diff(bottom
, top
):
1035 # if git.apply_diff() fails, the patch requires a diff3
1036 # merge and can be reported as modified
1039 # merge can fail but the patch needs to be pushed
1041 git
.merge(bottom
, head
, top
, recursive
= True)
1042 except git
.GitException
, ex
:
1043 out
.error('The merge failed during "push".',
1044 'Use "refresh" after fixing the conflicts or'
1045 ' revert the operation with "push --undo".')
1047 append_string(self
.__applied
_file
, name
)
1049 unapplied
.remove(name
)
1050 write_strings(self
.__unapplied
_file
, unapplied
)
1052 # head == bottom case doesn't need to refresh the patch
1053 if empty
or head
!= bottom
:
1055 # if the merge was OK and no conflicts, just refresh the patch
1056 # The GIT cache was already updated by the merge operation
1061 self
.refresh_patch(cache_update
= False, log
= log
)
1063 # we store the correctly merged files only for
1064 # tracking the conflict history. Note that the
1065 # git.merge() operations should always leave the index
1066 # in a valid state (i.e. only stage 0 files)
1067 self
.refresh_patch(cache_update
= False, log
= 'push(c)')
1068 raise StackException
, str(ex
)
1072 def undo_push(self
):
1073 name
= self
.get_current()
1076 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
1077 old_bottom
= patch
.get_old_bottom()
1078 old_top
= patch
.get_old_top()
1080 # the top of the patch is changed by a push operation only
1081 # together with the bottom (otherwise the top was probably
1082 # modified by 'refresh'). If they are both unchanged, there
1083 # was a fast forward
1084 if old_bottom
== patch
.get_bottom() and old_top
!= patch
.get_top():
1085 raise StackException
, 'No undo information available'
1088 self
.pop_patch(name
)
1089 ret
= patch
.restore_old_boundaries()
1091 self
.log_patch(patch
, 'undo')
1095 def pop_patch(self
, name
, keep
= False):
1096 """Pops the top patch from the stack
1098 applied
= self
.get_applied()
1100 assert(name
in applied
)
1102 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
1104 if git
.get_head_file() == self
.get_name():
1105 if keep
and not git
.apply_diff(git
.get_head(), patch
.get_bottom()):
1106 raise StackException(
1107 'Failed to pop patches while preserving the local changes')
1108 git
.switch(patch
.get_bottom(), keep
)
1110 git
.set_branch(self
.get_name(), patch
.get_bottom())
1112 # save the new applied list
1113 idx
= applied
.index(name
) + 1
1115 popped
= applied
[:idx
]
1117 unapplied
= popped
+ self
.get_unapplied()
1118 write_strings(self
.__unapplied
_file
, unapplied
)
1122 write_strings(self
.__applied
_file
, applied
)
1124 def empty_patch(self
, name
):
1125 """Returns True if the patch is empty
1127 self
.__patch
_name
_valid
(name
)
1128 patch
= Patch(name
, self
.__patch
_dir
, self
.__refs
_dir
)
1129 bottom
= patch
.get_bottom()
1130 top
= patch
.get_top()
1134 elif git
.get_commit(top
).get_tree() \
1135 == git
.get_commit(bottom
).get_tree():
1140 def rename_patch(self
, oldname
, newname
):
1141 self
.__patch
_name
_valid
(newname
)
1143 applied
= self
.get_applied()
1144 unapplied
= self
.get_unapplied()
1146 if oldname
== newname
:
1147 raise StackException
, '"To" name and "from" name are the same'
1149 if newname
in applied
or newname
in unapplied
:
1150 raise StackException
, 'Patch "%s" already exists' % newname
1152 if oldname
in unapplied
:
1153 Patch(oldname
, self
.__patch
_dir
, self
.__refs
_dir
).rename(newname
)
1154 unapplied
[unapplied
.index(oldname
)] = newname
1155 write_strings(self
.__unapplied
_file
, unapplied
)
1156 elif oldname
in applied
:
1157 Patch(oldname
, self
.__patch
_dir
, self
.__refs
_dir
).rename(newname
)
1159 applied
[applied
.index(oldname
)] = newname
1160 write_strings(self
.__applied
_file
, applied
)
1162 raise StackException
, 'Unknown patch "%s"' % oldname
1164 def log_patch(self
, patch
, message
):
1165 """Generate a log commit for a patch
1167 top
= git
.get_commit(patch
.get_top())
1168 msg
= '%s\t%s' % (message
, top
.get_id_hash())
1170 old_log
= patch
.get_log()
1176 log
= git
.commit(message
= msg
, parents
= parents
,
1177 cache_update
= False, tree_id
= top
.get_tree(),
1181 def hide_patch(self
, name
):
1182 """Add the patch to the hidden list.
1184 unapplied
= self
.get_unapplied()
1185 if name
not in unapplied
:
1186 # keep the checking order for backward compatibility with
1187 # the old hidden patches functionality
1188 if self
.patch_applied(name
):
1189 raise StackException
, 'Cannot hide applied patch "%s"' % name
1190 elif self
.patch_hidden(name
):
1191 raise StackException
, 'Patch "%s" already hidden' % name
1193 raise StackException
, 'Unknown patch "%s"' % name
1195 if not self
.patch_hidden(name
):
1196 # check needed for backward compatibility with the old
1197 # hidden patches functionality
1198 append_string(self
.__hidden
_file
, name
)
1200 unapplied
.remove(name
)
1201 write_strings(self
.__unapplied
_file
, unapplied
)
1203 def unhide_patch(self
, name
):
1204 """Remove the patch from the hidden list.
1206 hidden
= self
.get_hidden()
1207 if not name
in hidden
:
1208 if self
.patch_applied(name
) or self
.patch_unapplied(name
):
1209 raise StackException
, 'Patch "%s" not hidden' % name
1211 raise StackException
, 'Unknown patch "%s"' % name
1214 write_strings(self
.__hidden
_file
, hidden
)
1216 if not self
.patch_applied(name
) and not self
.patch_unapplied(name
):
1217 # check needed for backward compatibility with the old
1218 # hidden patches functionality
1219 append_string(self
.__unapplied
_file
, name
)