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
, \
122 'local changes in the tree. Use "refresh" or "status --reset"'
124 def check_head_top_equal(crt_series
):
125 if not crt_series
.head_top_equal():
127 """HEAD and top are not the same. This can happen if you
128 modify a branch with git. "stg repair --help" explains
129 more about what to do next.""")
131 def check_conflicts():
132 if git
.get_conflicts():
133 raise CmdException
, \
134 'Unsolved conflicts. Please resolve them first or\n' \
135 ' revert the changes with "status --reset"'
137 def print_crt_patch(crt_series
, branch
= None):
139 patch
= crt_series
.get_current()
141 patch
= stack
.Series(branch
).get_current()
144 out
.info('Now at patch "%s"' % patch
)
146 out
.info('No patches applied')
148 def resolved_all(reset
= None):
149 conflicts
= git
.get_conflicts()
150 git
.resolved(conflicts
, reset
)
152 def push_patches(crt_series
, patches
, check_merged
= False):
153 """Push multiple patches onto the stack. This function is shared
154 between the push and pull commands
156 forwarded
= crt_series
.forward_patches(patches
)
158 out
.info('Fast-forwarded patches "%s" - "%s"'
159 %
(patches
[0], patches
[forwarded
- 1]))
161 out
.info('Fast-forwarded patch "%s"' % patches
[0])
163 names
= patches
[forwarded
:]
165 # check for patches merged upstream
166 if names
and check_merged
:
167 out
.start('Checking for patches merged upstream')
169 merged
= crt_series
.merged_patches(names
)
171 out
.done('%d found' %
len(merged
))
176 out
.start('Pushing patch "%s"' % p
)
179 crt_series
.push_empty_patch(p
)
180 out
.done('merged upstream')
182 modified
= crt_series
.push_patch(p
)
184 if crt_series
.empty_patch(p
):
185 out
.done('empty patch')
191 def pop_patches(crt_series
, patches
, keep
= False):
192 """Pop the patches in the list from the stack. It is assumed that
193 the patches are listed in the stack reverse order.
195 if len(patches
) == 0:
196 out
.info('Nothing to push/pop')
199 if len(patches
) == 1:
200 out
.start('Popping patch "%s"' % p
)
202 out
.start('Popping patches "%s" - "%s"' %
(patches
[0], p
))
203 crt_series
.pop_patch(p
, keep
)
206 def parse_patches(patch_args
, patch_list
, boundary
= 0, ordered
= False):
207 """Parse patch_args list for patch names in patch_list and return
208 a list. The names can be individual patches and/or in the
209 patch1..patch2 format.
213 for name
in patch_args
:
214 pair
= name
.split('..')
216 if p
and not p
in patch_list
:
217 raise CmdException
, 'Unknown patch name: %s' % p
223 # patch range [p1]..[p2]
226 first
= patch_list
.index(pair
[0])
231 last
= patch_list
.index(pair
[1]) + 1
235 # only cross the boundary if explicitly asked
237 boundary
= len(patch_list
)
247 last
= len(patch_list
)
250 pl
= patch_list
[first
:last
]
252 pl
= patch_list
[(last
- 1):(first
+ 1)]
255 raise CmdException
, 'Malformed patch name: %s' % name
259 raise CmdException
, 'Duplicate patch name: %s' % p
264 patches
= [p
for p
in patch_list
if p
in patches
]
268 def name_email(address
):
269 """Return a tuple consisting of the name and email parsed from a
270 standard 'name <email>' or 'email (name)' string
272 address
= re
.sub(r
'[\\"]', r
'\\\g<0>', address
)
273 str_list
= re
.findall('^(.*)\s*<(.*)>\s*$', address
)
275 str_list
= re
.findall('^(.*)\s*\((.*)\)\s*$', address
)
277 raise CmdException('Incorrect "name <email>"/"email (name)"'
278 ' string: %s' % address
)
279 return ( str_list
[0][1], str_list
[0][0] )
283 def name_email_date(address
):
284 """Return a tuple consisting of the name, email and date parsed
285 from a 'name <email> date' string
287 address
= re
.sub(r
'[\\"]', r
'\\\g<0>', address
)
288 str_list
= re
.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address
)
290 raise CmdException
, 'Incorrect "name <email> date" string: %s' % address
294 def address_or_alias(addr_str
):
295 """Return the address if it contains an e-mail address or look up
296 the aliases in the config files.
298 def __address_or_alias(addr
):
301 if addr
.find('@') >= 0:
302 # it's an e-mail address
304 alias
= config
.get('mail.alias.'+addr
)
308 raise CmdException
, 'unknown e-mail alias: %s' % addr
310 addr_list
= [__address_or_alias(addr
.strip())
311 for addr
in addr_str
.split(',')]
312 return ', '.join([addr
for addr
in addr_list
if addr
])
314 def prepare_rebase(crt_series
):
316 applied
= crt_series
.get_applied()
318 out
.start('Popping all applied patches')
319 crt_series
.pop_patch(applied
[0])
323 def rebase(crt_series
, target
):
325 tree_id
= git_id(crt_series
, target
)
327 # it might be that we use a custom rebase command with its own
330 if tree_id
== git
.get_head():
331 out
.info('Already at "%s", no need for rebasing.' % target
)
334 out
.start('Rebasing to "%s"' % target
)
336 out
.start('Rebasing to the default target')
337 git
.rebase(tree_id
= tree_id
)
340 def post_rebase(crt_series
, applied
, nopush
, merged
):
341 # memorize that we rebased to here
342 crt_series
._set_field('orig-base', git
.get_head())
343 # push the patches back
345 push_patches(crt_series
, applied
, merged
)
348 # Patch description/e-mail/diff parsing
350 def __end_descr(line
):
351 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
352 re
.match('Index: ', line
)
354 def __split_descr_diff(string
):
355 """Return the description and the diff from the given string
360 for line
in string
.split('\n'):
362 if not __end_descr(line
):
369 return (descr
.rstrip(), diff
)
371 def __parse_description(descr
):
372 """Parse the patch description and return the new description and
373 author information (if any).
376 authname
= authemail
= authdate
= None
378 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
380 raise CmdException
, "Empty patch description"
383 end
= len(descr_lines
)
385 # Parse the patch header
386 for pos
in range(0, end
):
387 if not descr_lines
[pos
]:
389 # check for a "From|Author:" line
390 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
391 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
392 authname
, authemail
= name_email(auth
)
395 # check for a "Date:" line
396 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
397 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
403 subject
= descr_lines
[pos
]
408 body
= reduce(lambda x
, y
: x
+ '\n' + y
, descr_lines
[lasthdr
:], '')
410 return (subject
+ body
, authname
, authemail
, authdate
)
413 """Parse the message object and return (description, authname,
414 authemail, authdate, diff)
416 from email
.Header
import decode_header
, make_header
418 def __decode_header(header
):
419 """Decode a qp-encoded e-mail header as per rfc2047"""
421 words_enc
= decode_header(header
)
422 hobj
= make_header(words_enc
)
423 except Exception, ex
:
424 raise CmdException
, 'header decoding error: %s' % str
(ex
)
425 return unicode(hobj
).encode('utf-8')
428 if msg
.has_key('from'):
429 authname
, authemail
= name_email(__decode_header(msg
['from']))
431 authname
= authemail
= None
433 # '\n\t' can be found on multi-line headers
434 descr
= __decode_header(msg
['subject']).replace('\n\t', ' ')
435 authdate
= msg
['date']
437 # remove the '[*PATCH*]' expression in the subject
439 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
442 raise CmdException
, 'Subject: line not found'
444 # the rest of the message
446 for part
in msg
.walk():
447 if part
.get_content_type() == 'text/plain':
448 msg_text
+= part
.get_payload(decode
= True)
450 rem_descr
, diff
= __split_descr_diff(msg_text
)
452 descr
+= '\n\n' + rem_descr
454 # parse the description for author information
455 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
456 __parse_description(descr
)
458 authname
= descr_authname
460 authemail
= descr_authemail
462 authdate
= descr_authdate
464 return (descr
, authname
, authemail
, authdate
, diff
)
466 def parse_patch(text
):
467 """Parse the input text and return (description, authname,
468 authemail, authdate, diff)
470 descr
, diff
= __split_descr_diff(text
)
471 descr
, authname
, authemail
, authdate
= __parse_description(descr
)
473 # we don't yet have an agreed place for the creation date.
475 return (descr
, authname
, authemail
, authdate
, diff
)
477 def readonly_constant_property(f
):
478 """Decorator that converts a function that computes a value to an
479 attribute that returns the value. The value is computed only once,
480 the first time it is accessed."""
482 n
= '__' + f
.__name__
483 if not hasattr(self
, n
):
484 setattr(self
, n
, f(self
))
485 return getattr(self
, n
)
486 return property(new_f
)
488 class DirectoryException(StgException
):
491 class _Directory(object):
492 def __init__(self
, needs_current_series
= True):
493 self
.needs_current_series
= needs_current_series
494 @readonly_constant_property
497 return Run('git', 'rev-parse', '--git-dir'
498 ).discard_stderr().output_one_line()
500 raise DirectoryException('No git repository found')
501 @readonly_constant_property
502 def __topdir_path(self
):
504 lines
= Run('git', 'rev-parse', '--show-cdup'
505 ).discard_stderr().output_lines()
508 elif len(lines
) == 1:
511 raise RunException('Too much output')
513 raise DirectoryException('No git repository found')
514 @readonly_constant_property
515 def is_inside_git_dir(self
):
516 return { 'true': True, 'false': False
517 }[Run('git', 'rev-parse', '--is-inside-git-dir'
519 @readonly_constant_property
520 def is_inside_worktree(self
):
521 return { 'true': True, 'false': False
522 }[Run('git', 'rev-parse', '--is-inside-work-tree'
524 def cd_to_topdir(self
):
525 os
.chdir(self
.__topdir_path
)
527 class DirectoryAnywhere(_Directory
):
531 class DirectoryHasRepository(_Directory
):
533 self
.git_dir
# might throw an exception
535 class DirectoryInWorktree(DirectoryHasRepository
):
537 DirectoryHasRepository
.setup(self
)
538 if not self
.is_inside_worktree
:
539 raise DirectoryException('Not inside a git worktree')
541 class DirectoryGotoToplevel(DirectoryInWorktree
):
543 DirectoryInWorktree
.setup(self
)
546 class DirectoryHasRepositoryLib(_Directory
):
547 """For commands that use the new infrastructure in stgit.lib.*."""
549 self
.needs_current_series
= False
551 # This will throw an exception if we don't have a repository.
552 self
.repository
= libstack
.Repository
.default()