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, see http://www.gnu.org/licenses/.
20 import sys
, os
, os
.path
, re
, email
.Utils
21 from stgit
.exception
import *
22 from stgit
.utils
import *
23 from stgit
.out
import *
24 from stgit
.run
import *
25 from stgit
import stack
, git
, basedir
26 from stgit
.config
import config
, file_extensions
27 from stgit
.lib
import stack
as libstack
28 from stgit
.lib
import git
as libgit
29 from stgit
.lib
import log
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 get_public_ref(branch_name
):
56 """Return the public ref of the branch."""
57 public_ref
= config
.get('branch.%s.public' % branch_name
)
59 public_ref
= 'refs/heads/%s.public' % branch_name
62 def git_commit(name
, repository
, branch_name
= None):
63 """Return the a Commit object if 'name' is a patch name or Git commit.
64 The patch names allowed are in the form '<branch>:<patch>' and can
65 be followed by standard symbols used by git rev-parse. If <patch>
66 is '{base}', it represents the bottom of the stack. If <patch> is
67 {public}, it represents the public branch corresponding to the stack as
68 described in the 'publish' command.
70 # Try a [branch:]patch name first
71 branch
, patch
= parse_rev(name
)
73 branch
= branch_name
or repository
.current_branch_name
76 if patch
.startswith('{base}'):
77 base_id
= repository
.get_stack(branch
).base
.sha1
78 return repository
.rev_parse(base_id
+
79 strip_prefix('{base}', patch
))
80 elif patch
.startswith('{public}'):
81 public_ref
= get_public_ref(branch
)
82 return repository
.rev_parse(public_ref
+
83 strip_prefix('{public}', patch
),
84 discard_stderr
= True)
86 # Other combination of branch and patch
88 return repository
.rev_parse('patches/%s/%s' % (branch
, patch
),
89 discard_stderr
= True)
90 except libgit
.RepositoryException
:
95 return repository
.rev_parse(name
, discard_stderr
= True)
96 except libgit
.RepositoryException
:
97 raise CmdException('%s: Unknown patch or revision name' % name
)
99 def color_diff_flags():
100 """Return the git flags for coloured diff output if the configuration and
102 stdout_is_tty
= (sys
.stdout
.isatty() and 'true') or 'false'
103 if config
.get_colorbool('color.diff', stdout_is_tty
) == 'true':
108 def check_local_changes():
109 if git
.local_changes():
110 raise CmdException('local changes in the tree. Use "refresh" or'
113 def check_head_top_equal(crt_series
):
114 if not crt_series
.head_top_equal():
115 raise CmdException('HEAD and top are not the same. This can happen'
116 ' if you modify a branch with git. "stg repair'
117 ' --help" explains more about what to do next.')
119 def check_conflicts():
120 if git
.get_conflicts():
121 raise CmdException('Unsolved conflicts. Please fix the conflicts'
122 ' then use "git add --update <files>" or revert the'
123 ' changes with "reset --hard".')
125 def print_crt_patch(crt_series
, branch
= None):
127 patch
= crt_series
.get_current()
129 patch
= stack
.Series(branch
).get_current()
132 out
.info('Now at patch "%s"' % patch
)
134 out
.info('No patches applied')
136 def resolved_all(reset
= None):
137 conflicts
= git
.get_conflicts()
138 git
.resolved(conflicts
, reset
)
140 def push_patches(crt_series
, patches
, check_merged
= False):
141 """Push multiple patches onto the stack. This function is shared
142 between the push and pull commands
144 forwarded
= crt_series
.forward_patches(patches
)
146 out
.info('Fast-forwarded patches "%s" - "%s"'
147 % (patches
[0], patches
[forwarded
- 1]))
149 out
.info('Fast-forwarded patch "%s"' % patches
[0])
151 names
= patches
[forwarded
:]
153 # check for patches merged upstream
154 if names
and check_merged
:
155 out
.start('Checking for patches merged upstream')
157 merged
= crt_series
.merged_patches(names
)
159 out
.done('%d found' % len(merged
))
164 out
.start('Pushing patch "%s"' % p
)
167 crt_series
.push_empty_patch(p
)
168 out
.done('merged upstream')
170 modified
= crt_series
.push_patch(p
)
172 if crt_series
.empty_patch(p
):
173 out
.done('empty patch')
179 def pop_patches(crt_series
, patches
, keep
= False):
180 """Pop the patches in the list from the stack. It is assumed that
181 the patches are listed in the stack reverse order.
183 if len(patches
) == 0:
184 out
.info('Nothing to push/pop')
187 if len(patches
) == 1:
188 out
.start('Popping patch "%s"' % p
)
190 out
.start('Popping patches "%s" - "%s"' % (patches
[0], p
))
191 crt_series
.pop_patch(p
, keep
)
194 def get_patch_from_list(part_name
, patch_list
):
195 candidates
= [full
for full
in patch_list
if str.find(full
, part_name
) != -1]
196 if len(candidates
) >= 2:
197 out
.info('Possible patches:\n %s' % '\n '.join(candidates
))
198 raise CmdException
, 'Ambiguous patch name "%s"' % part_name
199 elif len(candidates
) == 1:
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.
209 # in case it receives a tuple
210 patch_list
= list(patch_list
)
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 p
= email
.Utils
.parseaddr(address
)
273 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
276 def name_email_date(address
):
277 p
= parse_name_email_date(address
)
281 raise CmdException('Incorrect "name <email> date" string: %s' % address
)
283 def address_or_alias(addr_pair
):
284 """Return a name-email tuple the e-mail address is valid or look up
285 the aliases in the config files.
289 # it's an e-mail address
291 alias
= config
.get('mail.alias.' + addr
)
294 return name_email(alias
)
295 raise CmdException
, 'unknown e-mail alias: %s' % addr
297 def prepare_rebase(crt_series
):
299 applied
= crt_series
.get_applied()
301 out
.start('Popping all applied patches')
302 crt_series
.pop_patch(applied
[0])
306 def rebase(crt_series
, target
):
308 tree_id
= git_id(crt_series
, target
)
310 # it might be that we use a custom rebase command with its own
314 out
.start('Rebasing to "%s"' % target
)
316 out
.start('Rebasing to the default target')
317 git
.rebase(tree_id
= tree_id
)
320 def post_rebase(crt_series
, applied
, nopush
, merged
):
321 # memorize that we rebased to here
322 crt_series
._set
_field
('orig-base', git
.get_head())
323 # push the patches back
325 push_patches(crt_series
, applied
, merged
)
328 # Patch description/e-mail/diff parsing
330 def __end_descr(line
):
331 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
332 re
.match('Index: ', line
) or re
.match('--- \w', line
)
334 def __split_descr_diff(string
):
335 """Return the description and the diff from the given string
340 for line
in string
.split('\n'):
342 if not __end_descr(line
):
349 return (descr
.rstrip(), diff
)
351 def __parse_description(descr
):
352 """Parse the patch description and return the new description and
353 author information (if any).
356 authname
= authemail
= authdate
= None
358 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
360 raise CmdException
, "Empty patch description"
363 end
= len(descr_lines
)
366 # Parse the patch header
367 for pos
in range(0, end
):
368 if not descr_lines
[pos
]:
370 # check for a "From|Author:" line
371 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
372 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
373 authname
, authemail
= name_email(auth
)
376 # check for a "Date:" line
377 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
378 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
384 subject
= descr_lines
[pos
][descr_strip
:]
385 if re
.match('commit [\da-f]{40}$', subject
):
386 # 'git show' output, look for the real subject
393 body
= '\n' + '\n'.join(l
[descr_strip
:] for l
in descr_lines
[lasthdr
:])
395 return (subject
+ body
, authname
, authemail
, authdate
)
398 """Parse the message object and return (description, authname,
399 authemail, authdate, diff)
401 from email
.Header
import decode_header
, make_header
403 def __decode_header(header
):
404 """Decode a qp-encoded e-mail header as per rfc2047"""
406 words_enc
= decode_header(header
)
407 hobj
= make_header(words_enc
)
408 except Exception, ex
:
409 raise CmdException
, 'header decoding error: %s' % str(ex
)
410 return unicode(hobj
).encode('utf-8')
413 if msg
.has_key('from'):
414 authname
, authemail
= name_email(__decode_header(msg
['from']))
416 authname
= authemail
= None
418 # '\n\t' can be found on multi-line headers
419 descr
= __decode_header(msg
['subject'])
420 descr
= re
.sub('\n[ \t]*', ' ', descr
)
421 authdate
= msg
['date']
423 # remove the '[*PATCH*]' expression in the subject
425 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
428 raise CmdException
, 'Subject: line not found'
430 # the rest of the message
432 for part
in msg
.walk():
433 if part
.get_content_type() in ['text/plain',
434 'application/octet-stream']:
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
, contains_diff
):
454 """Parse the input text and return (description, authname,
455 authemail, authdate, diff)
458 (text
, diff
) = __split_descr_diff(text
)
461 (descr
, authname
, authemail
, authdate
) = __parse_description(text
)
463 # we don't yet have an agreed place for the creation date.
465 return (descr
, authname
, authemail
, authdate
, diff
)
467 def readonly_constant_property(f
):
468 """Decorator that converts a function that computes a value to an
469 attribute that returns the value. The value is computed only once,
470 the first time it is accessed."""
472 n
= '__' + f
.__name
__
473 if not hasattr(self
, n
):
474 setattr(self
, n
, f(self
))
475 return getattr(self
, n
)
476 return property(new_f
)
478 def run_commit_msg_hook(repo
, cd
, editor_is_used
=True):
479 """Run the commit-msg hook (if any) on a commit.
481 @param cd: The L{CommitData<stgit.lib.git.CommitData>} to run the
484 Return the new L{CommitData<stgit.lib.git.CommitData>}."""
486 if not editor_is_used
:
487 env
['GIT_EDITOR'] = ':'
488 commit_msg_hook
= get_hook(repo
, 'commit-msg', env
)
491 new_msg
= run_hook_on_string(commit_msg_hook
, cd
.message
)
492 except RunException
, exc
:
493 raise EditorException
, str(exc
)
495 return cd
.set_message(new_msg
)
497 def update_commit_data(cd
, options
):
498 """Return a new CommitData object updated according to the command line
500 # Set the commit message from commandline.
501 if options
.message
is not None:
502 cd
= cd
.set_message(options
.message
)
504 # Modify author data.
505 cd
= cd
.set_author(options
.author(cd
.author
))
507 # Add Signed-off-by: or similar.
508 if options
.sign_str
!= None:
509 sign_str
= options
.sign_str
511 sign_str
= config
.get("stgit.autosign")
514 add_sign_line(cd
.message
, sign_str
,
515 cd
.committer
.name
, cd
.committer
.email
))
517 # Let user edit the commit message manually, unless
518 # --save-template or --message was specified.
519 if not getattr(options
, 'save_template', None) and options
.message
is None:
520 cd
= cd
.set_message(edit_string(cd
.message
, '.stgit-new.txt'))
524 class DirectoryException(StgException
):
527 class _Directory(object):
528 def __init__(self
, needs_current_series
= True, log
= True):
529 self
.needs_current_series
= needs_current_series
531 @readonly_constant_property
534 return Run('git', 'rev-parse', '--git-dir'
535 ).discard_stderr().output_one_line()
537 raise DirectoryException('No git repository found')
538 @readonly_constant_property
539 def __topdir_path(self
):
541 lines
= Run('git', 'rev-parse', '--show-cdup'
542 ).discard_stderr().output_lines()
545 elif len(lines
) == 1:
548 raise RunException('Too much output')
550 raise DirectoryException('No git repository found')
551 @readonly_constant_property
552 def is_inside_git_dir(self
):
553 return { 'true': True, 'false': False
554 }[Run('git', 'rev-parse', '--is-inside-git-dir'
556 @readonly_constant_property
557 def is_inside_worktree(self
):
558 return { 'true': True, 'false': False
559 }[Run('git', 'rev-parse', '--is-inside-work-tree'
561 def cd_to_topdir(self
):
562 os
.chdir(self
.__topdir
_path
)
563 def write_log(self
, msg
):
565 log
.compat_log_entry(msg
)
567 class DirectoryAnywhere(_Directory
):
571 class DirectoryHasRepository(_Directory
):
573 self
.git_dir
# might throw an exception
574 log
.compat_log_external_mods()
576 class DirectoryInWorktree(DirectoryHasRepository
):
578 DirectoryHasRepository
.setup(self
)
579 if not self
.is_inside_worktree
:
580 raise DirectoryException('Not inside a git worktree')
582 class DirectoryGotoToplevel(DirectoryInWorktree
):
584 DirectoryInWorktree
.setup(self
)
587 class DirectoryHasRepositoryLib(_Directory
):
588 """For commands that use the new infrastructure in stgit.lib.*."""
590 self
.needs_current_series
= False
591 self
.log
= False # stgit.lib.transaction handles logging
593 # This will throw an exception if we don't have a repository.
594 self
.repository
= libstack
.Repository
.default()