Using the --message option with the new command fails. Fix it.
[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
22
23 from stgit.utils import *
24 from stgit import git
25 from stgit.config import config
26
27
28 # stack exception class
29 class StackException(Exception):
30 pass
31
32 #
33 # Functions
34 #
35 __comment_prefix = 'STG:'
36
37 def __clean_comments(f):
38 """Removes lines marked for status in a commit file
39 """
40 f.seek(0)
41
42 # remove status-prefixed lines
43 lines = filter(lambda x: x[0:len(__comment_prefix)] != __comment_prefix,
44 f.readlines())
45 # remove empty lines at the end
46 while len(lines) != 0 and lines[-1] == '\n':
47 del lines[-1]
48
49 f.seek(0); f.truncate()
50 f.writelines(lines)
51
52 def edit_file(string, comment):
53 fname = '.stgit.msg'
54 tmpl = os.path.join(git.base_dir, 'patchdescr.tmpl')
55
56 f = file(fname, 'w+')
57 if string:
58 print >> f, string
59 elif os.path.isfile(tmpl):
60 print >> f, file(tmpl).read().rstrip()
61 else:
62 print >> f
63 print >> f, __comment_prefix, comment
64 print >> f, __comment_prefix, \
65 'Lines prefixed with "%s" will be automatically removed.' \
66 % __comment_prefix
67 print >> f, __comment_prefix, \
68 'Trailing empty lines will be automatically removed.'
69 f.close()
70
71 # the editor
72 if 'EDITOR' in os.environ:
73 editor = os.environ['EDITOR']
74 else:
75 editor = 'vi'
76 editor += ' %s' % fname
77
78 print 'Invoking the editor: "%s"...' % editor,
79 sys.stdout.flush()
80 print 'done (exit code: %d)' % os.system(editor)
81
82 f = file(fname, 'r+')
83
84 __clean_comments(f)
85 f.seek(0)
86 string = f.read()
87
88 f.close()
89 os.remove(fname)
90
91 return string
92
93 #
94 # Classes
95 #
96
97 class Patch:
98 """Basic patch implementation
99 """
100 def __init__(self, name, patch_dir):
101 self.__patch_dir = patch_dir
102 self.__name = name
103 self.__dir = os.path.join(self.__patch_dir, self.__name)
104
105 def create(self):
106 os.mkdir(self.__dir)
107 create_empty_file(os.path.join(self.__dir, 'bottom'))
108 create_empty_file(os.path.join(self.__dir, 'top'))
109
110 def delete(self):
111 for f in os.listdir(self.__dir):
112 os.remove(os.path.join(self.__dir, f))
113 os.rmdir(self.__dir)
114
115 def get_name(self):
116 return self.__name
117
118 def __get_field(self, name, multiline = False):
119 id_file = os.path.join(self.__dir, name)
120 if os.path.isfile(id_file):
121 string = read_string(id_file, multiline)
122 if string == '':
123 return None
124 else:
125 return string
126 else:
127 return None
128
129 def __set_field(self, name, string, multiline = False):
130 fname = os.path.join(self.__dir, name)
131 if string and string != '':
132 write_string(fname, string, multiline)
133 elif os.path.isfile(fname):
134 os.remove(fname)
135
136 def get_bottom(self):
137 return self.__get_field('bottom')
138
139 def set_bottom(self, string, backup = False):
140 if backup:
141 self.__set_field('bottom.old', self.__get_field('bottom'))
142 self.__set_field('bottom', string)
143
144 def get_top(self):
145 return self.__get_field('top')
146
147 def set_top(self, string, backup = False):
148 if backup:
149 self.__set_field('top.old', self.__get_field('top'))
150 self.__set_field('top', string)
151
152 def restore_old_boundaries(self):
153 bottom = self.__get_field('bottom.old')
154 top = self.__get_field('top.old')
155
156 if top and bottom:
157 self.__set_field('bottom', bottom)
158 self.__set_field('top', top)
159 else:
160 raise StackException, 'No patch undo information'
161
162 def get_description(self):
163 return self.__get_field('description', True)
164
165 def set_description(self, string):
166 self.__set_field('description', string, True)
167
168 def get_authname(self):
169 return self.__get_field('authname')
170
171 def set_authname(self, string):
172 if not string and config.has_option('stgit', 'authname'):
173 string = config.get('stgit', 'authname')
174 self.__set_field('authname', string)
175
176 def get_authemail(self):
177 return self.__get_field('authemail')
178
179 def set_authemail(self, string):
180 if not string and config.has_option('stgit', 'authemail'):
181 string = config.get('stgit', 'authemail')
182 self.__set_field('authemail', string)
183
184 def get_authdate(self):
185 return self.__get_field('authdate')
186
187 def set_authdate(self, string):
188 self.__set_field('authdate', string)
189
190 def get_commname(self):
191 return self.__get_field('commname')
192
193 def set_commname(self, string):
194 if not string and config.has_option('stgit', 'commname'):
195 string = config.get('stgit', 'commname')
196 self.__set_field('commname', string)
197
198 def get_commemail(self):
199 return self.__get_field('commemail')
200
201 def set_commemail(self, string):
202 if not string and config.has_option('stgit', 'commemail'):
203 string = config.get('stgit', 'commemail')
204 self.__set_field('commemail', string)
205
206
207 class Series:
208 """Class including the operations on series
209 """
210 def __init__(self, name = None):
211 """Takes a series name as the parameter. A valid .git/patches/name
212 directory should exist
213 """
214 if name:
215 self.__name = name
216 else:
217 self.__name = git.get_head_file()
218
219 if self.__name:
220 self.__patch_dir = os.path.join(git.base_dir, 'patches',
221 self.__name)
222 self.__base_file = os.path.join(git.base_dir, 'refs', 'bases',
223 self.__name)
224 self.__applied_file = os.path.join(self.__patch_dir, 'applied')
225 self.__unapplied_file = os.path.join(self.__patch_dir, 'unapplied')
226 self.__current_file = os.path.join(self.__patch_dir, 'current')
227
228 def __set_current(self, name):
229 """Sets the topmost patch
230 """
231 if name:
232 write_string(self.__current_file, name)
233 else:
234 create_empty_file(self.__current_file)
235
236 def get_patch(self, name):
237 """Return a Patch object for the given name
238 """
239 return Patch(name, self.__patch_dir)
240
241 def get_current(self):
242 """Return a Patch object representing the topmost patch
243 """
244 if os.path.isfile(self.__current_file):
245 name = read_string(self.__current_file)
246 else:
247 return None
248 if name == '':
249 return None
250 else:
251 return name
252
253 def get_applied(self):
254 f = file(self.__applied_file)
255 names = [line.strip() for line in f.readlines()]
256 f.close()
257 return names
258
259 def get_unapplied(self):
260 f = file(self.__unapplied_file)
261 names = [line.strip() for line in f.readlines()]
262 f.close()
263 return names
264
265 def get_base_file(self):
266 return self.__base_file
267
268 def __patch_is_current(self, patch):
269 return patch.get_name() == read_string(self.__current_file)
270
271 def __patch_applied(self, name):
272 """Return true if the patch exists in the applied list
273 """
274 return name in self.get_applied()
275
276 def __patch_unapplied(self, name):
277 """Return true if the patch exists in the unapplied list
278 """
279 return name in self.get_unapplied()
280
281 def __begin_stack_check(self):
282 """Save the current HEAD into .git/refs/heads/base if the stack
283 is empty
284 """
285 if len(self.get_applied()) == 0:
286 head = git.get_head()
287 if os.path.exists(self.__base_file):
288 raise StackException, 'stack empty but the base file exists'
289 write_string(self.__base_file, head)
290
291 def __end_stack_check(self):
292 """Remove .git/refs/heads/base if the stack is empty
293 """
294 if len(self.get_applied()) == 0:
295 if not os.path.exists(self.__base_file):
296 print 'Warning: stack empty but the base file is missing'
297 else:
298 os.remove(self.__base_file)
299
300 def head_top_equal(self):
301 """Return true if the head and the top are the same
302 """
303 crt = self.get_current()
304 if not crt:
305 # we don't care, no patches applied
306 return True
307 return git.get_head() == Patch(crt, self.__patch_dir).get_top()
308
309 def init(self):
310 """Initialises the stgit series
311 """
312 bases_dir = os.path.join(git.base_dir, 'refs', 'bases')
313
314 if os.path.isdir(self.__patch_dir):
315 raise StackException, self.__patch_dir + ' already exists'
316 os.makedirs(self.__patch_dir)
317
318 if not os.path.isdir(bases_dir):
319 os.makedirs(bases_dir)
320
321 create_empty_file(self.__applied_file)
322 create_empty_file(self.__unapplied_file)
323
324 def refresh_patch(self, message = None, edit = False,
325 author_name = None, author_email = None,
326 author_date = None,
327 committer_name = None, committer_email = None):
328 """Generates a new commit for the given patch
329 """
330 name = self.get_current()
331 if not name:
332 raise StackException, 'No patches applied'
333
334 patch = Patch(name, self.__patch_dir)
335
336 descr = patch.get_description()
337 if not (message or descr):
338 edit = True
339 descr = ''
340 elif message:
341 descr = message
342
343 if not message and edit:
344 descr = edit_file(descr.rstrip(), \
345 'Please edit the description for patch "%s" ' \
346 'above.' % name)
347
348 if not author_name:
349 author_name = patch.get_authname()
350 if not author_email:
351 author_email = patch.get_authemail()
352 if not author_date:
353 author_date = patch.get_authdate()
354 if not committer_name:
355 committer_name = patch.get_commname()
356 if not committer_email:
357 committer_email = patch.get_commemail()
358
359 commit_id = git.commit(message = descr, parents = [patch.get_bottom()],
360 allowempty = True,
361 author_name = author_name,
362 author_email = author_email,
363 author_date = author_date,
364 committer_name = committer_name,
365 committer_email = committer_email)
366
367 patch.set_top(commit_id)
368 patch.set_description(descr)
369 patch.set_authname(author_name)
370 patch.set_authemail(author_email)
371 patch.set_authdate(author_date)
372 patch.set_commname(committer_name)
373 patch.set_commemail(committer_email)
374
375 def new_patch(self, name, message = None, edit = False,
376 author_name = None, author_email = None, author_date = None,
377 committer_name = None, committer_email = None):
378 """Creates a new patch
379 """
380 if self.__patch_applied(name) or self.__patch_unapplied(name):
381 raise StackException, 'Patch "%s" already exists' % name
382
383 if not message:
384 descr = edit_file(None, \
385 'Please enter the description for patch "%s" ' \
386 'above.' % name)
387 else:
388 descr = message
389
390 head = git.get_head()
391
392 self.__begin_stack_check()
393
394 patch = Patch(name, self.__patch_dir)
395 patch.create()
396 patch.set_bottom(head)
397 patch.set_top(head)
398 patch.set_description(descr)
399 patch.set_authname(author_name)
400 patch.set_authemail(author_email)
401 patch.set_authdate(author_date)
402 patch.set_commname(committer_name)
403 patch.set_commemail(committer_email)
404
405 append_string(self.__applied_file, patch.get_name())
406 self.__set_current(name)
407
408 def delete_patch(self, name):
409 """Deletes a patch
410 """
411 patch = Patch(name, self.__patch_dir)
412
413 if self.__patch_is_current(patch):
414 self.pop_patch(name)
415 elif self.__patch_applied(name):
416 raise StackException, 'Cannot remove an applied patch, "%s", ' \
417 'which is not current' % name
418 elif not name in self.get_unapplied():
419 raise StackException, 'Unknown patch "%s"' % name
420
421 patch.delete()
422
423 unapplied = self.get_unapplied()
424 unapplied.remove(name)
425 f = file(self.__unapplied_file, 'w+')
426 f.writelines([line + '\n' for line in unapplied])
427 f.close()
428
429 def push_patch(self, name):
430 """Pushes a patch on the stack
431 """
432 unapplied = self.get_unapplied()
433 assert(name in unapplied)
434
435 self.__begin_stack_check()
436
437 patch = Patch(name, self.__patch_dir)
438
439 head = git.get_head()
440 bottom = patch.get_bottom()
441 top = patch.get_top()
442
443 ex = None
444
445 # top != bottom always since we have a commit for each patch
446 if head == bottom:
447 # reset the backup information
448 patch.set_bottom(bottom, backup = True)
449 patch.set_top(top, backup = True)
450
451 git.switch(top)
452 else:
453 # new patch needs to be refreshed.
454 # The current patch is empty after merge.
455 patch.set_bottom(head, backup = True)
456 patch.set_top(head, backup = True)
457 # merge/refresh can fail but the patch needs to be pushed
458 try:
459 git.merge(bottom, head, top)
460 except git.GitException, ex:
461 print >> sys.stderr, \
462 'The merge failed during "push". ' \
463 'Use "refresh" after fixing the conflicts'
464 pass
465
466 append_string(self.__applied_file, name)
467
468 unapplied.remove(name)
469 f = file(self.__unapplied_file, 'w+')
470 f.writelines([line + '\n' for line in unapplied])
471 f.close()
472
473 self.__set_current(name)
474
475 if not ex:
476 # if the merge was OK and no conflicts, just refresh the patch
477 self.refresh_patch()
478 else:
479 raise StackException, str(ex)
480
481 def undo_push(self):
482 name = self.get_current()
483 assert(name)
484
485 patch = Patch(name, self.__patch_dir)
486 self.pop_patch(name)
487 patch.restore_old_boundaries()
488
489 def pop_patch(self, name):
490 """Pops the top patch from the stack
491 """
492 applied = self.get_applied()
493 applied.reverse()
494 assert(name in applied)
495
496 patch = Patch(name, self.__patch_dir)
497
498 git.switch(patch.get_bottom())
499
500 # save the new applied list
501 idx = applied.index(name) + 1
502
503 popped = applied[:idx]
504 popped.reverse()
505 unapplied = popped + self.get_unapplied()
506
507 f = file(self.__unapplied_file, 'w+')
508 f.writelines([line + '\n' for line in unapplied])
509 f.close()
510
511 del applied[:idx]
512 applied.reverse()
513
514 f = file(self.__applied_file, 'w+')
515 f.writelines([line + '\n' for line in applied])
516 f.close()
517
518 if applied == []:
519 self.__set_current(None)
520 else:
521 self.__set_current(applied[-1])
522
523 self.__end_stack_check()
524
525 def empty_patch(self, name):
526 """Returns True if the patch is empty
527 """
528 patch = Patch(name, self.__patch_dir)
529 bottom = patch.get_bottom()
530 top = patch.get_top()
531
532 if bottom == top:
533 return True
534 elif git.Commit(top).get_tree() == git.Commit(bottom).get_tree():
535 return True
536
537 return False