1 """Function/variables common to all the commands
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
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.
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.
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
21 import sys, os, os.path, re, email.Utils
22 from stgit.exception import *
23 from stgit.utils import *
24 from stgit.out import *
25 from stgit.run import *
26 from stgit import stack, git, basedir
27 from stgit.config import config, file_extensions
28 from stgit.lib import stack as libstack
29 from stgit.lib import git as libgit
30 from stgit.lib import log
32 # Command exception class
33 class CmdException(StgException):
38 """Parse a revision specification into its branch:patch parts.
41 branch, patch = rev.split(':', 1)
46 return (branch, patch)
48 def git_id(crt_series, rev):
51 # TODO: remove this function once all the occurrences were converted
53 repository = libstack.Repository.default()
54 return git_commit(rev, repository, crt_series.get_name()).sha1
56 def git_commit(name, repository, branch_name = None):
57 """Return the a Commit object if 'name' is a patch name or Git commit.
58 The patch names allowed are in the form '<branch>:<patch>' and can
59 be followed by standard symbols used by git rev-parse. If <patch>
60 is '{base}', it represents the bottom of the stack.
62 # Try a [branch:]patch name first
63 branch, patch = parse_rev(name)
65 branch = branch_name or repository.current_branch_name
68 if patch.startswith('{base}'):
69 base_id = repository.get_stack(branch).base.sha1
70 return repository.rev_parse(base_id +
71 strip_prefix('{base}', patch))
73 # Other combination of branch and patch
75 return repository.rev_parse('patches/%s/%s' % (branch, patch),
76 discard_stderr = True)
77 except libgit.RepositoryException:
82 return repository.rev_parse(name, discard_stderr = True)
83 except libgit.RepositoryException:
84 raise CmdException('%s: Unknown patch or revision name' % name)
86 def check_local_changes():
87 if git.local_changes():
88 raise CmdException('local changes in the tree. Use "refresh" or'
91 def check_head_top_equal(crt_series):
92 if not crt_series.head_top_equal():
93 raise CmdException('HEAD and top are not the same. This can happen'
94 ' if you modify a branch with git. "stg repair'
95 ' --help" explains more about what to do next.')
97 def check_conflicts():
98 if git.get_conflicts():
99 raise CmdException('Unsolved conflicts. Please resolve them first'
100 ' or revert the changes with "status --reset"')
102 def print_crt_patch(crt_series, branch = None):
104 patch = crt_series.get_current()
106 patch = stack.Series(branch).get_current()
109 out.info('Now at patch "%s"' % patch)
111 out.info('No patches applied')
113 def resolved_all(reset = None):
114 conflicts = git.get_conflicts()
115 git.resolved(conflicts, reset)
117 def push_patches(crt_series, patches, check_merged = False):
118 """Push multiple patches onto the stack. This function is shared
119 between the push and pull commands
121 forwarded = crt_series.forward_patches(patches)
123 out.info('Fast-forwarded patches "%s" - "%s"'
124 % (patches[0], patches[forwarded - 1]))
126 out.info('Fast-forwarded patch "%s"' % patches[0])
128 names = patches[forwarded:]
130 # check for patches merged upstream
131 if names and check_merged:
132 out.start('Checking for patches merged upstream')
134 merged = crt_series.merged_patches(names)
136 out.done('%d found' % len(merged))
141 out.start('Pushing patch "%s"' % p)
144 crt_series.push_empty_patch(p)
145 out.done('merged upstream')
147 modified = crt_series.push_patch(p)
149 if crt_series.empty_patch(p):
150 out.done('empty patch')
156 def pop_patches(crt_series, patches, keep = False):
157 """Pop the patches in the list from the stack. It is assumed that
158 the patches are listed in the stack reverse order.
160 if len(patches) == 0:
161 out.info('Nothing to push/pop')
164 if len(patches) == 1:
165 out.start('Popping patch "%s"' % p)
167 out.start('Popping patches "%s" - "%s"' % (patches[0], p))
168 crt_series.pop_patch(p, keep)
171 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
172 """Parse patch_args list for patch names in patch_list and return
173 a list. The names can be individual patches and/or in the
174 patch1..patch2 format.
176 # in case it receives a tuple
177 patch_list = list(patch_list)
180 for name in patch_args:
181 pair = name.split('..')
183 if p and not p in patch_list:
184 raise CmdException, 'Unknown patch name: %s' % p
190 # patch range [p1]..[p2]
193 first = patch_list.index(pair[0])
198 last = patch_list.index(pair[1]) + 1
202 # only cross the boundary if explicitly asked
204 boundary = len(patch_list)
214 last = len(patch_list)
217 pl = patch_list[first:last]
219 pl = patch_list[(last - 1):(first + 1)]
222 raise CmdException, 'Malformed patch name: %s' % name
226 raise CmdException, 'Duplicate patch name: %s' % p
231 patches = [p for p in patch_list if p in patches]
235 def name_email(address):
236 p = email.Utils.parseaddr(address)
240 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
243 def name_email_date(address):
244 p = parse_name_email_date(address)
248 raise CmdException('Incorrect "name <email> date" string: %s' % address)
250 def address_or_alias(addr_pair):
251 """Return a name-email tuple the e-mail address is valid or look up
252 the aliases in the config files.
256 # it's an e-mail address
258 alias = config.get('mail.alias.' + addr)
261 return name_email(alias)
262 raise CmdException, 'unknown e-mail alias: %s' % addr
264 def prepare_rebase(crt_series):
266 applied = crt_series.get_applied()
268 out.start('Popping all applied patches')
269 crt_series.pop_patch(applied[0])
273 def rebase(crt_series, target):
275 tree_id = git_id(crt_series, target)
277 # it might be that we use a custom rebase command with its own
280 if tree_id == git.get_head():
281 out.info('Already at "%s", no need for rebasing.' % target)
284 out.start('Rebasing to "%s"' % target)
286 out.start('Rebasing to the default target')
287 git.rebase(tree_id = tree_id)
290 def post_rebase(crt_series, applied, nopush, merged):
291 # memorize that we rebased to here
292 crt_series._set_field('orig-base', git.get_head())
293 # push the patches back
295 push_patches(crt_series, applied, merged)
298 # Patch description/e-mail/diff parsing
300 def __end_descr(line):
301 return re.match('---\s*$', line) or re.match('diff -', line) or \
302 re.match('Index: ', line)
304 def __split_descr_diff(string):
305 """Return the description and the diff from the given string
310 for line in string.split('\n'):
312 if not __end_descr(line):
319 return (descr.rstrip(), diff)
321 def __parse_description(descr):
322 """Parse the patch description and return the new description and
323 author information (if any).
326 authname = authemail = authdate = None
328 descr_lines = [line.rstrip() for line in descr.split('\n')]
330 raise CmdException, "Empty patch description"
333 end = len(descr_lines)
335 # Parse the patch header
336 for pos in range(0, end):
337 if not descr_lines[pos]:
339 # check for a "From|Author:" line
340 if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
341 auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
342 authname, authemail = name_email(auth)
345 # check for a "Date:" line
346 if re.match('\s*date:\s+', descr_lines[pos], re.I):
347 authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
353 subject = descr_lines[pos]
358 body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
360 return (subject + body, authname, authemail, authdate)
363 """Parse the message object and return (description, authname,
364 authemail, authdate, diff)
366 from email.Header import decode_header, make_header
368 def __decode_header(header):
369 """Decode a qp-encoded e-mail header as per rfc2047"""
371 words_enc = decode_header(header)
372 hobj = make_header(words_enc)
373 except Exception, ex:
374 raise CmdException, 'header decoding error: %s' % str(ex)
375 return unicode(hobj).encode('utf-8')
378 if msg.has_key('from'):
379 authname, authemail = name_email(__decode_header(msg['from']))
381 authname = authemail = None
383 # '\n\t' can be found on multi-line headers
384 descr = __decode_header(msg['subject']).replace('\n\t', ' ')
385 authdate = msg['date']
387 # remove the '[*PATCH*]' expression in the subject
389 descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
392 raise CmdException, 'Subject: line not found'
394 # the rest of the message
396 for part in msg.walk():
397 if part.get_content_type() == 'text/plain':
398 msg_text += part.get_payload(decode = True)
400 rem_descr, diff = __split_descr_diff(msg_text)
402 descr += '\n\n' + rem_descr
404 # parse the description for author information
405 descr, descr_authname, descr_authemail, descr_authdate = \
406 __parse_description(descr)
408 authname = descr_authname
410 authemail = descr_authemail
412 authdate = descr_authdate
414 return (descr, authname, authemail, authdate, diff)
416 def parse_patch(text, contains_diff):
417 """Parse the input text and return (description, authname,
418 authemail, authdate, diff)
421 (text, diff) = __split_descr_diff(text)
424 (descr, authname, authemail, authdate) = __parse_description(text)
426 # we don't yet have an agreed place for the creation date.
428 return (descr, authname, authemail, authdate, diff)
430 def readonly_constant_property(f):
431 """Decorator that converts a function that computes a value to an
432 attribute that returns the value. The value is computed only once,
433 the first time it is accessed."""
435 n = '__' + f.__name__
436 if not hasattr(self, n):
437 setattr(self, n, f(self))
438 return getattr(self, n)
439 return property(new_f)
441 class DirectoryException(StgException):
444 class _Directory(object):
445 def __init__(self, needs_current_series = True, log = True):
446 self.needs_current_series = needs_current_series
448 @readonly_constant_property
451 return Run('git', 'rev-parse', '--git-dir'
452 ).discard_stderr().output_one_line()
454 raise DirectoryException('No git repository found')
455 @readonly_constant_property
456 def __topdir_path(self):
458 lines = Run('git', 'rev-parse', '--show-cdup'
459 ).discard_stderr().output_lines()
462 elif len(lines) == 1:
465 raise RunException('Too much output')
467 raise DirectoryException('No git repository found')
468 @readonly_constant_property
469 def is_inside_git_dir(self):
470 return { 'true': True, 'false': False
471 }[Run('git', 'rev-parse', '--is-inside-git-dir'
473 @readonly_constant_property
474 def is_inside_worktree(self):
475 return { 'true': True, 'false': False
476 }[Run('git', 'rev-parse', '--is-inside-work-tree'
478 def cd_to_topdir(self):
479 os.chdir(self.__topdir_path)
480 def write_log(self, msg):
482 log.compat_log_entry(msg)
484 class DirectoryAnywhere(_Directory):
488 class DirectoryHasRepository(_Directory):
490 self.git_dir # might throw an exception
491 log.compat_log_external_mods()
493 class DirectoryInWorktree(DirectoryHasRepository):
495 DirectoryHasRepository.setup(self)
496 if not self.is_inside_worktree:
497 raise DirectoryException('Not inside a git worktree')
499 class DirectoryGotoToplevel(DirectoryInWorktree):
501 DirectoryInWorktree.setup(self)
504 class DirectoryHasRepositoryLib(_Directory):
505 """For commands that use the new infrastructure in stgit.lib.*."""
507 self.needs_current_series = False
508 self.log = False # stgit.lib.transaction handles logging
510 # This will throw an exception if we don't have a repository.
511 self.repository = libstack.Repository.default()