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
22 from email
.Utils
import formatdate
24 from stgit
.exception
import *
25 from stgit
.utils
import *
26 from stgit
.out
import *
27 from stgit
.run
import *
28 from stgit
import git
, basedir
, templates
29 from stgit
.config
import config
30 from shutil
import copyfile
33 # stack exception class
34 class StackException(StgException
):
39 self
.should_print
= True
40 def __call__(self
, x
, until_test
, prefix
):
42 self
.should_print
= False
44 return x
[0:len(prefix
)] != prefix
50 __comment_prefix
= 'STG:'
51 __patch_prefix
= 'STG_PATCH:'
53 def __clean_comments(f
):
54 """Removes lines marked for status in a commit file
58 # remove status-prefixed lines
61 patch_filter
= FilterUntil()
62 until_test
= lambda t
: t
== (__patch_prefix
+ '\n')
63 lines
= [l
for l
in lines
if patch_filter(l
, until_test
, __comment_prefix
)]
65 # remove empty lines at the end
66 while len(lines
) != 0 and lines
[-1] == '\n':
69 f
.seek(0); f
.truncate()
72 # TODO: move this out of the stgit.stack module, it is really for
73 # higher level commands to handle the user interaction
74 def edit_file(series
, line
, comment
, show_patch
= True):
75 fname
= '.stgitmsg.txt'
76 tmpl
= templates
.get_template('patchdescr.tmpl')
85 print >> f
, __comment_prefix
, comment
86 print >> f
, __comment_prefix
, \
87 'Lines prefixed with "%s" will be automatically removed.' \
89 print >> f
, __comment_prefix
, \
90 'Trailing empty lines will be automatically removed.'
93 print >> f
, __patch_prefix
94 # series.get_patch(series.get_current()).get_top()
95 diff_str
= git
.diff(rev1
= series
.get_patch(series
.get_current()).get_bottom())
98 #Vim modeline must be near the end.
99 print >> f
, __comment_prefix
, 'vi: set textwidth=75 filetype=diff nobackup:'
104 f
= file(fname
, 'r+')
120 """An object with stgit-like properties stored as files in a directory
122 def _set_dir(self
, dir):
127 def create_empty_field(self
, name
):
128 create_empty_file(os
.path
.join(self
.__dir
, name
))
130 def _get_field(self
, name
, multiline
= False):
131 id_file
= os
.path
.join(self
.__dir
, name
)
132 if os
.path
.isfile(id_file
):
133 line
= read_string(id_file
, multiline
)
141 def _set_field(self
, name
, value
, multiline
= False):
142 fname
= os
.path
.join(self
.__dir
, name
)
143 if value
and value
!= '':
144 write_string(fname
, value
, multiline
)
145 elif os
.path
.isfile(fname
):
149 class Patch(StgitObject
):
150 """Basic patch implementation
152 def __init_refs(self
):
153 self
.__top_ref
= self
.__refs_base
+ '/' + self
.__name
154 self
.__log_ref
= self
.__top_ref
+ '.log'
156 def __init__(self
, name
, series_dir
, refs_base
):
157 self
.__series_dir
= series_dir
159 self
._set_dir(os
.path
.join(self
.__series_dir
, self
.__name
))
160 self
.__refs_base
= refs_base
164 os
.mkdir(self
._dir())
166 def delete(self
, keep_log
= False):
167 if os
.path
.isdir(self
._dir()):
168 for f
in os
.listdir(self
._dir()):
169 os
.remove(os
.path
.join(self
._dir(), f
))
170 os
.rmdir(self
._dir())
172 out
.warn('Patch directory "%s" does not exist' % self
._dir())
174 # the reference might not exist if the repository was corrupted
175 git
.delete_ref(self
.__top_ref
)
176 except git
.GitException
, e
:
178 if not keep_log
and git
.ref_exists(self
.__log_ref
):
179 git
.delete_ref(self
.__log_ref
)
184 def rename(self
, newname
):
186 old_top_ref
= self
.__top_ref
187 old_log_ref
= self
.__log_ref
188 self
.__name
= newname
189 self
._set_dir(os
.path
.join(self
.__series_dir
, self
.__name
))
192 git
.rename_ref(old_top_ref
, self
.__top_ref
)
193 if git
.ref_exists(old_log_ref
):
194 git
.rename_ref(old_log_ref
, self
.__log_ref
)
195 os
.rename(olddir
, self
._dir())
197 def __update_top_ref(self
, ref
):
198 git
.set_ref(self
.__top_ref
, ref
)
200 def __update_log_ref(self
, ref
):
201 git
.set_ref(self
.__log_ref
, ref
)
203 def get_old_bottom(self
):
204 return git
.get_commit(self
.get_old_top()).get_parent()
206 def get_bottom(self
):
207 return git
.get_commit(self
.get_top()).get_parent()
209 def get_old_top(self
):
210 return self
._get_field('top.old')
213 return git
.rev_parse(self
.__top_ref
)
215 def set_top(self
, value
, backup
= False):
217 curr
= self
.get_top()
218 self
._set_field('top.old', curr
)
219 self
.__update_top_ref(value
)
221 def restore_old_boundaries(self
):
222 top
= self
._get_field('top.old')
225 self
.__update_top_ref(top
)
230 def get_description(self
):
231 return self
._get_field('description', True)
233 def set_description(self
, line
):
234 self
._set_field('description', line
, True)
236 def get_authname(self
):
237 return self
._get_field('authname')
239 def set_authname(self
, name
):
240 self
._set_field('authname', name
or git
.author().name
)
242 def get_authemail(self
):
243 return self
._get_field('authemail')
245 def set_authemail(self
, email
):
246 self
._set_field('authemail', email
or git
.author().email
)
248 def get_authdate(self
):
249 date
= self
._get_field('authdate')
253 if re
.match('[0-9]+\s+[+-][0-9]+', date
):
254 # Unix time (seconds) + time zone
255 secs_tz
= date
.split()
256 date
= formatdate(int(secs_tz
[0]))[:-5] + secs_tz
[1]
260 def set_authdate(self
, date
):
261 self
._set_field('authdate', date
or git
.author().date
)
263 def get_commname(self
):
264 return self
._get_field('commname')
266 def set_commname(self
, name
):
267 self
._set_field('commname', name
or git
.committer().name
)
269 def get_commemail(self
):
270 return self
._get_field('commemail')
272 def set_commemail(self
, email
):
273 self
._set_field('commemail', email
or git
.committer().email
)
276 return self
._get_field('log')
278 def set_log(self
, value
, backup
= False):
279 self
._set_field('log', value
)
280 self
.__update_log_ref(value
)
282 # The current StGIT metadata format version.
285 class PatchSet(StgitObject
):
286 def __init__(self
, name
= None):
291 self
.set_name (git
.get_head_file())
292 self
.__base_dir
= basedir
.get()
293 except git
.GitException
, ex
:
294 raise StackException
, 'GIT tree not initialised: %s' % ex
296 self
._set_dir(os
.path
.join(self
.__base_dir
, 'patches', self
.get_name()))
300 def set_name(self
, name
):
304 return self
.__base_dir
307 """Return the head of the branch
309 crt
= self
.get_current_patch()
313 return self
.get_base()
315 def get_protected(self
):
316 return os
.path
.isfile(os
.path
.join(self
._dir(), 'protected'))
319 protect_file
= os
.path
.join(self
._dir(), 'protected')
320 if not os
.path
.isfile(protect_file
):
321 create_empty_file(protect_file
)
324 protect_file
= os
.path
.join(self
._dir(), 'protected')
325 if os
.path
.isfile(protect_file
):
326 os
.remove(protect_file
)
328 def __branch_descr(self
):
329 return 'branch.%s.description' % self
.get_name()
331 def get_description(self
):
332 return config
.get(self
.__branch_descr()) or ''
334 def set_description(self
, line
):
336 config
.set(self
.__branch_descr(), line
)
338 config
.unset(self
.__branch_descr())
340 def head_top_equal(self
):
341 """Return true if the head and the top are the same
343 crt
= self
.get_current_patch()
345 # we don't care, no patches applied
347 return git
.get_head() == crt
.get_top()
349 def is_initialised(self
):
350 """Checks if series is already initialised
352 return bool(config
.get(self
.format_version_key()))
355 def shortlog(patches
):
356 log
= ''.join(Run('git', 'log', '--pretty=short',
357 p
.get_top(), '^%s' % p
.get_bottom()).raw_output()
359 return Run('git', 'shortlog').raw_input(log
).raw_output()
361 class Series(PatchSet
):
362 """Class including the operations on series
364 def __init__(self
, name
= None):
365 """Takes a series name as the parameter.
367 PatchSet
.__init__(self
, name
)
369 # Update the branch to the latest format version if it is
370 # initialized, but don't touch it if it isn't.
371 self
.update_to_current_format_version()
373 self
.__refs_base
= 'refs/patches/%s' % self
.get_name()
375 self
.__applied_file
= os
.path
.join(self
._dir(), 'applied')
376 self
.__unapplied_file
= os
.path
.join(self
._dir(), 'unapplied')
377 self
.__hidden_file
= os
.path
.join(self
._dir(), 'hidden')
379 # where this series keeps its patches
380 self
.__patch_dir
= os
.path
.join(self
._dir(), 'patches')
383 self
.__trash_dir
= os
.path
.join(self
._dir(), 'trash')
385 def format_version_key(self
):
386 return 'branch.%s.stgit.stackformatversion' % self
.get_name()
388 def update_to_current_format_version(self
):
389 """Update a potentially older StGIT directory structure to the
390 latest version. Note: This function should depend as little as
391 possible on external functions that may change during a format
392 version bump, since it must remain able to process older formats."""
394 branch_dir
= os
.path
.join(self
._basedir(), 'patches', self
.get_name())
395 def get_format_version():
396 """Return the integer format version number, or None if the
397 branch doesn't have any StGIT metadata at all, of any version."""
398 fv
= config
.get(self
.format_version_key())
399 ofv
= config
.get('branch.%s.stgitformatversion' % self
.get_name())
401 # Great, there's an explicitly recorded format version
402 # number, which means that the branch is initialized and
403 # of that exact version.
406 # Old name for the version info, upgrade it
407 config
.set(self
.format_version_key(), ofv
)
408 config
.unset('branch.%s.stgitformatversion' % self
.get_name())
410 elif os
.path
.isdir(os
.path
.join(branch_dir
, 'patches')):
411 # There's a .git/patches/<branch>/patches dirctory, which
412 # means this is an initialized version 1 branch.
414 elif os
.path
.isdir(branch_dir
):
415 # There's a .git/patches/<branch> directory, which means
416 # this is an initialized version 0 branch.
419 # The branch doesn't seem to be initialized at all.
421 def set_format_version(v
):
422 out
.info('Upgraded branch %s to format version %d' %
(self
.get_name(), v
))
423 config
.set(self
.format_version_key(), '%d' % v
)
425 if not os
.path
.isdir(d
):
428 if os
.path
.exists(f
):
431 if git
.ref_exists(ref
):
435 if get_format_version() == 0:
436 mkdir(os
.path
.join(branch_dir
, 'trash'))
437 patch_dir
= os
.path
.join(branch_dir
, 'patches')
439 refs_base
= 'refs/patches/%s' % self
.get_name()
440 for patch
in (file(os
.path
.join(branch_dir
, 'unapplied')).readlines()
441 + file(os
.path
.join(branch_dir
, 'applied')).readlines()):
442 patch
= patch
.strip()
443 os
.rename(os
.path
.join(branch_dir
, patch
),
444 os
.path
.join(patch_dir
, patch
))
445 topfield
= os
.path
.join(patch_dir
, patch
, 'top')
446 if os
.path
.isfile(topfield
):
447 top
= read_string(topfield
, False)
451 git
.set_ref(refs_base
+ '/' + patch
, top
)
452 set_format_version(1)
455 if get_format_version() == 1:
456 desc_file
= os
.path
.join(branch_dir
, 'description')
457 if os
.path
.isfile(desc_file
):
458 desc
= read_string(desc_file
)
460 config
.set('branch.%s.description' % self
.get_name(), desc
)
462 rm(os
.path
.join(branch_dir
, 'current'))
463 rm_ref('refs/bases/%s' % self
.get_name())
464 set_format_version(2)
466 # Make sure we're at the latest version.
467 if not get_format_version() in [None, FORMAT_VERSION
]:
468 raise StackException('Branch %s is at format version %d, expected %d'
469 %
(self
.get_name(), get_format_version(), FORMAT_VERSION
))
471 def __patch_name_valid(self
, name
):
472 """Raise an exception if the patch name is not valid.
474 if not name
or re
.search('[^\w.-]', name
):
475 raise StackException
, 'Invalid patch name: "%s"' % name
477 def get_patch(self
, name
):
478 """Return a Patch object for the given name
480 return Patch(name
, self
.__patch_dir
, self
.__refs_base
)
482 def get_current_patch(self
):
483 """Return a Patch object representing the topmost patch, or
484 None if there is no such patch."""
485 crt
= self
.get_current()
488 return self
.get_patch(crt
)
490 def get_current(self
):
491 """Return the name of the topmost patch, or None if there is
494 applied
= self
.get_applied()
495 except StackException
:
496 # No "applied" file: branch is not initialized.
501 # No patches applied.
504 def get_applied(self
):
505 if not os
.path
.isfile(self
.__applied_file
):
506 raise StackException
, 'Branch "%s" not initialised' % self
.get_name()
507 return read_strings(self
.__applied_file
)
509 def set_applied(self
, applied
):
510 write_strings(self
.__applied_file
, applied
)
512 def get_unapplied(self
):
513 if not os
.path
.isfile(self
.__unapplied_file
):
514 raise StackException
, 'Branch "%s" not initialised' % self
.get_name()
515 return read_strings(self
.__unapplied_file
)
517 def set_unapplied(self
, unapplied
):
518 write_strings(self
.__unapplied_file
, unapplied
)
520 def get_hidden(self
):
521 if not os
.path
.isfile(self
.__hidden_file
):
523 return read_strings(self
.__hidden_file
)
526 # Return the parent of the bottommost patch, if there is one.
527 if os
.path
.isfile(self
.__applied_file
):
528 bottommost
= file(self
.__applied_file
).readline().strip()
530 return self
.get_patch(bottommost
).get_bottom()
531 # No bottommost patch, so just return HEAD
532 return git
.get_head()
534 def get_parent_remote(self
):
535 value
= config
.get('branch.%s.remote' % self
.get_name())
538 elif 'origin' in git
.remotes_list():
539 out
.note(('No parent remote declared for stack "%s",'
540 ' defaulting to "origin".' % self
.get_name()),
541 ('Consider setting "branch.%s.remote" and'
542 ' "branch.%s.merge" with "git config".'
543 %
(self
.get_name(), self
.get_name())))
546 raise StackException
, 'Cannot find a parent remote for "%s"' % self
.get_name()
548 def __set_parent_remote(self
, remote
):
549 value
= config
.set('branch.%s.remote' % self
.get_name(), remote
)
551 def get_parent_branch(self
):
552 value
= config
.get('branch.%s.stgit.parentbranch' % self
.get_name())
555 elif git
.rev_parse('heads/origin'):
556 out
.note(('No parent branch declared for stack "%s",'
557 ' defaulting to "heads/origin".' % self
.get_name()),
558 ('Consider setting "branch.%s.stgit.parentbranch"'
559 ' with "git config".' % self
.get_name()))
560 return 'heads/origin'
562 raise StackException
, 'Cannot find a parent branch for "%s"' % self
.get_name()
564 def __set_parent_branch(self
, name
):
565 if config
.get('branch.%s.remote' % self
.get_name()):
566 # Never set merge if remote is not set to avoid
567 # possibly-erroneous lookups into 'origin'
568 config
.set('branch.%s.merge' % self
.get_name(), name
)
569 config
.set('branch.%s.stgit.parentbranch' % self
.get_name(), name
)
571 def set_parent(self
, remote
, localbranch
):
574 self
.__set_parent_remote(remote
)
575 self
.__set_parent_branch(localbranch
)
576 # We'll enforce this later
578 # raise StackException, 'Parent branch (%s) should be specified for %s' % localbranch, self.get_name()
580 def __patch_is_current(self
, patch
):
581 return patch
.get_name() == self
.get_current()
583 def patch_applied(self
, name
):
584 """Return true if the patch exists in the applied list
586 return name
in self
.get_applied()
588 def patch_unapplied(self
, name
):
589 """Return true if the patch exists in the unapplied list
591 return name
in self
.get_unapplied()
593 def patch_hidden(self
, name
):
594 """Return true if the patch is hidden.
596 return name
in self
.get_hidden()
598 def patch_exists(self
, name
):
599 """Return true if there is a patch with the given name, false
601 return self
.patch_applied(name
) or self
.patch_unapplied(name
) \
602 or self
.patch_hidden(name
)
604 def init(self
, create_at
=False, parent_remote
=None, parent_branch
=None):
605 """Initialises the stgit series
607 if self
.is_initialised():
608 raise StackException
, '%s already initialized' % self
.get_name()
609 for d
in [self
._dir()]:
610 if os
.path
.exists(d
):
611 raise StackException
, '%s already exists' % d
613 if (create_at
!=False):
614 git
.create_branch(self
.get_name(), create_at
)
616 os
.makedirs(self
.__patch_dir
)
618 self
.set_parent(parent_remote
, parent_branch
)
620 self
.create_empty_field('applied')
621 self
.create_empty_field('unapplied')
623 config
.set(self
.format_version_key(), str(FORMAT_VERSION
))
625 def rename(self
, to_name
):
628 to_stack
= Series(to_name
)
630 if to_stack
.is_initialised():
631 raise StackException
, '"%s" already exists' % to_stack
.get_name()
633 patches
= self
.get_applied() + self
.get_unapplied()
635 git
.rename_branch(self
.get_name(), to_name
)
637 for patch
in patches
:
638 git
.rename_ref('refs/patches/%s/%s' %
(self
.get_name(), patch
),
639 'refs/patches/%s/%s' %
(to_name
, patch
))
640 git
.rename_ref('refs/patches/%s/%s.log' %
(self
.get_name(), patch
),
641 'refs/patches/%s/%s.log' %
(to_name
, patch
))
642 if os
.path
.isdir(self
._dir()):
643 rename(os
.path
.join(self
._basedir(), 'patches'),
644 self
.get_name(), to_stack
.get_name())
646 # Rename the config section
647 for k
in ['branch.%s', 'branch.%s.stgit']:
648 config
.rename_section(k % self
.get_name(), k % to_name
)
650 self
.__init__(to_name
)
652 def clone(self
, target_series
):
656 # allow cloning of branches not under StGIT control
657 base
= self
.get_base()
659 base
= git
.get_head()
660 Series(target_series
).init(create_at
= base
)
661 new_series
= Series(target_series
)
663 # generate an artificial description file
664 new_series
.set_description('clone of "%s"' % self
.get_name())
666 # clone self's entire series as unapplied patches
668 # allow cloning of branches not under StGIT control
669 applied
= self
.get_applied()
670 unapplied
= self
.get_unapplied()
671 patches
= applied
+ unapplied
674 patches
= applied
= unapplied
= []
676 patch
= self
.get_patch(p
)
677 newpatch
= new_series
.new_patch(p
, message
= patch
.get_description(),
678 can_edit
= False, unapplied
= True,
679 bottom
= patch
.get_bottom(),
680 top
= patch
.get_top(),
681 author_name
= patch
.get_authname(),
682 author_email
= patch
.get_authemail(),
683 author_date
= patch
.get_authdate())
685 out
.info('Setting log to %s' % patch
.get_log())
686 newpatch
.set_log(patch
.get_log())
688 out
.info('No log for %s' % p
)
690 # fast forward the cloned series to self's top
691 new_series
.forward_patches(applied
)
693 # Clone parent informations
694 value
= config
.get('branch.%s.remote' % self
.get_name())
696 config
.set('branch.%s.remote' % target_series
, value
)
698 value
= config
.get('branch.%s.merge' % self
.get_name())
700 config
.set('branch.%s.merge' % target_series
, value
)
702 value
= config
.get('branch.%s.stgit.parentbranch' % self
.get_name())
704 config
.set('branch.%s.stgit.parentbranch' % target_series
, value
)
706 def delete(self
, force
= False):
707 """Deletes an stgit series
709 if self
.is_initialised():
710 patches
= self
.get_unapplied() + self
.get_applied()
711 if not force
and patches
:
712 raise StackException
, \
713 'Cannot delete: the series still contains patches'
715 self
.get_patch(p
).delete()
717 # remove the trash directory if any
718 if os
.path
.exists(self
.__trash_dir
):
719 for fname
in os
.listdir(self
.__trash_dir
):
720 os
.remove(os
.path
.join(self
.__trash_dir
, fname
))
721 os
.rmdir(self
.__trash_dir
)
723 # FIXME: find a way to get rid of those manual removals
724 # (move functionality to StgitObject ?)
725 if os
.path
.exists(self
.__applied_file
):
726 os
.remove(self
.__applied_file
)
727 if os
.path
.exists(self
.__unapplied_file
):
728 os
.remove(self
.__unapplied_file
)
729 if os
.path
.exists(self
.__hidden_file
):
730 os
.remove(self
.__hidden_file
)
731 if os
.path
.exists(self
._dir()+'/orig-base'):
732 os
.remove(self
._dir()+'/orig-base')
734 if not os
.listdir(self
.__patch_dir
):
735 os
.rmdir(self
.__patch_dir
)
737 out
.warn('Patch directory %s is not empty' % self
.__patch_dir
)
740 os
.removedirs(self
._dir())
742 raise StackException('Series directory %s is not empty'
746 git
.delete_branch(self
.get_name())
748 out
.warn('Could not delete branch "%s"' % self
.get_name())
750 config
.remove_section('branch.%s' % self
.get_name())
751 config
.remove_section('branch.%s.stgit' % self
.get_name())
753 def refresh_patch(self
, files
= None, message
= None, edit
= False,
756 author_name
= None, author_email
= None,
758 committer_name
= None, committer_email
= None,
759 backup
= True, sign_str
= None, log
= 'refresh',
760 notes
= None, bottom
= None):
761 """Generates a new commit for the topmost patch
763 patch
= self
.get_current_patch()
765 raise StackException
, 'No patches applied'
767 descr
= patch
.get_description()
768 if not (message
or descr
):
774 # TODO: move this out of the stgit.stack module, it is really
775 # for higher level commands to handle the user interaction
776 if not message
and edit
:
777 descr
= edit_file(self
, descr
.rstrip(), \
778 'Please edit the description for patch "%s" ' \
779 'above.' % patch
.get_name(), show_patch
)
782 author_name
= patch
.get_authname()
784 author_email
= patch
.get_authemail()
786 author_date
= patch
.get_authdate()
787 if not committer_name
:
788 committer_name
= patch
.get_commname()
789 if not committer_email
:
790 committer_email
= patch
.get_commemail()
792 descr
= add_sign_line(descr
, sign_str
, committer_name
, committer_email
)
795 bottom
= patch
.get_bottom()
797 commit_id
= git
.commit(files
= files
,
798 message
= descr
, parents
= [bottom
],
799 cache_update
= cache_update
,
801 author_name
= author_name
,
802 author_email
= author_email
,
803 author_date
= author_date
,
804 committer_name
= committer_name
,
805 committer_email
= committer_email
)
807 patch
.set_top(commit_id
, backup
= backup
)
808 patch
.set_description(descr
)
809 patch
.set_authname(author_name
)
810 patch
.set_authemail(author_email
)
811 patch
.set_authdate(author_date
)
812 patch
.set_commname(committer_name
)
813 patch
.set_commemail(committer_email
)
816 self
.log_patch(patch
, log
, notes
)
820 def undo_refresh(self
):
821 """Undo the patch boundaries changes caused by 'refresh'
823 name
= self
.get_current()
826 patch
= self
.get_patch(name
)
827 old_bottom
= patch
.get_old_bottom()
828 old_top
= patch
.get_old_top()
830 # the bottom of the patch is not changed by refresh. If the
831 # old_bottom is different, there wasn't any previous 'refresh'
832 # command (probably only a 'push')
833 if old_bottom
!= patch
.get_bottom() or old_top
== patch
.get_top():
834 raise StackException
, 'No undo information available'
836 git
.reset(tree_id
= old_top
, check_out
= False)
837 if patch
.restore_old_boundaries():
838 self
.log_patch(patch
, 'undo')
840 def new_patch(self
, name
, message
= None, can_edit
= True,
841 unapplied
= False, show_patch
= False,
842 top
= None, bottom
= None, commit
= True,
843 author_name
= None, author_email
= None, author_date
= None,
844 committer_name
= None, committer_email
= None,
845 before_existing
= False, sign_str
= None):
846 """Creates a new patch, either pointing to an existing commit object,
847 or by creating a new commit object.
850 assert commit
or (top
and bottom
)
851 assert not before_existing
or (top
and bottom
)
852 assert not (commit
and before_existing
)
853 assert (top
and bottom
) or (not top
and not bottom
)
854 assert commit
or (not top
or (bottom
== git
.get_commit(top
).get_parent()))
857 self
.__patch_name_valid(name
)
858 if self
.patch_exists(name
):
859 raise StackException
, 'Patch "%s" already exists' % name
861 # TODO: move this out of the stgit.stack module, it is really
862 # for higher level commands to handle the user interaction
864 return add_sign_line(msg
, sign_str
,
865 committer_name
or git
.committer().name
,
866 committer_email
or git
.committer().email
)
867 if not message
and can_edit
:
870 'Please enter the description for the patch above.',
873 descr
= sign(message
)
875 head
= git
.get_head()
878 name
= make_patch_name(descr
, self
.patch_exists
)
880 patch
= self
.get_patch(name
)
883 patch
.set_description(descr
)
884 patch
.set_authname(author_name
)
885 patch
.set_authemail(author_email
)
886 patch
.set_authdate(author_date
)
887 patch
.set_commname(committer_name
)
888 patch
.set_commemail(committer_email
)
891 insert_string(self
.__applied_file
, patch
.get_name())
893 patches
= [patch
.get_name()] + self
.get_unapplied()
894 write_strings(self
.__unapplied_file
, patches
)
897 append_string(self
.__applied_file
, patch
.get_name())
902 top_commit
= git
.get_commit(top
)
905 top_commit
= git
.get_commit(head
)
907 # create a commit for the patch (may be empty if top == bottom);
908 # only commit on top of the current branch
909 assert(unapplied
or bottom
== head
)
910 commit_id
= git
.commit(message
= descr
, parents
= [bottom
],
911 cache_update
= False,
912 tree_id
= top_commit
.get_tree(),
913 allowempty
= True, set_head
= set_head
,
914 author_name
= author_name
,
915 author_email
= author_email
,
916 author_date
= author_date
,
917 committer_name
= committer_name
,
918 committer_email
= committer_email
)
919 # set the patch top to the new commit
920 patch
.set_top(commit_id
)
924 self
.log_patch(patch
, 'new')
928 def delete_patch(self
, name
, keep_log
= False):
931 self
.__patch_name_valid(name
)
932 patch
= self
.get_patch(name
)
934 if self
.__patch_is_current(patch
):
936 elif self
.patch_applied(name
):
937 raise StackException
, 'Cannot remove an applied patch, "%s", ' \
938 'which is not current' % name
939 elif not name
in self
.get_unapplied():
940 raise StackException
, 'Unknown patch "%s"' % name
942 # save the commit id to a trash file
943 write_string(os
.path
.join(self
.__trash_dir
, name
), patch
.get_top())
945 patch
.delete(keep_log
= keep_log
)
947 unapplied
= self
.get_unapplied()
948 unapplied
.remove(name
)
949 write_strings(self
.__unapplied_file
, unapplied
)
951 def forward_patches(self
, names
):
952 """Try to fast-forward an array of patches.
954 On return, patches in names[0:returned_value] have been pushed on the
955 stack. Apply the rest with push_patch
957 unapplied
= self
.get_unapplied()
963 assert(name
in unapplied
)
965 patch
= self
.get_patch(name
)
968 bottom
= patch
.get_bottom()
969 top
= patch
.get_top()
971 # top != bottom always since we have a commit for each patch
973 # reset the backup information. No logging since the
974 # patch hasn't changed
975 patch
.set_top(top
, backup
= True)
978 head_tree
= git
.get_commit(head
).get_tree()
979 bottom_tree
= git
.get_commit(bottom
).get_tree()
980 if head_tree
== bottom_tree
:
981 # We must just reparent this patch and create a new commit
983 descr
= patch
.get_description()
984 author_name
= patch
.get_authname()
985 author_email
= patch
.get_authemail()
986 author_date
= patch
.get_authdate()
987 committer_name
= patch
.get_commname()
988 committer_email
= patch
.get_commemail()
990 top_tree
= git
.get_commit(top
).get_tree()
992 top
= git
.commit(message
= descr
, parents
= [head
],
993 cache_update
= False,
996 author_name
= author_name
,
997 author_email
= author_email
,
998 author_date
= author_date
,
999 committer_name
= committer_name
,
1000 committer_email
= committer_email
)
1002 patch
.set_top(top
, backup
= True)
1004 self
.log_patch(patch
, 'push(f)')
1007 # stop the fast-forwarding, must do a real merge
1011 unapplied
.remove(name
)
1018 append_strings(self
.__applied_file
, names
[0:forwarded
])
1019 write_strings(self
.__unapplied_file
, unapplied
)
1023 def merged_patches(self
, names
):
1024 """Test which patches were merged upstream by reverse-applying
1025 them in reverse order. The function returns the list of
1026 patches detected to have been applied. The state of the tree
1027 is restored to the original one
1029 patches
= [self
.get_patch(name
) for name
in names
]
1034 if git
.apply_diff(p
.get_top(), p
.get_bottom()):
1035 merged
.append(p
.get_name())
1042 def push_empty_patch(self
, name
):
1043 """Pushes an empty patch on the stack
1045 unapplied
= self
.get_unapplied()
1046 assert(name
in unapplied
)
1048 # patch = self.get_patch(name)
1049 head
= git
.get_head()
1051 append_string(self
.__applied_file
, name
)
1053 unapplied
.remove(name
)
1054 write_strings(self
.__unapplied_file
, unapplied
)
1056 self
.refresh_patch(bottom
= head
, cache_update
= False, log
= 'push(m)')
1058 def push_patch(self
, name
):
1059 """Pushes a patch on the stack
1061 unapplied
= self
.get_unapplied()
1062 assert(name
in unapplied
)
1064 patch
= self
.get_patch(name
)
1066 head
= git
.get_head()
1067 bottom
= patch
.get_bottom()
1068 top
= patch
.get_top()
1069 # top != bottom always since we have a commit for each patch
1072 # A fast-forward push. Just reset the backup
1073 # information. No need for logging
1074 patch
.set_top(top
, backup
= True)
1077 append_string(self
.__applied_file
, name
)
1079 unapplied
.remove(name
)
1080 write_strings(self
.__unapplied_file
, unapplied
)
1083 # Need to create a new commit an merge in the old patch
1087 # Try the fast applying first. If this fails, fall back to the
1089 if not git
.apply_diff(bottom
, top
):
1090 # if git.apply_diff() fails, the patch requires a diff3
1091 # merge and can be reported as modified
1094 # merge can fail but the patch needs to be pushed
1096 git
.merge(bottom
, head
, top
, recursive
= True)
1097 except git
.GitException
, ex
:
1098 out
.error('The merge failed during "push".',
1099 'Use "refresh" after fixing the conflicts or'
1100 ' revert the operation with "push --undo".')
1102 append_string(self
.__applied_file
, name
)
1104 unapplied
.remove(name
)
1105 write_strings(self
.__unapplied_file
, unapplied
)
1108 # if the merge was OK and no conflicts, just refresh the patch
1109 # The GIT cache was already updated by the merge operation
1114 self
.refresh_patch(bottom
= head
, cache_update
= False, log
= log
)
1116 # we store the correctly merged files only for
1117 # tracking the conflict history. Note that the
1118 # git.merge() operations should always leave the index
1119 # in a valid state (i.e. only stage 0 files)
1120 self
.refresh_patch(bottom
= head
, cache_update
= False,
1122 raise StackException
, str(ex
)
1126 def undo_push(self
):
1127 name
= self
.get_current()
1130 patch
= self
.get_patch(name
)
1131 old_bottom
= patch
.get_old_bottom()
1132 old_top
= patch
.get_old_top()
1134 # the top of the patch is changed by a push operation only
1135 # together with the bottom (otherwise the top was probably
1136 # modified by 'refresh'). If they are both unchanged, there
1137 # was a fast forward
1138 if old_bottom
== patch
.get_bottom() and old_top
!= patch
.get_top():
1139 raise StackException
, 'No undo information available'
1142 self
.pop_patch(name
)
1143 ret
= patch
.restore_old_boundaries()
1145 self
.log_patch(patch
, 'undo')
1149 def pop_patch(self
, name
, keep
= False):
1150 """Pops the top patch from the stack
1152 applied
= self
.get_applied()
1154 assert(name
in applied
)
1156 patch
= self
.get_patch(name
)
1158 if git
.get_head_file() == self
.get_name():
1159 if keep
and not git
.apply_diff(git
.get_head(), patch
.get_bottom(),
1160 check_index
= False):
1161 raise StackException(
1162 'Failed to pop patches while preserving the local changes')
1163 git
.switch(patch
.get_bottom(), keep
)
1165 git
.set_branch(self
.get_name(), patch
.get_bottom())
1167 # save the new applied list
1168 idx
= applied
.index(name
) + 1
1170 popped
= applied
[:idx
]
1172 unapplied
= popped
+ self
.get_unapplied()
1173 write_strings(self
.__unapplied_file
, unapplied
)
1177 write_strings(self
.__applied_file
, applied
)
1179 def empty_patch(self
, name
):
1180 """Returns True if the patch is empty
1182 self
.__patch_name_valid(name
)
1183 patch
= self
.get_patch(name
)
1184 bottom
= patch
.get_bottom()
1185 top
= patch
.get_top()
1189 elif git
.get_commit(top
).get_tree() \
1190 == git
.get_commit(bottom
).get_tree():
1195 def rename_patch(self
, oldname
, newname
):
1196 self
.__patch_name_valid(newname
)
1198 applied
= self
.get_applied()
1199 unapplied
= self
.get_unapplied()
1201 if oldname
== newname
:
1202 raise StackException
, '"To" name and "from" name are the same'
1204 if newname
in applied
or newname
in unapplied
:
1205 raise StackException
, 'Patch "%s" already exists' % newname
1207 if oldname
in unapplied
:
1208 self
.get_patch(oldname
).rename(newname
)
1209 unapplied
[unapplied
.index(oldname
)] = newname
1210 write_strings(self
.__unapplied_file
, unapplied
)
1211 elif oldname
in applied
:
1212 self
.get_patch(oldname
).rename(newname
)
1214 applied
[applied
.index(oldname
)] = newname
1215 write_strings(self
.__applied_file
, applied
)
1217 raise StackException
, 'Unknown patch "%s"' % oldname
1219 def log_patch(self
, patch
, message
, notes
= None):
1220 """Generate a log commit for a patch
1222 top
= git
.get_commit(patch
.get_top())
1223 old_log
= patch
.get_log()
1226 # replace the current log entry
1228 raise StackException
, \
1229 'No log entry to annotate for patch "%s"' \
1232 log_commit
= git
.get_commit(old_log
)
1233 msg
= log_commit
.get_log().split('\n')[0]
1234 log_parent
= log_commit
.get_parent()
1236 parents
= [log_parent
]
1240 # generate a new log entry
1242 msg
= '%s\t%s' %
(message
, top
.get_id_hash())
1249 msg
+= '\n\n' + notes
1251 log
= git
.commit(message
= msg
, parents
= parents
,
1252 cache_update
= False, tree_id
= top
.get_tree(),
1256 def hide_patch(self
, name
):
1257 """Add the patch to the hidden list.
1259 unapplied
= self
.get_unapplied()
1260 if name
not in unapplied
:
1261 # keep the checking order for backward compatibility with
1262 # the old hidden patches functionality
1263 if self
.patch_applied(name
):
1264 raise StackException
, 'Cannot hide applied patch "%s"' % name
1265 elif self
.patch_hidden(name
):
1266 raise StackException
, 'Patch "%s" already hidden' % name
1268 raise StackException
, 'Unknown patch "%s"' % name
1270 if not self
.patch_hidden(name
):
1271 # check needed for backward compatibility with the old
1272 # hidden patches functionality
1273 append_string(self
.__hidden_file
, name
)
1275 unapplied
.remove(name
)
1276 write_strings(self
.__unapplied_file
, unapplied
)
1278 def unhide_patch(self
, name
):
1279 """Remove the patch from the hidden list.
1281 hidden
= self
.get_hidden()
1282 if not name
in hidden
:
1283 if self
.patch_applied(name
) or self
.patch_unapplied(name
):
1284 raise StackException
, 'Patch "%s" not hidden' % name
1286 raise StackException
, 'Unknown patch "%s"' % name
1289 write_strings(self
.__hidden_file
, hidden
)
1291 if not self
.patch_applied(name
) and not self
.patch_unapplied(name
):
1292 # check needed for backward compatibility with the old
1293 # hidden patches functionality
1294 append_string(self
.__unapplied_file
, name
)