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
.exception
import *
25 from stgit
.utils
import *
26 from stgit
.out
import *
27 from stgit
.run
import *
28 from stgit
import stack
, git
, basedir
29 from stgit
.config
import config
, file_extensions
30 from stgit
.lib
import stack
as libstack
32 # Command exception class
33 class CmdException(StgException
):
37 class RevParseException(StgException
):
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 if '/' in ''.join(git
.get_heads()):
46 # We have branch names with / in them.
47 branch_chars
= r
'[^@]'
50 # No / in branch names.
51 branch_chars
= r
'[^@/]'
52 patch_id_mark
= r
'(/|//)'
53 patch_re
= r
'(?P<patch>[^@/]+)'
54 branch_re
= r
'@(?P<branch>%s+)' % branch_chars
55 patch_id_re
= r
'%s(?P<patch_id>[a-z.]*)' % patch_id_mark
58 m
= re
.match(r
'^%s$' % patch_id_re
, rev
)
60 return None, None, m
.group('patch_id')
62 # Try path[@branch]//patch_id.
63 m
= re
.match(r
'^%s(%s)?%s$' %
(patch_re
, branch_re
, patch_id_re
), rev
)
65 return m
.group('patch'), m
.group('branch'), m
.group('patch_id')
68 m
= re
.match(r
'^%s(%s)?$' %
(patch_re
, branch_re
), rev
)
70 return m
.group('patch'), m
.group('branch'), None
72 # No, we can't parse that.
73 raise RevParseException
75 def git_id(crt_series
, rev
):
81 # try a GIT revision first
83 return git
.rev_parse(rev
+ '^{commit}')
84 except git
.GitException
:
87 # try an StGIT patch name
89 patch
, branch
, patch_id
= parse_rev(rev
)
93 series
= stack
.Series(branch
)
95 patch
= series
.get_current()
97 raise CmdException
, 'No patches applied'
98 if patch
in series
.get_applied() or patch
in series
.get_unapplied() or \
99 patch
in series
.get_hidden():
100 if patch_id
in ['top', '', None]:
101 return series
.get_patch(patch
).get_top()
102 elif patch_id
== 'bottom':
103 return series
.get_patch(patch
).get_bottom()
104 elif patch_id
== 'top.old':
105 return series
.get_patch(patch
).get_old_top()
106 elif patch_id
== 'bottom.old':
107 return series
.get_patch(patch
).get_old_bottom()
108 elif patch_id
== 'log':
109 return series
.get_patch(patch
).get_log()
110 if patch
== 'base' and patch_id
== None:
111 return series
.get_base()
112 except RevParseException
:
114 except stack
.StackException
:
117 raise CmdException
, 'Unknown patch or revision: %s' % rev
119 def check_local_changes():
120 if git
.local_changes():
121 raise CmdException('local changes in the tree. Use "refresh" or'
124 def check_head_top_equal(crt_series
):
125 if not crt_series
.head_top_equal():
126 raise CmdException('HEAD and top are not the same. This can happen'
127 ' if you modify a branch with git. "stg repair'
128 ' --help" explains more about what to do next.')
130 def check_conflicts():
131 if git
.get_conflicts():
132 raise CmdException('Unsolved conflicts. Please resolve them first'
133 ' or revert the changes with "status --reset"')
135 def print_crt_patch(crt_series
, branch
= None):
137 patch
= crt_series
.get_current()
139 patch
= stack
.Series(branch
).get_current()
142 out
.info('Now at patch "%s"' % patch
)
144 out
.info('No patches applied')
146 def resolved_all(reset
= None):
147 conflicts
= git
.get_conflicts()
148 git
.resolved(conflicts
, reset
)
150 def push_patches(crt_series
, patches
, check_merged
= False):
151 """Push multiple patches onto the stack. This function is shared
152 between the push and pull commands
154 forwarded
= crt_series
.forward_patches(patches
)
156 out
.info('Fast-forwarded patches "%s" - "%s"'
157 %
(patches
[0], patches
[forwarded
- 1]))
159 out
.info('Fast-forwarded patch "%s"' % patches
[0])
161 names
= patches
[forwarded
:]
163 # check for patches merged upstream
164 if names
and check_merged
:
165 out
.start('Checking for patches merged upstream')
167 merged
= crt_series
.merged_patches(names
)
169 out
.done('%d found' %
len(merged
))
174 out
.start('Pushing patch "%s"' % p
)
177 crt_series
.push_empty_patch(p
)
178 out
.done('merged upstream')
180 modified
= crt_series
.push_patch(p
)
182 if crt_series
.empty_patch(p
):
183 out
.done('empty patch')
189 def pop_patches(crt_series
, patches
, keep
= False):
190 """Pop the patches in the list from the stack. It is assumed that
191 the patches are listed in the stack reverse order.
193 if len(patches
) == 0:
194 out
.info('Nothing to push/pop')
197 if len(patches
) == 1:
198 out
.start('Popping patch "%s"' % p
)
200 out
.start('Popping patches "%s" - "%s"' %
(patches
[0], p
))
201 crt_series
.pop_patch(p
, keep
)
204 def parse_patches(patch_args
, patch_list
, boundary
= 0, ordered
= False):
205 """Parse patch_args list for patch names in patch_list and return
206 a list. The names can be individual patches and/or in the
207 patch1..patch2 format.
211 for name
in patch_args
:
212 pair
= name
.split('..')
214 if p
and not p
in patch_list
:
215 raise CmdException
, 'Unknown patch name: %s' % p
221 # patch range [p1]..[p2]
224 first
= patch_list
.index(pair
[0])
229 last
= patch_list
.index(pair
[1]) + 1
233 # only cross the boundary if explicitly asked
235 boundary
= len(patch_list
)
245 last
= len(patch_list
)
248 pl
= patch_list
[first
:last
]
250 pl
= patch_list
[(last
- 1):(first
+ 1)]
253 raise CmdException
, 'Malformed patch name: %s' % name
257 raise CmdException
, 'Duplicate patch name: %s' % p
262 patches
= [p
for p
in patch_list
if p
in patches
]
266 def name_email(address
):
267 p
= parse_name_email(address
)
271 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
274 def name_email_date(address
):
275 p
= parse_name_email_date(address
)
279 raise CmdException('Incorrect "name <email> date" string: %s' % address
)
281 def address_or_alias(addr_str
):
282 """Return the address if it contains an e-mail address or look up
283 the aliases in the config files.
285 def __address_or_alias(addr
):
288 if addr
.find('@') >= 0:
289 # it's an e-mail address
291 alias
= config
.get('mail.alias.'+addr
)
295 raise CmdException
, 'unknown e-mail alias: %s' % addr
297 addr_list
= [__address_or_alias(addr
.strip())
298 for addr
in addr_str
.split(',')]
299 return ', '.join([addr
for addr
in addr_list
if addr
])
301 def prepare_rebase(crt_series
):
303 applied
= crt_series
.get_applied()
305 out
.start('Popping all applied patches')
306 crt_series
.pop_patch(applied
[0])
310 def rebase(crt_series
, target
):
312 tree_id
= git_id(crt_series
, target
)
314 # it might be that we use a custom rebase command with its own
317 if tree_id
== git
.get_head():
318 out
.info('Already at "%s", no need for rebasing.' % target
)
321 out
.start('Rebasing to "%s"' % target
)
323 out
.start('Rebasing to the default target')
324 git
.rebase(tree_id
= tree_id
)
327 def post_rebase(crt_series
, applied
, nopush
, merged
):
328 # memorize that we rebased to here
329 crt_series
._set_field('orig-base', git
.get_head())
330 # push the patches back
332 push_patches(crt_series
, applied
, merged
)
335 # Patch description/e-mail/diff parsing
337 def __end_descr(line
):
338 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
339 re
.match('Index: ', line
)
341 def __split_descr_diff(string
):
342 """Return the description and the diff from the given string
347 for line
in string
.split('\n'):
349 if not __end_descr(line
):
356 return (descr
.rstrip(), diff
)
358 def __parse_description(descr
):
359 """Parse the patch description and return the new description and
360 author information (if any).
363 authname
= authemail
= authdate
= None
365 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
367 raise CmdException
, "Empty patch description"
370 end
= len(descr_lines
)
372 # Parse the patch header
373 for pos
in range(0, end
):
374 if not descr_lines
[pos
]:
376 # check for a "From|Author:" line
377 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
378 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
379 authname
, authemail
= name_email(auth
)
382 # check for a "Date:" line
383 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
384 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
390 subject
= descr_lines
[pos
]
395 body
= reduce(lambda x
, y
: x
+ '\n' + y
, descr_lines
[lasthdr
:], '')
397 return (subject
+ body
, authname
, authemail
, authdate
)
400 """Parse the message object and return (description, authname,
401 authemail, authdate, diff)
403 from email
.Header
import decode_header
, make_header
405 def __decode_header(header
):
406 """Decode a qp-encoded e-mail header as per rfc2047"""
408 words_enc
= decode_header(header
)
409 hobj
= make_header(words_enc
)
410 except Exception, ex
:
411 raise CmdException
, 'header decoding error: %s' % str
(ex
)
412 return unicode(hobj
).encode('utf-8')
415 if msg
.has_key('from'):
416 authname
, authemail
= name_email(__decode_header(msg
['from']))
418 authname
= authemail
= None
420 # '\n\t' can be found on multi-line headers
421 descr
= __decode_header(msg
['subject']).replace('\n\t', ' ')
422 authdate
= msg
['date']
424 # remove the '[*PATCH*]' expression in the subject
426 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
429 raise CmdException
, 'Subject: line not found'
431 # the rest of the message
433 for part
in msg
.walk():
434 if part
.get_content_type() == 'text/plain':
435 msg_text
+= part
.get_payload(decode
= True)
437 rem_descr
, diff
= __split_descr_diff(msg_text
)
439 descr
+= '\n\n' + rem_descr
441 # parse the description for author information
442 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
443 __parse_description(descr
)
445 authname
= descr_authname
447 authemail
= descr_authemail
449 authdate
= descr_authdate
451 return (descr
, authname
, authemail
, authdate
, diff
)
453 def parse_patch(text
):
454 """Parse the input text and return (description, authname,
455 authemail, authdate, diff)
457 descr
, diff
= __split_descr_diff(text
)
458 descr
, authname
, authemail
, authdate
= __parse_description(descr
)
460 # we don't yet have an agreed place for the creation date.
462 return (descr
, authname
, authemail
, authdate
, diff
)
464 def readonly_constant_property(f
):
465 """Decorator that converts a function that computes a value to an
466 attribute that returns the value. The value is computed only once,
467 the first time it is accessed."""
469 n
= '__' + f
.__name__
470 if not hasattr(self
, n
):
471 setattr(self
, n
, f(self
))
472 return getattr(self
, n
)
473 return property(new_f
)
475 class DirectoryException(StgException
):
478 class _Directory(object):
479 def __init__(self
, needs_current_series
= True):
480 self
.needs_current_series
= needs_current_series
481 @readonly_constant_property
484 return Run('git', 'rev-parse', '--git-dir'
485 ).discard_stderr().output_one_line()
487 raise DirectoryException('No git repository found')
488 @readonly_constant_property
489 def __topdir_path(self
):
491 lines
= Run('git', 'rev-parse', '--show-cdup'
492 ).discard_stderr().output_lines()
495 elif len(lines
) == 1:
498 raise RunException('Too much output')
500 raise DirectoryException('No git repository found')
501 @readonly_constant_property
502 def is_inside_git_dir(self
):
503 return { 'true': True, 'false': False
504 }[Run('git', 'rev-parse', '--is-inside-git-dir'
506 @readonly_constant_property
507 def is_inside_worktree(self
):
508 return { 'true': True, 'false': False
509 }[Run('git', 'rev-parse', '--is-inside-work-tree'
511 def cd_to_topdir(self
):
512 os
.chdir(self
.__topdir_path
)
514 class DirectoryAnywhere(_Directory
):
518 class DirectoryHasRepository(_Directory
):
520 self
.git_dir
# might throw an exception
522 class DirectoryInWorktree(DirectoryHasRepository
):
524 DirectoryHasRepository
.setup(self
)
525 if not self
.is_inside_worktree
:
526 raise DirectoryException('Not inside a git worktree')
528 class DirectoryGotoToplevel(DirectoryInWorktree
):
530 DirectoryInWorktree
.setup(self
)
533 class DirectoryHasRepositoryLib(_Directory
):
534 """For commands that use the new infrastructure in stgit.lib.*."""
536 self
.needs_current_series
= False
538 # This will throw an exception if we don't have a repository.
539 self
.repository
= libstack
.Repository
.default()