Merge branch 'stable' into stable-master-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(r'[\\"]', r'\\\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)"'
278 ' string: %s' % address)
279 return ( str_list[0][1], str_list[0][0] )
280
281 return str_list[0]
282
283 def name_email_date(address):
284 """Return a tuple consisting of the name, email and date parsed
285 from a 'name <email> date' string
286 """
287 address = re.sub(r'[\\"]', r'\\\g<0>', address)
288 str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address)
289 if not str_list:
290 raise CmdException, 'Incorrect "name <email> date" string: %s' % address
291
292 return str_list[0]
293
294 def address_or_alias(addr_str):
295 """Return the address if it contains an e-mail address or look up
296 the aliases in the config files.
297 """
298 def __address_or_alias(addr):
299 if not addr:
300 return None
301 if addr.find('@') >= 0:
302 # it's an e-mail address
303 return addr
304 alias = config.get('mail.alias.'+addr)
305 if alias:
306 # it's an alias
307 return alias
308 raise CmdException, 'unknown e-mail alias: %s' % addr
309
310 addr_list = [__address_or_alias(addr.strip())
311 for addr in addr_str.split(',')]
312 return ', '.join([addr for addr in addr_list if addr])
313
314 def prepare_rebase(crt_series):
315 # pop all patches
316 applied = crt_series.get_applied()
317 if len(applied) > 0:
318 out.start('Popping all applied patches')
319 crt_series.pop_patch(applied[0])
320 out.done()
321 return applied
322
323 def rebase(crt_series, target):
324 try:
325 tree_id = git_id(crt_series, target)
326 except:
327 # it might be that we use a custom rebase command with its own
328 # target type
329 tree_id = target
330 if tree_id == git.get_head():
331 out.info('Already at "%s", no need for rebasing.' % target)
332 return
333 if target:
334 out.start('Rebasing to "%s"' % target)
335 else:
336 out.start('Rebasing to the default target')
337 git.rebase(tree_id = tree_id)
338 out.done()
339
340 def post_rebase(crt_series, applied, nopush, merged):
341 # memorize that we rebased to here
342 crt_series._set_field('orig-base', git.get_head())
343 # push the patches back
344 if not nopush:
345 push_patches(crt_series, applied, merged)
346
347 #
348 # Patch description/e-mail/diff parsing
349 #
350 def __end_descr(line):
351 return re.match('---\s*$', line) or re.match('diff -', line) or \
352 re.match('Index: ', line)
353
354 def __split_descr_diff(string):
355 """Return the description and the diff from the given string
356 """
357 descr = diff = ''
358 top = True
359
360 for line in string.split('\n'):
361 if top:
362 if not __end_descr(line):
363 descr += line + '\n'
364 continue
365 else:
366 top = False
367 diff += line + '\n'
368
369 return (descr.rstrip(), diff)
370
371 def __parse_description(descr):
372 """Parse the patch description and return the new description and
373 author information (if any).
374 """
375 subject = body = ''
376 authname = authemail = authdate = None
377
378 descr_lines = [line.rstrip() for line in descr.split('\n')]
379 if not descr_lines:
380 raise CmdException, "Empty patch description"
381
382 lasthdr = 0
383 end = len(descr_lines)
384
385 # Parse the patch header
386 for pos in range(0, end):
387 if not descr_lines[pos]:
388 continue
389 # check for a "From|Author:" line
390 if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
391 auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
392 authname, authemail = name_email(auth)
393 lasthdr = pos + 1
394 continue
395 # check for a "Date:" line
396 if re.match('\s*date:\s+', descr_lines[pos], re.I):
397 authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
398 lasthdr = pos + 1
399 continue
400 if subject:
401 break
402 # get the subject
403 subject = descr_lines[pos]
404 lasthdr = pos + 1
405
406 # get the body
407 if lasthdr < end:
408 body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
409
410 return (subject + body, authname, authemail, authdate)
411
412 def parse_mail(msg):
413 """Parse the message object and return (description, authname,
414 authemail, authdate, diff)
415 """
416 from email.Header import decode_header, make_header
417
418 def __decode_header(header):
419 """Decode a qp-encoded e-mail header as per rfc2047"""
420 try:
421 words_enc = decode_header(header)
422 hobj = make_header(words_enc)
423 except Exception, ex:
424 raise CmdException, 'header decoding error: %s' % str(ex)
425 return unicode(hobj).encode('utf-8')
426
427 # parse the headers
428 if msg.has_key('from'):
429 authname, authemail = name_email(__decode_header(msg['from']))
430 else:
431 authname = authemail = None
432
433 # '\n\t' can be found on multi-line headers
434 descr = __decode_header(msg['subject']).replace('\n\t', ' ')
435 authdate = msg['date']
436
437 # remove the '[*PATCH*]' expression in the subject
438 if descr:
439 descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
440 descr)[0][1]
441 else:
442 raise CmdException, 'Subject: line not found'
443
444 # the rest of the message
445 msg_text = ''
446 for part in msg.walk():
447 if part.get_content_type() == 'text/plain':
448 msg_text += part.get_payload(decode = True)
449
450 rem_descr, diff = __split_descr_diff(msg_text)
451 if rem_descr:
452 descr += '\n\n' + rem_descr
453
454 # parse the description for author information
455 descr, descr_authname, descr_authemail, descr_authdate = \
456 __parse_description(descr)
457 if descr_authname:
458 authname = descr_authname
459 if descr_authemail:
460 authemail = descr_authemail
461 if descr_authdate:
462 authdate = descr_authdate
463
464 return (descr, authname, authemail, authdate, diff)
465
466 def parse_patch(text):
467 """Parse the input text and return (description, authname,
468 authemail, authdate, diff)
469 """
470 descr, diff = __split_descr_diff(text)
471 descr, authname, authemail, authdate = __parse_description(descr)
472
473 # we don't yet have an agreed place for the creation date.
474 # Just return None
475 return (descr, authname, authemail, authdate, diff)
476
477 def readonly_constant_property(f):
478 """Decorator that converts a function that computes a value to an
479 attribute that returns the value. The value is computed only once,
480 the first time it is accessed."""
481 def new_f(self):
482 n = '__' + f.__name__
483 if not hasattr(self, n):
484 setattr(self, n, f(self))
485 return getattr(self, n)
486 return property(new_f)
487
488 class DirectoryException(StgException):
489 pass
490
491 class _Directory(object):
492 def __init__(self, needs_current_series = True):
493 self.needs_current_series = needs_current_series
494 @readonly_constant_property
495 def git_dir(self):
496 try:
497 return Run('git', 'rev-parse', '--git-dir'
498 ).discard_stderr().output_one_line()
499 except RunException:
500 raise DirectoryException('No git repository found')
501 @readonly_constant_property
502 def __topdir_path(self):
503 try:
504 lines = Run('git', 'rev-parse', '--show-cdup'
505 ).discard_stderr().output_lines()
506 if len(lines) == 0:
507 return '.'
508 elif len(lines) == 1:
509 return lines[0]
510 else:
511 raise RunException('Too much output')
512 except RunException:
513 raise DirectoryException('No git repository found')
514 @readonly_constant_property
515 def is_inside_git_dir(self):
516 return { 'true': True, 'false': False
517 }[Run('git', 'rev-parse', '--is-inside-git-dir'
518 ).output_one_line()]
519 @readonly_constant_property
520 def is_inside_worktree(self):
521 return { 'true': True, 'false': False
522 }[Run('git', 'rev-parse', '--is-inside-work-tree'
523 ).output_one_line()]
524 def cd_to_topdir(self):
525 os.chdir(self.__topdir_path)
526
527 class DirectoryAnywhere(_Directory):
528 def setup(self):
529 pass
530
531 class DirectoryHasRepository(_Directory):
532 def setup(self):
533 self.git_dir # might throw an exception
534
535 class DirectoryInWorktree(DirectoryHasRepository):
536 def setup(self):
537 DirectoryHasRepository.setup(self)
538 if not self.is_inside_worktree:
539 raise DirectoryException('Not inside a git worktree')
540
541 class DirectoryGotoToplevel(DirectoryInWorktree):
542 def setup(self):
543 DirectoryInWorktree.setup(self)
544 self.cd_to_topdir()
545
546 class DirectoryHasRepositoryLib(_Directory):
547 """For commands that use the new infrastructure in stgit.lib.*."""
548 def __init__(self):
549 self.needs_current_series = False
550 def setup(self):
551 # This will throw an exception if we don't have a repository.
552 self.repository = libstack.Repository.default()