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 stgit
.exception
import *
23 from stgit
.utils
import *
24 from stgit
.out
import *
25 from stgit
.run
import *
26 from stgit
import stack
, git
, basedir
27 from stgit
.config
import config
, file_extensions
28 from stgit
.lib
import stack
as libstack
29 from stgit
.lib
import git
as libgit
31 # Command exception class
32 class CmdException(StgException
):
37 """Parse a revision specification into its branch:patch parts.
40 branch
, patch
= rev
.split(':', 1)
45 return (branch
, patch
)
47 def git_id(crt_series
, rev
):
50 # TODO: remove this function once all the occurrences were converted
52 repository
= libstack
.Repository
.default()
53 return git_commit(rev
, repository
, crt_series
.get_name()).sha1
55 def git_commit(name
, repository
, branch_name
= None):
56 """Return the a Commit object if 'name' is a patch name or Git commit.
57 The patch names allowed are in the form '<branch>:<patch>' and can
58 be followed by standard symbols used by git rev-parse. If <patch>
59 is '{base}', it represents the bottom of the stack.
61 # Try a [branch:]patch name first
62 branch
, patch
= parse_rev(name
)
64 branch
= branch_name
or repository
.current_branch_name
67 if patch
.startswith('{base}'):
68 base_id
= repository
.get_stack(branch
).base
.sha1
69 return repository
.rev_parse(base_id
+
70 strip_prefix('{base}', patch
))
72 # Other combination of branch and patch
74 return repository
.rev_parse('patches/%s/%s' %
(branch
, patch
),
75 discard_stderr
= True)
76 except libgit
.RepositoryException
:
81 return repository
.rev_parse(name
, discard_stderr
= True)
82 except libgit
.RepositoryException
:
83 raise CmdException('%s: Unknown patch or revision name' % name
)
85 def check_local_changes():
86 if git
.local_changes():
87 raise CmdException('local changes in the tree. Use "refresh" or'
90 def check_head_top_equal(crt_series
):
91 if not crt_series
.head_top_equal():
92 raise CmdException('HEAD and top are not the same. This can happen'
93 ' if you modify a branch with git. "stg repair'
94 ' --help" explains more about what to do next.')
96 def check_conflicts():
97 if git
.get_conflicts():
98 raise CmdException('Unsolved conflicts. Please resolve them first'
99 ' or revert the changes with "status --reset"')
101 def print_crt_patch(crt_series
, branch
= None):
103 patch
= crt_series
.get_current()
105 patch
= stack
.Series(branch
).get_current()
108 out
.info('Now at patch "%s"' % patch
)
110 out
.info('No patches applied')
112 def resolved_all(reset
= None):
113 conflicts
= git
.get_conflicts()
114 git
.resolved(conflicts
, reset
)
116 def push_patches(crt_series
, patches
, check_merged
= False):
117 """Push multiple patches onto the stack. This function is shared
118 between the push and pull commands
120 forwarded
= crt_series
.forward_patches(patches
)
122 out
.info('Fast-forwarded patches "%s" - "%s"'
123 %
(patches
[0], patches
[forwarded
- 1]))
125 out
.info('Fast-forwarded patch "%s"' % patches
[0])
127 names
= patches
[forwarded
:]
129 # check for patches merged upstream
130 if names
and check_merged
:
131 out
.start('Checking for patches merged upstream')
133 merged
= crt_series
.merged_patches(names
)
135 out
.done('%d found' %
len(merged
))
140 out
.start('Pushing patch "%s"' % p
)
143 crt_series
.push_empty_patch(p
)
144 out
.done('merged upstream')
146 modified
= crt_series
.push_patch(p
)
148 if crt_series
.empty_patch(p
):
149 out
.done('empty patch')
155 def pop_patches(crt_series
, patches
, keep
= False):
156 """Pop the patches in the list from the stack. It is assumed that
157 the patches are listed in the stack reverse order.
159 if len(patches
) == 0:
160 out
.info('Nothing to push/pop')
163 if len(patches
) == 1:
164 out
.start('Popping patch "%s"' % p
)
166 out
.start('Popping patches "%s" - "%s"' %
(patches
[0], p
))
167 crt_series
.pop_patch(p
, keep
)
170 def parse_patches(patch_args
, patch_list
, boundary
= 0, ordered
= False):
171 """Parse patch_args list for patch names in patch_list and return
172 a list. The names can be individual patches and/or in the
173 patch1..patch2 format.
175 # in case it receives a tuple
176 patch_list
= list(patch_list
)
179 for name
in patch_args
:
180 pair
= name
.split('..')
182 if p
and not p
in patch_list
:
183 raise CmdException
, 'Unknown patch name: %s' % p
189 # patch range [p1]..[p2]
192 first
= patch_list
.index(pair
[0])
197 last
= patch_list
.index(pair
[1]) + 1
201 # only cross the boundary if explicitly asked
203 boundary
= len(patch_list
)
213 last
= len(patch_list
)
216 pl
= patch_list
[first
:last
]
218 pl
= patch_list
[(last
- 1):(first
+ 1)]
221 raise CmdException
, 'Malformed patch name: %s' % name
225 raise CmdException
, 'Duplicate patch name: %s' % p
230 patches
= [p
for p
in patch_list
if p
in patches
]
234 def name_email(address
):
235 p
= parse_name_email(address
)
239 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
242 def name_email_date(address
):
243 p
= parse_name_email_date(address
)
247 raise CmdException('Incorrect "name <email> date" string: %s' % address
)
249 def address_or_alias(addr_str
):
250 """Return the address if it contains an e-mail address or look up
251 the aliases in the config files.
253 def __address_or_alias(addr
):
256 if addr
.find('@') >= 0:
257 # it's an e-mail address
259 alias
= config
.get('mail.alias.'+addr
)
263 raise CmdException
, 'unknown e-mail alias: %s' % addr
265 addr_list
= [__address_or_alias(addr
.strip())
266 for addr
in addr_str
.split(',')]
267 return ', '.join([addr
for addr
in addr_list
if addr
])
269 def prepare_rebase(crt_series
):
271 applied
= crt_series
.get_applied()
273 out
.start('Popping all applied patches')
274 crt_series
.pop_patch(applied
[0])
278 def rebase(crt_series
, target
):
280 tree_id
= git_id(crt_series
, target
)
282 # it might be that we use a custom rebase command with its own
285 if tree_id
== git
.get_head():
286 out
.info('Already at "%s", no need for rebasing.' % target
)
289 out
.start('Rebasing to "%s"' % target
)
291 out
.start('Rebasing to the default target')
292 git
.rebase(tree_id
= tree_id
)
295 def post_rebase(crt_series
, applied
, nopush
, merged
):
296 # memorize that we rebased to here
297 crt_series
._set_field('orig-base', git
.get_head())
298 # push the patches back
300 push_patches(crt_series
, applied
, merged
)
303 # Patch description/e-mail/diff parsing
305 def __end_descr(line
):
306 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
307 re
.match('Index: ', line
)
309 def __split_descr_diff(string
):
310 """Return the description and the diff from the given string
315 for line
in string
.split('\n'):
317 if not __end_descr(line
):
324 return (descr
.rstrip(), diff
)
326 def __parse_description(descr
):
327 """Parse the patch description and return the new description and
328 author information (if any).
331 authname
= authemail
= authdate
= None
333 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
335 raise CmdException
, "Empty patch description"
338 end
= len(descr_lines
)
340 # Parse the patch header
341 for pos
in range(0, end
):
342 if not descr_lines
[pos
]:
344 # check for a "From|Author:" line
345 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
346 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
347 authname
, authemail
= name_email(auth
)
350 # check for a "Date:" line
351 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
352 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
358 subject
= descr_lines
[pos
]
363 body
= reduce(lambda x
, y
: x
+ '\n' + y
, descr_lines
[lasthdr
:], '')
365 return (subject
+ body
, authname
, authemail
, authdate
)
368 """Parse the message object and return (description, authname,
369 authemail, authdate, diff)
371 from email
.Header
import decode_header
, make_header
373 def __decode_header(header
):
374 """Decode a qp-encoded e-mail header as per rfc2047"""
376 words_enc
= decode_header(header
)
377 hobj
= make_header(words_enc
)
378 except Exception, ex
:
379 raise CmdException
, 'header decoding error: %s' % str
(ex
)
380 return unicode(hobj
).encode('utf-8')
383 if msg
.has_key('from'):
384 authname
, authemail
= name_email(__decode_header(msg
['from']))
386 authname
= authemail
= None
388 # '\n\t' can be found on multi-line headers
389 descr
= __decode_header(msg
['subject']).replace('\n\t', ' ')
390 authdate
= msg
['date']
392 # remove the '[*PATCH*]' expression in the subject
394 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
397 raise CmdException
, 'Subject: line not found'
399 # the rest of the message
401 for part
in msg
.walk():
402 if part
.get_content_type() == 'text/plain':
403 msg_text
+= part
.get_payload(decode
= True)
405 rem_descr
, diff
= __split_descr_diff(msg_text
)
407 descr
+= '\n\n' + rem_descr
409 # parse the description for author information
410 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
411 __parse_description(descr
)
413 authname
= descr_authname
415 authemail
= descr_authemail
417 authdate
= descr_authdate
419 return (descr
, authname
, authemail
, authdate
, diff
)
421 def parse_patch(text
):
422 """Parse the input text and return (description, authname,
423 authemail, authdate, diff)
425 descr
, diff
= __split_descr_diff(text
)
426 descr
, authname
, authemail
, authdate
= __parse_description(descr
)
428 # we don't yet have an agreed place for the creation date.
430 return (descr
, authname
, authemail
, authdate
, diff
)
432 def readonly_constant_property(f
):
433 """Decorator that converts a function that computes a value to an
434 attribute that returns the value. The value is computed only once,
435 the first time it is accessed."""
437 n
= '__' + f
.__name__
438 if not hasattr(self
, n
):
439 setattr(self
, n
, f(self
))
440 return getattr(self
, n
)
441 return property(new_f
)
443 class DirectoryException(StgException
):
446 class _Directory(object):
447 def __init__(self
, needs_current_series
= True):
448 self
.needs_current_series
= needs_current_series
449 @readonly_constant_property
452 return Run('git', 'rev-parse', '--git-dir'
453 ).discard_stderr().output_one_line()
455 raise DirectoryException('No git repository found')
456 @readonly_constant_property
457 def __topdir_path(self
):
459 lines
= Run('git', 'rev-parse', '--show-cdup'
460 ).discard_stderr().output_lines()
463 elif len(lines
) == 1:
466 raise RunException('Too much output')
468 raise DirectoryException('No git repository found')
469 @readonly_constant_property
470 def is_inside_git_dir(self
):
471 return { 'true': True, 'false': False
472 }[Run('git', 'rev-parse', '--is-inside-git-dir'
474 @readonly_constant_property
475 def is_inside_worktree(self
):
476 return { 'true': True, 'false': False
477 }[Run('git', 'rev-parse', '--is-inside-work-tree'
479 def cd_to_topdir(self
):
480 os
.chdir(self
.__topdir_path
)
482 class DirectoryAnywhere(_Directory
):
486 class DirectoryHasRepository(_Directory
):
488 self
.git_dir
# might throw an exception
490 class DirectoryInWorktree(DirectoryHasRepository
):
492 DirectoryHasRepository
.setup(self
)
493 if not self
.is_inside_worktree
:
494 raise DirectoryException('Not inside a git worktree')
496 class DirectoryGotoToplevel(DirectoryInWorktree
):
498 DirectoryInWorktree
.setup(self
)
501 class DirectoryHasRepositoryLib(_Directory
):
502 """For commands that use the new infrastructure in stgit.lib.*."""
504 self
.needs_current_series
= False
506 # This will throw an exception if we don't have a repository.
507 self
.repository
= libstack
.Repository
.default()