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 os
.path
.exists(os
.path
.join(basedir
.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 reset_file
= filename
+ file_extensions()[reset
]
151 if os
.path
.isfile(reset_file
):
152 if os
.path
.isfile(filename
):
154 os
.rename(reset_file
, filename
)
156 git
.update_cache([filename
], force
= True)
158 for ext
in file_extensions().values():
160 if os
.path
.isfile(fn
):
163 def resolved_all(reset
= None):
164 conflicts
= git
.get_conflicts()
166 for filename
in conflicts
:
167 resolved(filename
, reset
)
168 os
.remove(os
.path
.join(basedir
.get(), 'conflicts'))
170 def push_patches(crt_series
, patches
, check_merged
= False):
171 """Push multiple patches onto the stack. This function is shared
172 between the push and pull commands
174 forwarded
= crt_series
.forward_patches(patches
)
176 out
.info('Fast-forwarded patches "%s" - "%s"'
177 %
(patches
[0], patches
[forwarded
- 1]))
179 out
.info('Fast-forwarded patch "%s"' % patches
[0])
181 names
= patches
[forwarded
:]
183 # check for patches merged upstream
184 if names
and check_merged
:
185 out
.start('Checking for patches merged upstream')
187 merged
= crt_series
.merged_patches(names
)
189 out
.done('%d found' %
len(merged
))
194 out
.start('Pushing patch "%s"' % p
)
197 crt_series
.push_empty_patch(p
)
198 out
.done('merged upstream')
200 modified
= crt_series
.push_patch(p
)
202 if crt_series
.empty_patch(p
):
203 out
.done('empty patch')
209 def pop_patches(crt_series
, patches
, keep
= False):
210 """Pop the patches in the list from the stack. It is assumed that
211 the patches are listed in the stack reverse order.
213 if len(patches
) == 0:
214 out
.info('Nothing to push/pop')
217 if len(patches
) == 1:
218 out
.start('Popping patch "%s"' % p
)
220 out
.start('Popping patches "%s" - "%s"' %
(patches
[0], p
))
221 crt_series
.pop_patch(p
, keep
)
224 def parse_patches(patch_args
, patch_list
, boundary
= 0, ordered
= False):
225 """Parse patch_args list for patch names in patch_list and return
226 a list. The names can be individual patches and/or in the
227 patch1..patch2 format.
231 for name
in patch_args
:
232 pair
= name
.split('..')
234 if p
and not p
in patch_list
:
235 raise CmdException
, 'Unknown patch name: %s' % p
241 # patch range [p1]..[p2]
244 first
= patch_list
.index(pair
[0])
249 last
= patch_list
.index(pair
[1]) + 1
253 # only cross the boundary if explicitly asked
255 boundary
= len(patch_list
)
265 last
= len(patch_list
)
268 pl
= patch_list
[first
:last
]
270 pl
= patch_list
[(last
- 1):(first
+ 1)]
273 raise CmdException
, 'Malformed patch name: %s' % name
277 raise CmdException
, 'Duplicate patch name: %s' % p
282 patches
= [p
for p
in patch_list
if p
in patches
]
286 def name_email(address
):
287 """Return a tuple consisting of the name and email parsed from a
288 standard 'name <email>' or 'email (name)' string
290 address
= re
.sub('[\\\\"]', '\\\\\g<0>', address
)
291 str_list
= re
.findall('^(.*)\s*<(.*)>\s*$', address
)
293 str_list
= re
.findall('^(.*)\s*\((.*)\)\s*$', address
)
295 raise CmdException
, 'Incorrect "name <email>"/"email (name)" string: %s' % address
296 return ( str_list
[0][1], str_list
[0][0] )
300 def name_email_date(address
):
301 """Return a tuple consisting of the name, email and date parsed
302 from a 'name <email> date' string
304 address
= re
.sub('[\\\\"]', '\\\\\g<0>', address
)
305 str_list
= re
.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address
)
307 raise CmdException
, 'Incorrect "name <email> date" string: %s' % address
311 def address_or_alias(addr_str
):
312 """Return the address if it contains an e-mail address or look up
313 the aliases in the config files.
315 def __address_or_alias(addr
):
318 if addr
.find('@') >= 0:
319 # it's an e-mail address
321 alias
= config
.get('mail.alias.'+addr
)
325 raise CmdException
, 'unknown e-mail alias: %s' % addr
327 addr_list
= [__address_or_alias(addr
.strip())
328 for addr
in addr_str
.split(',')]
329 return ', '.join([addr
for addr
in addr_list
if addr
])
331 def prepare_rebase(crt_series
):
333 applied
= crt_series
.get_applied()
335 out
.start('Popping all applied patches')
336 crt_series
.pop_patch(applied
[0])
340 def rebase(crt_series
, target
):
342 tree_id
= git_id(crt_series
, target
)
344 # it might be that we use a custom rebase command with its own
347 if tree_id
== git
.get_head():
348 out
.info('Already at "%s", no need for rebasing.' % target
)
351 out
.start('Rebasing to "%s"' % target
)
353 out
.start('Rebasing to the default target')
354 git
.rebase(tree_id
= tree_id
)
357 def post_rebase(crt_series
, applied
, nopush
, merged
):
358 # memorize that we rebased to here
359 crt_series
._set_field('orig-base', git
.get_head())
360 # push the patches back
362 push_patches(crt_series
, applied
, merged
)
365 # Patch description/e-mail/diff parsing
367 def __end_descr(line
):
368 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
369 re
.match('Index: ', line
)
371 def __split_descr_diff(string
):
372 """Return the description and the diff from the given string
377 for line
in string
.split('\n'):
379 if not __end_descr(line
):
386 return (descr
.rstrip(), diff
)
388 def __parse_description(descr
):
389 """Parse the patch description and return the new description and
390 author information (if any).
393 authname
= authemail
= authdate
= None
395 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
397 raise CmdException
, "Empty patch description"
400 end
= len(descr_lines
)
402 # Parse the patch header
403 for pos
in range(0, end
):
404 if not descr_lines
[pos
]:
406 # check for a "From|Author:" line
407 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
408 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
409 authname
, authemail
= name_email(auth
)
412 # check for a "Date:" line
413 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
414 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
420 subject
= descr_lines
[pos
]
425 body
= reduce(lambda x
, y
: x
+ '\n' + y
, descr_lines
[lasthdr
:], '')
427 return (subject
+ body
, authname
, authemail
, authdate
)
430 """Parse the message object and return (description, authname,
431 authemail, authdate, diff)
433 from email
.Header
import decode_header
, make_header
435 def __decode_header(header
):
436 """Decode a qp-encoded e-mail header as per rfc2047"""
438 words_enc
= decode_header(header
)
439 hobj
= make_header(words_enc
)
440 except Exception, ex
:
441 raise CmdException
, 'header decoding error: %s' % str
(ex
)
442 return unicode(hobj
).encode('utf-8')
445 if msg
.has_key('from'):
446 authname
, authemail
= name_email(__decode_header(msg
['from']))
448 authname
= authemail
= None
450 # '\n\t' can be found on multi-line headers
451 descr
= __decode_header(msg
['subject']).replace('\n\t', ' ')
452 authdate
= msg
['date']
454 # remove the '[*PATCH*]' expression in the subject
456 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
459 raise CmdException
, 'Subject: line not found'
461 # the rest of the message
463 for part
in msg
.walk():
464 if part
.get_content_type() == 'text/plain':
465 msg_text
+= part
.get_payload(decode
= True)
467 rem_descr
, diff
= __split_descr_diff(msg_text
)
469 descr
+= '\n\n' + rem_descr
471 # parse the description for author information
472 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
473 __parse_description(descr
)
475 authname
= descr_authname
477 authemail
= descr_authemail
479 authdate
= descr_authdate
481 return (descr
, authname
, authemail
, authdate
, diff
)
483 def parse_patch(fobj
):
484 """Parse the input file and return (description, authname,
485 authemail, authdate, diff)
487 descr
, diff
= __split_descr_diff(fobj
.read())
488 descr
, authname
, authemail
, authdate
= __parse_description(descr
)
490 # we don't yet have an agreed place for the creation date.
492 return (descr
, authname
, authemail
, authdate
, diff
)
494 def readonly_constant_property(f
):
495 """Decorator that converts a function that computes a value to an
496 attribute that returns the value. The value is computed only once,
497 the first time it is accessed."""
499 n
= '__' + f
.__name__
500 if not hasattr(self
, n
):
501 setattr(self
, n
, f(self
))
502 return getattr(self
, n
)
503 return property(new_f
)
505 class DirectoryException(StgException
):
508 class _Directory(object):
509 def __init__(self
, needs_current_series
= True):
510 self
.needs_current_series
= needs_current_series
511 @readonly_constant_property
514 return Run('git', 'rev-parse', '--git-dir'
515 ).discard_stderr().output_one_line()
517 raise DirectoryException('No git repository found')
518 @readonly_constant_property
519 def __topdir_path(self
):
521 lines
= Run('git', 'rev-parse', '--show-cdup'
522 ).discard_stderr().output_lines()
525 elif len(lines
) == 1:
528 raise RunException('Too much output')
530 raise DirectoryException('No git repository found')
531 @readonly_constant_property
532 def is_inside_git_dir(self
):
533 return { 'true': True, 'false': False
534 }[Run('git', 'rev-parse', '--is-inside-git-dir'
536 @readonly_constant_property
537 def is_inside_worktree(self
):
538 return { 'true': True, 'false': False
539 }[Run('git', 'rev-parse', '--is-inside-work-tree'
541 def cd_to_topdir(self
):
542 os
.chdir(self
.__topdir_path
)
544 class DirectoryAnywhere(_Directory
):
548 class DirectoryHasRepository(_Directory
):
550 self
.git_dir
# might throw an exception
552 class DirectoryInWorktree(DirectoryHasRepository
):
554 DirectoryHasRepository
.setup(self
)
555 if not self
.is_inside_worktree
:
556 raise DirectoryException('Not inside a git worktree')
558 class DirectoryGotoToplevel(DirectoryInWorktree
):
560 DirectoryInWorktree
.setup(self
)