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