Fix up help string for "stg clone"
[stgit] / stgit / stack.py
CommitLineData
41a6d859
CM
1"""Basic quilt-like functionality
2"""
3
4__copyright__ = """
5Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7This program is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License version 2 as
9published by the Free Software Foundation.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19"""
20
21import sys, os
22
23from stgit.utils import *
24from stgit import git
25from stgit.config import config
26
27
28# stack exception class
29class StackException(Exception):
30 pass
31
6ad48e48
PBG
32class FilterUntil:
33 def __init__(self):
34 self.should_print = True
35 def __call__(self, x, until_test, prefix):
36 if until_test(x):
37 self.should_print = False
38 if self.should_print:
39 return x[0:len(prefix)] != prefix
40 return False
41
41a6d859
CM
42#
43# Functions
44#
45__comment_prefix = 'STG:'
6ad48e48 46__patch_prefix = 'STG_PATCH:'
41a6d859
CM
47
48def __clean_comments(f):
49 """Removes lines marked for status in a commit file
50 """
51 f.seek(0)
52
53 # remove status-prefixed lines
6ad48e48
PBG
54 lines = f.readlines()
55
56 patch_filter = FilterUntil()
57 until_test = lambda t: t == (__patch_prefix + '\n')
58 lines = [l for l in lines if patch_filter(l, until_test, __comment_prefix)]
59
41a6d859
CM
60 # remove empty lines at the end
61 while len(lines) != 0 and lines[-1] == '\n':
62 del lines[-1]
63
64 f.seek(0); f.truncate()
65 f.writelines(lines)
66
6ad48e48 67def edit_file(series, string, comment, show_patch = True):
41a6d859
CM
68 fname = '.stgit.msg'
69 tmpl = os.path.join(git.base_dir, 'patchdescr.tmpl')
70
71 f = file(fname, 'w+')
72 if string:
73 print >> f, string
74 elif os.path.isfile(tmpl):
75 print >> f, file(tmpl).read().rstrip()
76 else:
77 print >> f
78 print >> f, __comment_prefix, comment
79 print >> f, __comment_prefix, \
80 'Lines prefixed with "%s" will be automatically removed.' \
81 % __comment_prefix
82 print >> f, __comment_prefix, \
83 'Trailing empty lines will be automatically removed.'
6ad48e48
PBG
84
85 if show_patch:
86 print >> f, __patch_prefix
87 # series.get_patch(series.get_current()).get_top()
88 git.diff([], series.get_patch(series.get_current()).get_bottom(), None, f)
89
90 #Vim modeline must be near the end.
b83e37e0 91 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:'
41a6d859
CM
92 f.close()
93
94 # the editor
cd076ff6
CL
95 if config.has_option('stgit', 'editor'):
96 editor = config.get('stgit', 'editor')
97 elif 'EDITOR' in os.environ:
41a6d859
CM
98 editor = os.environ['EDITOR']
99 else:
100 editor = 'vi'
101 editor += ' %s' % fname
102
103 print 'Invoking the editor: "%s"...' % editor,
104 sys.stdout.flush()
105 print 'done (exit code: %d)' % os.system(editor)
106
107 f = file(fname, 'r+')
108
109 __clean_comments(f)
110 f.seek(0)
111 string = f.read()
112
113 f.close()
114 os.remove(fname)
115
116 return string
117
118#
119# Classes
120#
121
122class Patch:
123 """Basic patch implementation
124 """
125 def __init__(self, name, patch_dir):
126 self.__patch_dir = patch_dir
127 self.__name = name
128 self.__dir = os.path.join(self.__patch_dir, self.__name)
129
130 def create(self):
131 os.mkdir(self.__dir)
132 create_empty_file(os.path.join(self.__dir, 'bottom'))
133 create_empty_file(os.path.join(self.__dir, 'top'))
134
135 def delete(self):
136 for f in os.listdir(self.__dir):
137 os.remove(os.path.join(self.__dir, f))
138 os.rmdir(self.__dir)
139
140 def get_name(self):
141 return self.__name
142
e55b53e0
CM
143 def rename(self, newname):
144 olddir = self.__dir
145 self.__name = newname
146 self.__dir = os.path.join(self.__patch_dir, self.__name)
147
148 os.rename(olddir, self.__dir)
149
41a6d859
CM
150 def __get_field(self, name, multiline = False):
151 id_file = os.path.join(self.__dir, name)
152 if os.path.isfile(id_file):
153 string = read_string(id_file, multiline)
154 if string == '':
155 return None
156 else:
157 return string
158 else:
159 return None
160
161 def __set_field(self, name, string, multiline = False):
162 fname = os.path.join(self.__dir, name)
163 if string and string != '':
164 write_string(fname, string, multiline)
165 elif os.path.isfile(fname):
166 os.remove(fname)
167
54b09584
PBG
168 def get_old_bottom(self):
169 return self.__get_field('bottom.old')
170
41a6d859
CM
171 def get_bottom(self):
172 return self.__get_field('bottom')
173
174 def set_bottom(self, string, backup = False):
175 if backup:
a5bbc44d
PBG
176 curr = self.__get_field('bottom')
177 if curr != string:
178 self.__set_field('bottom.old', curr)
179 else:
180 self.__set_field('bottom.old', None)
41a6d859
CM
181 self.__set_field('bottom', string)
182
54b09584
PBG
183 def get_old_top(self):
184 return self.__get_field('top.old')
185
41a6d859
CM
186 def get_top(self):
187 return self.__get_field('top')
188
189 def set_top(self, string, backup = False):
190 if backup:
a5bbc44d
PBG
191 curr = self.__get_field('top')
192 if curr != string:
193 self.__set_field('top.old', curr)
194 else:
195 self.__set_field('top.old', None)
41a6d859
CM
196 self.__set_field('top', string)
197
198 def restore_old_boundaries(self):
199 bottom = self.__get_field('bottom.old')
200 top = self.__get_field('top.old')
201
202 if top and bottom:
203 self.__set_field('bottom', bottom)
204 self.__set_field('top', top)
a5bbc44d 205 return True
41a6d859 206 else:
a5bbc44d 207 return False
41a6d859
CM
208
209 def get_description(self):
210 return self.__get_field('description', True)
211
212 def set_description(self, string):
213 self.__set_field('description', string, True)
214
215 def get_authname(self):
216 return self.__get_field('authname')
217
218 def set_authname(self, string):
219 if not string and config.has_option('stgit', 'authname'):
220 string = config.get('stgit', 'authname')
221 self.__set_field('authname', string)
222
223 def get_authemail(self):
224 return self.__get_field('authemail')
225
226 def set_authemail(self, string):
227 if not string and config.has_option('stgit', 'authemail'):
228 string = config.get('stgit', 'authemail')
229 self.__set_field('authemail', string)
230
231 def get_authdate(self):
232 return self.__get_field('authdate')
233
234 def set_authdate(self, string):
235 self.__set_field('authdate', string)
236
237 def get_commname(self):
238 return self.__get_field('commname')
239
240 def set_commname(self, string):
241 if not string and config.has_option('stgit', 'commname'):
242 string = config.get('stgit', 'commname')
243 self.__set_field('commname', string)
244
245 def get_commemail(self):
246 return self.__get_field('commemail')
247
248 def set_commemail(self, string):
249 if not string and config.has_option('stgit', 'commemail'):
250 string = config.get('stgit', 'commemail')
251 self.__set_field('commemail', string)
252
253
254class Series:
255 """Class including the operations on series
256 """
257 def __init__(self, name = None):
40e65b92 258 """Takes a series name as the parameter.
41a6d859
CM
259 """
260 if name:
261 self.__name = name
262 else:
263 self.__name = git.get_head_file()
264
265 if self.__name:
266 self.__patch_dir = os.path.join(git.base_dir, 'patches',
267 self.__name)
268 self.__base_file = os.path.join(git.base_dir, 'refs', 'bases',
269 self.__name)
270 self.__applied_file = os.path.join(self.__patch_dir, 'applied')
271 self.__unapplied_file = os.path.join(self.__patch_dir, 'unapplied')
272 self.__current_file = os.path.join(self.__patch_dir, 'current')
c1fe1f99 273 self.__descr_file = os.path.join(self.__patch_dir, 'description')
41a6d859 274
629ddd02
CM
275 def get_branch(self):
276 """Return the branch name for the Series object
277 """
278 return self.__name
279
41a6d859
CM
280 def __set_current(self, name):
281 """Sets the topmost patch
282 """
283 if name:
284 write_string(self.__current_file, name)
285 else:
286 create_empty_file(self.__current_file)
287
288 def get_patch(self, name):
289 """Return a Patch object for the given name
290 """
291 return Patch(name, self.__patch_dir)
292
293 def get_current(self):
294 """Return a Patch object representing the topmost patch
295 """
296 if os.path.isfile(self.__current_file):
297 name = read_string(self.__current_file)
298 else:
299 return None
300 if name == '':
301 return None
302 else:
303 return name
304
305 def get_applied(self):
40e65b92 306 if not os.path.isfile(self.__applied_file):
a2dcde71 307 raise StackException, 'Branch "%s" not initialised' % self.__name
41a6d859
CM
308 f = file(self.__applied_file)
309 names = [line.strip() for line in f.readlines()]
310 f.close()
311 return names
312
313 def get_unapplied(self):
40e65b92 314 if not os.path.isfile(self.__unapplied_file):
a2dcde71 315 raise StackException, 'Branch "%s" not initialised' % self.__name
41a6d859
CM
316 f = file(self.__unapplied_file)
317 names = [line.strip() for line in f.readlines()]
318 f.close()
319 return names
320
321 def get_base_file(self):
322 return self.__base_file
323
0b4b9499
CL
324 def get_protected(self):
325 return os.path.isfile(os.path.join(self.__patch_dir, 'protected'))
326
327 def protect(self):
328 protect_file = os.path.join(self.__patch_dir, 'protected')
329 if not os.path.isfile(protect_file):
330 create_empty_file(protect_file)
331
332 def unprotect(self):
333 protect_file = os.path.join(self.__patch_dir, 'protected')
334 if os.path.isfile(protect_file):
335 os.remove(protect_file)
336
c1fe1f99
CL
337 def get_description(self):
338 if os.path.isfile(self.__descr_file):
339 return read_string(self.__descr_file)
340 else:
341 return ''
342
41a6d859
CM
343 def __patch_is_current(self, patch):
344 return patch.get_name() == read_string(self.__current_file)
345
346 def __patch_applied(self, name):
347 """Return true if the patch exists in the applied list
348 """
349 return name in self.get_applied()
350
351 def __patch_unapplied(self, name):
352 """Return true if the patch exists in the unapplied list
353 """
354 return name in self.get_unapplied()
355
356 def __begin_stack_check(self):
357 """Save the current HEAD into .git/refs/heads/base if the stack
358 is empty
359 """
360 if len(self.get_applied()) == 0:
361 head = git.get_head()
41a6d859
CM
362 write_string(self.__base_file, head)
363
364 def __end_stack_check(self):
f338c3c0
CM
365 """Remove .git/refs/heads/base if the stack is empty.
366 This warning should never happen
41a6d859 367 """
f338c3c0
CM
368 if len(self.get_applied()) == 0 \
369 and read_string(self.__base_file) != git.get_head():
370 print 'Warning: stack empty but the HEAD and base are different'
41a6d859
CM
371
372 def head_top_equal(self):
373 """Return true if the head and the top are the same
374 """
375 crt = self.get_current()
376 if not crt:
377 # we don't care, no patches applied
378 return True
379 return git.get_head() == Patch(crt, self.__patch_dir).get_top()
380
381 def init(self):
382 """Initialises the stgit series
383 """
384 bases_dir = os.path.join(git.base_dir, 'refs', 'bases')
385
386 if os.path.isdir(self.__patch_dir):
387 raise StackException, self.__patch_dir + ' already exists'
388 os.makedirs(self.__patch_dir)
389
390 if not os.path.isdir(bases_dir):
391 os.makedirs(bases_dir)
392
393 create_empty_file(self.__applied_file)
394 create_empty_file(self.__unapplied_file)
c1fe1f99 395 create_empty_file(self.__descr_file)
6872f46b 396 self.__begin_stack_check()
41a6d859 397
fc804a49
CL
398 def delete(self, force = False):
399 """Deletes an stgit series
400 """
401 if os.path.isdir(self.__patch_dir):
402 patches = self.get_unapplied() + self.get_applied()
403 if not force and patches:
404 raise StackException, \
405 'Cannot delete: the series still contains patches'
406 patches.reverse()
407 for p in patches:
408 self.delete_patch(p)
409
410 if os.path.isfile(self.__applied_file):
411 os.remove(self.__applied_file)
412 if os.path.isfile(self.__unapplied_file):
413 os.remove(self.__unapplied_file)
414 if os.path.isfile(self.__current_file):
415 os.remove(self.__current_file)
c1fe1f99
CL
416 if os.path.isfile(self.__descr_file):
417 os.remove(self.__descr_file)
fc804a49
CL
418 if not os.listdir(self.__patch_dir):
419 os.rmdir(self.__patch_dir)
420 else:
421 print 'Series directory %s is not empty.' % self.__name
422
423 if os.path.isfile(self.__base_file):
424 os.remove(self.__base_file)
425
6ad48e48
PBG
426 def refresh_patch(self, message = None, edit = False, show_patch = False,
427 cache_update = True,
41a6d859
CM
428 author_name = None, author_email = None,
429 author_date = None,
84fcbc3b 430 committer_name = None, committer_email = None):
41a6d859
CM
431 """Generates a new commit for the given patch
432 """
433 name = self.get_current()
434 if not name:
435 raise StackException, 'No patches applied'
436
437 patch = Patch(name, self.__patch_dir)
438
439 descr = patch.get_description()
440 if not (message or descr):
441 edit = True
442 descr = ''
443 elif message:
444 descr = message
445
446 if not message and edit:
6ad48e48 447 descr = edit_file(self, descr.rstrip(), \
41a6d859 448 'Please edit the description for patch "%s" ' \
6ad48e48 449 'above.' % name, show_patch)
41a6d859
CM
450
451 if not author_name:
452 author_name = patch.get_authname()
453 if not author_email:
454 author_email = patch.get_authemail()
455 if not author_date:
456 author_date = patch.get_authdate()
457 if not committer_name:
458 committer_name = patch.get_commname()
459 if not committer_email:
460 committer_email = patch.get_commemail()
461
462 commit_id = git.commit(message = descr, parents = [patch.get_bottom()],
402ad990 463 cache_update = cache_update,
41a6d859
CM
464 allowempty = True,
465 author_name = author_name,
466 author_email = author_email,
467 author_date = author_date,
468 committer_name = committer_name,
469 committer_email = committer_email)
470
84fcbc3b
CM
471 patch.set_top(commit_id)
472 patch.set_description(descr)
473 patch.set_authname(author_name)
474 patch.set_authemail(author_email)
475 patch.set_authdate(author_date)
476 patch.set_commname(committer_name)
477 patch.set_commemail(committer_email)
c14444b9
CM
478
479 return commit_id
41a6d859 480
37a4d1bf
CM
481 def new_patch(self, name, message = None, can_edit = True,
482 unapplied = False, show_patch = False,
483 top = None, bottom = None,
41a6d859
CM
484 author_name = None, author_email = None, author_date = None,
485 committer_name = None, committer_email = None):
486 """Creates a new patch
487 """
488 if self.__patch_applied(name) or self.__patch_unapplied(name):
489 raise StackException, 'Patch "%s" already exists' % name
490
95742cfc 491 if not message and can_edit:
6ad48e48 492 descr = edit_file(self, None, \
41a6d859 493 'Please enter the description for patch "%s" ' \
6ad48e48 494 'above.' % name, show_patch)
4de718c3
BL
495 else:
496 descr = message
41a6d859
CM
497
498 head = git.get_head()
499
500 self.__begin_stack_check()
501
502 patch = Patch(name, self.__patch_dir)
503 patch.create()
37a4d1bf
CM
504
505 if bottom:
506 patch.set_bottom(bottom)
507 else:
508 patch.set_bottom(head)
509 if top:
510 patch.set_top(top)
511 else:
512 patch.set_top(head)
513
41a6d859
CM
514 patch.set_description(descr)
515 patch.set_authname(author_name)
516 patch.set_authemail(author_email)
517 patch.set_authdate(author_date)
518 patch.set_commname(committer_name)
519 patch.set_commemail(committer_email)
520
37a4d1bf
CM
521 if unapplied:
522 patches = [patch.get_name()] + self.get_unapplied()
523
524 f = file(self.__unapplied_file, 'w+')
525 f.writelines([line + '\n' for line in patches])
526 f.close()
527 else:
528 append_string(self.__applied_file, patch.get_name())
529 self.__set_current(name)
41a6d859
CM
530
531 def delete_patch(self, name):
532 """Deletes a patch
533 """
534 patch = Patch(name, self.__patch_dir)
535
536 if self.__patch_is_current(patch):
537 self.pop_patch(name)
538 elif self.__patch_applied(name):
539 raise StackException, 'Cannot remove an applied patch, "%s", ' \
540 'which is not current' % name
541 elif not name in self.get_unapplied():
542 raise StackException, 'Unknown patch "%s"' % name
543
544 patch.delete()
545
546 unapplied = self.get_unapplied()
547 unapplied.remove(name)
548 f = file(self.__unapplied_file, 'w+')
549 f.writelines([line + '\n' for line in unapplied])
550 f.close()
551
680e3a32
PBG
552 def forward_patches(self, names):
553 """Try to fast-forward an array of patches.
554
555 On return, patches in names[0:returned_value] have been pushed on the
556 stack. Apply the rest with push_patch
557 """
558 unapplied = self.get_unapplied()
559 self.__begin_stack_check()
560
561 forwarded = 0
562 top = git.get_head()
563
564 for name in names:
565 assert(name in unapplied)
566
567 patch = Patch(name, self.__patch_dir)
568
569 head = top
570 bottom = patch.get_bottom()
571 top = patch.get_top()
572
573 # top != bottom always since we have a commit for each patch
574 if head == bottom:
575 # reset the backup information
d3cf7d86 576 patch.set_bottom(head, backup = True)
680e3a32
PBG
577 patch.set_top(top, backup = True)
578
579 else:
d3cf7d86
PBG
580 head_tree = git.get_commit(head).get_tree()
581 bottom_tree = git.get_commit(bottom).get_tree()
582 if head_tree == bottom_tree:
583 # We must just reparent this patch and create a new commit
584 # for it
585 descr = patch.get_description()
586 author_name = patch.get_authname()
587 author_email = patch.get_authemail()
588 author_date = patch.get_authdate()
589 committer_name = patch.get_commname()
590 committer_email = patch.get_commemail()
591
592 top_tree = git.get_commit(top).get_tree()
593
594 top = git.commit(message = descr, parents = [head],
595 cache_update = False,
596 tree_id = top_tree,
597 allowempty = True,
598 author_name = author_name,
599 author_email = author_email,
600 author_date = author_date,
601 committer_name = committer_name,
602 committer_email = committer_email)
603
604 patch.set_bottom(head, backup = True)
605 patch.set_top(top, backup = True)
606 else:
607 top = head
608 # stop the fast-forwarding, must do a real merge
609 break
680e3a32
PBG
610
611 forwarded+=1
612 unapplied.remove(name)
613
614 git.switch(top)
615
616 append_strings(self.__applied_file, names[0:forwarded])
617
618 f = file(self.__unapplied_file, 'w+')
619 f.writelines([line + '\n' for line in unapplied])
620 f.close()
621
622 self.__set_current(name)
623
624 return forwarded
625
41a6d859
CM
626 def push_patch(self, name):
627 """Pushes a patch on the stack
628 """
629 unapplied = self.get_unapplied()
630 assert(name in unapplied)
631
632 self.__begin_stack_check()
633
634 patch = Patch(name, self.__patch_dir)
635
636 head = git.get_head()
637 bottom = patch.get_bottom()
638 top = patch.get_top()
639
640 ex = None
718a5e51 641 modified = False
41a6d859
CM
642
643 # top != bottom always since we have a commit for each patch
644 if head == bottom:
645 # reset the backup information
646 patch.set_bottom(bottom, backup = True)
647 patch.set_top(top, backup = True)
648
649 git.switch(top)
650 else:
651 # new patch needs to be refreshed.
652 # The current patch is empty after merge.
653 patch.set_bottom(head, backup = True)
654 patch.set_top(head, backup = True)
575a7e7c
CM
655
656 # Try the fast applying first. If this fails, fall back to the
657 # three-way merge
658 if not git.apply_diff(bottom, top):
718a5e51
CM
659 # if git.apply_diff() fails, the patch requires a diff3
660 # merge and can be reported as modified
661 modified = True
662
575a7e7c
CM
663 # merge can fail but the patch needs to be pushed
664 try:
665 git.merge(bottom, head, top)
666 except git.GitException, ex:
667 print >> sys.stderr, \
668 'The merge failed during "push". ' \
669 'Use "refresh" after fixing the conflicts'
41a6d859
CM
670
671 append_string(self.__applied_file, name)
672
673 unapplied.remove(name)
674 f = file(self.__unapplied_file, 'w+')
675 f.writelines([line + '\n' for line in unapplied])
676 f.close()
677
678 self.__set_current(name)
679
a322940b
CM
680 # head == bottom case doesn't need to refresh the patch
681 if head != bottom:
682 if not ex:
683 # if the merge was OK and no conflicts, just refresh the patch
402ad990
CM
684 # The GIT cache was already updated by the merge operation
685 self.refresh_patch(cache_update = False)
a322940b
CM
686 else:
687 raise StackException, str(ex)
41a6d859 688
718a5e51
CM
689 return modified
690
41a6d859
CM
691 def undo_push(self):
692 name = self.get_current()
693 assert(name)
694
695 patch = Patch(name, self.__patch_dir)
05d593c0 696 git.reset()
41a6d859 697 self.pop_patch(name)
a5bbc44d 698 return patch.restore_old_boundaries()
41a6d859
CM
699
700 def pop_patch(self, name):
701 """Pops the top patch from the stack
702 """
703 applied = self.get_applied()
704 applied.reverse()
705 assert(name in applied)
706
707 patch = Patch(name, self.__patch_dir)
708
709 git.switch(patch.get_bottom())
710
711 # save the new applied list
712 idx = applied.index(name) + 1
713
714 popped = applied[:idx]
715 popped.reverse()
716 unapplied = popped + self.get_unapplied()
717
718 f = file(self.__unapplied_file, 'w+')
719 f.writelines([line + '\n' for line in unapplied])
720 f.close()
721
722 del applied[:idx]
723 applied.reverse()
724
725 f = file(self.__applied_file, 'w+')
726 f.writelines([line + '\n' for line in applied])
727 f.close()
728
729 if applied == []:
730 self.__set_current(None)
731 else:
732 self.__set_current(applied[-1])
733
734 self.__end_stack_check()
735
736 def empty_patch(self, name):
737 """Returns True if the patch is empty
738 """
739 patch = Patch(name, self.__patch_dir)
740 bottom = patch.get_bottom()
741 top = patch.get_top()
742
743 if bottom == top:
744 return True
8e29bcd2
CM
745 elif git.get_commit(top).get_tree() \
746 == git.get_commit(bottom).get_tree():
41a6d859
CM
747 return True
748
749 return False
e55b53e0
CM
750
751 def rename_patch(self, oldname, newname):
752 applied = self.get_applied()
753 unapplied = self.get_unapplied()
754
755 if newname in applied or newname in unapplied:
756 raise StackException, 'Patch "%s" already exists' % newname
757
758 if oldname in unapplied:
759 Patch(oldname, self.__patch_dir).rename(newname)
760 unapplied[unapplied.index(oldname)] = newname
761
762 f = file(self.__unapplied_file, 'w+')
763 f.writelines([line + '\n' for line in unapplied])
764 f.close()
765 elif oldname in applied:
766 Patch(oldname, self.__patch_dir).rename(newname)
767 if oldname == self.get_current():
768 self.__set_current(newname)
769
770 applied[applied.index(oldname)] = newname
771
772 f = file(self.__applied_file, 'w+')
773 f.writelines([line + '\n' for line in applied])
774 f.close()
775 else:
776 raise StackException, 'Unknown patch "%s"' % oldname