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
, email
.Utils
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
30 from stgit
.lib
import log
32 # Command exception class
33 class CmdException(StgException
):
38 """Parse a revision specification into its branch:patch parts.
41 branch
, patch
= rev
.split(':', 1)
46 return (branch
, patch
)
48 def git_id(crt_series
, rev
):
51 # TODO: remove this function once all the occurrences were converted
53 repository
= libstack
.Repository
.default()
54 return git_commit(rev
, repository
, crt_series
.get_name()).sha1
56 def get_public_ref(branch_name
):
57 """Return the public ref of the branch."""
58 public_ref
= config
.get('branch.%s.public' % branch_name
)
60 public_ref
= 'refs/heads/%s.public' % branch_name
63 def git_commit(name
, repository
, branch_name
= None):
64 """Return the a Commit object if 'name' is a patch name or Git commit.
65 The patch names allowed are in the form '<branch>:<patch>' and can
66 be followed by standard symbols used by git rev-parse. If <patch>
67 is '{base}', it represents the bottom of the stack. If <patch> is
68 {public}, it represents the public branch corresponding to the stack as
69 described in the 'publish' command.
71 # Try a [branch:]patch name first
72 branch
, patch
= parse_rev(name
)
74 branch
= branch_name
or repository
.current_branch_name
77 if patch
.startswith('{base}'):
78 base_id
= repository
.get_stack(branch
).base
.sha1
79 return repository
.rev_parse(base_id
+
80 strip_prefix('{base}', patch
))
81 elif patch
.startswith('{public}'):
82 public_ref
= get_public_ref(branch
)
83 return repository
.rev_parse(public_ref
+
84 strip_prefix('{public}', patch
),
85 discard_stderr
= True)
87 # Other combination of branch and patch
89 return repository
.rev_parse('patches/%s/%s' %
(branch
, patch
),
90 discard_stderr
= True)
91 except libgit
.RepositoryException
:
96 return repository
.rev_parse(name
, discard_stderr
= True)
97 except libgit
.RepositoryException
:
98 raise CmdException('%s: Unknown patch or revision name' % name
)
100 def color_diff_flags():
101 """Return the git flags for coloured diff output if the configuration and
103 stdout_is_tty
= (sys
.stdout
.isatty() and 'true') or 'false'
104 if config
.get_colorbool('color.diff', stdout_is_tty
) == 'true':
109 def check_local_changes():
110 if git
.local_changes():
111 raise CmdException('local changes in the tree. Use "refresh" or'
114 def check_head_top_equal(crt_series
):
115 if not crt_series
.head_top_equal():
116 raise CmdException('HEAD and top are not the same. This can happen'
117 ' if you modify a branch with git. "stg repair'
118 ' --help" explains more about what to do next.')
120 def check_conflicts():
121 if git
.get_conflicts():
122 raise CmdException('Unsolved conflicts. Please fix the conflicts'
123 ' then use "git add --update <files>" or revert the'
124 ' changes with "status --reset".')
126 def print_crt_patch(crt_series
, branch
= None):
128 patch
= crt_series
.get_current()
130 patch
= stack
.Series(branch
).get_current()
133 out
.info('Now at patch "%s"' % patch
)
135 out
.info('No patches applied')
137 def resolved_all(reset
= None):
138 conflicts
= git
.get_conflicts()
139 git
.resolved(conflicts
, reset
)
141 def push_patches(crt_series
, patches
, check_merged
= False):
142 """Push multiple patches onto the stack. This function is shared
143 between the push and pull commands
145 forwarded
= crt_series
.forward_patches(patches
)
147 out
.info('Fast-forwarded patches "%s" - "%s"'
148 %
(patches
[0], patches
[forwarded
- 1]))
150 out
.info('Fast-forwarded patch "%s"' % patches
[0])
152 names
= patches
[forwarded
:]
154 # check for patches merged upstream
155 if names
and check_merged
:
156 out
.start('Checking for patches merged upstream')
158 merged
= crt_series
.merged_patches(names
)
160 out
.done('%d found' %
len(merged
))
165 out
.start('Pushing patch "%s"' % p
)
168 crt_series
.push_empty_patch(p
)
169 out
.done('merged upstream')
171 modified
= crt_series
.push_patch(p
)
173 if crt_series
.empty_patch(p
):
174 out
.done('empty patch')
180 def pop_patches(crt_series
, patches
, keep
= False):
181 """Pop the patches in the list from the stack. It is assumed that
182 the patches are listed in the stack reverse order.
184 if len(patches
) == 0:
185 out
.info('Nothing to push/pop')
188 if len(patches
) == 1:
189 out
.start('Popping patch "%s"' % p
)
191 out
.start('Popping patches "%s" - "%s"' %
(patches
[0], p
))
192 crt_series
.pop_patch(p
, keep
)
195 def parse_patches(patch_args
, patch_list
, boundary
= 0, ordered
= False):
196 """Parse patch_args list for patch names in patch_list and return
197 a list. The names can be individual patches and/or in the
198 patch1..patch2 format.
200 # in case it receives a tuple
201 patch_list
= list(patch_list
)
204 for name
in patch_args
:
205 pair
= name
.split('..')
207 if p
and not p
in patch_list
:
208 raise CmdException
, 'Unknown patch name: %s' % p
214 # patch range [p1]..[p2]
217 first
= patch_list
.index(pair
[0])
222 last
= patch_list
.index(pair
[1]) + 1
226 # only cross the boundary if explicitly asked
228 boundary
= len(patch_list
)
238 last
= len(patch_list
)
241 pl
= patch_list
[first
:last
]
243 pl
= patch_list
[(last
- 1):(first
+ 1)]
246 raise CmdException
, 'Malformed patch name: %s' % name
250 raise CmdException
, 'Duplicate patch name: %s' % p
255 patches
= [p
for p
in patch_list
if p
in patches
]
259 def name_email(address
):
260 p
= email
.Utils
.parseaddr(address
)
264 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
267 def name_email_date(address
):
268 p
= parse_name_email_date(address
)
272 raise CmdException('Incorrect "name <email> date" string: %s' % address
)
274 def address_or_alias(addr_pair
):
275 """Return a name-email tuple the e-mail address is valid or look up
276 the aliases in the config files.
280 # it's an e-mail address
282 alias
= config
.get('mail.alias.' + addr
)
285 return name_email(alias
)
286 raise CmdException
, 'unknown e-mail alias: %s' % addr
288 def prepare_rebase(crt_series
):
290 applied
= crt_series
.get_applied()
292 out
.start('Popping all applied patches')
293 crt_series
.pop_patch(applied
[0])
297 def rebase(crt_series
, target
):
299 tree_id
= git_id(crt_series
, target
)
301 # it might be that we use a custom rebase command with its own
304 if tree_id
== git
.get_head():
305 out
.info('Already at "%s", no need for rebasing.' % target
)
308 out
.start('Rebasing to "%s"' % target
)
310 out
.start('Rebasing to the default target')
311 git
.rebase(tree_id
= tree_id
)
314 def post_rebase(crt_series
, applied
, nopush
, merged
):
315 # memorize that we rebased to here
316 crt_series
._set_field('orig-base', git
.get_head())
317 # push the patches back
319 push_patches(crt_series
, applied
, merged
)
322 # Patch description/e-mail/diff parsing
324 def __end_descr(line
):
325 return re
.match('---\s*$', line
) or re
.match('diff -', line
) or \
326 re
.match('Index: ', line
) or re
.match('--- \w', line
)
328 def __split_descr_diff(string
):
329 """Return the description and the diff from the given string
334 for line
in string
.split('\n'):
336 if not __end_descr(line
):
343 return (descr
.rstrip(), diff
)
345 def __parse_description(descr
):
346 """Parse the patch description and return the new description and
347 author information (if any).
350 authname
= authemail
= authdate
= None
352 descr_lines
= [line
.rstrip() for line
in descr
.split('\n')]
354 raise CmdException
, "Empty patch description"
357 end
= len(descr_lines
)
360 # Parse the patch header
361 for pos
in range(0, end
):
362 if not descr_lines
[pos
]:
364 # check for a "From|Author:" line
365 if re
.match('\s*(?:from|author):\s+', descr_lines
[pos
], re
.I
):
366 auth
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
367 authname
, authemail
= name_email(auth
)
370 # check for a "Date:" line
371 if re
.match('\s*date:\s+', descr_lines
[pos
], re
.I
):
372 authdate
= re
.findall('^.*?:\s+(.*)$', descr_lines
[pos
])[0]
378 subject
= descr_lines
[pos
][descr_strip
:]
379 if re
.match('commit [\da-f]{40}$', subject
):
380 # 'git show' output, look for the real subject
387 body
= '\n' + '\n'.join(l
[descr_strip
:] for l
in descr_lines
[lasthdr
:])
389 return (subject
+ body
, authname
, authemail
, authdate
)
392 """Parse the message object and return (description, authname,
393 authemail, authdate, diff)
395 from email
.Header
import decode_header
, make_header
397 def __decode_header(header
):
398 """Decode a qp-encoded e-mail header as per rfc2047"""
400 words_enc
= decode_header(header
)
401 hobj
= make_header(words_enc
)
402 except Exception, ex
:
403 raise CmdException
, 'header decoding error: %s' % str
(ex
)
404 return unicode(hobj
).encode('utf-8')
407 if msg
.has_key('from'):
408 authname
, authemail
= name_email(__decode_header(msg
['from']))
410 authname
= authemail
= None
412 # '\n\t' can be found on multi-line headers
413 descr
= __decode_header(msg
['subject'])
414 descr
= re
.sub('\n[ \t]*', ' ', descr
)
415 authdate
= msg
['date']
417 # remove the '[*PATCH*]' expression in the subject
419 descr
= re
.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
422 raise CmdException
, 'Subject: line not found'
424 # the rest of the message
426 for part
in msg
.walk():
427 if part
.get_content_type() in ['text/plain',
428 'application/octet-stream']:
429 msg_text
+= part
.get_payload(decode
= True)
431 rem_descr
, diff
= __split_descr_diff(msg_text
)
433 descr
+= '\n\n' + rem_descr
435 # parse the description for author information
436 descr
, descr_authname
, descr_authemail
, descr_authdate
= \
437 __parse_description(descr
)
439 authname
= descr_authname
441 authemail
= descr_authemail
443 authdate
= descr_authdate
445 return (descr
, authname
, authemail
, authdate
, diff
)
447 def parse_patch(text
, contains_diff
):
448 """Parse the input text and return (description, authname,
449 authemail, authdate, diff)
452 (text
, diff
) = __split_descr_diff(text
)
455 (descr
, authname
, authemail
, authdate
) = __parse_description(text
)
457 # we don't yet have an agreed place for the creation date.
459 return (descr
, authname
, authemail
, authdate
, diff
)
461 def readonly_constant_property(f
):
462 """Decorator that converts a function that computes a value to an
463 attribute that returns the value. The value is computed only once,
464 the first time it is accessed."""
466 n
= '__' + f
.__name__
467 if not hasattr(self
, n
):
468 setattr(self
, n
, f(self
))
469 return getattr(self
, n
)
470 return property(new_f
)
472 def update_commit_data(cd
, options
):
473 """Return a new CommitData object updated according to the command line
475 # Set the commit message from commandline.
476 if options
.message
!= None:
477 cd
= cd
.set_message(options
.message
)
479 # Modify author data.
480 cd
= cd
.set_author(options
.author(cd
.author
))
482 # Add Signed-off-by: or similar.
483 if options
.sign_str
!= None:
484 sign_str
= options
.sign_str
486 sign_str
= config
.get("stgit.autosign")
489 add_sign_line(cd
.message
, sign_str
,
490 cd
.committer
.name
, cd
.committer
.email
))
492 # Let user edit the commit message manually, unless
493 # --save-template or --message was specified.
494 if not getattr(options
, 'save_template', None) and not options
.message
:
495 cd
= cd
.set_message(edit_string(cd
.message
, '.stgit-new.txt'))
499 class DirectoryException(StgException
):
502 class _Directory(object):
503 def __init__(self
, needs_current_series
= True, log
= True):
504 self
.needs_current_series
= needs_current_series
506 @readonly_constant_property
509 return Run('git', 'rev-parse', '--git-dir'
510 ).discard_stderr().output_one_line()
512 raise DirectoryException('No git repository found')
513 @readonly_constant_property
514 def __topdir_path(self
):
516 lines
= Run('git', 'rev-parse', '--show-cdup'
517 ).discard_stderr().output_lines()
520 elif len(lines
) == 1:
523 raise RunException('Too much output')
525 raise DirectoryException('No git repository found')
526 @readonly_constant_property
527 def is_inside_git_dir(self
):
528 return { 'true': True, 'false': False
529 }[Run('git', 'rev-parse', '--is-inside-git-dir'
531 @readonly_constant_property
532 def is_inside_worktree(self
):
533 return { 'true': True, 'false': False
534 }[Run('git', 'rev-parse', '--is-inside-work-tree'
536 def cd_to_topdir(self
):
537 os
.chdir(self
.__topdir_path
)
538 def write_log(self
, msg
):
540 log
.compat_log_entry(msg
)
542 class DirectoryAnywhere(_Directory
):
546 class DirectoryHasRepository(_Directory
):
548 self
.git_dir
# might throw an exception
549 log
.compat_log_external_mods()
551 class DirectoryInWorktree(DirectoryHasRepository
):
553 DirectoryHasRepository
.setup(self
)
554 if not self
.is_inside_worktree
:
555 raise DirectoryException('Not inside a git worktree')
557 class DirectoryGotoToplevel(DirectoryInWorktree
):
559 DirectoryInWorktree
.setup(self
)
562 class DirectoryHasRepositoryLib(_Directory
):
563 """For commands that use the new infrastructure in stgit.lib.*."""
565 self
.needs_current_series
= False
566 self
.log
= False # stgit.lib.transaction handles logging
568 # This will throw an exception if we don't have a repository.
569 self
.repository
= libstack
.Repository
.default()