Allow the rebase command to be defined
[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.utils import *
25 from stgit.out import *
26 from stgit import stack, git, basedir
27 from stgit.config import config, file_extensions
28 from stgit.run import *
29
30 crt_series = None
31
32
33 # Command exception class
34 class CmdException(Exception):
35 pass
36
37 class CmdRunException(CmdException):
38 pass
39 class CmdRun(Run):
40 exc = CmdRunException
41
42 # Utility functions
43 class RevParseException(Exception):
44 """Revision spec parse error."""
45 pass
46
47 def parse_rev(rev):
48 """Parse a revision specification into its
49 patchname@branchname//patch_id parts. If no branch name has a slash
50 in it, also accept / instead of //."""
51 if '/' in ''.join(git.get_heads()):
52 # We have branch names with / in them.
53 branch_chars = r'[^@]'
54 patch_id_mark = r'//'
55 else:
56 # No / in branch names.
57 branch_chars = r'[^@/]'
58 patch_id_mark = r'(/|//)'
59 patch_re = r'(?P<patch>[^@/]+)'
60 branch_re = r'@(?P<branch>%s+)' % branch_chars
61 patch_id_re = r'%s(?P<patch_id>[a-z.]*)' % patch_id_mark
62
63 # Try //patch_id.
64 m = re.match(r'^%s$' % patch_id_re, rev)
65 if m:
66 return None, None, m.group('patch_id')
67
68 # Try path[@branch]//patch_id.
69 m = re.match(r'^%s(%s)?%s$' % (patch_re, branch_re, patch_id_re), rev)
70 if m:
71 return m.group('patch'), m.group('branch'), m.group('patch_id')
72
73 # Try patch[@branch].
74 m = re.match(r'^%s(%s)?$' % (patch_re, branch_re), rev)
75 if m:
76 return m.group('patch'), m.group('branch'), None
77
78 # No, we can't parse that.
79 raise RevParseException
80
81 def git_id(rev):
82 """Return the GIT id
83 """
84 if not rev:
85 return None
86 try:
87 patch, branch, patch_id = parse_rev(rev)
88 if branch == None:
89 series = crt_series
90 else:
91 series = stack.Series(branch)
92 if patch == None:
93 patch = series.get_current()
94 if not patch:
95 raise CmdException, 'No patches applied'
96 if patch in series.get_applied() or patch in series.get_unapplied() or \
97 patch in series.get_hidden():
98 if patch_id in ['top', '', None]:
99 return series.get_patch(patch).get_top()
100 elif patch_id == 'bottom':
101 return series.get_patch(patch).get_bottom()
102 elif patch_id == 'top.old':
103 return series.get_patch(patch).get_old_top()
104 elif patch_id == 'bottom.old':
105 return series.get_patch(patch).get_old_bottom()
106 elif patch_id == 'log':
107 return series.get_patch(patch).get_log()
108 if patch == 'base' and patch_id == None:
109 return series.get_base()
110 except RevParseException:
111 pass
112 return git.rev_parse(rev + '^{commit}')
113
114 def check_local_changes():
115 if git.local_changes():
116 raise CmdException, \
117 'local changes in the tree. Use "refresh" or "status --reset"'
118
119 def check_head_top_equal():
120 if not crt_series.head_top_equal():
121 raise CmdException(
122 'HEAD and top are not the same. You probably committed\n'
123 ' changes to the tree outside of StGIT. To bring them\n'
124 ' into StGIT, use the "assimilate" command')
125
126 def check_conflicts():
127 if os.path.exists(os.path.join(basedir.get(), 'conflicts')):
128 raise CmdException, \
129 'Unsolved conflicts. Please resolve them first or\n' \
130 ' revert the changes with "status --reset"'
131
132 def print_crt_patch(branch = None):
133 if not branch:
134 patch = crt_series.get_current()
135 else:
136 patch = stack.Series(branch).get_current()
137
138 if patch:
139 out.info('Now at patch "%s"' % patch)
140 else:
141 out.info('No patches applied')
142
143 def resolved(filename, reset = None):
144 if reset:
145 reset_file = filename + file_extensions()[reset]
146 if os.path.isfile(reset_file):
147 if os.path.isfile(filename):
148 os.remove(filename)
149 os.rename(reset_file, filename)
150
151 git.update_cache([filename], force = True)
152
153 for ext in file_extensions().values():
154 fn = filename + ext
155 if os.path.isfile(fn):
156 os.remove(fn)
157
158 def resolved_all(reset = None):
159 conflicts = git.get_conflicts()
160 if conflicts:
161 for filename in conflicts:
162 resolved(filename, reset)
163 os.remove(os.path.join(basedir.get(), 'conflicts'))
164
165 def push_patches(patches, check_merged = False):
166 """Push multiple patches onto the stack. This function is shared
167 between the push and pull commands
168 """
169 forwarded = crt_series.forward_patches(patches)
170 if forwarded > 1:
171 out.info('Fast-forwarded patches "%s" - "%s"'
172 % (patches[0], patches[forwarded - 1]))
173 elif forwarded == 1:
174 out.info('Fast-forwarded patch "%s"' % patches[0])
175
176 names = patches[forwarded:]
177
178 # check for patches merged upstream
179 if names and check_merged:
180 out.start('Checking for patches merged upstream')
181
182 merged = crt_series.merged_patches(names)
183
184 out.done('%d found' % len(merged))
185 else:
186 merged = []
187
188 for p in names:
189 out.start('Pushing patch "%s"' % p)
190
191 if p in merged:
192 crt_series.push_empty_patch(p)
193 out.done('merged upstream')
194 else:
195 modified = crt_series.push_patch(p)
196
197 if crt_series.empty_patch(p):
198 out.done('empty patch')
199 elif modified:
200 out.done('modified')
201 else:
202 out.done()
203
204 def pop_patches(patches, keep = False):
205 """Pop the patches in the list from the stack. It is assumed that
206 the patches are listed in the stack reverse order.
207 """
208 if len(patches) == 0:
209 out.info('Nothing to push/pop')
210 else:
211 p = patches[-1]
212 if len(patches) == 1:
213 out.start('Popping patch "%s"' % p)
214 else:
215 out.start('Popping patches "%s" - "%s"' % (patches[0], p))
216 crt_series.pop_patch(p, keep)
217 out.done()
218
219 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
220 """Parse patch_args list for patch names in patch_list and return
221 a list. The names can be individual patches and/or in the
222 patch1..patch2 format.
223 """
224 patches = []
225
226 for name in patch_args:
227 pair = name.split('..')
228 for p in pair:
229 if p and not p in patch_list:
230 raise CmdException, 'Unknown patch name: %s' % p
231
232 if len(pair) == 1:
233 # single patch name
234 pl = pair
235 elif len(pair) == 2:
236 # patch range [p1]..[p2]
237 # inclusive boundary
238 if pair[0]:
239 first = patch_list.index(pair[0])
240 else:
241 first = -1
242 # exclusive boundary
243 if pair[1]:
244 last = patch_list.index(pair[1]) + 1
245 else:
246 last = -1
247
248 # only cross the boundary if explicitly asked
249 if not boundary:
250 boundary = len(patch_list)
251 if first < 0:
252 if last <= boundary:
253 first = 0
254 else:
255 first = boundary
256 if last < 0:
257 if first < boundary:
258 last = boundary
259 else:
260 last = len(patch_list)
261
262 if last > first:
263 pl = patch_list[first:last]
264 else:
265 pl = patch_list[(last - 1):(first + 1)]
266 pl.reverse()
267 else:
268 raise CmdException, 'Malformed patch name: %s' % name
269
270 for p in pl:
271 if p in patches:
272 raise CmdException, 'Duplicate patch name: %s' % p
273
274 patches += pl
275
276 if ordered:
277 patches = [p for p in patch_list if p in patches]
278
279 return patches
280
281 def name_email(address):
282 """Return a tuple consisting of the name and email parsed from a
283 standard 'name <email>' or 'email (name)' string
284 """
285 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
286 str_list = re.findall('^(.*)\s*<(.*)>\s*$', address)
287 if not str_list:
288 str_list = re.findall('^(.*)\s*\((.*)\)\s*$', address)
289 if not str_list:
290 raise CmdException, 'Incorrect "name <email>"/"email (name)" string: %s' % address
291 return ( str_list[0][1], str_list[0][0] )
292
293 return str_list[0]
294
295 def name_email_date(address):
296 """Return a tuple consisting of the name, email and date parsed
297 from a 'name <email> date' string
298 """
299 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
300 str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address)
301 if not str_list:
302 raise CmdException, 'Incorrect "name <email> date" string: %s' % address
303
304 return str_list[0]
305
306 def address_or_alias(addr_str):
307 """Return the address if it contains an e-mail address or look up
308 the aliases in the config files.
309 """
310 def __address_or_alias(addr):
311 if not addr:
312 return None
313 if addr.find('@') >= 0:
314 # it's an e-mail address
315 return addr
316 alias = config.get('mail.alias.'+addr)
317 if alias:
318 # it's an alias
319 return alias
320 raise CmdException, 'unknown e-mail alias: %s' % addr
321
322 addr_list = [__address_or_alias(addr.strip())
323 for addr in addr_str.split(',')]
324 return ', '.join([addr for addr in addr_list if addr])
325
326 def prepare_rebase(force=None):
327 if not force:
328 # Be sure we won't loose results of stg-(un)commit by error.
329 # Do not require an existing orig-base for compatibility with 0.12 and earlier.
330 origbase = crt_series._get_field('orig-base')
331 if origbase and crt_series.get_base() != origbase:
332 raise CmdException, 'Rebasing would possibly lose data'
333
334 # pop all patches
335 applied = crt_series.get_applied()
336 if len(applied) > 0:
337 out.start('Popping all applied patches')
338 crt_series.pop_patch(applied[0])
339 out.done()
340 return applied
341
342 def rebase(target):
343 if target == git.get_head():
344 out.info('Already at "%s", no need for rebasing.' % target)
345 return
346 command = config.get('branch.%s.stgit.rebasecmd' % git.get_head_file()) \
347 or config.get('stgit.rebasecmd')
348 if target:
349 args = [target]
350 out.start('Rebasing to "%s"' % target)
351 elif command:
352 args = []
353 out.start('Rebasing to the default target')
354 else:
355 raise CmdException, 'Default rebasing requires a target'
356 if command:
357 CmdRun(*(command.split() + args)).run()
358 else:
359 git.reset(tree_id = git_id(target))
360 out.done()
361
362 def post_rebase(applied, nopush, merged):
363 # memorize that we rebased to here
364 crt_series._set_field('orig-base', git.get_head())
365 # push the patches back
366 if not nopush:
367 push_patches(applied, merged)
368
369 #
370 # Patch description/e-mail/diff parsing
371 #
372 def __end_descr(line):
373 return re.match('---\s*$', line) or re.match('diff -', line) or \
374 re.match('Index: ', line)
375
376 def __split_descr_diff(string):
377 """Return the description and the diff from the given string
378 """
379 descr = diff = ''
380 top = True
381
382 for line in string.split('\n'):
383 if top:
384 if not __end_descr(line):
385 descr += line + '\n'
386 continue
387 else:
388 top = False
389 diff += line + '\n'
390
391 return (descr.rstrip(), diff)
392
393 def __parse_description(descr):
394 """Parse the patch description and return the new description and
395 author information (if any).
396 """
397 subject = body = ''
398 authname = authemail = authdate = None
399
400 descr_lines = [line.rstrip() for line in descr.split('\n')]
401 if not descr_lines:
402 raise CmdException, "Empty patch description"
403
404 lasthdr = 0
405 end = len(descr_lines)
406
407 # Parse the patch header
408 for pos in range(0, end):
409 if not descr_lines[pos]:
410 continue
411 # check for a "From|Author:" line
412 if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
413 auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
414 authname, authemail = name_email(auth)
415 lasthdr = pos + 1
416 continue
417 # check for a "Date:" line
418 if re.match('\s*date:\s+', descr_lines[pos], re.I):
419 authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
420 lasthdr = pos + 1
421 continue
422 if subject:
423 break
424 # get the subject
425 subject = descr_lines[pos]
426 lasthdr = pos + 1
427
428 # get the body
429 if lasthdr < end:
430 body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
431
432 return (subject + body, authname, authemail, authdate)
433
434 def parse_mail(msg):
435 """Parse the message object and return (description, authname,
436 authemail, authdate, diff)
437 """
438 from email.Header import decode_header, make_header
439
440 def __decode_header(header):
441 """Decode a qp-encoded e-mail header as per rfc2047"""
442 try:
443 words_enc = decode_header(header)
444 hobj = make_header(words_enc)
445 except Exception, ex:
446 raise CmdException, 'header decoding error: %s' % str(ex)
447 return unicode(hobj).encode('utf-8')
448
449 # parse the headers
450 if msg.has_key('from'):
451 authname, authemail = name_email(__decode_header(msg['from']))
452 else:
453 authname = authemail = None
454
455 # '\n\t' can be found on multi-line headers
456 descr = __decode_header(msg['subject']).replace('\n\t', ' ')
457 authdate = msg['date']
458
459 # remove the '[*PATCH*]' expression in the subject
460 if descr:
461 descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
462 descr)[0][1]
463 else:
464 raise CmdException, 'Subject: line not found'
465
466 # the rest of the message
467 msg_text = ''
468 for part in msg.walk():
469 if part.get_content_type() == 'text/plain':
470 msg_text += part.get_payload(decode = True)
471
472 rem_descr, diff = __split_descr_diff(msg_text)
473 if rem_descr:
474 descr += '\n\n' + rem_descr
475
476 # parse the description for author information
477 descr, descr_authname, descr_authemail, descr_authdate = \
478 __parse_description(descr)
479 if descr_authname:
480 authname = descr_authname
481 if descr_authemail:
482 authemail = descr_authemail
483 if descr_authdate:
484 authdate = descr_authdate
485
486 return (descr, authname, authemail, authdate, diff)
487
488 def parse_patch(fobj):
489 """Parse the input file and return (description, authname,
490 authemail, authdate, diff)
491 """
492 descr, diff = __split_descr_diff(fobj.read())
493 descr, authname, authemail, authdate = __parse_description(descr)
494
495 # we don't yet have an agreed place for the creation date.
496 # Just return None
497 return (descr, authname, authemail, authdate, diff)