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 fix the conflicts'
100 ' then use "resolve <files>" or revert the'
101 ' changes with "status --reset".')
103 def print_crt_patch(crt_series, branch = None):
105 patch = crt_series.get_current()
107 patch = stack.Series(branch).get_current()
110 out.info('Now at patch "%s"' % patch)
112 out.info('No patches applied')
114 def resolved_all(reset = None):
115 conflicts = git.get_conflicts()
116 git.resolved(conflicts, reset)
118 def push_patches(crt_series, patches, check_merged = False):
119 """Push multiple patches onto the stack. This function is shared
120 between the push and pull commands
122 forwarded = crt_series.forward_patches(patches)
124 out.info('Fast-forwarded patches "%s" - "%s"'
125 % (patches[0], patches[forwarded - 1]))
127 out.info('Fast-forwarded patch "%s"' % patches[0])
129 names = patches[forwarded:]
131 # check for patches merged upstream
132 if names and check_merged:
133 out.start('Checking for patches merged upstream')
135 merged = crt_series.merged_patches(names)
137 out.done('%d found' % len(merged))
142 out.start('Pushing patch "%s"' % p)
145 crt_series.push_empty_patch(p)
146 out.done('merged upstream')
148 modified = crt_series.push_patch(p)
150 if crt_series.empty_patch(p):
151 out.done('empty patch')
157 def pop_patches(crt_series, patches, keep = False):
158 """Pop the patches in the list from the stack. It is assumed that
159 the patches are listed in the stack reverse order.
161 if len(patches) == 0:
162 out.info('Nothing to push/pop')
165 if len(patches) == 1:
166 out.start('Popping patch "%s"' % p)
168 out.start('Popping patches "%s" - "%s"' % (patches[0], p))
169 crt_series.pop_patch(p, keep)
172 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
173 """Parse patch_args list for patch names in patch_list and return
174 a list. The names can be individual patches and/or in the
175 patch1..patch2 format.
177 # in case it receives a tuple
178 patch_list = list(patch_list)
181 for name in patch_args:
182 pair = name.split('..')
184 if p and not p in patch_list:
185 raise CmdException, 'Unknown patch name: %s' % p
191 # patch range [p1]..[p2]
194 first = patch_list.index(pair[0])
199 last = patch_list.index(pair[1]) + 1
203 # only cross the boundary if explicitly asked
205 boundary = len(patch_list)
215 last = len(patch_list)
218 pl = patch_list[first:last]
220 pl = patch_list[(last - 1):(first + 1)]
223 raise CmdException, 'Malformed patch name: %s' % name
227 raise CmdException, 'Duplicate patch name: %s' % p
232 patches = [p for p in patch_list if p in patches]
236 def name_email(address):
237 p = email.Utils.parseaddr(address)
241 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
244 def name_email_date(address):
245 p = parse_name_email_date(address)
249 raise CmdException('Incorrect "name <email> date" string: %s' % address)
251 def address_or_alias(addr_pair):
252 """Return a name-email tuple the e-mail address is valid or look up
253 the aliases in the config files.
257 # it's an e-mail address
259 alias = config.get('mail.alias.' + addr)
262 return name_email(alias)
263 raise CmdException, 'unknown e-mail alias: %s' % addr
265 def prepare_rebase(crt_series):
267 applied = crt_series.get_applied()
269 out.start('Popping all applied patches')
270 crt_series.pop_patch(applied[0])
274 def rebase(crt_series, target):
276 tree_id = git_id(crt_series, target)
278 # it might be that we use a custom rebase command with its own
281 if tree_id == git.get_head():
282 out.info('Already at "%s", no need for rebasing.' % target)
285 out.start('Rebasing to "%s"' % target)
287 out.start('Rebasing to the default target')
288 git.rebase(tree_id = tree_id)
291 def post_rebase(crt_series, applied, nopush, merged):
292 # memorize that we rebased to here
293 crt_series._set_field('orig-base', git.get_head())
294 # push the patches back
296 push_patches(crt_series, applied, merged)
299 # Patch description/e-mail/diff parsing
301 def __end_descr(line):
302 return re.match('---\s*$', line) or re.match('diff -', line) or \
303 re.match('Index: ', line)
305 def __split_descr_diff(string):
306 """Return the description and the diff from the given string
311 for line in string.split('\n'):
313 if not __end_descr(line):
320 return (descr.rstrip(), diff)
322 def __parse_description(descr):
323 """Parse the patch description and return the new description and
324 author information (if any).
327 authname = authemail = authdate = None
329 descr_lines = [line.rstrip() for line in descr.split('\n')]
331 raise CmdException, "Empty patch description"
334 end = len(descr_lines)
336 # Parse the patch header
337 for pos in range(0, end):
338 if not descr_lines[pos]:
340 # check for a "From|Author:" line
341 if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
342 auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
343 authname, authemail = name_email(auth)
346 # check for a "Date:" line
347 if re.match('\s*date:\s+', descr_lines[pos], re.I):
348 authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
354 subject = descr_lines[pos]
359 body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
361 return (subject + body, authname, authemail, authdate)
364 """Parse the message object and return (description, authname,
365 authemail, authdate, diff)
367 from email.Header import decode_header, make_header
369 def __decode_header(header):
370 """Decode a qp-encoded e-mail header as per rfc2047"""
372 words_enc = decode_header(header)
373 hobj = make_header(words_enc)
374 except Exception, ex:
375 raise CmdException, 'header decoding error: %s' % str(ex)
376 return unicode(hobj).encode('utf-8')
379 if msg.has_key('from'):
380 authname, authemail = name_email(__decode_header(msg['from']))
382 authname = authemail = None
384 # '\n\t' can be found on multi-line headers
385 descr = __decode_header(msg['subject']).replace('\n\t', ' ')
386 authdate = msg['date']
388 # remove the '[*PATCH*]' expression in the subject
390 descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
393 raise CmdException, 'Subject: line not found'
395 # the rest of the message
397 for part in msg.walk():
398 if part.get_content_type() == 'text/plain':
399 msg_text += part.get_payload(decode = True)
401 rem_descr, diff = __split_descr_diff(msg_text)
403 descr += '\n\n' + rem_descr
405 # parse the description for author information
406 descr, descr_authname, descr_authemail, descr_authdate = \
407 __parse_description(descr)
409 authname = descr_authname
411 authemail = descr_authemail
413 authdate = descr_authdate
415 return (descr, authname, authemail, authdate, diff)
417 def parse_patch(text, contains_diff):
418 """Parse the input text and return (description, authname,
419 authemail, authdate, diff)
422 (text, diff) = __split_descr_diff(text)
425 (descr, authname, authemail, authdate) = __parse_description(text)
427 # we don't yet have an agreed place for the creation date.
429 return (descr, authname, authemail, authdate, diff)
431 def readonly_constant_property(f):
432 """Decorator that converts a function that computes a value to an
433 attribute that returns the value. The value is computed only once,
434 the first time it is accessed."""
436 n = '__' + f.__name__
437 if not hasattr(self, n):
438 setattr(self, n, f(self))
439 return getattr(self, n)
440 return property(new_f)
442 def update_commit_data(cd, options, allow_edit = False):
443 """Return a new CommitData object updated according to the command line
445 # Set the commit message from commandline.
446 if options.message != None:
447 cd = cd.set_message(options.message)
449 # Modify author data.
450 cd = cd.set_author(options.author(cd.author))
452 # Add Signed-off-by: or similar.
453 if options.sign_str != None:
454 sign_str = options.sign_str
456 sign_str = config.get("stgit.autosign")
459 add_sign_line(cd.message, sign_str,
460 cd.committer.name, cd.committer.email))
462 # Let user edit the commit message manually.
463 if allow_edit and not options.message:
464 cd = cd.set_message(edit_string(cd.message, '.stgit-new.txt'))
468 class DirectoryException(StgException):
471 class _Directory(object):
472 def __init__(self, needs_current_series = True, log = True):
473 self.needs_current_series = needs_current_series
475 @readonly_constant_property
478 return Run('git', 'rev-parse', '--git-dir'
479 ).discard_stderr().output_one_line()
481 raise DirectoryException('No git repository found')
482 @readonly_constant_property
483 def __topdir_path(self):
485 lines = Run('git', 'rev-parse', '--show-cdup'
486 ).discard_stderr().output_lines()
489 elif len(lines) == 1:
492 raise RunException('Too much output')
494 raise DirectoryException('No git repository found')
495 @readonly_constant_property
496 def is_inside_git_dir(self):
497 return { 'true': True, 'false': False
498 }[Run('git', 'rev-parse', '--is-inside-git-dir'
500 @readonly_constant_property
501 def is_inside_worktree(self):
502 return { 'true': True, 'false': False
503 }[Run('git', 'rev-parse', '--is-inside-work-tree'
505 def cd_to_topdir(self):
506 os.chdir(self.__topdir_path)
507 def write_log(self, msg):
509 log.compat_log_entry(msg)
511 class DirectoryAnywhere(_Directory):
515 class DirectoryHasRepository(_Directory):
517 self.git_dir # might throw an exception
518 log.compat_log_external_mods()
520 class DirectoryInWorktree(DirectoryHasRepository):
522 DirectoryHasRepository.setup(self)
523 if not self.is_inside_worktree:
524 raise DirectoryException('Not inside a git worktree')
526 class DirectoryGotoToplevel(DirectoryInWorktree):
528 DirectoryInWorktree.setup(self)
531 class DirectoryHasRepositoryLib(_Directory):
532 """For commands that use the new infrastructure in stgit.lib.*."""
534 self.needs_current_series = False
535 self.log = False # stgit.lib.transaction handles logging
537 # This will throw an exception if we don't have a repository.
538 self.repository = libstack.Repository.default()