Re-add the interactive merge
[stgit] / stgit / commands / common.py
1 """Function/variables common to all the commands
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, os.path, re
22 from optparse import OptionParser, make_option
23
24 from stgit.exception import *
25 from stgit.utils import *
26 from stgit.out import *
27 from stgit.run import *
28 from stgit import stack, git, basedir
29 from stgit.config import config, file_extensions
30 from stgit.lib import stack as libstack
31
32 # Command exception class
33 class CmdException(StgException):
34 pass
35
36 # Utility functions
37 class RevParseException(StgException):
38 """Revision spec parse error."""
39 pass
40
41 def parse_rev(rev):
42 """Parse a revision specification into its
43 patchname@branchname//patch_id parts. If no branch name has a slash
44 in it, also accept / instead of //."""
45 if '/' in ''.join(git.get_heads()):
46 # We have branch names with / in them.
47 branch_chars = r'[^@]'
48 patch_id_mark = r'//'
49 else:
50 # No / in branch names.
51 branch_chars = r'[^@/]'
52 patch_id_mark = r'(/|//)'
53 patch_re = r'(?P<patch>[^@/]+)'
54 branch_re = r'@(?P<branch>%s+)' % branch_chars
55 patch_id_re = r'%s(?P<patch_id>[a-z.]*)' % patch_id_mark
56
57 # Try //patch_id.
58 m = re.match(r'^%s$' % patch_id_re, rev)
59 if m:
60 return None, None, m.group('patch_id')
61
62 # Try path[@branch]//patch_id.
63 m = re.match(r'^%s(%s)?%s$' % (patch_re, branch_re, patch_id_re), rev)
64 if m:
65 return m.group('patch'), m.group('branch'), m.group('patch_id')
66
67 # Try patch[@branch].
68 m = re.match(r'^%s(%s)?$' % (patch_re, branch_re), rev)
69 if m:
70 return m.group('patch'), m.group('branch'), None
71
72 # No, we can't parse that.
73 raise RevParseException
74
75 def git_id(crt_series, rev):
76 """Return the GIT id
77 """
78 if not rev:
79 return None
80
81 # try a GIT revision first
82 try:
83 return git.rev_parse(rev + '^{commit}')
84 except git.GitException:
85 pass
86
87 # try an StGIT patch name
88 try:
89 patch, branch, patch_id = parse_rev(rev)
90 if branch == None:
91 series = crt_series
92 else:
93 series = stack.Series(branch)
94 if patch == None:
95 patch = series.get_current()
96 if not patch:
97 raise CmdException, 'No patches applied'
98 if patch in series.get_applied() or patch in series.get_unapplied() or \
99 patch in series.get_hidden():
100 if patch_id in ['top', '', None]:
101 return series.get_patch(patch).get_top()
102 elif patch_id == 'bottom':
103 return series.get_patch(patch).get_bottom()
104 elif patch_id == 'top.old':
105 return series.get_patch(patch).get_old_top()
106 elif patch_id == 'bottom.old':
107 return series.get_patch(patch).get_old_bottom()
108 elif patch_id == 'log':
109 return series.get_patch(patch).get_log()
110 if patch == 'base' and patch_id == None:
111 return series.get_base()
112 except RevParseException:
113 pass
114 except stack.StackException:
115 pass
116
117 raise CmdException, 'Unknown patch or revision: %s' % rev
118
119 def check_local_changes():
120 if git.local_changes():
121 raise CmdException, \
122 'local changes in the tree. Use "refresh" or "status --reset"'
123
124 def check_head_top_equal(crt_series):
125 if not crt_series.head_top_equal():
126 raise CmdException(
127 """HEAD and top are not the same. This can happen if you
128 modify a branch with git. "stg repair --help" explains
129 more about what to do next.""")
130
131 def check_conflicts():
132 if git.get_conflicts():
133 raise CmdException, \
134 'Unsolved conflicts. Please resolve them first or\n' \
135 ' revert the changes with "status --reset"'
136
137 def print_crt_patch(crt_series, branch = None):
138 if not branch:
139 patch = crt_series.get_current()
140 else:
141 patch = stack.Series(branch).get_current()
142
143 if patch:
144 out.info('Now at patch "%s"' % patch)
145 else:
146 out.info('No patches applied')
147
148 def resolved_all(reset = None):
149 conflicts = git.get_conflicts()
150 git.resolved(conflicts, reset)
151
152 def push_patches(crt_series, patches, check_merged = False):
153 """Push multiple patches onto the stack. This function is shared
154 between the push and pull commands
155 """
156 forwarded = crt_series.forward_patches(patches)
157 if forwarded > 1:
158 out.info('Fast-forwarded patches "%s" - "%s"'
159 % (patches[0], patches[forwarded - 1]))
160 elif forwarded == 1:
161 out.info('Fast-forwarded patch "%s"' % patches[0])
162
163 names = patches[forwarded:]
164
165 # check for patches merged upstream
166 if names and check_merged:
167 out.start('Checking for patches merged upstream')
168
169 merged = crt_series.merged_patches(names)
170
171 out.done('%d found' % len(merged))
172 else:
173 merged = []
174
175 for p in names:
176 out.start('Pushing patch "%s"' % p)
177
178 if p in merged:
179 crt_series.push_empty_patch(p)
180 out.done('merged upstream')
181 else:
182 modified = crt_series.push_patch(p)
183
184 if crt_series.empty_patch(p):
185 out.done('empty patch')
186 elif modified:
187 out.done('modified')
188 else:
189 out.done()
190
191 def pop_patches(crt_series, patches, keep = False):
192 """Pop the patches in the list from the stack. It is assumed that
193 the patches are listed in the stack reverse order.
194 """
195 if len(patches) == 0:
196 out.info('Nothing to push/pop')
197 else:
198 p = patches[-1]
199 if len(patches) == 1:
200 out.start('Popping patch "%s"' % p)
201 else:
202 out.start('Popping patches "%s" - "%s"' % (patches[0], p))
203 crt_series.pop_patch(p, keep)
204 out.done()
205
206 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
207 """Parse patch_args list for patch names in patch_list and return
208 a list. The names can be individual patches and/or in the
209 patch1..patch2 format.
210 """
211 patches = []
212
213 for name in patch_args:
214 pair = name.split('..')
215 for p in pair:
216 if p and not p in patch_list:
217 raise CmdException, 'Unknown patch name: %s' % p
218
219 if len(pair) == 1:
220 # single patch name
221 pl = pair
222 elif len(pair) == 2:
223 # patch range [p1]..[p2]
224 # inclusive boundary
225 if pair[0]:
226 first = patch_list.index(pair[0])
227 else:
228 first = -1
229 # exclusive boundary
230 if pair[1]:
231 last = patch_list.index(pair[1]) + 1
232 else:
233 last = -1
234
235 # only cross the boundary if explicitly asked
236 if not boundary:
237 boundary = len(patch_list)
238 if first < 0:
239 if last <= boundary:
240 first = 0
241 else:
242 first = boundary
243 if last < 0:
244 if first < boundary:
245 last = boundary
246 else:
247 last = len(patch_list)
248
249 if last > first:
250 pl = patch_list[first:last]
251 else:
252 pl = patch_list[(last - 1):(first + 1)]
253 pl.reverse()
254 else:
255 raise CmdException, 'Malformed patch name: %s' % name
256
257 for p in pl:
258 if p in patches:
259 raise CmdException, 'Duplicate patch name: %s' % p
260
261 patches += pl
262
263 if ordered:
264 patches = [p for p in patch_list if p in patches]
265
266 return patches
267
268 def name_email(address):
269 """Return a tuple consisting of the name and email parsed from a
270 standard 'name <email>' or 'email (name)' string
271 """
272 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
273 str_list = re.findall('^(.*)\s*<(.*)>\s*$', address)
274 if not str_list:
275 str_list = re.findall('^(.*)\s*\((.*)\)\s*$', address)
276 if not str_list:
277 raise CmdException, 'Incorrect "name <email>"/"email (name)" string: %s' % address
278 return ( str_list[0][1], str_list[0][0] )
279
280 return str_list[0]
281
282 def name_email_date(address):
283 """Return a tuple consisting of the name, email and date parsed
284 from a 'name <email> date' string
285 """
286 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
287 str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address)
288 if not str_list:
289 raise CmdException, 'Incorrect "name <email> date" string: %s' % address
290
291 return str_list[0]
292
293 def address_or_alias(addr_str):
294 """Return the address if it contains an e-mail address or look up
295 the aliases in the config files.
296 """
297 def __address_or_alias(addr):
298 if not addr:
299 return None
300 if addr.find('@') >= 0:
301 # it's an e-mail address
302 return addr
303 alias = config.get('mail.alias.'+addr)
304 if alias:
305 # it's an alias
306 return alias
307 raise CmdException, 'unknown e-mail alias: %s' % addr
308
309 addr_list = [__address_or_alias(addr.strip())
310 for addr in addr_str.split(',')]
311 return ', '.join([addr for addr in addr_list if addr])
312
313 def prepare_rebase(crt_series):
314 # pop all patches
315 applied = crt_series.get_applied()
316 if len(applied) > 0:
317 out.start('Popping all applied patches')
318 crt_series.pop_patch(applied[0])
319 out.done()
320 return applied
321
322 def rebase(crt_series, target):
323 try:
324 tree_id = git_id(crt_series, target)
325 except:
326 # it might be that we use a custom rebase command with its own
327 # target type
328 tree_id = target
329 if tree_id == git.get_head():
330 out.info('Already at "%s", no need for rebasing.' % target)
331 return
332 if target:
333 out.start('Rebasing to "%s"' % target)
334 else:
335 out.start('Rebasing to the default target')
336 git.rebase(tree_id = tree_id)
337 out.done()
338
339 def post_rebase(crt_series, applied, nopush, merged):
340 # memorize that we rebased to here
341 crt_series._set_field('orig-base', git.get_head())
342 # push the patches back
343 if not nopush:
344 push_patches(crt_series, applied, merged)
345
346 #
347 # Patch description/e-mail/diff parsing
348 #
349 def __end_descr(line):
350 return re.match('---\s*$', line) or re.match('diff -', line) or \
351 re.match('Index: ', line)
352
353 def __split_descr_diff(string):
354 """Return the description and the diff from the given string
355 """
356 descr = diff = ''
357 top = True
358
359 for line in string.split('\n'):
360 if top:
361 if not __end_descr(line):
362 descr += line + '\n'
363 continue
364 else:
365 top = False
366 diff += line + '\n'
367
368 return (descr.rstrip(), diff)
369
370 def __parse_description(descr):
371 """Parse the patch description and return the new description and
372 author information (if any).
373 """
374 subject = body = ''
375 authname = authemail = authdate = None
376
377 descr_lines = [line.rstrip() for line in descr.split('\n')]
378 if not descr_lines:
379 raise CmdException, "Empty patch description"
380
381 lasthdr = 0
382 end = len(descr_lines)
383
384 # Parse the patch header
385 for pos in range(0, end):
386 if not descr_lines[pos]:
387 continue
388 # check for a "From|Author:" line
389 if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
390 auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
391 authname, authemail = name_email(auth)
392 lasthdr = pos + 1
393 continue
394 # check for a "Date:" line
395 if re.match('\s*date:\s+', descr_lines[pos], re.I):
396 authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
397 lasthdr = pos + 1
398 continue
399 if subject:
400 break
401 # get the subject
402 subject = descr_lines[pos]
403 lasthdr = pos + 1
404
405 # get the body
406 if lasthdr < end:
407 body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
408
409 return (subject + body, authname, authemail, authdate)
410
411 def parse_mail(msg):
412 """Parse the message object and return (description, authname,
413 authemail, authdate, diff)
414 """
415 from email.Header import decode_header, make_header
416
417 def __decode_header(header):
418 """Decode a qp-encoded e-mail header as per rfc2047"""
419 try:
420 words_enc = decode_header(header)
421 hobj = make_header(words_enc)
422 except Exception, ex:
423 raise CmdException, 'header decoding error: %s' % str(ex)
424 return unicode(hobj).encode('utf-8')
425
426 # parse the headers
427 if msg.has_key('from'):
428 authname, authemail = name_email(__decode_header(msg['from']))
429 else:
430 authname = authemail = None
431
432 # '\n\t' can be found on multi-line headers
433 descr = __decode_header(msg['subject']).replace('\n\t', ' ')
434 authdate = msg['date']
435
436 # remove the '[*PATCH*]' expression in the subject
437 if descr:
438 descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
439 descr)[0][1]
440 else:
441 raise CmdException, 'Subject: line not found'
442
443 # the rest of the message
444 msg_text = ''
445 for part in msg.walk():
446 if part.get_content_type() == 'text/plain':
447 msg_text += part.get_payload(decode = True)
448
449 rem_descr, diff = __split_descr_diff(msg_text)
450 if rem_descr:
451 descr += '\n\n' + rem_descr
452
453 # parse the description for author information
454 descr, descr_authname, descr_authemail, descr_authdate = \
455 __parse_description(descr)
456 if descr_authname:
457 authname = descr_authname
458 if descr_authemail:
459 authemail = descr_authemail
460 if descr_authdate:
461 authdate = descr_authdate
462
463 return (descr, authname, authemail, authdate, diff)
464
465 def parse_patch(text):
466 """Parse the input text and return (description, authname,
467 authemail, authdate, diff)
468 """
469 descr, diff = __split_descr_diff(text)
470 descr, authname, authemail, authdate = __parse_description(descr)
471
472 # we don't yet have an agreed place for the creation date.
473 # Just return None
474 return (descr, authname, authemail, authdate, diff)
475
476 def readonly_constant_property(f):
477 """Decorator that converts a function that computes a value to an
478 attribute that returns the value. The value is computed only once,
479 the first time it is accessed."""
480 def new_f(self):
481 n = '__' + f.__name__
482 if not hasattr(self, n):
483 setattr(self, n, f(self))
484 return getattr(self, n)
485 return property(new_f)
486
487 class DirectoryException(StgException):
488 pass
489
490 class _Directory(object):
491 def __init__(self, needs_current_series = True):
492 self.needs_current_series = needs_current_series
493 @readonly_constant_property
494 def git_dir(self):
495 try:
496 return Run('git', 'rev-parse', '--git-dir'
497 ).discard_stderr().output_one_line()
498 except RunException:
499 raise DirectoryException('No git repository found')
500 @readonly_constant_property
501 def __topdir_path(self):
502 try:
503 lines = Run('git', 'rev-parse', '--show-cdup'
504 ).discard_stderr().output_lines()
505 if len(lines) == 0:
506 return '.'
507 elif len(lines) == 1:
508 return lines[0]
509 else:
510 raise RunException('Too much output')
511 except RunException:
512 raise DirectoryException('No git repository found')
513 @readonly_constant_property
514 def is_inside_git_dir(self):
515 return { 'true': True, 'false': False
516 }[Run('git', 'rev-parse', '--is-inside-git-dir'
517 ).output_one_line()]
518 @readonly_constant_property
519 def is_inside_worktree(self):
520 return { 'true': True, 'false': False
521 }[Run('git', 'rev-parse', '--is-inside-work-tree'
522 ).output_one_line()]
523 def cd_to_topdir(self):
524 os.chdir(self.__topdir_path)
525
526 class DirectoryAnywhere(_Directory):
527 def setup(self):
528 pass
529
530 class DirectoryHasRepository(_Directory):
531 def setup(self):
532 self.git_dir # might throw an exception
533
534 class DirectoryInWorktree(DirectoryHasRepository):
535 def setup(self):
536 DirectoryHasRepository.setup(self)
537 if not self.is_inside_worktree:
538 raise DirectoryException('Not inside a git worktree')
539
540 class DirectoryGotoToplevel(DirectoryInWorktree):
541 def setup(self):
542 DirectoryInWorktree.setup(self)
543 self.cd_to_topdir()
544
545 class DirectoryHasRepositoryLib(_Directory):
546 """For commands that use the new infrastructure in stgit.lib.*."""
547 def __init__(self):
548 self.needs_current_series = False
549 def setup(self):
550 # This will throw an exception if we don't have a repository.
551 self.repository = libstack.Repository.default()