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