d040ee950b3b6a1e6034ea9b80ce36b8900e117d
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
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(filename
, reset
= None):
150 stage
= {'ancestor': 1, 'current': 2, 'patched': 3}[reset
]
151 Run('git', 'checkout-index', '--no-create', '--stage=%d' % stage
, '--',
152 filename
).no_output()
154 os
.utime(filename
, None) # update the access and modificatied times
156 def resolved_all(reset
= None):
157 conflicts
= git
.get_conflicts()
158 for filename
in conflicts
:
159 resolved(filename
, reset
)
161 def push_patches(crt_series
, 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_empty_patch(p
)
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(crt_series
, 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(crt_series
):
324 applied
= crt_series
.get_applied()
326 out
.start('Popping all applied patches')
327 crt_series
.pop_patch(applied
[0])
331 def rebase(crt_series
, target
):
333 tree_id
= git_id(crt_series
, target
)
335 # it might be that we use a custom rebase command with its own
338 if tree_id
== git
.get_head():
339 out
.info('Already at "%s", no need for rebasing.' % target
)
342 out
.start('Rebasing to "%s"' % target
)
344 out
.start('Rebasing to the default target')
345 git
.rebase(tree_id
= tree_id
)
348 def post_rebase(crt_series
, applied
, nopush
, merged
):
349 # memorize that we rebased to here
350 crt_series
._set_field('orig-base', git
.get_head())
351 # push the patches back
353 push_patches(crt_series
, applied
, merged
)
356 # Patch description/e-mail/diff parsing
358 def __end_descr(line
):
359 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
360 re
.match('Index: ', line
)
362 def __split_descr_diff(string
):
363 """Return the description and the diff from the given string
368 for line
in string
.split('\n'):
370 if not __end_descr(line
):
377 return (descr
.rstrip(), diff
)
379 def __parse_description(descr
):
380 """Parse the patch description and return the new description and
381 author information (if any).
384 authname
= authemail
= authdate
= None
386 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
388 raise CmdException
, "Empty patch description"
391 end
= len(descr_lines
)
393 # Parse the patch header
394 for pos
in range(0, end
):
395 if not descr_lines
[pos
]:
397 # check for a "From|Author:" line
398 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
399 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
400 authname
, authemail
= name_email(auth
)
403 # check for a "Date:" line
404 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
405 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
411 subject
= descr_lines
[pos
]
416 body
= reduce(lambda x
, y
: x
+ '\n' + y
, descr_lines
[lasthdr
:], '')
418 return (subject
+ body
, authname
, authemail
, authdate
)
421 """Parse the message object and return (description, authname,
422 authemail, authdate, diff)
424 from email
.Header
import decode_header
, make_header
426 def __decode_header(header
):
427 """Decode a qp-encoded e-mail header as per rfc2047"""
429 words_enc
= decode_header(header
)
430 hobj
= make_header(words_enc
)
431 except Exception, ex
:
432 raise CmdException
, 'header decoding error: %s' % str
(ex
)
433 return unicode(hobj
).encode('utf-8')
436 if msg
.has_key('from'):
437 authname
, authemail
= name_email(__decode_header(msg
['from']))
439 authname
= authemail
= None
441 # '\n\t' can be found on multi-line headers
442 descr
= __decode_header(msg
['subject']).replace('\n\t', ' ')
443 authdate
= msg
['date']
445 # remove the '[*PATCH*]' expression in the subject
447 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
450 raise CmdException
, 'Subject: line not found'
452 # the rest of the message
454 for part
in msg
.walk():
455 if part
.get_content_type() == 'text/plain':
456 msg_text
+= part
.get_payload(decode
= True)
458 rem_descr
, diff
= __split_descr_diff(msg_text
)
460 descr
+= '\n\n' + rem_descr
462 # parse the description for author information
463 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
464 __parse_description(descr
)
466 authname
= descr_authname
468 authemail
= descr_authemail
470 authdate
= descr_authdate
472 return (descr
, authname
, authemail
, authdate
, diff
)
474 def parse_patch(text
):
475 """Parse the input text and return (description, authname,
476 authemail, authdate, diff)
478 descr
, diff
= __split_descr_diff(text
)
479 descr
, authname
, authemail
, authdate
= __parse_description(descr
)
481 # we don't yet have an agreed place for the creation date.
483 return (descr
, authname
, authemail
, authdate
, diff
)
485 def readonly_constant_property(f
):
486 """Decorator that converts a function that computes a value to an
487 attribute that returns the value. The value is computed only once,
488 the first time it is accessed."""
490 n
= '__' + f
.__name__
491 if not hasattr(self
, n
):
492 setattr(self
, n
, f(self
))
493 return getattr(self
, n
)
494 return property(new_f
)
496 class DirectoryException(StgException
):
499 class _Directory(object):
500 def __init__(self
, needs_current_series
= True):
501 self
.needs_current_series
= needs_current_series
502 @readonly_constant_property
505 return Run('git', 'rev-parse', '--git-dir'
506 ).discard_stderr().output_one_line()
508 raise DirectoryException('No git repository found')
509 @readonly_constant_property
510 def __topdir_path(self
):
512 lines
= Run('git', 'rev-parse', '--show-cdup'
513 ).discard_stderr().output_lines()
516 elif len(lines
) == 1:
519 raise RunException('Too much output')
521 raise DirectoryException('No git repository found')
522 @readonly_constant_property
523 def is_inside_git_dir(self
):
524 return { 'true': True, 'false': False
525 }[Run('git', 'rev-parse', '--is-inside-git-dir'
527 @readonly_constant_property
528 def is_inside_worktree(self
):
529 return { 'true': True, 'false': False
530 }[Run('git', 'rev-parse', '--is-inside-work-tree'
532 def cd_to_topdir(self
):
533 os
.chdir(self
.__topdir_path
)
535 class DirectoryAnywhere(_Directory
):
539 class DirectoryHasRepository(_Directory
):
541 self
.git_dir
# might throw an exception
543 class DirectoryInWorktree(DirectoryHasRepository
):
545 DirectoryHasRepository
.setup(self
)
546 if not self
.is_inside_worktree
:
547 raise DirectoryException('Not inside a git worktree')
549 class DirectoryGotoToplevel(DirectoryInWorktree
):
551 DirectoryInWorktree
.setup(self
)