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