Remove the 'top' field
[stgit] / stgit / stack.py
1 """Basic quilt-like functionality
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os, re
22 from email.Utils import formatdate
23
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
31
32
33 # stack exception class
34 class StackException(StgException):
35 pass
36
37 class FilterUntil:
38 def __init__(self):
39 self.should_print = True
40 def __call__(self, x, until_test, prefix):
41 if until_test(x):
42 self.should_print = False
43 if self.should_print:
44 return x[0:len(prefix)] != prefix
45 return False
46
47 #
48 # Functions
49 #
50 __comment_prefix = 'STG:'
51 __patch_prefix = 'STG_PATCH:'
52
53 def __clean_comments(f):
54 """Removes lines marked for status in a commit file
55 """
56 f.seek(0)
57
58 # remove status-prefixed lines
59 lines = f.readlines()
60
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)]
64
65 # remove empty lines at the end
66 while len(lines) != 0 and lines[-1] == '\n':
67 del lines[-1]
68
69 f.seek(0); f.truncate()
70 f.writelines(lines)
71
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')
77
78 f = file(fname, 'w+')
79 if line:
80 print >> f, line
81 elif tmpl:
82 print >> f, tmpl,
83 else:
84 print >> f
85 print >> f, __comment_prefix, comment
86 print >> f, __comment_prefix, \
87 'Lines prefixed with "%s" will be automatically removed.' \
88 % __comment_prefix
89 print >> f, __comment_prefix, \
90 'Trailing empty lines will be automatically removed.'
91
92 if show_patch:
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())
96 f.write(diff_str)
97
98 #Vim modeline must be near the end.
99 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:'
100 f.close()
101
102 call_editor(fname)
103
104 f = file(fname, 'r+')
105
106 __clean_comments(f)
107 f.seek(0)
108 result = f.read()
109
110 f.close()
111 os.remove(fname)
112
113 return result
114
115 #
116 # Classes
117 #
118
119 class StgitObject:
120 """An object with stgit-like properties stored as files in a directory
121 """
122 def _set_dir(self, dir):
123 self.__dir = dir
124 def _dir(self):
125 return self.__dir
126
127 def create_empty_field(self, name):
128 create_empty_file(os.path.join(self.__dir, name))
129
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)
134 if line == '':
135 return None
136 else:
137 return line
138 else:
139 return None
140
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):
146 os.remove(fname)
147
148
149 class Patch(StgitObject):
150 """Basic patch implementation
151 """
152 def __init_refs(self):
153 self.__top_ref = self.__refs_base + '/' + self.__name
154 self.__log_ref = self.__top_ref + '.log'
155
156 def __init__(self, name, series_dir, refs_base):
157 self.__series_dir = series_dir
158 self.__name = name
159 self._set_dir(os.path.join(self.__series_dir, self.__name))
160 self.__refs_base = refs_base
161 self.__init_refs()
162
163 def create(self):
164 os.mkdir(self._dir())
165
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())
171 else:
172 out.warn('Patch directory "%s" does not exist' % self._dir())
173 try:
174 # the reference might not exist if the repository was corrupted
175 git.delete_ref(self.__top_ref)
176 except git.GitException, e:
177 out.warn(str(e))
178 if not keep_log and git.ref_exists(self.__log_ref):
179 git.delete_ref(self.__log_ref)
180
181 def get_name(self):
182 return self.__name
183
184 def rename(self, newname):
185 olddir = self._dir()
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))
190 self.__init_refs()
191
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())
196
197 def __update_top_ref(self, ref):
198 git.set_ref(self.__top_ref, ref)
199
200 def __update_log_ref(self, ref):
201 git.set_ref(self.__log_ref, ref)
202
203 def get_old_bottom(self):
204 return git.get_commit(self.get_old_top()).get_parent()
205
206 def get_bottom(self):
207 return git.get_commit(self.get_top()).get_parent()
208
209 def get_old_top(self):
210 return self._get_field('top.old')
211
212 def get_top(self):
213 return git.rev_parse(self.__top_ref)
214
215 def set_top(self, value, backup = False):
216 if backup:
217 curr = self.get_top()
218 self._set_field('top.old', curr)
219 self.__update_top_ref(value)
220
221 def restore_old_boundaries(self):
222 top = self._get_field('top.old')
223
224 if top:
225 self.__update_top_ref(top)
226 return True
227 else:
228 return False
229
230 def get_description(self):
231 return self._get_field('description', True)
232
233 def set_description(self, line):
234 self._set_field('description', line, True)
235
236 def get_authname(self):
237 return self._get_field('authname')
238
239 def set_authname(self, name):
240 self._set_field('authname', name or git.author().name)
241
242 def get_authemail(self):
243 return self._get_field('authemail')
244
245 def set_authemail(self, email):
246 self._set_field('authemail', email or git.author().email)
247
248 def get_authdate(self):
249 date = self._get_field('authdate')
250 if not date:
251 return date
252
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]
257
258 return date
259
260 def set_authdate(self, date):
261 self._set_field('authdate', date or git.author().date)
262
263 def get_commname(self):
264 return self._get_field('commname')
265
266 def set_commname(self, name):
267 self._set_field('commname', name or git.committer().name)
268
269 def get_commemail(self):
270 return self._get_field('commemail')
271
272 def set_commemail(self, email):
273 self._set_field('commemail', email or git.committer().email)
274
275 def get_log(self):
276 return self._get_field('log')
277
278 def set_log(self, value, backup = False):
279 self._set_field('log', value)
280 self.__update_log_ref(value)
281
282 # The current StGIT metadata format version.
283 FORMAT_VERSION = 2
284
285 class PatchSet(StgitObject):
286 def __init__(self, name = None):
287 try:
288 if name:
289 self.set_name (name)
290 else:
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
295
296 self._set_dir(os.path.join(self.__base_dir, 'patches', self.get_name()))
297
298 def get_name(self):
299 return self.__name
300 def set_name(self, name):
301 self.__name = name
302
303 def _basedir(self):
304 return self.__base_dir
305
306 def get_head(self):
307 """Return the head of the branch
308 """
309 crt = self.get_current_patch()
310 if crt:
311 return crt.get_top()
312 else:
313 return self.get_base()
314
315 def get_protected(self):
316 return os.path.isfile(os.path.join(self._dir(), 'protected'))
317
318 def protect(self):
319 protect_file = os.path.join(self._dir(), 'protected')
320 if not os.path.isfile(protect_file):
321 create_empty_file(protect_file)
322
323 def unprotect(self):
324 protect_file = os.path.join(self._dir(), 'protected')
325 if os.path.isfile(protect_file):
326 os.remove(protect_file)
327
328 def __branch_descr(self):
329 return 'branch.%s.description' % self.get_name()
330
331 def get_description(self):
332 return config.get(self.__branch_descr()) or ''
333
334 def set_description(self, line):
335 if line:
336 config.set(self.__branch_descr(), line)
337 else:
338 config.unset(self.__branch_descr())
339
340 def head_top_equal(self):
341 """Return true if the head and the top are the same
342 """
343 crt = self.get_current_patch()
344 if not crt:
345 # we don't care, no patches applied
346 return True
347 return git.get_head() == crt.get_top()
348
349 def is_initialised(self):
350 """Checks if series is already initialised
351 """
352 return bool(config.get(self.format_version_key()))
353
354
355 def shortlog(patches):
356 log = ''.join(Run('git', 'log', '--pretty=short',
357 p.get_top(), '^%s' % p.get_bottom()).raw_output()
358 for p in patches)
359 return Run('git', 'shortlog').raw_input(log).raw_output()
360
361 class Series(PatchSet):
362 """Class including the operations on series
363 """
364 def __init__(self, name = None):
365 """Takes a series name as the parameter.
366 """
367 PatchSet.__init__(self, name)
368
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()
372
373 self.__refs_base = 'refs/patches/%s' % self.get_name()
374
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')
378
379 # where this series keeps its patches
380 self.__patch_dir = os.path.join(self._dir(), 'patches')
381
382 # trash directory
383 self.__trash_dir = os.path.join(self._dir(), 'trash')
384
385 def format_version_key(self):
386 return 'branch.%s.stgit.stackformatversion' % self.get_name()
387
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."""
393
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())
400 if fv:
401 # Great, there's an explicitly recorded format version
402 # number, which means that the branch is initialized and
403 # of that exact version.
404 return int(fv)
405 elif ofv:
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())
409 return int(ofv)
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.
413 return 1
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.
417 return 0
418 else:
419 # The branch doesn't seem to be initialized at all.
420 return None
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)
424 def mkdir(d):
425 if not os.path.isdir(d):
426 os.makedirs(d)
427 def rm(f):
428 if os.path.exists(f):
429 os.remove(f)
430 def rm_ref(ref):
431 if git.ref_exists(ref):
432 git.delete_ref(ref)
433
434 # Update 0 -> 1.
435 if get_format_version() == 0:
436 mkdir(os.path.join(branch_dir, 'trash'))
437 patch_dir = os.path.join(branch_dir, 'patches')
438 mkdir(patch_dir)
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)
448 else:
449 top = None
450 if top:
451 git.set_ref(refs_base + '/' + patch, top)
452 set_format_version(1)
453
454 # Update 1 -> 2.
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)
459 if desc:
460 config.set('branch.%s.description' % self.get_name(), desc)
461 rm(desc_file)
462 rm(os.path.join(branch_dir, 'current'))
463 rm_ref('refs/bases/%s' % self.get_name())
464 set_format_version(2)
465
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))
470
471 def __patch_name_valid(self, name):
472 """Raise an exception if the patch name is not valid.
473 """
474 if not name or re.search('[^\w.-]', name):
475 raise StackException, 'Invalid patch name: "%s"' % name
476
477 def get_patch(self, name):
478 """Return a Patch object for the given name
479 """
480 return Patch(name, self.__patch_dir, self.__refs_base)
481
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()
486 if not crt:
487 return None
488 return self.get_patch(crt)
489
490 def get_current(self):
491 """Return the name of the topmost patch, or None if there is
492 no such patch."""
493 try:
494 applied = self.get_applied()
495 except StackException:
496 # No "applied" file: branch is not initialized.
497 return None
498 try:
499 return applied[-1]
500 except IndexError:
501 # No patches applied.
502 return None
503
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)
508
509 def set_applied(self, applied):
510 write_strings(self.__applied_file, applied)
511
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)
516
517 def set_unapplied(self, unapplied):
518 write_strings(self.__unapplied_file, unapplied)
519
520 def get_hidden(self):
521 if not os.path.isfile(self.__hidden_file):
522 return []
523 return read_strings(self.__hidden_file)
524
525 def get_base(self):
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()
529 if bottommost:
530 return self.get_patch(bottommost).get_bottom()
531 # No bottommost patch, so just return HEAD
532 return git.get_head()
533
534 def get_parent_remote(self):
535 value = config.get('branch.%s.remote' % self.get_name())
536 if value:
537 return value
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())))
544 return 'origin'
545 else:
546 raise StackException, 'Cannot find a parent remote for "%s"' % self.get_name()
547
548 def __set_parent_remote(self, remote):
549 value = config.set('branch.%s.remote' % self.get_name(), remote)
550
551 def get_parent_branch(self):
552 value = config.get('branch.%s.stgit.parentbranch' % self.get_name())
553 if value:
554 return value
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'
561 else:
562 raise StackException, 'Cannot find a parent branch for "%s"' % self.get_name()
563
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)
570
571 def set_parent(self, remote, localbranch):
572 if localbranch:
573 if remote:
574 self.__set_parent_remote(remote)
575 self.__set_parent_branch(localbranch)
576 # We'll enforce this later
577 # else:
578 # raise StackException, 'Parent branch (%s) should be specified for %s' % localbranch, self.get_name()
579
580 def __patch_is_current(self, patch):
581 return patch.get_name() == self.get_current()
582
583 def patch_applied(self, name):
584 """Return true if the patch exists in the applied list
585 """
586 return name in self.get_applied()
587
588 def patch_unapplied(self, name):
589 """Return true if the patch exists in the unapplied list
590 """
591 return name in self.get_unapplied()
592
593 def patch_hidden(self, name):
594 """Return true if the patch is hidden.
595 """
596 return name in self.get_hidden()
597
598 def patch_exists(self, name):
599 """Return true if there is a patch with the given name, false
600 otherwise."""
601 return self.patch_applied(name) or self.patch_unapplied(name) \
602 or self.patch_hidden(name)
603
604 def init(self, create_at=False, parent_remote=None, parent_branch=None):
605 """Initialises the stgit series
606 """
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
612
613 if (create_at!=False):
614 git.create_branch(self.get_name(), create_at)
615
616 os.makedirs(self.__patch_dir)
617
618 self.set_parent(parent_remote, parent_branch)
619
620 self.create_empty_field('applied')
621 self.create_empty_field('unapplied')
622
623 config.set(self.format_version_key(), str(FORMAT_VERSION))
624
625 def rename(self, to_name):
626 """Renames a series
627 """
628 to_stack = Series(to_name)
629
630 if to_stack.is_initialised():
631 raise StackException, '"%s" already exists' % to_stack.get_name()
632
633 patches = self.get_applied() + self.get_unapplied()
634
635 git.rename_branch(self.get_name(), to_name)
636
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())
645
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)
649
650 self.__init__(to_name)
651
652 def clone(self, target_series):
653 """Clones a series
654 """
655 try:
656 # allow cloning of branches not under StGIT control
657 base = self.get_base()
658 except:
659 base = git.get_head()
660 Series(target_series).init(create_at = base)
661 new_series = Series(target_series)
662
663 # generate an artificial description file
664 new_series.set_description('clone of "%s"' % self.get_name())
665
666 # clone self's entire series as unapplied patches
667 try:
668 # allow cloning of branches not under StGIT control
669 applied = self.get_applied()
670 unapplied = self.get_unapplied()
671 patches = applied + unapplied
672 patches.reverse()
673 except:
674 patches = applied = unapplied = []
675 for p in patches:
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())
684 if patch.get_log():
685 out.info('Setting log to %s' % patch.get_log())
686 newpatch.set_log(patch.get_log())
687 else:
688 out.info('No log for %s' % p)
689
690 # fast forward the cloned series to self's top
691 new_series.forward_patches(applied)
692
693 # Clone parent informations
694 value = config.get('branch.%s.remote' % self.get_name())
695 if value:
696 config.set('branch.%s.remote' % target_series, value)
697
698 value = config.get('branch.%s.merge' % self.get_name())
699 if value:
700 config.set('branch.%s.merge' % target_series, value)
701
702 value = config.get('branch.%s.stgit.parentbranch' % self.get_name())
703 if value:
704 config.set('branch.%s.stgit.parentbranch' % target_series, value)
705
706 def delete(self, force = False):
707 """Deletes an stgit series
708 """
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'
714 for p in patches:
715 self.get_patch(p).delete()
716
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)
722
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')
733
734 if not os.listdir(self.__patch_dir):
735 os.rmdir(self.__patch_dir)
736 else:
737 out.warn('Patch directory %s is not empty' % self.__patch_dir)
738
739 try:
740 os.removedirs(self._dir())
741 except OSError:
742 raise StackException('Series directory %s is not empty'
743 % self._dir())
744
745 try:
746 git.delete_branch(self.get_name())
747 except GitException:
748 out.warn('Could not delete branch "%s"' % self.get_name())
749
750 config.remove_section('branch.%s' % self.get_name())
751 config.remove_section('branch.%s.stgit' % self.get_name())
752
753 def refresh_patch(self, files = None, message = None, edit = False,
754 show_patch = False,
755 cache_update = True,
756 author_name = None, author_email = None,
757 author_date = 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
762 """
763 patch = self.get_current_patch()
764 if not patch:
765 raise StackException, 'No patches applied'
766
767 descr = patch.get_description()
768 if not (message or descr):
769 edit = True
770 descr = ''
771 elif message:
772 descr = message
773
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)
780
781 if not author_name:
782 author_name = patch.get_authname()
783 if not author_email:
784 author_email = patch.get_authemail()
785 if not author_date:
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()
791
792 descr = add_sign_line(descr, sign_str, committer_name, committer_email)
793
794 if not bottom:
795 bottom = patch.get_bottom()
796
797 commit_id = git.commit(files = files,
798 message = descr, parents = [bottom],
799 cache_update = cache_update,
800 allowempty = True,
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)
806
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)
814
815 if log:
816 self.log_patch(patch, log, notes)
817
818 return commit_id
819
820 def undo_refresh(self):
821 """Undo the patch boundaries changes caused by 'refresh'
822 """
823 name = self.get_current()
824 assert(name)
825
826 patch = self.get_patch(name)
827 old_bottom = patch.get_old_bottom()
828 old_top = patch.get_old_top()
829
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'
835
836 git.reset(tree_id = old_top, check_out = False)
837 if patch.restore_old_boundaries():
838 self.log_patch(patch, 'undo')
839
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.
848 """
849
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()))
855
856 if name != None:
857 self.__patch_name_valid(name)
858 if self.patch_exists(name):
859 raise StackException, 'Patch "%s" already exists' % name
860
861 # TODO: move this out of the stgit.stack module, it is really
862 # for higher level commands to handle the user interaction
863 def sign(msg):
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:
868 descr = edit_file(
869 self, sign(''),
870 'Please enter the description for the patch above.',
871 show_patch)
872 else:
873 descr = sign(message)
874
875 head = git.get_head()
876
877 if name == None:
878 name = make_patch_name(descr, self.patch_exists)
879
880 patch = self.get_patch(name)
881 patch.create()
882
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)
889
890 if before_existing:
891 insert_string(self.__applied_file, patch.get_name())
892 elif unapplied:
893 patches = [patch.get_name()] + self.get_unapplied()
894 write_strings(self.__unapplied_file, patches)
895 set_head = False
896 else:
897 append_string(self.__applied_file, patch.get_name())
898 set_head = True
899
900 if commit:
901 if top:
902 top_commit = git.get_commit(top)
903 else:
904 bottom = head
905 top_commit = git.get_commit(head)
906
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)
921 else:
922 patch.set_top(top)
923
924 self.log_patch(patch, 'new')
925
926 return patch
927
928 def delete_patch(self, name, keep_log = False):
929 """Deletes a patch
930 """
931 self.__patch_name_valid(name)
932 patch = self.get_patch(name)
933
934 if self.__patch_is_current(patch):
935 self.pop_patch(name)
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
941
942 # save the commit id to a trash file
943 write_string(os.path.join(self.__trash_dir, name), patch.get_top())
944
945 patch.delete(keep_log = keep_log)
946
947 unapplied = self.get_unapplied()
948 unapplied.remove(name)
949 write_strings(self.__unapplied_file, unapplied)
950
951 def forward_patches(self, names):
952 """Try to fast-forward an array of patches.
953
954 On return, patches in names[0:returned_value] have been pushed on the
955 stack. Apply the rest with push_patch
956 """
957 unapplied = self.get_unapplied()
958
959 forwarded = 0
960 top = git.get_head()
961
962 for name in names:
963 assert(name in unapplied)
964
965 patch = self.get_patch(name)
966
967 head = top
968 bottom = patch.get_bottom()
969 top = patch.get_top()
970
971 # top != bottom always since we have a commit for each patch
972 if head == bottom:
973 # reset the backup information. No logging since the
974 # patch hasn't changed
975 patch.set_top(top, backup = True)
976
977 else:
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
982 # for it
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()
989
990 top_tree = git.get_commit(top).get_tree()
991
992 top = git.commit(message = descr, parents = [head],
993 cache_update = False,
994 tree_id = top_tree,
995 allowempty = True,
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)
1001
1002 patch.set_top(top, backup = True)
1003
1004 self.log_patch(patch, 'push(f)')
1005 else:
1006 top = head
1007 # stop the fast-forwarding, must do a real merge
1008 break
1009
1010 forwarded+=1
1011 unapplied.remove(name)
1012
1013 if forwarded == 0:
1014 return 0
1015
1016 git.switch(top)
1017
1018 append_strings(self.__applied_file, names[0:forwarded])
1019 write_strings(self.__unapplied_file, unapplied)
1020
1021 return forwarded
1022
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
1028 """
1029 patches = [self.get_patch(name) for name in names]
1030 patches.reverse()
1031
1032 merged = []
1033 for p in patches:
1034 if git.apply_diff(p.get_top(), p.get_bottom()):
1035 merged.append(p.get_name())
1036 merged.reverse()
1037
1038 git.reset()
1039
1040 return merged
1041
1042 def push_empty_patch(self, name):
1043 """Pushes an empty patch on the stack
1044 """
1045 unapplied = self.get_unapplied()
1046 assert(name in unapplied)
1047
1048 # patch = self.get_patch(name)
1049 head = git.get_head()
1050
1051 append_string(self.__applied_file, name)
1052
1053 unapplied.remove(name)
1054 write_strings(self.__unapplied_file, unapplied)
1055
1056 self.refresh_patch(bottom = head, cache_update = False, log = 'push(m)')
1057
1058 def push_patch(self, name):
1059 """Pushes a patch on the stack
1060 """
1061 unapplied = self.get_unapplied()
1062 assert(name in unapplied)
1063
1064 patch = self.get_patch(name)
1065
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
1070
1071 if head == bottom:
1072 # A fast-forward push. Just reset the backup
1073 # information. No need for logging
1074 patch.set_top(top, backup = True)
1075
1076 git.switch(top)
1077 append_string(self.__applied_file, name)
1078
1079 unapplied.remove(name)
1080 write_strings(self.__unapplied_file, unapplied)
1081 return False
1082
1083 # Need to create a new commit an merge in the old patch
1084 ex = None
1085 modified = False
1086
1087 # Try the fast applying first. If this fails, fall back to the
1088 # three-way merge
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
1092 modified = True
1093
1094 # merge can fail but the patch needs to be pushed
1095 try:
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".')
1101
1102 append_string(self.__applied_file, name)
1103
1104 unapplied.remove(name)
1105 write_strings(self.__unapplied_file, unapplied)
1106
1107 if not ex:
1108 # if the merge was OK and no conflicts, just refresh the patch
1109 # The GIT cache was already updated by the merge operation
1110 if modified:
1111 log = 'push(m)'
1112 else:
1113 log = 'push'
1114 self.refresh_patch(bottom = head, cache_update = False, log = log)
1115 else:
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,
1121 log = 'push(c)')
1122 raise StackException, str(ex)
1123
1124 return modified
1125
1126 def undo_push(self):
1127 name = self.get_current()
1128 assert(name)
1129
1130 patch = self.get_patch(name)
1131 old_bottom = patch.get_old_bottom()
1132 old_top = patch.get_old_top()
1133
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'
1140
1141 git.reset()
1142 self.pop_patch(name)
1143 ret = patch.restore_old_boundaries()
1144 if ret:
1145 self.log_patch(patch, 'undo')
1146
1147 return ret
1148
1149 def pop_patch(self, name, keep = False):
1150 """Pops the top patch from the stack
1151 """
1152 applied = self.get_applied()
1153 applied.reverse()
1154 assert(name in applied)
1155
1156 patch = self.get_patch(name)
1157
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)
1164 else:
1165 git.set_branch(self.get_name(), patch.get_bottom())
1166
1167 # save the new applied list
1168 idx = applied.index(name) + 1
1169
1170 popped = applied[:idx]
1171 popped.reverse()
1172 unapplied = popped + self.get_unapplied()
1173 write_strings(self.__unapplied_file, unapplied)
1174
1175 del applied[:idx]
1176 applied.reverse()
1177 write_strings(self.__applied_file, applied)
1178
1179 def empty_patch(self, name):
1180 """Returns True if the patch is empty
1181 """
1182 self.__patch_name_valid(name)
1183 patch = self.get_patch(name)
1184 bottom = patch.get_bottom()
1185 top = patch.get_top()
1186
1187 if bottom == top:
1188 return True
1189 elif git.get_commit(top).get_tree() \
1190 == git.get_commit(bottom).get_tree():
1191 return True
1192
1193 return False
1194
1195 def rename_patch(self, oldname, newname):
1196 self.__patch_name_valid(newname)
1197
1198 applied = self.get_applied()
1199 unapplied = self.get_unapplied()
1200
1201 if oldname == newname:
1202 raise StackException, '"To" name and "from" name are the same'
1203
1204 if newname in applied or newname in unapplied:
1205 raise StackException, 'Patch "%s" already exists' % newname
1206
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)
1213
1214 applied[applied.index(oldname)] = newname
1215 write_strings(self.__applied_file, applied)
1216 else:
1217 raise StackException, 'Unknown patch "%s"' % oldname
1218
1219 def log_patch(self, patch, message, notes = None):
1220 """Generate a log commit for a patch
1221 """
1222 top = git.get_commit(patch.get_top())
1223 old_log = patch.get_log()
1224
1225 if message is None:
1226 # replace the current log entry
1227 if not old_log:
1228 raise StackException, \
1229 'No log entry to annotate for patch "%s"' \
1230 % patch.get_name()
1231 replace = True
1232 log_commit = git.get_commit(old_log)
1233 msg = log_commit.get_log().split('\n')[0]
1234 log_parent = log_commit.get_parent()
1235 if log_parent:
1236 parents = [log_parent]
1237 else:
1238 parents = []
1239 else:
1240 # generate a new log entry
1241 replace = False
1242 msg = '%s\t%s' % (message, top.get_id_hash())
1243 if old_log:
1244 parents = [old_log]
1245 else:
1246 parents = []
1247
1248 if notes:
1249 msg += '\n\n' + notes
1250
1251 log = git.commit(message = msg, parents = parents,
1252 cache_update = False, tree_id = top.get_tree(),
1253 allowempty = True)
1254 patch.set_log(log)
1255
1256 def hide_patch(self, name):
1257 """Add the patch to the hidden list.
1258 """
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
1267 else:
1268 raise StackException, 'Unknown patch "%s"' % name
1269
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)
1274
1275 unapplied.remove(name)
1276 write_strings(self.__unapplied_file, unapplied)
1277
1278 def unhide_patch(self, name):
1279 """Remove the patch from the hidden list.
1280 """
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
1285 else:
1286 raise StackException, 'Unknown patch "%s"' % name
1287
1288 hidden.remove(name)
1289 write_strings(self.__hidden_file, hidden)
1290
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)