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
.out
import *
26 from stgit
import stack
, git
, basedir
27 from stgit
.config
import config
, file_extensions
28 from stgit
.run
import *
33 # Command exception class
34 class CmdException(Exception):
37 class CmdRunException(CmdException
):
43 class RevParseException(Exception):
44 """Revision spec parse error."""
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
'[^@]'
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
64 m
= re
.match(r
'^%s$' % patch_id_re
, rev
)
66 return None, None, m
.group('patch_id')
68 # Try path[@branch]//patch_id.
69 m
= re
.match(r
'^%s(%s)?%s$' %
(patch_re
, branch_re
, patch_id_re
), rev
)
71 return m
.group('patch'), m
.group('branch'), m
.group('patch_id')
74 m
= re
.match(r
'^%s(%s)?$' %
(patch_re
, branch_re
), rev
)
76 return m
.group('patch'), m
.group('branch'), None
78 # No, we can't parse that.
79 raise RevParseException
87 patch
, branch
, patch_id
= parse_rev(rev
)
91 series
= stack
.Series(branch
)
93 patch
= series
.get_current()
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
:
112 return git
.rev_parse(rev
+ '^{commit}')
114 def check_local_changes():
115 if git
.local_changes():
116 raise CmdException
, \
117 'local changes in the tree. Use "refresh" or "status --reset"'
119 def check_head_top_equal():
120 if not crt_series
.head_top_equal():
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')
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"'
132 def print_crt_patch(branch
= None):
134 patch
= crt_series
.get_current()
136 patch
= stack
.Series(branch
).get_current()
139 out
.info('Now at patch "%s"' % patch
)
141 out
.info('No patches applied')
143 def resolved(filename
, reset
= None):
145 reset_file
= filename
+ file_extensions()[reset
]
146 if os
.path
.isfile(reset_file
):
147 if os
.path
.isfile(filename
):
149 os
.rename(reset_file
, filename
)
151 git
.update_cache([filename
], force
= True)
153 for ext
in file_extensions().values():
155 if os
.path
.isfile(fn
):
158 def resolved_all(reset
= None):
159 conflicts
= git
.get_conflicts()
161 for filename
in conflicts
:
162 resolved(filename
, reset
)
163 os
.remove(os
.path
.join(basedir
.get(), 'conflicts'))
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
169 forwarded
= crt_series
.forward_patches(patches
)
171 out
.info('Fast-forwarded patches "%s" - "%s"'
172 %
(patches
[0], patches
[forwarded
- 1]))
174 out
.info('Fast-forwarded patch "%s"' % patches
[0])
176 names
= patches
[forwarded
:]
178 # check for patches merged upstream
179 if names
and check_merged
:
180 out
.start('Checking for patches merged upstream')
182 merged
= crt_series
.merged_patches(names
)
184 out
.done('%d found' %
len(merged
))
189 out
.start('Pushing patch "%s"' % p
)
192 crt_series
.push_empty_patch(p
)
193 out
.done('merged upstream')
195 modified
= crt_series
.push_patch(p
)
197 if crt_series
.empty_patch(p
):
198 out
.done('empty patch')
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.
208 if len(patches
) == 0:
209 out
.info('Nothing to push/pop')
212 if len(patches
) == 1:
213 out
.start('Popping patch "%s"' % p
)
215 out
.start('Popping patches "%s" - "%s"' %
(patches
[0], p
))
216 crt_series
.pop_patch(p
, keep
)
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.
226 for name
in patch_args
:
227 pair
= name
.split('..')
229 if p
and not p
in patch_list
:
230 raise CmdException
, 'Unknown patch name: %s' % p
236 # patch range [p1]..[p2]
239 first
= patch_list
.index(pair
[0])
244 last
= patch_list
.index(pair
[1]) + 1
248 # only cross the boundary if explicitly asked
250 boundary
= len(patch_list
)
260 last
= len(patch_list
)
263 pl
= patch_list
[first
:last
]
265 pl
= patch_list
[(last
- 1):(first
+ 1)]
268 raise CmdException
, 'Malformed patch name: %s' % name
272 raise CmdException
, 'Duplicate patch name: %s' % p
277 patches
= [p
for p
in patch_list
if p
in patches
]
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
285 address
= re
.sub('[\\\\"]', '\\\\\g<0>', address
)
286 str_list
= re
.findall('^(.*)\s*<(.*)>\s*$', address
)
288 str_list
= re
.findall('^(.*)\s*\((.*)\)\s*$', address
)
290 raise CmdException
, 'Incorrect "name <email>"/"email (name)" string: %s' % address
291 return ( str_list
[0][1], str_list
[0][0] )
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
299 address
= re
.sub('[\\\\"]', '\\\\\g<0>', address
)
300 str_list
= re
.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address
)
302 raise CmdException
, 'Incorrect "name <email> date" string: %s' % address
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.
310 def __address_or_alias(addr
):
313 if addr
.find('@') >= 0:
314 # it's an e-mail address
316 alias
= config
.get('mail.alias.'+addr
)
320 raise CmdException
, 'unknown e-mail alias: %s' % addr
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
])
326 def prepare_rebase(force
=None):
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'
335 applied
= crt_series
.get_applied()
337 out
.start('Popping all applied patches')
338 crt_series
.pop_patch(applied
[0])
343 if target
== git
.get_head():
344 out
.info('Already at "%s", no need for rebasing.' % target
)
346 command
= config
.get('branch.%s.stgit.rebasecmd' % git
.get_head_file()) \
347 or config
.get('stgit.rebasecmd')
350 out
.start('Rebasing to "%s"' % target
)
353 out
.start('Rebasing to the default target')
355 raise CmdException
, 'Default rebasing requires a target'
357 CmdRun(*(command
.split() + args
)).run()
359 git
.reset(tree_id
= git_id(target
))
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
367 push_patches(applied
, merged
)
370 # Patch description/e-mail/diff parsing
372 def __end_descr(line
):
373 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
374 re
.match('Index: ', line
)
376 def __split_descr_diff(string
):
377 """Return the description and the diff from the given string
382 for line
in string
.split('\n'):
384 if not __end_descr(line
):
391 return (descr
.rstrip(), diff
)
393 def __parse_description(descr
):
394 """Parse the patch description and return the new description and
395 author information (if any).
398 authname
= authemail
= authdate
= None
400 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
402 raise CmdException
, "Empty patch description"
405 end
= len(descr_lines
)
407 # Parse the patch header
408 for pos
in range(0, end
):
409 if not descr_lines
[pos
]:
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
)
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]
425 subject
= descr_lines
[pos
]
430 body
= reduce(lambda x
, y
: x
+ '\n' + y
, descr_lines
[lasthdr
:], '')
432 return (subject
+ body
, authname
, authemail
, authdate
)
435 """Parse the message object and return (description, authname,
436 authemail, authdate, diff)
438 from email
.Header
import decode_header
, make_header
440 def __decode_header(header
):
441 """Decode a qp-encoded e-mail header as per rfc2047"""
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')
450 if msg
.has_key('from'):
451 authname
, authemail
= name_email(__decode_header(msg
['from']))
453 authname
= authemail
= None
455 # '\n\t' can be found on multi-line headers
456 descr
= __decode_header(msg
['subject']).replace('\n\t', ' ')
457 authdate
= msg
['date']
459 # remove the '[*PATCH*]' expression in the subject
461 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
464 raise CmdException
, 'Subject: line not found'
466 # the rest of the message
468 for part
in msg
.walk():
469 if part
.get_content_type() == 'text/plain':
470 msg_text
+= part
.get_payload(decode
= True)
472 rem_descr
, diff
= __split_descr_diff(msg_text
)
474 descr
+= '\n\n' + rem_descr
476 # parse the description for author information
477 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
478 __parse_description(descr
)
480 authname
= descr_authname
482 authemail
= descr_authemail
484 authdate
= descr_authdate
486 return (descr
, authname
, authemail
, authdate
, diff
)
488 def parse_patch(fobj
):
489 """Parse the input file and return (description, authname,
490 authemail, authdate, diff)
492 descr
, diff
= __split_descr_diff(fobj
.read())
493 descr
, authname
, authemail
, authdate
= __parse_description(descr
)
495 # we don't yet have an agreed place for the creation date.
497 return (descr
, authname
, authemail
, authdate
, diff
)