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