Adjust stgit for post 0.99.7 renames.
[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.
91 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff:'
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
168 def get_bottom(self):
169 return self.__get_field('bottom')
170
171 def set_bottom(self, string, backup = False):
172 if backup:
a5bbc44d
PBG
173 curr = self.__get_field('bottom')
174 if curr != string:
175 self.__set_field('bottom.old', curr)
176 else:
177 self.__set_field('bottom.old', None)
41a6d859
CM
178 self.__set_field('bottom', string)
179
180 def get_top(self):
181 return self.__get_field('top')
182
183 def set_top(self, string, backup = False):
184 if backup:
a5bbc44d
PBG
185 curr = self.__get_field('top')
186 if curr != string:
187 self.__set_field('top.old', curr)
188 else:
189 self.__set_field('top.old', None)
41a6d859
CM
190 self.__set_field('top', string)
191
192 def restore_old_boundaries(self):
193 bottom = self.__get_field('bottom.old')
194 top = self.__get_field('top.old')
195
196 if top and bottom:
197 self.__set_field('bottom', bottom)
198 self.__set_field('top', top)
a5bbc44d 199 return True
41a6d859 200 else:
a5bbc44d 201 return False
41a6d859
CM
202
203 def get_description(self):
204 return self.__get_field('description', True)
205
206 def set_description(self, string):
207 self.__set_field('description', string, True)
208
209 def get_authname(self):
210 return self.__get_field('authname')
211
212 def set_authname(self, string):
213 if not string and config.has_option('stgit', 'authname'):
214 string = config.get('stgit', 'authname')
215 self.__set_field('authname', string)
216
217 def get_authemail(self):
218 return self.__get_field('authemail')
219
220 def set_authemail(self, string):
221 if not string and config.has_option('stgit', 'authemail'):
222 string = config.get('stgit', 'authemail')
223 self.__set_field('authemail', string)
224
225 def get_authdate(self):
226 return self.__get_field('authdate')
227
228 def set_authdate(self, string):
229 self.__set_field('authdate', string)
230
231 def get_commname(self):
232 return self.__get_field('commname')
233
234 def set_commname(self, string):
235 if not string and config.has_option('stgit', 'commname'):
236 string = config.get('stgit', 'commname')
237 self.__set_field('commname', string)
238
239 def get_commemail(self):
240 return self.__get_field('commemail')
241
242 def set_commemail(self, string):
243 if not string and config.has_option('stgit', 'commemail'):
244 string = config.get('stgit', 'commemail')
245 self.__set_field('commemail', string)
246
247
248class Series:
249 """Class including the operations on series
250 """
251 def __init__(self, name = None):
252 """Takes a series name as the parameter. A valid .git/patches/name
253 directory should exist
254 """
255 if name:
256 self.__name = name
257 else:
258 self.__name = git.get_head_file()
259
260 if self.__name:
261 self.__patch_dir = os.path.join(git.base_dir, 'patches',
262 self.__name)
263 self.__base_file = os.path.join(git.base_dir, 'refs', 'bases',
264 self.__name)
265 self.__applied_file = os.path.join(self.__patch_dir, 'applied')
266 self.__unapplied_file = os.path.join(self.__patch_dir, 'unapplied')
267 self.__current_file = os.path.join(self.__patch_dir, 'current')
268
629ddd02
CM
269 def get_branch(self):
270 """Return the branch name for the Series object
271 """
272 return self.__name
273
41a6d859
CM
274 def __set_current(self, name):
275 """Sets the topmost patch
276 """
277 if name:
278 write_string(self.__current_file, name)
279 else:
280 create_empty_file(self.__current_file)
281
282 def get_patch(self, name):
283 """Return a Patch object for the given name
284 """
285 return Patch(name, self.__patch_dir)
286
287 def get_current(self):
288 """Return a Patch object representing the topmost patch
289 """
290 if os.path.isfile(self.__current_file):
291 name = read_string(self.__current_file)
292 else:
293 return None
294 if name == '':
295 return None
296 else:
297 return name
298
299 def get_applied(self):
300 f = file(self.__applied_file)
301 names = [line.strip() for line in f.readlines()]
302 f.close()
303 return names
304
305 def get_unapplied(self):
306 f = file(self.__unapplied_file)
307 names = [line.strip() for line in f.readlines()]
308 f.close()
309 return names
310
311 def get_base_file(self):
312 return self.__base_file
313
314 def __patch_is_current(self, patch):
315 return patch.get_name() == read_string(self.__current_file)
316
317 def __patch_applied(self, name):
318 """Return true if the patch exists in the applied list
319 """
320 return name in self.get_applied()
321
322 def __patch_unapplied(self, name):
323 """Return true if the patch exists in the unapplied list
324 """
325 return name in self.get_unapplied()
326
327 def __begin_stack_check(self):
328 """Save the current HEAD into .git/refs/heads/base if the stack
329 is empty
330 """
331 if len(self.get_applied()) == 0:
332 head = git.get_head()
41a6d859
CM
333 write_string(self.__base_file, head)
334
335 def __end_stack_check(self):
f338c3c0
CM
336 """Remove .git/refs/heads/base if the stack is empty.
337 This warning should never happen
41a6d859 338 """
f338c3c0
CM
339 if len(self.get_applied()) == 0 \
340 and read_string(self.__base_file) != git.get_head():
341 print 'Warning: stack empty but the HEAD and base are different'
41a6d859
CM
342
343 def head_top_equal(self):
344 """Return true if the head and the top are the same
345 """
346 crt = self.get_current()
347 if not crt:
348 # we don't care, no patches applied
349 return True
350 return git.get_head() == Patch(crt, self.__patch_dir).get_top()
351
352 def init(self):
353 """Initialises the stgit series
354 """
355 bases_dir = os.path.join(git.base_dir, 'refs', 'bases')
356
357 if os.path.isdir(self.__patch_dir):
358 raise StackException, self.__patch_dir + ' already exists'
359 os.makedirs(self.__patch_dir)
360
361 if not os.path.isdir(bases_dir):
362 os.makedirs(bases_dir)
363
364 create_empty_file(self.__applied_file)
365 create_empty_file(self.__unapplied_file)
6872f46b 366 self.__begin_stack_check()
41a6d859 367
6ad48e48
PBG
368 def refresh_patch(self, message = None, edit = False, show_patch = False,
369 cache_update = True,
41a6d859
CM
370 author_name = None, author_email = None,
371 author_date = None,
c14444b9
CM
372 committer_name = None, committer_email = None,
373 commit_only = False):
41a6d859
CM
374 """Generates a new commit for the given patch
375 """
376 name = self.get_current()
377 if not name:
378 raise StackException, 'No patches applied'
379
380 patch = Patch(name, self.__patch_dir)
381
382 descr = patch.get_description()
383 if not (message or descr):
384 edit = True
385 descr = ''
386 elif message:
387 descr = message
388
389 if not message and edit:
6ad48e48 390 descr = edit_file(self, descr.rstrip(), \
41a6d859 391 'Please edit the description for patch "%s" ' \
6ad48e48 392 'above.' % name, show_patch)
41a6d859
CM
393
394 if not author_name:
395 author_name = patch.get_authname()
396 if not author_email:
397 author_email = patch.get_authemail()
398 if not author_date:
399 author_date = patch.get_authdate()
400 if not committer_name:
401 committer_name = patch.get_commname()
402 if not committer_email:
403 committer_email = patch.get_commemail()
404
405 commit_id = git.commit(message = descr, parents = [patch.get_bottom()],
402ad990 406 cache_update = cache_update,
41a6d859
CM
407 allowempty = True,
408 author_name = author_name,
409 author_email = author_email,
410 author_date = author_date,
411 committer_name = committer_name,
412 committer_email = committer_email)
413
c14444b9
CM
414 if not commit_only:
415 patch.set_top(commit_id)
416 patch.set_description(descr)
417 patch.set_authname(author_name)
418 patch.set_authemail(author_email)
419 patch.set_authdate(author_date)
420 patch.set_commname(committer_name)
421 patch.set_commemail(committer_email)
422
423 return commit_id
41a6d859 424
37a4d1bf
CM
425 def new_patch(self, name, message = None, can_edit = True,
426 unapplied = False, show_patch = False,
427 top = None, bottom = None,
41a6d859
CM
428 author_name = None, author_email = None, author_date = None,
429 committer_name = None, committer_email = None):
430 """Creates a new patch
431 """
432 if self.__patch_applied(name) or self.__patch_unapplied(name):
433 raise StackException, 'Patch "%s" already exists' % name
434
95742cfc 435 if not message and can_edit:
6ad48e48 436 descr = edit_file(self, None, \
41a6d859 437 'Please enter the description for patch "%s" ' \
6ad48e48 438 'above.' % name, show_patch)
4de718c3
BL
439 else:
440 descr = message
41a6d859
CM
441
442 head = git.get_head()
443
444 self.__begin_stack_check()
445
446 patch = Patch(name, self.__patch_dir)
447 patch.create()
37a4d1bf
CM
448
449 if bottom:
450 patch.set_bottom(bottom)
451 else:
452 patch.set_bottom(head)
453 if top:
454 patch.set_top(top)
455 else:
456 patch.set_top(head)
457
41a6d859
CM
458 patch.set_description(descr)
459 patch.set_authname(author_name)
460 patch.set_authemail(author_email)
461 patch.set_authdate(author_date)
462 patch.set_commname(committer_name)
463 patch.set_commemail(committer_email)
464
37a4d1bf
CM
465 if unapplied:
466 patches = [patch.get_name()] + self.get_unapplied()
467
468 f = file(self.__unapplied_file, 'w+')
469 f.writelines([line + '\n' for line in patches])
470 f.close()
471 else:
472 append_string(self.__applied_file, patch.get_name())
473 self.__set_current(name)
41a6d859
CM
474
475 def delete_patch(self, name):
476 """Deletes a patch
477 """
478 patch = Patch(name, self.__patch_dir)
479
480 if self.__patch_is_current(patch):
481 self.pop_patch(name)
482 elif self.__patch_applied(name):
483 raise StackException, 'Cannot remove an applied patch, "%s", ' \
484 'which is not current' % name
485 elif not name in self.get_unapplied():
486 raise StackException, 'Unknown patch "%s"' % name
487
488 patch.delete()
489
490 unapplied = self.get_unapplied()
491 unapplied.remove(name)
492 f = file(self.__unapplied_file, 'w+')
493 f.writelines([line + '\n' for line in unapplied])
494 f.close()
495
680e3a32
PBG
496 def forward_patches(self, names):
497 """Try to fast-forward an array of patches.
498
499 On return, patches in names[0:returned_value] have been pushed on the
500 stack. Apply the rest with push_patch
501 """
502 unapplied = self.get_unapplied()
503 self.__begin_stack_check()
504
505 forwarded = 0
506 top = git.get_head()
507
508 for name in names:
509 assert(name in unapplied)
510
511 patch = Patch(name, self.__patch_dir)
512
513 head = top
514 bottom = patch.get_bottom()
515 top = patch.get_top()
516
517 # top != bottom always since we have a commit for each patch
518 if head == bottom:
519 # reset the backup information
d3cf7d86 520 patch.set_bottom(head, backup = True)
680e3a32
PBG
521 patch.set_top(top, backup = True)
522
523 else:
d3cf7d86
PBG
524 head_tree = git.get_commit(head).get_tree()
525 bottom_tree = git.get_commit(bottom).get_tree()
526 if head_tree == bottom_tree:
527 # We must just reparent this patch and create a new commit
528 # for it
529 descr = patch.get_description()
530 author_name = patch.get_authname()
531 author_email = patch.get_authemail()
532 author_date = patch.get_authdate()
533 committer_name = patch.get_commname()
534 committer_email = patch.get_commemail()
535
536 top_tree = git.get_commit(top).get_tree()
537
538 top = git.commit(message = descr, parents = [head],
539 cache_update = False,
540 tree_id = top_tree,
541 allowempty = True,
542 author_name = author_name,
543 author_email = author_email,
544 author_date = author_date,
545 committer_name = committer_name,
546 committer_email = committer_email)
547
548 patch.set_bottom(head, backup = True)
549 patch.set_top(top, backup = True)
550 else:
551 top = head
552 # stop the fast-forwarding, must do a real merge
553 break
680e3a32
PBG
554
555 forwarded+=1
556 unapplied.remove(name)
557
558 git.switch(top)
559
560 append_strings(self.__applied_file, names[0:forwarded])
561
562 f = file(self.__unapplied_file, 'w+')
563 f.writelines([line + '\n' for line in unapplied])
564 f.close()
565
566 self.__set_current(name)
567
568 return forwarded
569
41a6d859
CM
570 def push_patch(self, name):
571 """Pushes a patch on the stack
572 """
573 unapplied = self.get_unapplied()
574 assert(name in unapplied)
575
576 self.__begin_stack_check()
577
578 patch = Patch(name, self.__patch_dir)
579
580 head = git.get_head()
581 bottom = patch.get_bottom()
582 top = patch.get_top()
583
584 ex = None
585
586 # top != bottom always since we have a commit for each patch
587 if head == bottom:
588 # reset the backup information
589 patch.set_bottom(bottom, backup = True)
590 patch.set_top(top, backup = True)
591
592 git.switch(top)
593 else:
594 # new patch needs to be refreshed.
595 # The current patch is empty after merge.
596 patch.set_bottom(head, backup = True)
597 patch.set_top(head, backup = True)
598 # merge/refresh can fail but the patch needs to be pushed
599 try:
600 git.merge(bottom, head, top)
601 except git.GitException, ex:
602 print >> sys.stderr, \
603 'The merge failed during "push". ' \
604 'Use "refresh" after fixing the conflicts'
605 pass
606
607 append_string(self.__applied_file, name)
608
609 unapplied.remove(name)
610 f = file(self.__unapplied_file, 'w+')
611 f.writelines([line + '\n' for line in unapplied])
612 f.close()
613
614 self.__set_current(name)
615
a322940b
CM
616 # head == bottom case doesn't need to refresh the patch
617 if head != bottom:
618 if not ex:
619 # if the merge was OK and no conflicts, just refresh the patch
402ad990
CM
620 # The GIT cache was already updated by the merge operation
621 self.refresh_patch(cache_update = False)
a322940b
CM
622 else:
623 raise StackException, str(ex)
41a6d859
CM
624
625 def undo_push(self):
626 name = self.get_current()
627 assert(name)
628
629 patch = Patch(name, self.__patch_dir)
05d593c0 630 git.reset()
41a6d859 631 self.pop_patch(name)
a5bbc44d 632 return patch.restore_old_boundaries()
41a6d859
CM
633
634 def pop_patch(self, name):
635 """Pops the top patch from the stack
636 """
637 applied = self.get_applied()
638 applied.reverse()
639 assert(name in applied)
640
641 patch = Patch(name, self.__patch_dir)
642
643 git.switch(patch.get_bottom())
644
645 # save the new applied list
646 idx = applied.index(name) + 1
647
648 popped = applied[:idx]
649 popped.reverse()
650 unapplied = popped + self.get_unapplied()
651
652 f = file(self.__unapplied_file, 'w+')
653 f.writelines([line + '\n' for line in unapplied])
654 f.close()
655
656 del applied[:idx]
657 applied.reverse()
658
659 f = file(self.__applied_file, 'w+')
660 f.writelines([line + '\n' for line in applied])
661 f.close()
662
663 if applied == []:
664 self.__set_current(None)
665 else:
666 self.__set_current(applied[-1])
667
668 self.__end_stack_check()
669
670 def empty_patch(self, name):
671 """Returns True if the patch is empty
672 """
673 patch = Patch(name, self.__patch_dir)
674 bottom = patch.get_bottom()
675 top = patch.get_top()
676
677 if bottom == top:
678 return True
8e29bcd2
CM
679 elif git.get_commit(top).get_tree() \
680 == git.get_commit(bottom).get_tree():
41a6d859
CM
681 return True
682
683 return False
e55b53e0
CM
684
685 def rename_patch(self, oldname, newname):
686 applied = self.get_applied()
687 unapplied = self.get_unapplied()
688
689 if newname in applied or newname in unapplied:
690 raise StackException, 'Patch "%s" already exists' % newname
691
692 if oldname in unapplied:
693 Patch(oldname, self.__patch_dir).rename(newname)
694 unapplied[unapplied.index(oldname)] = newname
695
696 f = file(self.__unapplied_file, 'w+')
697 f.writelines([line + '\n' for line in unapplied])
698 f.close()
699 elif oldname in applied:
700 Patch(oldname, self.__patch_dir).rename(newname)
701 if oldname == self.get_current():
702 self.__set_current(newname)
703
704 applied[applied.index(oldname)] = newname
705
706 f = file(self.__applied_file, 'w+')
707 f.writelines([line + '\n' for line in applied])
708 f.close()
709 else:
710 raise StackException, 'Unknown patch "%s"' % oldname