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
22 from optparse import OptionParser, make_option
24 from stgit.utils import *
25 from stgit import stack, git, basedir
26 from stgit.config import config, file_extensions
31 # Command exception class
32 class CmdException(Exception):
37 class RevParseException(Exception):
38 """Revision spec parse error."""
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 files, dirs = list_files_and_dirs(os.path.join(basedir.get(),
48 # We have branch names with / in them.
49 branch_chars = r'[^@]'
52 # No / in branch names.
53 branch_chars = r'[^@/]'
54 patch_id_mark = r'(/|//)'
55 patch_re = r'(?P<patch>[^@/]+)'
56 branch_re = r'@(?P<branch>%s+)' % branch_chars
57 patch_id_re = r'%s(?P<patch_id>[a-z.]*)' % patch_id_mark
60 m = re.match(r'^%s$' % patch_id_re, rev)
62 return None, None, m.group('patch_id')
64 # Try path[@branch]//patch_id.
65 m = re.match(r'^%s(%s)?%s$' % (patch_re, branch_re, patch_id_re), rev)
67 return m.group('patch'), m.group('branch'), m.group('patch_id')
70 m = re.match(r'^%s(%s)?$' % (patch_re, branch_re), rev)
72 return m.group('patch'), m.group('branch'), None
74 # No, we can't parse that.
75 raise RevParseException
83 patch, branch, patch_id = parse_rev(rev)
87 series = stack.Series(branch)
89 patch = series.get_current()
91 raise CmdException, 'No patches applied'
92 if patch in series.get_applied() or patch in series.get_unapplied() or \
93 patch in series.get_hidden():
94 if patch_id in ['top', '', None]:
95 return series.get_patch(patch).get_top()
96 elif patch_id == 'bottom':
97 return series.get_patch(patch).get_bottom()
98 elif patch_id == 'top.old':
99 return series.get_patch(patch).get_old_top()
100 elif patch_id == 'bottom.old':
101 return series.get_patch(patch).get_old_bottom()
102 elif patch_id == 'log':
103 return series.get_patch(patch).get_log()
104 if patch == 'base' and patch_id == None:
105 return series.get_base()
106 except RevParseException:
108 return git.rev_parse(rev + '^{commit}')
110 def check_local_changes():
111 if git.local_changes():
112 raise CmdException, \
113 'local changes in the tree. Use "refresh" or "status --reset"'
115 def check_head_top_equal():
116 if not crt_series.head_top_equal():
118 'HEAD and top are not the same. You probably committed\n'
119 ' changes to the tree outside of StGIT. To bring them\n'
120 ' into StGIT, use the "assimilate" command')
122 def check_conflicts():
123 if os.path.exists(os.path.join(basedir.get(), 'conflicts')):
124 raise CmdException, \
125 'Unsolved conflicts. Please resolve them first or\n' \
126 ' revert the changes with "status --reset"'
128 def print_crt_patch(branch = None):
130 patch = crt_series.get_current()
132 patch = stack.Series(branch).get_current()
135 out.info('Now at patch "%s"' % patch)
137 out.info('No patches applied')
139 def resolved(filename, reset = None):
141 reset_file = filename + file_extensions()[reset]
142 if os.path.isfile(reset_file):
143 if os.path.isfile(filename):
145 os.rename(reset_file, filename)
147 git.update_cache([filename], force = True)
149 for ext in file_extensions().values():
151 if os.path.isfile(fn):
154 def resolved_all(reset = None):
155 conflicts = git.get_conflicts()
157 for filename in conflicts:
158 resolved(filename, reset)
159 os.remove(os.path.join(basedir.get(), 'conflicts'))
161 def push_patches(patches, check_merged = False):
162 """Push multiple patches onto the stack. This function is shared
163 between the push and pull commands
165 forwarded = crt_series.forward_patches(patches)
167 out.info('Fast-forwarded patches "%s" - "%s"'
168 % (patches[0], patches[forwarded - 1]))
170 out.info('Fast-forwarded patch "%s"' % patches[0])
172 names = patches[forwarded:]
174 # check for patches merged upstream
175 if names and check_merged:
176 out.start('Checking for patches merged upstream')
178 merged = crt_series.merged_patches(names)
180 out.done('%d found' % len(merged))
185 out.start('Pushing patch "%s"' % p)
188 crt_series.push_patch(p, empty = True)
189 out.done('merged upstream')
191 modified = crt_series.push_patch(p)
193 if crt_series.empty_patch(p):
194 out.done('empty patch')
200 def pop_patches(patches, keep = False):
201 """Pop the patches in the list from the stack. It is assumed that
202 the patches are listed in the stack reverse order.
204 if len(patches) == 0:
205 out.info('Nothing to push/pop')
208 if len(patches) == 1:
209 out.start('Popping patch "%s"' % p)
211 out.start('Popping patches "%s" - "%s"' % (patches[0], p))
212 crt_series.pop_patch(p, keep)
215 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
216 """Parse patch_args list for patch names in patch_list and return
217 a list. The names can be individual patches and/or in the
218 patch1..patch2 format.
222 for name in patch_args:
223 pair = name.split('..')
225 if p and not p in patch_list:
226 raise CmdException, 'Unknown patch name: %s' % p
232 # patch range [p1]..[p2]
235 first = patch_list.index(pair[0])
240 last = patch_list.index(pair[1]) + 1
244 # only cross the boundary if explicitly asked
246 boundary = len(patch_list)
256 last = len(patch_list)
259 pl = patch_list[first:last]
261 pl = patch_list[(last - 1):(first + 1)]
264 raise CmdException, 'Malformed patch name: %s' % name
268 raise CmdException, 'Duplicate patch name: %s' % p
273 patches = [p for p in patch_list if p in patches]
277 def name_email(address):
278 """Return a tuple consisting of the name and email parsed from a
279 standard 'name <email>' or 'email (name)' string
281 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
282 str_list = re.findall('^(.*)\s*<(.*)>\s*$', address)
284 str_list = re.findall('^(.*)\s*\((.*)\)\s*$', address)
286 raise CmdException, 'Incorrect "name <email>"/"email (name)" string: %s' % address
287 return ( str_list[0][1], str_list[0][0] )
291 def name_email_date(address):
292 """Return a tuple consisting of the name, email and date parsed
293 from a 'name <email> date' string
295 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
296 str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address)
298 raise CmdException, 'Incorrect "name <email> date" string: %s' % address
302 def address_or_alias(addr_str):
303 """Return the address if it contains an e-mail address or look up
304 the aliases in the config files.
306 def __address_or_alias(addr):
309 if addr.find('@') >= 0:
310 # it's an e-mail address
312 alias = config.get('mail.alias.'+addr)
316 raise CmdException, 'unknown e-mail alias: %s' % addr
318 addr_list = [__address_or_alias(addr.strip())
319 for addr in addr_str.split(',')]
320 return ', '.join([addr for addr in addr_list if addr])
322 def prepare_rebase(force=None):
324 # Be sure we won't loose results of stg-(un)commit by error.
325 # Do not require an existing orig-base for compatibility with 0.12 and earlier.
326 origbase = crt_series._get_field('orig-base')
327 if origbase and crt_series.get_base() != origbase:
328 raise CmdException, 'Rebasing would possibly lose data'
331 applied = crt_series.get_applied()
333 out.start('Popping all applied patches')
334 crt_series.pop_patch(applied[0])
339 if target == git.get_head():
340 out.info('Already at "%s", no need for rebasing.' % target)
342 out.start('Rebasing to "%s"' % target)
343 git.reset(tree_id = git_id(target))
346 def post_rebase(applied, nopush, merged):
347 # memorize that we rebased to here
348 crt_series._set_field('orig-base', git.get_head())
349 # push the patches back
351 push_patches(applied, merged)