chiark / gitweb /
dee8c38acf62b9ee2d0a0af00c0c1b20ff09e79b
[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
23 from stgit.utils import *
24 from stgit import git, basedir, templates
25 from stgit.config import config
26 from shutil import copyfile
27
28
29 # stack exception class
30 class StackException(Exception):
31     pass
32
33 class FilterUntil:
34     def __init__(self):
35         self.should_print = True
36     def __call__(self, x, until_test, prefix):
37         if until_test(x):
38             self.should_print = False
39         if self.should_print:
40             return x[0:len(prefix)] != prefix
41         return False
42
43 #
44 # Functions
45 #
46 __comment_prefix = 'STG:'
47 __patch_prefix = 'STG_PATCH:'
48
49 def __clean_comments(f):
50     """Removes lines marked for status in a commit file
51     """
52     f.seek(0)
53
54     # remove status-prefixed lines
55     lines = f.readlines()
56
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)]
60
61     # remove empty lines at the end
62     while len(lines) != 0 and lines[-1] == '\n':
63         del lines[-1]
64
65     f.seek(0); f.truncate()
66     f.writelines(lines)
67
68 def edit_file(series, line, comment, show_patch = True):
69     fname = '.stgitmsg.txt'
70     tmpl = templates.get_template('patchdescr.tmpl')
71
72     f = file(fname, 'w+')
73     if line:
74         print >> f, line
75     elif tmpl:
76         print >> f, tmpl,
77     else:
78         print >> f
79     print >> f, __comment_prefix, comment
80     print >> f, __comment_prefix, \
81           'Lines prefixed with "%s" will be automatically removed.' \
82           % __comment_prefix
83     print >> f, __comment_prefix, \
84           'Trailing empty lines will be automatically removed.'
85
86     if show_patch:
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)
90
91     #Vim modeline must be near the end.
92     print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:'
93     f.close()
94
95     call_editor(fname)
96
97     f = file(fname, 'r+')
98
99     __clean_comments(f)
100     f.seek(0)
101     result = f.read()
102
103     f.close()
104     os.remove(fname)
105
106     return result
107
108 #
109 # Classes
110 #
111
112 class StgitObject:
113     """An object with stgit-like properties stored as files in a directory
114     """
115     def _set_dir(self, dir):
116         self.__dir = dir
117     def _dir(self):
118         return self.__dir
119
120     def create_empty_field(self, name):
121         create_empty_file(os.path.join(self.__dir, name))
122
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)
127             if line == '':
128                 return None
129             else:
130                 return line
131         else:
132             return None
133
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):
139             os.remove(fname)
140
141     
142 class Patch(StgitObject):
143     """Basic patch implementation
144     """
145     def __init__(self, name, series_dir, refs_dir):
146         self.__series_dir = series_dir
147         self.__name = name
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')
153
154     def create(self):
155         os.mkdir(self._dir())
156         self.create_empty_field('bottom')
157         self.create_empty_field('top')
158
159     def delete(self):
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)
166
167     def get_name(self):
168         return self.__name
169
170     def rename(self, newname):
171         olddir = self._dir()
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')
179
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)
184
185     def __update_top_ref(self, ref):
186         write_string(self.__top_ref_file, ref)
187
188     def __update_log_ref(self, ref):
189         write_string(self.__log_ref_file, ref)
190
191     def update_top_ref(self):
192         top = self.get_top()
193         if top:
194             self.__update_top_ref(top)
195
196     def get_old_bottom(self):
197         return self._get_field('bottom.old')
198
199     def get_bottom(self):
200         return self._get_field('bottom')
201
202     def set_bottom(self, value, backup = False):
203         if backup:
204             curr = self._get_field('bottom')
205             self._set_field('bottom.old', curr)
206         self._set_field('bottom', value)
207
208     def get_old_top(self):
209         return self._get_field('top.old')
210
211     def get_top(self):
212         return self._get_field('top')
213
214     def set_top(self, value, backup = False):
215         if backup:
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)
220
221     def restore_old_boundaries(self):
222         bottom = self._get_field('bottom.old')
223         top = self._get_field('top.old')
224
225         if top and bottom:
226             self._set_field('bottom', bottom)
227             self._set_field('top', top)
228             self.__update_top_ref(top)
229             return True
230         else:
231             return False
232
233     def get_description(self):
234         return self._get_field('description', True)
235
236     def set_description(self, line):
237         self._set_field('description', line, True)
238
239     def get_authname(self):
240         return self._get_field('authname')
241
242     def set_authname(self, name):
243         self._set_field('authname', name or git.author().name)
244
245     def get_authemail(self):
246         return self._get_field('authemail')
247
248     def set_authemail(self, email):
249         self._set_field('authemail', email or git.author().email)
250
251     def get_authdate(self):
252         return self._get_field('authdate')
253
254     def set_authdate(self, date):
255         self._set_field('authdate', date or git.author().date)
256
257     def get_commname(self):
258         return self._get_field('commname')
259
260     def set_commname(self, name):
261         self._set_field('commname', name or git.committer().name)
262
263     def get_commemail(self):
264         return self._get_field('commemail')
265
266     def set_commemail(self, email):
267         self._set_field('commemail', email or git.committer().email)
268
269     def get_log(self):
270         return self._get_field('log')
271
272     def set_log(self, value, backup = False):
273         self._set_field('log', value)
274         self.__update_log_ref(value)
275
276 # The current StGIT metadata format version.
277 FORMAT_VERSION = 2
278
279 class PatchSet(StgitObject):
280     def get_name(self):
281         return self.__name
282     def set_name(self, name):
283         self.__name = name
284
285     def get_head(self):
286         """Return the head of the branch
287         """
288         crt = self.get_current_patch()
289         if crt:
290             return crt.get_top()
291         else:
292             return self.get_base()
293
294     def get_protected(self):
295         return os.path.isfile(os.path.join(self._dir(), 'protected'))
296
297     def protect(self):
298         protect_file = os.path.join(self._dir(), 'protected')
299         if not os.path.isfile(protect_file):
300             create_empty_file(protect_file)
301
302     def unprotect(self):
303         protect_file = os.path.join(self._dir(), 'protected')
304         if os.path.isfile(protect_file):
305             os.remove(protect_file)
306
307     def __branch_descr(self):
308         return 'branch.%s.description' % self.get_name()
309
310     def get_description(self):
311         return config.get(self.__branch_descr()) or ''
312
313     def set_description(self, line):
314         if line:
315             config.set(self.__branch_descr(), line)
316         else:
317             config.unset(self.__branch_descr())
318
319     def head_top_equal(self):
320         """Return true if the head and the top are the same
321         """
322         crt = self.get_current_patch()
323         if not crt:
324             # we don't care, no patches applied
325             return True
326         return git.get_head() == crt.get_top()
327
328     def is_initialised(self):
329         """Checks if series is already initialised
330         """
331         return bool(config.get(self.format_version_key()))
332
333
334 class Series(PatchSet):
335     """Class including the operations on series
336     """
337     def __init__(self, name = None):
338         """Takes a series name as the parameter.
339         """
340         try:
341             if name:
342                 self.set_name (name)
343             else:
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
348
349         self._set_dir(os.path.join(self.__base_dir, 'patches', self.get_name()))
350
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()
354
355         self.__refs_dir = os.path.join(self.__base_dir, 'refs', 'patches',
356                                        self.get_name())
357
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')
361
362         # where this series keeps its patches
363         self.__patch_dir = os.path.join(self._dir(), 'patches')
364
365         # trash directory
366         self.__trash_dir = os.path.join(self._dir(), 'trash')
367
368     def format_version_key(self):
369         return 'branch.%s.stgit.stackformatversion' % self.get_name()
370
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."""
376
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())
383             if fv:
384                 # Great, there's an explicitly recorded format version
385                 # number, which means that the branch is initialized and
386                 # of that exact version.
387                 return int(fv)
388             elif ofv:
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())
392                 return int(ofv)
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.
396                 return 1
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.
400                 return 0
401             else:
402                 # The branch doesn't seem to be initialized at all.
403                 return None
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)
407         def mkdir(d):
408             if not os.path.isdir(d):
409                 os.makedirs(d)
410         def rm(f):
411             if os.path.exists(f):
412                 os.remove(f)
413
414         # Update 0 -> 1.
415         if get_format_version() == 0:
416             mkdir(os.path.join(branch_dir, 'trash'))
417             patch_dir = os.path.join(branch_dir, 'patches')
418             mkdir(patch_dir)
419             refs_dir = os.path.join(self.__base_dir, 'refs', 'patches', self.get_name())
420             mkdir(refs_dir)
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)
428
429         # Update 1 -> 2.
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)
434                 if desc:
435                     config.set('branch.%s.description' % self.get_name(), desc)
436                 rm(desc_file)
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)
440
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))
445
446     def __patch_name_valid(self, name):
447         """Raise an exception if the patch name is not valid.
448         """
449         if not name or re.search('[^\w.-]', name):
450             raise StackException, 'Invalid patch name: "%s"' % name
451
452     def get_patch(self, name):
453         """Return a Patch object for the given name
454         """
455         return Patch(name, self.__patch_dir, self.__refs_dir)
456
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()
461         if not crt:
462             return None
463         return Patch(crt, self.__patch_dir, self.__refs_dir)
464
465     def get_current(self):
466         """Return the name of the topmost patch, or None if there is
467         no such patch."""
468         try:
469             applied = self.get_applied()
470         except StackException:
471             # No "applied" file: branch is not initialized.
472             return None
473         try:
474             return applied[-1]
475         except IndexError:
476             # No patches applied.
477             return None
478
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)
483
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)
488
489     def get_hidden(self):
490         if not os.path.isfile(self.__hidden_file):
491             return []
492         return read_strings(self.__hidden_file)
493
494     def get_base(self):
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()
498             if bottommost:
499                 return self.get_patch(bottommost).get_bottom()
500         # No bottommost patch, so just return HEAD
501         return git.get_head()
502
503     def get_parent_remote(self):
504         value = config.get('branch.%s.remote' % self.get_name())
505         if value:
506             return value
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())))
513             return 'origin'
514         else:
515             raise StackException, 'Cannot find a parent remote for "%s"' % self.get_name()
516
517     def __set_parent_remote(self, remote):
518         value = config.set('branch.%s.remote' % self.get_name(), remote)
519
520     def get_parent_branch(self):
521         value = config.get('branch.%s.stgit.parentbranch' % self.get_name())
522         if value:
523             return value
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'
530         else:
531             raise StackException, 'Cannot find a parent branch for "%s"' % self.get_name()
532
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)
539
540     def set_parent(self, remote, localbranch):
541         if localbranch:
542             self.__set_parent_remote(remote)
543             self.__set_parent_branch(localbranch)
544         # We'll enforce this later
545 #         else:
546 #             raise StackException, 'Parent branch (%s) should be specified for %s' % localbranch, self.get_name()
547
548     def __patch_is_current(self, patch):
549         return patch.get_name() == self.get_current()
550
551     def patch_applied(self, name):
552         """Return true if the patch exists in the applied list
553         """
554         return name in self.get_applied()
555
556     def patch_unapplied(self, name):
557         """Return true if the patch exists in the unapplied list
558         """
559         return name in self.get_unapplied()
560
561     def patch_hidden(self, name):
562         """Return true if the patch is hidden.
563         """
564         return name in self.get_hidden()
565
566     def patch_exists(self, name):
567         """Return true if there is a patch with the given name, false
568         otherwise."""
569         return self.patch_applied(name) or self.patch_unapplied(name) \
570                or self.patch_hidden(name)
571
572     def init(self, create_at=False, parent_remote=None, parent_branch=None):
573         """Initialises the stgit series
574         """
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
580
581         if (create_at!=False):
582             git.create_branch(self.get_name(), create_at)
583
584         os.makedirs(self.__patch_dir)
585
586         self.set_parent(parent_remote, parent_branch)
587
588         self.create_empty_field('applied')
589         self.create_empty_field('unapplied')
590         os.makedirs(self.__refs_dir)
591
592         config.set(self.format_version_key(), str(FORMAT_VERSION))
593
594     def rename(self, to_name):
595         """Renames a series
596         """
597         to_stack = Series(to_name)
598
599         if to_stack.is_initialised():
600             raise StackException, '"%s" already exists' % to_stack.get_name()
601
602         git.rename_branch(self.get_name(), to_name)
603
604         if os.path.isdir(self._dir()):
605             rename(os.path.join(self.__base_dir, 'patches'),
606                    self.get_name(), to_stack.get_name())
607         if os.path.exists(self.__refs_dir):
608             rename(os.path.join(self.__base_dir, 'refs', 'patches'),
609                    self.get_name(), to_stack.get_name())
610
611         # Rename the config section
612         config.rename_section("branch.%s" % self.get_name(),
613                               "branch.%s" % to_name)
614
615         self.__init__(to_name)
616
617     def clone(self, target_series):
618         """Clones a series
619         """
620         try:
621             # allow cloning of branches not under StGIT control
622             base = self.get_base()
623         except:
624             base = git.get_head()
625         Series(target_series).init(create_at = base)
626         new_series = Series(target_series)
627
628         # generate an artificial description file
629         new_series.set_description('clone of "%s"' % self.get_name())
630
631         # clone self's entire series as unapplied patches
632         try:
633             # allow cloning of branches not under StGIT control
634             applied = self.get_applied()
635             unapplied = self.get_unapplied()
636             patches = applied + unapplied
637             patches.reverse()
638         except:
639             patches = applied = unapplied = []
640         for p in patches:
641             patch = self.get_patch(p)
642             newpatch = new_series.new_patch(p, message = patch.get_description(),
643                                             can_edit = False, unapplied = True,
644                                             bottom = patch.get_bottom(),
645                                             top = patch.get_top(),
646                                             author_name = patch.get_authname(),
647                                             author_email = patch.get_authemail(),
648                                             author_date = patch.get_authdate())
649             if patch.get_log():
650                 out.info('Setting log to %s' %  patch.get_log())
651                 newpatch.set_log(patch.get_log())
652             else:
653                 out.info('No log for %s' % p)
654
655         # fast forward the cloned series to self's top
656         new_series.forward_patches(applied)
657
658         # Clone parent informations
659         value = config.get('branch.%s.remote' % self.get_name())
660         if value:
661             config.set('branch.%s.remote' % target_series, value)
662
663         value = config.get('branch.%s.merge' % self.get_name())
664         if value:
665             config.set('branch.%s.merge' % target_series, value)
666
667         value = config.get('branch.%s.stgit.parentbranch' % self.get_name())
668         if value:
669             config.set('branch.%s.stgit.parentbranch' % target_series, value)
670
671     def delete(self, force = False):
672         """Deletes an stgit series
673         """
674         if self.is_initialised():
675             patches = self.get_unapplied() + self.get_applied()
676             if not force and patches:
677                 raise StackException, \
678                       'Cannot delete: the series still contains patches'
679             for p in patches:
680                 Patch(p, self.__patch_dir, self.__refs_dir).delete()
681
682             # remove the trash directory if any
683             if os.path.exists(self.__trash_dir):
684                 for fname in os.listdir(self.__trash_dir):
685                     os.remove(os.path.join(self.__trash_dir, fname))
686                 os.rmdir(self.__trash_dir)
687
688             # FIXME: find a way to get rid of those manual removals
689             # (move functionality to StgitObject ?)
690             if os.path.exists(self.__applied_file):
691                 os.remove(self.__applied_file)
692             if os.path.exists(self.__unapplied_file):
693                 os.remove(self.__unapplied_file)
694             if os.path.exists(self.__hidden_file):
695                 os.remove(self.__hidden_file)
696             if os.path.exists(self._dir()+'/orig-base'):
697                 os.remove(self._dir()+'/orig-base')
698
699             if not os.listdir(self.__patch_dir):
700                 os.rmdir(self.__patch_dir)
701             else:
702                 out.warn('Patch directory %s is not empty' % self.__patch_dir)
703
704             try:
705                 os.removedirs(self._dir())
706             except OSError:
707                 raise StackException('Series directory %s is not empty'
708                                      % self._dir())
709
710             try:
711                 os.removedirs(self.__refs_dir)
712             except OSError:
713                 out.warn('Refs directory %s is not empty' % self.__refs_dir)
714
715         # Cleanup parent informations
716         # FIXME: should one day make use of git-config --section-remove,
717         # scheduled for 1.5.1
718         config.unset('branch.%s.remote' % self.get_name())
719         config.unset('branch.%s.merge' % self.get_name())
720         config.unset('branch.%s.stgit.parentbranch' % self.get_name())
721         config.unset(self.format_version_key())
722
723     def refresh_patch(self, files = None, message = None, edit = False,
724                       show_patch = False,
725                       cache_update = True,
726                       author_name = None, author_email = None,
727                       author_date = None,
728                       committer_name = None, committer_email = None,
729                       backup = False, sign_str = None, log = 'refresh'):
730         """Generates a new commit for the given patch
731         """
732         name = self.get_current()
733         if not name:
734             raise StackException, 'No patches applied'
735
736         patch = Patch(name, self.__patch_dir, self.__refs_dir)
737
738         descr = patch.get_description()
739         if not (message or descr):
740             edit = True
741             descr = ''
742         elif message:
743             descr = message
744
745         if not message and edit:
746             descr = edit_file(self, descr.rstrip(), \
747                               'Please edit the description for patch "%s" ' \
748                               'above.' % name, show_patch)
749
750         if not author_name:
751             author_name = patch.get_authname()
752         if not author_email:
753             author_email = patch.get_authemail()
754         if not author_date:
755             author_date = patch.get_authdate()
756         if not committer_name:
757             committer_name = patch.get_commname()
758         if not committer_email:
759             committer_email = patch.get_commemail()
760
761         if sign_str:
762             descr = descr.rstrip()
763             if descr.find("\nSigned-off-by:") < 0 \
764                and descr.find("\nAcked-by:") < 0:
765                 descr = descr + "\n"
766
767             descr = '%s\n%s: %s <%s>\n' % (descr, sign_str,
768                                            committer_name, committer_email)
769
770         bottom = patch.get_bottom()
771
772         commit_id = git.commit(files = files,
773                                message = descr, parents = [bottom],
774                                cache_update = cache_update,
775                                allowempty = True,
776                                author_name = author_name,
777                                author_email = author_email,
778                                author_date = author_date,
779                                committer_name = committer_name,
780                                committer_email = committer_email)
781
782         patch.set_bottom(bottom, backup = backup)
783         patch.set_top(commit_id, backup = backup)
784         patch.set_description(descr)
785         patch.set_authname(author_name)
786         patch.set_authemail(author_email)
787         patch.set_authdate(author_date)
788         patch.set_commname(committer_name)
789         patch.set_commemail(committer_email)
790
791         if log:
792             self.log_patch(patch, log)
793
794         return commit_id
795
796     def undo_refresh(self):
797         """Undo the patch boundaries changes caused by 'refresh'
798         """
799         name = self.get_current()
800         assert(name)
801
802         patch = Patch(name, self.__patch_dir, self.__refs_dir)
803         old_bottom = patch.get_old_bottom()
804         old_top = patch.get_old_top()
805
806         # the bottom of the patch is not changed by refresh. If the
807         # old_bottom is different, there wasn't any previous 'refresh'
808         # command (probably only a 'push')
809         if old_bottom != patch.get_bottom() or old_top == patch.get_top():
810             raise StackException, 'No undo information available'
811
812         git.reset(tree_id = old_top, check_out = False)
813         if patch.restore_old_boundaries():
814             self.log_patch(patch, 'undo')
815
816     def new_patch(self, name, message = None, can_edit = True,
817                   unapplied = False, show_patch = False,
818                   top = None, bottom = None,
819                   author_name = None, author_email = None, author_date = None,
820                   committer_name = None, committer_email = None,
821                   before_existing = False, refresh = True):
822         """Creates a new patch
823         """
824
825         if name != None:
826             self.__patch_name_valid(name)
827             if self.patch_exists(name):
828                 raise StackException, 'Patch "%s" already exists' % name
829
830         if not message and can_edit:
831             descr = edit_file(
832                 self, None,
833                 'Please enter the description for the patch above.',
834                 show_patch)
835         else:
836             descr = message
837
838         head = git.get_head()
839
840         if name == None:
841             name = make_patch_name(descr, self.patch_exists)
842
843         patch = Patch(name, self.__patch_dir, self.__refs_dir)
844         patch.create()
845
846         if bottom:
847             patch.set_bottom(bottom)
848         else:
849             patch.set_bottom(head)
850         if top:
851             patch.set_top(top)
852         else:
853             patch.set_top(head)
854
855         patch.set_description(descr)
856         patch.set_authname(author_name)
857         patch.set_authemail(author_email)
858         patch.set_authdate(author_date)
859         patch.set_commname(committer_name)
860         patch.set_commemail(committer_email)
861
862         if unapplied:
863             self.log_patch(patch, 'new')
864
865             patches = [patch.get_name()] + self.get_unapplied()
866             write_strings(self.__unapplied_file, patches)
867         elif before_existing:
868             self.log_patch(patch, 'new')
869
870             insert_string(self.__applied_file, patch.get_name())
871         else:
872             append_string(self.__applied_file, patch.get_name())
873             if refresh:
874                 self.refresh_patch(cache_update = False, log = 'new')
875
876         return patch
877
878     def delete_patch(self, name):
879         """Deletes a patch
880         """
881         self.__patch_name_valid(name)
882         patch = Patch(name, self.__patch_dir, self.__refs_dir)
883
884         if self.__patch_is_current(patch):
885             self.pop_patch(name)
886         elif self.patch_applied(name):
887             raise StackException, 'Cannot remove an applied patch, "%s", ' \
888                   'which is not current' % name
889         elif not name in self.get_unapplied():
890             raise StackException, 'Unknown patch "%s"' % name
891
892         # save the commit id to a trash file
893         write_string(os.path.join(self.__trash_dir, name), patch.get_top())
894
895         patch.delete()
896
897         unapplied = self.get_unapplied()
898         unapplied.remove(name)
899         write_strings(self.__unapplied_file, unapplied)
900
901     def forward_patches(self, names):
902         """Try to fast-forward an array of patches.
903
904         On return, patches in names[0:returned_value] have been pushed on the
905         stack. Apply the rest with push_patch
906         """
907         unapplied = self.get_unapplied()
908
909         forwarded = 0
910         top = git.get_head()
911
912         for name in names:
913             assert(name in unapplied)
914
915             patch = Patch(name, self.__patch_dir, self.__refs_dir)
916
917             head = top
918             bottom = patch.get_bottom()
919             top = patch.get_top()
920
921             # top != bottom always since we have a commit for each patch
922             if head == bottom:
923                 # reset the backup information. No logging since the
924                 # patch hasn't changed
925                 patch.set_bottom(head, backup = True)
926                 patch.set_top(top, backup = True)
927
928             else:
929                 head_tree = git.get_commit(head).get_tree()
930                 bottom_tree = git.get_commit(bottom).get_tree()
931                 if head_tree == bottom_tree:
932                     # We must just reparent this patch and create a new commit
933                     # for it
934                     descr = patch.get_description()
935                     author_name = patch.get_authname()
936                     author_email = patch.get_authemail()
937                     author_date = patch.get_authdate()
938                     committer_name = patch.get_commname()
939                     committer_email = patch.get_commemail()
940
941                     top_tree = git.get_commit(top).get_tree()
942
943                     top = git.commit(message = descr, parents = [head],
944                                      cache_update = False,
945                                      tree_id = top_tree,
946                                      allowempty = True,
947                                      author_name = author_name,
948                                      author_email = author_email,
949                                      author_date = author_date,
950                                      committer_name = committer_name,
951                                      committer_email = committer_email)
952
953                     patch.set_bottom(head, backup = True)
954                     patch.set_top(top, backup = True)
955
956                     self.log_patch(patch, 'push(f)')
957                 else:
958                     top = head
959                     # stop the fast-forwarding, must do a real merge
960                     break
961
962             forwarded+=1
963             unapplied.remove(name)
964
965         if forwarded == 0:
966             return 0
967
968         git.switch(top)
969
970         append_strings(self.__applied_file, names[0:forwarded])
971         write_strings(self.__unapplied_file, unapplied)
972
973         return forwarded
974
975     def merged_patches(self, names):
976         """Test which patches were merged upstream by reverse-applying
977         them in reverse order. The function returns the list of
978         patches detected to have been applied. The state of the tree
979         is restored to the original one
980         """
981         patches = [Patch(name, self.__patch_dir, self.__refs_dir)
982                    for name in names]
983         patches.reverse()
984
985         merged = []
986         for p in patches:
987             if git.apply_diff(p.get_top(), p.get_bottom()):
988                 merged.append(p.get_name())
989         merged.reverse()
990
991         git.reset()
992
993         return merged
994
995     def push_patch(self, name, empty = False):
996         """Pushes a patch on the stack
997         """
998         unapplied = self.get_unapplied()
999         assert(name in unapplied)
1000
1001         patch = Patch(name, self.__patch_dir, self.__refs_dir)
1002
1003         head = git.get_head()
1004         bottom = patch.get_bottom()
1005         top = patch.get_top()
1006
1007         ex = None
1008         modified = False
1009
1010         # top != bottom always since we have a commit for each patch
1011         if empty:
1012             # just make an empty patch (top = bottom = HEAD). This
1013             # option is useful to allow undoing already merged
1014             # patches. The top is updated by refresh_patch since we
1015             # need an empty commit
1016             patch.set_bottom(head, backup = True)
1017             patch.set_top(head, backup = True)
1018             modified = True
1019         elif head == bottom:
1020             # reset the backup information. No need for logging
1021             patch.set_bottom(bottom, backup = True)
1022             patch.set_top(top, backup = True)
1023
1024             git.switch(top)
1025         else:
1026             # new patch needs to be refreshed.
1027             # The current patch is empty after merge.
1028             patch.set_bottom(head, backup = True)
1029             patch.set_top(head, backup = True)
1030
1031             # Try the fast applying first. If this fails, fall back to the
1032             # three-way merge
1033             if not git.apply_diff(bottom, top):
1034                 # if git.apply_diff() fails, the patch requires a diff3
1035                 # merge and can be reported as modified
1036                 modified = True
1037
1038                 # merge can fail but the patch needs to be pushed
1039                 try:
1040                     git.merge(bottom, head, top, recursive = True)
1041                 except git.GitException, ex:
1042                     out.error('The merge failed during "push".',
1043                               'Use "refresh" after fixing the conflicts or'
1044                               ' revert the operation with "push --undo".')
1045
1046         append_string(self.__applied_file, name)
1047
1048         unapplied.remove(name)
1049         write_strings(self.__unapplied_file, unapplied)
1050
1051         # head == bottom case doesn't need to refresh the patch
1052         if empty or head != bottom:
1053             if not ex:
1054                 # if the merge was OK and no conflicts, just refresh the patch
1055                 # The GIT cache was already updated by the merge operation
1056                 if modified:
1057                     log = 'push(m)'
1058                 else:
1059                     log = 'push'
1060                 self.refresh_patch(cache_update = False, log = log)
1061             else:
1062                 # we store the correctly merged files only for
1063                 # tracking the conflict history. Note that the
1064                 # git.merge() operations should always leave the index
1065                 # in a valid state (i.e. only stage 0 files)
1066                 self.refresh_patch(cache_update = False, log = 'push(c)')
1067                 raise StackException, str(ex)
1068
1069         return modified
1070
1071     def undo_push(self):
1072         name = self.get_current()
1073         assert(name)
1074
1075         patch = Patch(name, self.__patch_dir, self.__refs_dir)
1076         old_bottom = patch.get_old_bottom()
1077         old_top = patch.get_old_top()
1078
1079         # the top of the patch is changed by a push operation only
1080         # together with the bottom (otherwise the top was probably
1081         # modified by 'refresh'). If they are both unchanged, there
1082         # was a fast forward
1083         if old_bottom == patch.get_bottom() and old_top != patch.get_top():
1084             raise StackException, 'No undo information available'
1085
1086         git.reset()
1087         self.pop_patch(name)
1088         ret = patch.restore_old_boundaries()
1089         if ret:
1090             self.log_patch(patch, 'undo')
1091
1092         return ret
1093
1094     def pop_patch(self, name, keep = False):
1095         """Pops the top patch from the stack
1096         """
1097         applied = self.get_applied()
1098         applied.reverse()
1099         assert(name in applied)
1100
1101         patch = Patch(name, self.__patch_dir, self.__refs_dir)
1102
1103         if git.get_head_file() == self.get_name():
1104             if keep and not git.apply_diff(git.get_head(), patch.get_bottom()):
1105                 raise StackException(
1106                     'Failed to pop patches while preserving the local changes')
1107             git.switch(patch.get_bottom(), keep)
1108         else:
1109             git.set_branch(self.get_name(), patch.get_bottom())
1110
1111         # save the new applied list
1112         idx = applied.index(name) + 1
1113
1114         popped = applied[:idx]
1115         popped.reverse()
1116         unapplied = popped + self.get_unapplied()
1117         write_strings(self.__unapplied_file, unapplied)
1118
1119         del applied[:idx]
1120         applied.reverse()
1121         write_strings(self.__applied_file, applied)
1122
1123     def empty_patch(self, name):
1124         """Returns True if the patch is empty
1125         """
1126         self.__patch_name_valid(name)
1127         patch = Patch(name, self.__patch_dir, self.__refs_dir)
1128         bottom = patch.get_bottom()
1129         top = patch.get_top()
1130
1131         if bottom == top:
1132             return True
1133         elif git.get_commit(top).get_tree() \
1134                  == git.get_commit(bottom).get_tree():
1135             return True
1136
1137         return False
1138
1139     def rename_patch(self, oldname, newname):
1140         self.__patch_name_valid(newname)
1141
1142         applied = self.get_applied()
1143         unapplied = self.get_unapplied()
1144
1145         if oldname == newname:
1146             raise StackException, '"To" name and "from" name are the same'
1147
1148         if newname in applied or newname in unapplied:
1149             raise StackException, 'Patch "%s" already exists' % newname
1150
1151         if oldname in unapplied:
1152             Patch(oldname, self.__patch_dir, self.__refs_dir).rename(newname)
1153             unapplied[unapplied.index(oldname)] = newname
1154             write_strings(self.__unapplied_file, unapplied)
1155         elif oldname in applied:
1156             Patch(oldname, self.__patch_dir, self.__refs_dir).rename(newname)
1157
1158             applied[applied.index(oldname)] = newname
1159             write_strings(self.__applied_file, applied)
1160         else:
1161             raise StackException, 'Unknown patch "%s"' % oldname
1162
1163     def log_patch(self, patch, message):
1164         """Generate a log commit for a patch
1165         """
1166         top = git.get_commit(patch.get_top())
1167         msg = '%s\t%s' % (message, top.get_id_hash())
1168
1169         old_log = patch.get_log()
1170         if old_log:
1171             parents = [old_log]
1172         else:
1173             parents = []
1174
1175         log = git.commit(message = msg, parents = parents,
1176                          cache_update = False, tree_id = top.get_tree(),
1177                          allowempty = True)
1178         patch.set_log(log)
1179
1180     def hide_patch(self, name):
1181         """Add the patch to the hidden list.
1182         """
1183         unapplied = self.get_unapplied()
1184         if name not in unapplied:
1185             # keep the checking order for backward compatibility with
1186             # the old hidden patches functionality
1187             if self.patch_applied(name):
1188                 raise StackException, 'Cannot hide applied patch "%s"' % name
1189             elif self.patch_hidden(name):
1190                 raise StackException, 'Patch "%s" already hidden' % name
1191             else:
1192                 raise StackException, 'Unknown patch "%s"' % name
1193
1194         if not self.patch_hidden(name):
1195             # check needed for backward compatibility with the old
1196             # hidden patches functionality
1197             append_string(self.__hidden_file, name)
1198
1199         unapplied.remove(name)
1200         write_strings(self.__unapplied_file, unapplied)
1201
1202     def unhide_patch(self, name):
1203         """Remove the patch from the hidden list.
1204         """
1205         hidden = self.get_hidden()
1206         if not name in hidden:
1207             if self.patch_applied(name) or self.patch_unapplied(name):
1208                 raise StackException, 'Patch "%s" not hidden' % name
1209             else:
1210                 raise StackException, 'Unknown patch "%s"' % name
1211
1212         hidden.remove(name)
1213         write_strings(self.__hidden_file, hidden)
1214
1215         if not self.patch_applied(name) and not self.patch_unapplied(name):
1216             # check needed for backward compatibility with the old
1217             # hidden patches functionality
1218             append_string(self.__unapplied_file, name)