commit: strip commentary from .git/MERGE_MSG
[git-cola.git] / cola / gitcmds.py
blob188817ce7cb488cbd103481b38a3319830af02f6
1 """Git commands and queries for Git"""
2 import json
3 import os
4 import re
5 from io import StringIO
7 from . import core
8 from . import utils
9 from . import version
10 from .git import STDOUT
11 from .git import EMPTY_TREE_OID
12 from .git import OID_LENGTH
13 from .i18n import N_
14 from .interaction import Interaction
15 from .models import prefs
18 def add(context, items, u=False):
19 """Run "git add" while preventing argument overflow"""
20 git_add = context.git.add
21 return utils.slice_func(
22 items, lambda paths: git_add('--', force=True, verbose=True, u=u, *paths)
26 def apply_diff(context, filename):
27 """Use "git apply" to apply the patch in `filename` to the staging area"""
28 git = context.git
29 return git.apply(filename, index=True, cached=True)
32 def apply_diff_to_worktree(context, filename):
33 """Use "git apply" to apply the patch in `filename` to the worktree"""
34 git = context.git
35 return git.apply(filename)
38 def get_branch(context, branch):
39 """Get the current branch"""
40 if branch is None:
41 branch = current_branch(context)
42 return branch
45 def upstream_remote(context, branch=None):
46 """Return the remote associated with the specified branch"""
47 config = context.cfg
48 branch = get_branch(context, branch)
49 return config.get('branch.%s.remote' % branch)
52 def remote_url(context, remote, push=False):
53 """Return the URL for the specified remote"""
54 config = context.cfg
55 url = config.get('remote.%s.url' % remote, '')
56 if push:
57 url = config.get('remote.%s.pushurl' % remote, url)
58 return url
61 def diff_index_filenames(context, ref):
62 """
63 Return a diff of filenames that have been modified relative to the index
64 """
65 git = context.git
66 out = git.diff_index(ref, name_only=True, z=True, _readonly=True)[STDOUT]
67 return _parse_diff_filenames(out)
70 def diff_filenames(context, *args):
71 """Return a list of filenames that have been modified"""
72 git = context.git
73 out = git.diff_tree(
74 name_only=True, no_commit_id=True, r=True, z=True, _readonly=True, *args
75 )[STDOUT]
76 return _parse_diff_filenames(out)
79 def listdir(context, dirname, ref='HEAD'):
80 """Get the contents of a directory according to Git
82 Query Git for the content of a directory, taking ignored
83 files into account.
85 """
86 dirs = []
87 files = []
89 # first, parse git ls-tree to get the tracked files
90 # in a list of (type, path) tuples
91 entries = ls_tree(context, dirname, ref=ref)
92 for entry in entries:
93 if entry[0][0] == 't': # tree
94 dirs.append(entry[1])
95 else:
96 files.append(entry[1])
98 # gather untracked files
99 untracked = untracked_files(context, paths=[dirname], directory=True)
100 for path in untracked:
101 if path.endswith('/'):
102 dirs.append(path[:-1])
103 else:
104 files.append(path)
106 dirs.sort()
107 files.sort()
109 return (dirs, files)
112 def diff(context, args):
113 """Return a list of filenames for the given diff arguments
115 :param args: list of arguments to pass to "git diff --name-only"
118 git = context.git
119 out = git.diff(name_only=True, z=True, _readonly=True, *args)[STDOUT]
120 return _parse_diff_filenames(out)
123 def _parse_diff_filenames(out):
124 if out:
125 return out[:-1].split('\0')
126 return []
129 def tracked_files(context, *args):
130 """Return the names of all files in the repository"""
131 git = context.git
132 out = git.ls_files('--', *args, z=True, _readonly=True)[STDOUT]
133 if out:
134 return sorted(out[:-1].split('\0'))
135 return []
138 def all_files(context, *args):
139 """Returns a sorted list of all files, including untracked files."""
140 git = context.git
141 ls_files = git.ls_files(
142 '--',
143 *args,
144 z=True,
145 cached=True,
146 others=True,
147 exclude_standard=True,
148 _readonly=True,
149 )[STDOUT]
150 return sorted([f for f in ls_files.split('\0') if f])
153 class CurrentBranchCache:
154 """Cache for current_branch()"""
156 key = None
157 value = None
160 def reset():
161 """Reset cached value in this module (eg. the cached current branch)"""
162 CurrentBranchCache.key = None
165 def current_branch(context):
166 """Return the current branch"""
167 git = context.git
168 head = git.git_path('HEAD')
169 try:
170 key = core.stat(head).st_mtime
171 if CurrentBranchCache.key == key:
172 return CurrentBranchCache.value
173 except OSError:
174 # OSError means we can't use the stat cache
175 key = 0
177 status, data, _ = git.rev_parse('HEAD', symbolic_full_name=True, _readonly=True)
178 if status != 0:
179 # git init -- read .git/HEAD. We could do this unconditionally...
180 data = _read_git_head(context, head)
182 for refs_prefix in ('refs/heads/', 'refs/remotes/', 'refs/tags/'):
183 if data.startswith(refs_prefix):
184 value = data[len(refs_prefix) :]
185 CurrentBranchCache.key = key
186 CurrentBranchCache.value = value
187 return value
188 # Detached head
189 return data
192 def _read_git_head(context, head, default='main'):
193 """Pure-python .git/HEAD reader"""
194 # Common .git/HEAD "ref: refs/heads/main" files
195 git = context.git
196 islink = core.islink(head)
197 if core.isfile(head) and not islink:
198 data = core.read(head).rstrip()
199 ref_prefix = 'ref: '
200 if data.startswith(ref_prefix):
201 return data[len(ref_prefix) :]
202 # Detached head
203 return data
204 # Legacy .git/HEAD symlinks
205 if islink:
206 refs_heads = core.realpath(git.git_path('refs', 'heads'))
207 path = core.abspath(head).replace('\\', '/')
208 if path.startswith(refs_heads + '/'):
209 return path[len(refs_heads) + 1 :]
211 return default
214 def branch_list(context, remote=False):
216 Return a list of local or remote branches
218 This explicitly removes HEAD from the list of remote branches.
221 if remote:
222 return for_each_ref_basename(context, 'refs/remotes')
223 return for_each_ref_basename(context, 'refs/heads')
226 def _version_sort(context, key='version:refname'):
227 if version.check_git(context, 'version-sort'):
228 sort = key
229 else:
230 sort = False
231 return sort
234 def for_each_ref_basename(context, refs):
235 """Return refs starting with 'refs'."""
236 git = context.git
237 sort = _version_sort(context)
238 _, out, _ = git.for_each_ref(refs, format='%(refname)', sort=sort, _readonly=True)
239 output = out.splitlines()
240 non_heads = [x for x in output if not x.endswith('/HEAD')]
241 offset = len(refs) + 1
242 return [x[offset:] for x in non_heads]
245 def _prefix_and_size(prefix, values):
246 """Return a tuple of (prefix, len(prefix) + 1, y) for <prefix>/ stripping"""
247 return (prefix, len(prefix) + 1, values)
250 def all_refs(context, split=False, sort_key='version:refname'):
251 """Return a tuple of (local branches, remote branches, tags)."""
252 git = context.git
253 local_branches = []
254 remote_branches = []
255 tags = []
256 query = (
257 _prefix_and_size('refs/tags', tags),
258 _prefix_and_size('refs/heads', local_branches),
259 _prefix_and_size('refs/remotes', remote_branches),
261 sort = _version_sort(context, key=sort_key)
262 _, out, _ = git.for_each_ref(format='%(refname)', sort=sort, _readonly=True)
263 for ref in out.splitlines():
264 for prefix, prefix_len, dst in query:
265 if ref.startswith(prefix) and not ref.endswith('/HEAD'):
266 dst.append(ref[prefix_len:])
267 continue
268 tags.reverse()
269 if split:
270 return local_branches, remote_branches, tags
271 return local_branches + remote_branches + tags
274 def tracked_branch(context, branch=None):
275 """Return the remote branch associated with 'branch'."""
276 if branch is None:
277 branch = current_branch(context)
278 if branch is None:
279 return None
280 config = context.cfg
281 remote = config.get('branch.%s.remote' % branch)
282 if not remote:
283 return None
284 merge_ref = config.get('branch.%s.merge' % branch)
285 if not merge_ref:
286 return None
287 refs_heads = 'refs/heads/'
288 if merge_ref.startswith(refs_heads):
289 return remote + '/' + merge_ref[len(refs_heads) :]
290 return None
293 def parse_remote_branch(branch):
294 """Split a remote branch apart into (remote, name) components"""
295 rgx = re.compile(r'^(?P<remote>[^/]+)/(?P<branch>.+)$')
296 match = rgx.match(branch)
297 remote = ''
298 branch = ''
299 if match:
300 remote = match.group('remote')
301 branch = match.group('branch')
302 return (remote, branch)
305 def untracked_files(context, paths=None, **kwargs):
306 """Returns a sorted list of untracked files."""
307 git = context.git
308 if paths is None:
309 paths = []
310 args = ['--'] + paths
311 out = git.ls_files(
312 z=True, others=True, exclude_standard=True, _readonly=True, *args, **kwargs
313 )[STDOUT]
314 if out:
315 return out[:-1].split('\0')
316 return []
319 def tag_list(context):
320 """Return a list of tags."""
321 result = for_each_ref_basename(context, 'refs/tags')
322 result.reverse()
323 return result
326 def log(git, *args, **kwargs):
327 return git.log(
328 no_color=True,
329 no_abbrev_commit=True,
330 no_ext_diff=True,
331 _readonly=True,
332 *args,
333 **kwargs,
334 )[STDOUT]
337 def commit_diff(context, oid):
338 git = context.git
339 return log(git, '-1', oid, '--') + '\n\n' + oid_diff(context, oid)
342 _diff_overrides = {}
345 def update_diff_overrides(space_at_eol, space_change, all_space, function_context):
346 _diff_overrides['ignore_space_at_eol'] = space_at_eol
347 _diff_overrides['ignore_space_change'] = space_change
348 _diff_overrides['ignore_all_space'] = all_space
349 _diff_overrides['function_context'] = function_context
352 def common_diff_opts(context):
353 config = context.cfg
354 # Default to --patience when diff.algorithm is unset
355 patience = not config.get('diff.algorithm', default='')
356 submodule = version.check_git(context, 'diff-submodule')
357 opts = {
358 'patience': patience,
359 'submodule': submodule,
360 'no_color': True,
361 'no_ext_diff': True,
362 'unified': config.get('gui.diffcontext', default=3),
363 '_raw': True,
364 '_readonly': True,
366 opts.update(_diff_overrides)
367 return opts
370 def _add_filename(args, filename):
371 if filename:
372 args.extend(['--', filename])
375 def oid_diff(context, oid, filename=None):
376 """Return the diff for an oid"""
377 # Naively "$oid^!" is what we'd like to use but that doesn't
378 # give the correct result for merges--the diff is reversed.
379 # Be explicit and compare oid against its first parent.
380 return oid_diff_range(context, oid + '~', oid, filename=filename)
383 def oid_diff_range(context, start, end, filename=None):
384 """Reeturn the diff for a commit range"""
385 args = [start, end]
386 git = context.git
387 opts = common_diff_opts(context)
388 _add_filename(args, filename)
389 status, out, _ = git.diff(*args, **opts)
390 if status != 0:
391 # We probably don't have "$oid~" because this is the root commit.
392 # "git show" is clever enough to handle the root commit.
393 args = [end + '^!']
394 _add_filename(args, filename)
395 _, out, _ = git.show(pretty='format:', *args, **opts)
396 out = out.lstrip()
397 return out
400 def diff_info(context, oid, filename=None):
401 """Return the diff for the specified oid"""
402 return diff_range(context, oid + '~', oid, filename=filename)
405 def diff_range(context, start, end, filename=None):
406 """Return the diff for the specified commit range"""
407 git = context.git
408 decoded = log(git, '-1', end, '--', pretty='format:%b').strip()
409 if decoded:
410 decoded += '\n\n'
411 return decoded + oid_diff_range(context, start, end, filename=filename)
414 # pylint: disable=too-many-arguments
415 def diff_helper(
416 context,
417 commit=None,
418 ref=None,
419 endref=None,
420 filename=None,
421 cached=True,
422 deleted=False,
423 head=None,
424 amending=False,
425 with_diff_header=False,
426 suppress_header=True,
427 reverse=False,
428 untracked=False,
430 'Invokes git diff on a filepath.'
431 git = context.git
432 cfg = context.cfg
433 if commit:
434 ref, endref = commit + '^', commit
435 argv = []
436 if ref and endref:
437 argv.append(f'{ref}..{endref}')
438 elif ref:
439 argv.extend(utils.shell_split(ref.strip()))
440 elif head and amending and cached:
441 argv.append(head)
443 encoding = None
444 if untracked:
445 argv.append('--no-index')
446 argv.append(os.devnull)
447 argv.append(filename)
448 elif filename:
449 argv.append('--')
450 if isinstance(filename, (list, tuple)):
451 argv.extend(filename)
452 else:
453 argv.append(filename)
454 encoding = cfg.file_encoding(filename)
456 status, out, _ = git.diff(
457 R=reverse,
458 M=True,
459 cached=cached,
460 _encoding=encoding,
461 *argv,
462 **common_diff_opts(context),
465 success = status == 0
467 # Diff will return 1 when comparing untracked file and it has change,
468 # therefore we will check for diff header from output to differentiate
469 # from actual error such as file not found.
470 if untracked and status == 1:
471 try:
472 _, second, _ = out.split('\n', 2)
473 except ValueError:
474 second = ''
475 success = second.startswith('new file mode ')
477 if not success:
478 # git init
479 if with_diff_header:
480 return ('', '')
481 return ''
483 result = extract_diff_header(deleted, with_diff_header, suppress_header, out)
484 return core.UStr(result, out.encoding)
487 def extract_diff_header(deleted, with_diff_header, suppress_header, diffoutput):
488 """Split a diff into a header section and payload section"""
490 if diffoutput.startswith('Submodule'):
491 if with_diff_header:
492 return ('', diffoutput)
493 return diffoutput
495 start = False
496 del_tag = 'deleted file mode '
498 output = StringIO()
499 headers = StringIO()
501 for line in diffoutput.split('\n'):
502 if not start and line[:2] == '@@' and '@@' in line[2:]:
503 start = True
504 if start or (deleted and del_tag in line):
505 output.write(line + '\n')
506 else:
507 if with_diff_header:
508 headers.write(line + '\n')
509 elif not suppress_header:
510 output.write(line + '\n')
512 output_text = output.getvalue()
513 output.close()
515 headers_text = headers.getvalue()
516 headers.close()
518 if with_diff_header:
519 return (headers_text, output_text)
520 return output_text
523 def format_patchsets(context, to_export, revs, output='patches'):
525 Group contiguous revision selection into patchsets
527 Exists to handle multi-selection.
528 Multiple disparate ranges in the revision selection
529 are grouped into continuous lists.
533 outs = []
534 errs = []
536 cur_rev = to_export[0]
537 cur_rev_idx = revs.index(cur_rev)
539 patches_to_export = [[cur_rev]]
540 patchset_idx = 0
542 # Group the patches into continuous sets
543 for rev in to_export[1:]:
544 # Limit the search to the current neighborhood for efficiency
545 try:
546 rev_idx = revs[cur_rev_idx:].index(rev)
547 rev_idx += cur_rev_idx
548 except ValueError:
549 rev_idx = revs.index(rev)
551 if rev_idx == cur_rev_idx + 1:
552 patches_to_export[patchset_idx].append(rev)
553 cur_rev_idx += 1
554 else:
555 patches_to_export.append([rev])
556 cur_rev_idx = rev_idx
557 patchset_idx += 1
559 # Export each patchsets
560 status = 0
561 for patchset in patches_to_export:
562 stat, out, err = export_patchset(
563 context,
564 patchset[0],
565 patchset[-1],
566 output=output,
567 n=len(patchset) > 1,
568 thread=True,
569 patch_with_stat=True,
571 outs.append(out)
572 if err:
573 errs.append(err)
574 status = max(stat, status)
575 return (status, '\n'.join(outs), '\n'.join(errs))
578 def export_patchset(context, start, end, output='patches', **kwargs):
579 """Export patches from start^ to end."""
580 git = context.git
581 return git.format_patch('-o', output, start + '^..' + end, **kwargs)
584 def reset_paths(context, head, items):
585 """Run "git reset" while preventing argument overflow"""
586 items = list(set(items))
587 func = context.git.reset
588 status, out, err = utils.slice_func(items, lambda paths: func(head, '--', *paths))
589 return (status, out, err)
592 def unstage_paths(context, args, head='HEAD'):
593 """Unstage paths while accounting for git init"""
594 status, out, err = reset_paths(context, head, args)
595 if status == 128:
596 # handle git init: we have to use 'git rm --cached'
597 # detect this condition by checking if the file is still staged
598 return untrack_paths(context, args)
599 return (status, out, err)
602 def untrack_paths(context, args):
603 if not args:
604 return (-1, N_('Nothing to do'), '')
605 git = context.git
606 return git.update_index('--', force_remove=True, *set(args))
609 def worktree_state(
610 context, head='HEAD', update_index=False, display_untracked=True, paths=None
612 """Return a dict of files in various states of being
614 :rtype: dict, keys are staged, unstaged, untracked, unmerged,
615 changed_upstream, and submodule.
618 git = context.git
619 if update_index:
620 git.update_index(refresh=True)
622 staged, unmerged, staged_deleted, staged_submods = diff_index(
623 context, head, paths=paths
625 modified, unstaged_deleted, modified_submods = diff_worktree(context, paths)
626 if display_untracked:
627 untracked = untracked_files(context, paths=paths)
628 else:
629 untracked = []
631 # Remove unmerged paths from the modified list
632 if unmerged:
633 unmerged_set = set(unmerged)
634 modified = [path for path in modified if path not in unmerged_set]
636 # Look for upstream modified files if this is a tracking branch
637 upstream_changed = diff_upstream(context, head)
639 # Keep stuff sorted
640 staged.sort()
641 modified.sort()
642 unmerged.sort()
643 untracked.sort()
644 upstream_changed.sort()
646 return {
647 'staged': staged,
648 'modified': modified,
649 'unmerged': unmerged,
650 'untracked': untracked,
651 'upstream_changed': upstream_changed,
652 'staged_deleted': staged_deleted,
653 'unstaged_deleted': unstaged_deleted,
654 'submodules': staged_submods | modified_submods,
658 def _parse_raw_diff(out):
659 while out:
660 info, path, out = out.split('\0', 2)
661 status = info[-1]
662 is_submodule = '160000' in info[1:14]
663 yield (path, status, is_submodule)
666 def diff_index(context, head, cached=True, paths=None):
667 git = context.git
668 staged = []
669 unmerged = []
670 deleted = set()
671 submodules = set()
673 if paths is None:
674 paths = []
675 args = [head, '--'] + paths
676 status, out, _ = git.diff_index(cached=cached, z=True, _readonly=True, *args)
677 if status != 0:
678 # handle git init
679 args[0] = EMPTY_TREE_OID
680 status, out, _ = git.diff_index(cached=cached, z=True, _readonly=True, *args)
682 for path, status, is_submodule in _parse_raw_diff(out):
683 if is_submodule:
684 submodules.add(path)
685 if status in 'DAMT':
686 staged.append(path)
687 if status == 'D':
688 deleted.add(path)
689 elif status == 'U':
690 unmerged.append(path)
692 return staged, unmerged, deleted, submodules
695 def diff_worktree(context, paths=None):
696 git = context.git
697 ignore_submodules_value = context.cfg.get('diff.ignoresubmodules', 'none')
698 ignore_submodules = ignore_submodules_value in {'all', 'dirty', 'untracked'}
699 modified = []
700 deleted = set()
701 submodules = set()
703 if paths is None:
704 paths = []
705 args = ['--'] + paths
706 status, out, _ = git.diff_files(z=True, _readonly=True, *args)
707 for path, status, is_submodule in _parse_raw_diff(out):
708 if is_submodule:
709 submodules.add(path)
710 if ignore_submodules:
711 continue
712 if status in 'DAMT':
713 modified.append(path)
714 if status == 'D':
715 deleted.add(path)
717 return modified, deleted, submodules
720 def diff_upstream(context, head):
721 """Given `ref`, return $(git merge-base ref HEAD)..ref."""
722 tracked = tracked_branch(context)
723 if not tracked:
724 return []
725 base = merge_base(context, head, tracked)
726 return diff_filenames(context, base, tracked)
729 def list_submodule(context):
730 """Return submodules in the format(state, sha1, path, describe)"""
731 git = context.git
732 status, data, _ = git.submodule('status')
733 ret = []
734 if status == 0 and data:
735 data = data.splitlines()
736 # see git submodule status
737 for line in data:
738 state = line[0].strip()
739 sha1 = line[1 : OID_LENGTH + 1]
740 left_bracket = line.find('(', OID_LENGTH + 3)
741 if left_bracket == -1:
742 left_bracket = len(line) + 1
743 path = line[OID_LENGTH + 2 : left_bracket - 1]
744 describe = line[left_bracket + 1 : -1]
745 ret.append((state, sha1, path, describe))
746 return ret
749 def merge_base(context, head, ref):
750 """Return the merge-base of head and ref"""
751 git = context.git
752 return git.merge_base(head, ref, _readonly=True)[STDOUT]
755 def merge_base_parent(context, branch):
756 tracked = tracked_branch(context, branch=branch)
757 if tracked:
758 return tracked
759 return 'HEAD'
762 def ls_tree(context, path, ref='HEAD'):
763 """Return a parsed git ls-tree result for a single directory"""
764 git = context.git
765 result = []
766 status, out, _ = git.ls_tree(
767 ref, '--', path, z=True, full_tree=True, _readonly=True
769 if status == 0 and out:
770 path_offset = 6 + 1 + 4 + 1 + OID_LENGTH + 1
771 for line in out[:-1].split('\0'):
772 # 1 1 1
773 # .....6 ...4 ......................................40
774 # 040000 tree c127cde9a0c644a3a8fef449a244f47d5272dfa6 relative
775 # 100644 blob 139e42bf4acaa4927ec9be1ec55a252b97d3f1e2 relative/path
776 # 0..... 7... 12...................................... 53
777 # path_offset = 6 + 1 + 4 + 1 + OID_LENGTH(40) + 1
778 objtype = line[7:11]
779 relpath = line[path_offset:]
780 result.append((objtype, relpath))
782 return result
785 # A regex for matching the output of git(log|rev-list) --pretty=oneline
786 REV_LIST_REGEX = re.compile(r'^([0-9a-f]{40}) (.*)$')
789 def parse_rev_list(raw_revs):
790 """Parse `git log --pretty=online` output into (oid, summary) pairs."""
791 revs = []
792 for line in raw_revs.splitlines():
793 match = REV_LIST_REGEX.match(line)
794 if match:
795 rev_id = match.group(1)
796 summary = match.group(2)
797 revs.append((
798 rev_id,
799 summary,
801 return revs
804 # pylint: disable=redefined-builtin
805 def log_helper(context, all=False, extra_args=None):
806 """Return parallel arrays containing oids and summaries."""
807 revs = []
808 summaries = []
809 args = []
810 if extra_args:
811 args = extra_args
812 git = context.git
813 output = log(git, pretty='oneline', all=all, *args)
814 for line in output.splitlines():
815 match = REV_LIST_REGEX.match(line)
816 if match:
817 revs.append(match.group(1))
818 summaries.append(match.group(2))
819 return (revs, summaries)
822 def rev_list_range(context, start, end):
823 """Return (oid, summary) pairs between start and end."""
824 git = context.git
825 revrange = f'{start}..{end}'
826 out = git.rev_list(revrange, pretty='oneline', _readonly=True)[STDOUT]
827 return parse_rev_list(out)
830 def commit_message_path(context):
831 """Return the path to .git/GIT_COLA_MSG"""
832 git = context.git
833 path = git.git_path('GIT_COLA_MSG')
834 if core.exists(path):
835 return path
836 return None
839 def merge_message_path(context):
840 """Return the path to .git/MERGE_MSG or .git/SQUASH_MSG."""
841 git = context.git
842 for basename in ('MERGE_MSG', 'SQUASH_MSG'):
843 path = git.git_path(basename)
844 if core.exists(path):
845 return path
846 return None
849 def read_merge_commit_message(context, path):
850 """Read a merge commit message from disk while stripping commentary"""
851 content = core.read(path)
852 cleanup_mode = prefs.commit_cleanup(context)
853 if cleanup_mode in ('verbatim', 'scissors', 'whitespace'):
854 return content
855 comment_char = prefs.comment_char(context)
856 return '\n'.join(
857 (line for line in content.splitlines() if not line.startswith(comment_char))
861 def prepare_commit_message_hook(context):
862 """Run the cola.preparecommitmessagehook to prepare the commit message"""
863 config = context.cfg
864 default_hook = config.hooks_path('cola-prepare-commit-msg')
865 return config.get('cola.preparecommitmessagehook', default=default_hook)
868 def cherry_pick(context, revs):
869 """Cherry-picks each revision into the current branch.
871 Returns (0, out, err) where stdout and stderr across all "git cherry-pick"
872 invocations are combined into single values when all cherry-picks succeed.
874 Returns a combined (status, out, err) of the first failing "git cherry-pick"
875 in the event of a non-zero exit status.
877 if not revs:
878 return []
879 outs = []
880 errs = []
881 status = 0
882 for rev in revs:
883 status, out, err = context.git.cherry_pick(rev)
884 if status != 0:
885 details = N_(
886 'Hint: The "Actions > Abort Cherry-Pick" menu action can be used to '
887 'cancel the current cherry-pick.'
889 output = f'# git cherry-pick {rev}\n# {details}\n\n{out}'
890 return (status, output, err)
891 outs.append(out)
892 errs.append(err)
893 return (0, '\n'.join(outs), '\n'.join(errs))
896 def abort_apply_patch(context):
897 """Abort a "git am" session."""
898 # Reset the worktree
899 git = context.git
900 status, out, err = git.am(abort=True)
901 return status, out, err
904 def abort_cherry_pick(context):
905 """Abort a cherry-pick."""
906 # Reset the worktree
907 git = context.git
908 status, out, err = git.cherry_pick(abort=True)
909 return status, out, err
912 def abort_merge(context):
913 """Abort a merge"""
914 # Reset the worktree
915 git = context.git
916 status, out, err = git.merge(abort=True)
917 return status, out, err
920 def strip_remote(remotes, remote_branch):
921 """Get branch names with the "<remote>/" prefix removed"""
922 for remote in remotes:
923 prefix = remote + '/'
924 if remote_branch.startswith(prefix):
925 return remote_branch[len(prefix) :]
926 return remote_branch.split('/', 1)[-1]
929 def parse_refs(context, argv):
930 """Parse command-line arguments into object IDs"""
931 git = context.git
932 status, out, _ = git.rev_parse(_readonly=True, *argv)
933 if status == 0:
934 oids = [oid for oid in out.splitlines() if oid]
935 else:
936 oids = argv
937 return oids
940 def prev_commitmsg(context, *args):
941 """Queries git for the latest commit message."""
942 git = context.git
943 return git.log(
944 '-1', no_color=True, pretty='format:%s%n%n%b', _readonly=True, *args
945 )[STDOUT]
948 def rev_parse(context, name):
949 """Call git rev-parse and return the output"""
950 git = context.git
951 status, out, _ = git.rev_parse(name, _readonly=True)
952 if status == 0:
953 result = out.strip()
954 else:
955 result = name
956 return result
959 def write_blob(context, oid, filename):
960 """Write a blob to a temporary file and return the path
962 Modern versions of Git allow invoking filters. Older versions
963 get the object content as-is.
966 if version.check_git(context, 'cat-file-filters-path'):
967 return cat_file_to_path(context, filename, oid)
968 return cat_file_blob(context, filename, oid)
971 def cat_file_blob(context, filename, oid):
972 """Write a blob from git to the specified filename"""
973 return cat_file(context, filename, 'blob', oid)
976 def cat_file_to_path(context, filename, oid):
977 """Extract a file from an commit ref and a write it to the specified filename"""
978 return cat_file(context, filename, oid, path=filename, filters=True)
981 def cat_file(context, filename, *args, **kwargs):
982 """Redirect git cat-file output to a path"""
983 result = None
984 git = context.git
985 # Use the original filename in the suffix so that the generated filename
986 # has the correct extension, and so that it resembles the original name.
987 basename = os.path.basename(filename)
988 suffix = '-' + basename # ensures the correct filename extension
989 path = utils.tmp_filename('blob', suffix=suffix)
990 with open(path, 'wb') as tmp_file:
991 status, out, err = git.cat_file(
992 _raw=True, _readonly=True, _stdout=tmp_file, *args, **kwargs
994 Interaction.command(N_('Error'), 'git cat-file', status, out, err)
995 if status == 0:
996 result = path
997 if not result:
998 core.unlink(path)
999 return result
1002 def write_blob_path(context, head, oid, filename):
1003 """Use write_blob() when modern git is available"""
1004 if version.check_git(context, 'cat-file-filters-path'):
1005 return write_blob(context, oid, filename)
1006 return cat_file_blob(context, filename, head + ':' + filename)
1009 def annex_path(context, head, filename):
1010 """Return the git-annex path for a filename at the specified commit"""
1011 git = context.git
1012 path = None
1013 annex_info = {}
1015 # unfortunately there's no way to filter this down to a single path
1016 # so we just have to scan all reported paths
1017 status, out, _ = git.annex('findref', '--json', head, _readonly=True)
1018 if status == 0:
1019 for line in out.splitlines():
1020 info = json.loads(line)
1021 try:
1022 annex_file = info['file']
1023 except (ValueError, KeyError):
1024 continue
1025 # we only care about this file so we can skip the rest
1026 if annex_file == filename:
1027 annex_info = info
1028 break
1029 key = annex_info.get('key', '')
1030 if key:
1031 status, out, _ = git.annex('contentlocation', key, _readonly=True)
1032 if status == 0 and os.path.exists(out):
1033 path = out
1035 return path
1038 def is_binary(context, filename):
1039 """A heustic to determine whether `filename` contains (non-text) binary content"""
1040 cfg_is_binary = context.cfg.is_binary(filename)
1041 if cfg_is_binary is not None:
1042 return cfg_is_binary
1043 # This is the same heuristic as xdiff-interface.c:buffer_is_binary().
1044 size = 8000
1045 try:
1046 result = core.read(filename, size=size, encoding='bytes')
1047 except OSError:
1048 result = b''
1050 return b'\0' in result
1053 def is_valid_ref(context, ref):
1054 """Is the provided Git ref a valid refname?"""
1055 status, _, _ = context.git.rev_parse(ref, quiet=True, verify=True, _readonly=True)
1056 return status == 0