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