Merge pull request #1391 from davvid/macos/hotkeys
[git-cola.git] / cola / gitcmds.py
blob4c0fd5dc46eaca8e3f779b9c4be3ca720236e8a8
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 out = diff_tree(context, *args)[STDOUT]
73 return _parse_diff_filenames(out)
76 def changed_files(context, oid):
77 """Return the list of filenames that changed in a given commit oid"""
78 status, out, _ = diff_tree(context, oid + '~', oid)
79 if status != 0:
80 # git init
81 status, out, _ = diff_tree(context, EMPTY_TREE_OID, oid)
82 if status == 0:
83 result = _parse_diff_filenames(out)
84 else:
85 result = []
86 return result
89 def diff_tree(context, *args):
90 """Return a list of filenames that have been modified"""
91 git = context.git
92 return git_diff_tree(git, *args)
95 def git_diff_tree(git, *args):
96 return git.diff_tree(
97 name_only=True, no_commit_id=True, r=True, z=True, _readonly=True, *args
101 def listdir(context, dirname, ref='HEAD'):
102 """Get the contents of a directory according to Git
104 Query Git for the content of a directory, taking ignored
105 files into account.
108 dirs = []
109 files = []
111 # first, parse git ls-tree to get the tracked files
112 # in a list of (type, path) tuples
113 entries = ls_tree(context, dirname, ref=ref)
114 for entry in entries:
115 if entry[0][0] == 't': # tree
116 dirs.append(entry[1])
117 else:
118 files.append(entry[1])
120 # gather untracked files
121 untracked = untracked_files(context, paths=[dirname], directory=True)
122 for path in untracked:
123 if path.endswith('/'):
124 dirs.append(path[:-1])
125 else:
126 files.append(path)
128 dirs.sort()
129 files.sort()
131 return (dirs, files)
134 def diff(context, args):
135 """Return a list of filenames for the given diff arguments
137 :param args: list of arguments to pass to "git diff --name-only"
140 git = context.git
141 out = git.diff(name_only=True, z=True, _readonly=True, *args)[STDOUT]
142 return _parse_diff_filenames(out)
145 def _parse_diff_filenames(out):
146 if out:
147 return out[:-1].split('\0')
148 return []
151 def tracked_files(context, *args):
152 """Return the names of all files in the repository"""
153 git = context.git
154 out = git.ls_files('--', *args, z=True, _readonly=True)[STDOUT]
155 if out:
156 return sorted(out[:-1].split('\0'))
157 return []
160 def all_files(context, *args):
161 """Returns a sorted list of all files, including untracked files."""
162 git = context.git
163 ls_files = git.ls_files(
164 '--',
165 *args,
166 z=True,
167 cached=True,
168 others=True,
169 exclude_standard=True,
170 _readonly=True,
171 )[STDOUT]
172 return sorted([f for f in ls_files.split('\0') if f])
175 class CurrentBranchCache:
176 """Cache for current_branch()"""
178 key = None
179 value = None
182 def reset():
183 """Reset cached value in this module (e.g. the cached current branch)"""
184 CurrentBranchCache.key = None
187 def current_branch(context):
188 """Return the current branch"""
189 git = context.git
190 head = git.git_path('HEAD')
191 try:
192 key = core.stat(head).st_mtime
193 if CurrentBranchCache.key == key:
194 return CurrentBranchCache.value
195 except OSError:
196 # OSError means we can't use the stat cache
197 key = 0
199 status, data, _ = git.rev_parse('HEAD', symbolic_full_name=True, _readonly=True)
200 if status != 0:
201 # git init -- read .git/HEAD. We could do this unconditionally...
202 data = _read_git_head(context, head)
204 for refs_prefix in ('refs/heads/', 'refs/remotes/', 'refs/tags/'):
205 if data.startswith(refs_prefix):
206 value = data[len(refs_prefix) :]
207 CurrentBranchCache.key = key
208 CurrentBranchCache.value = value
209 return value
210 # Detached head
211 return data
214 def _read_git_head(context, head, default='main'):
215 """Pure-python .git/HEAD reader"""
216 # Common .git/HEAD "ref: refs/heads/main" files
217 git = context.git
218 islink = core.islink(head)
219 if core.isfile(head) and not islink:
220 data = core.read(head).rstrip()
221 ref_prefix = 'ref: '
222 if data.startswith(ref_prefix):
223 return data[len(ref_prefix) :]
224 # Detached head
225 return data
226 # Legacy .git/HEAD symlinks
227 if islink:
228 refs_heads = core.realpath(git.git_path('refs', 'heads'))
229 path = core.abspath(head).replace('\\', '/')
230 if path.startswith(refs_heads + '/'):
231 return path[len(refs_heads) + 1 :]
233 return default
236 def branch_list(context, remote=False):
238 Return a list of local or remote branches
240 This explicitly removes HEAD from the list of remote branches.
243 if remote:
244 return for_each_ref_basename(context, 'refs/remotes')
245 return for_each_ref_basename(context, 'refs/heads')
248 def _version_sort(context, key='version:refname'):
249 if version.check_git(context, 'version-sort'):
250 sort = key
251 else:
252 sort = False
253 return sort
256 def for_each_ref_basename(context, refs):
257 """Return refs starting with 'refs'."""
258 git = context.git
259 sort = _version_sort(context)
260 _, out, _ = git.for_each_ref(refs, format='%(refname)', sort=sort, _readonly=True)
261 output = out.splitlines()
262 non_heads = [x for x in output if not x.endswith('/HEAD')]
263 offset = len(refs) + 1
264 return [x[offset:] for x in non_heads]
267 def _prefix_and_size(prefix, values):
268 """Return a tuple of (prefix, len(prefix) + 1, y) for <prefix>/ stripping"""
269 return (prefix, len(prefix) + 1, values)
272 def all_refs(context, split=False, sort_key='version:refname'):
273 """Return a tuple of (local branches, remote branches, tags)."""
274 git = context.git
275 local_branches = []
276 remote_branches = []
277 tags = []
278 query = (
279 _prefix_and_size('refs/tags', tags),
280 _prefix_and_size('refs/heads', local_branches),
281 _prefix_and_size('refs/remotes', remote_branches),
283 sort = _version_sort(context, key=sort_key)
284 _, out, _ = git.for_each_ref(format='%(refname)', sort=sort, _readonly=True)
285 for ref in out.splitlines():
286 for prefix, prefix_len, dst in query:
287 if ref.startswith(prefix) and not ref.endswith('/HEAD'):
288 dst.append(ref[prefix_len:])
289 continue
290 tags.reverse()
291 if split:
292 return local_branches, remote_branches, tags
293 return local_branches + remote_branches + tags
296 def tracked_branch(context, branch=None):
297 """Return the remote branch associated with 'branch'."""
298 if branch is None:
299 branch = current_branch(context)
300 if branch is None:
301 return None
302 config = context.cfg
303 remote = config.get('branch.%s.remote' % branch)
304 if not remote:
305 return None
306 merge_ref = config.get('branch.%s.merge' % branch)
307 if not merge_ref:
308 return None
309 refs_heads = 'refs/heads/'
310 if merge_ref.startswith(refs_heads):
311 return remote + '/' + merge_ref[len(refs_heads) :]
312 return None
315 def parse_remote_branch(branch):
316 """Split a remote branch apart into (remote, name) components"""
317 rgx = re.compile(r'^(?P<remote>[^/]+)/(?P<branch>.+)$')
318 match = rgx.match(branch)
319 remote = ''
320 branch = ''
321 if match:
322 remote = match.group('remote')
323 branch = match.group('branch')
324 return (remote, branch)
327 def untracked_files(context, paths=None, **kwargs):
328 """Returns a sorted list of untracked files."""
329 git = context.git
330 if paths is None:
331 paths = []
332 args = ['--'] + paths
333 out = git.ls_files(
334 z=True, others=True, exclude_standard=True, _readonly=True, *args, **kwargs
335 )[STDOUT]
336 if out:
337 return out[:-1].split('\0')
338 return []
341 def tag_list(context):
342 """Return a list of tags."""
343 result = for_each_ref_basename(context, 'refs/tags')
344 result.reverse()
345 return result
348 def log(git, *args, **kwargs):
349 return git.log(
350 no_color=True,
351 no_abbrev_commit=True,
352 no_ext_diff=True,
353 _readonly=True,
354 *args,
355 **kwargs,
356 )[STDOUT]
359 def commit_diff(context, oid):
360 git = context.git
361 return log(git, '-1', oid, '--') + '\n\n' + oid_diff(context, oid)
364 _diff_overrides = {}
367 def update_diff_overrides(space_at_eol, space_change, all_space, function_context):
368 _diff_overrides['ignore_space_at_eol'] = space_at_eol
369 _diff_overrides['ignore_space_change'] = space_change
370 _diff_overrides['ignore_all_space'] = all_space
371 _diff_overrides['function_context'] = function_context
374 def common_diff_opts(context):
375 config = context.cfg
376 # Default to --patience when diff.algorithm is unset
377 patience = not config.get('diff.algorithm', default='')
378 submodule = version.check_git(context, 'diff-submodule')
379 opts = {
380 'patience': patience,
381 'submodule': submodule,
382 'no_color': True,
383 'no_ext_diff': True,
384 'unified': config.get('gui.diffcontext', default=3),
385 '_raw': True,
386 '_readonly': True,
388 opts.update(_diff_overrides)
389 return opts
392 def _add_filename(args, filename):
393 if filename:
394 args.extend(['--', filename])
397 def oid_diff(context, oid, filename=None):
398 """Return the diff for an oid"""
399 # Naively "$oid^!" is what we'd like to use but that doesn't
400 # give the correct result for merges--the diff is reversed.
401 # Be explicit and compare oid against its first parent.
402 return oid_diff_range(context, oid + '~', oid, filename=filename)
405 def oid_diff_range(context, start, end, filename=None):
406 """Return the diff for a commit range"""
407 args = [start, end]
408 git = context.git
409 opts = common_diff_opts(context)
410 _add_filename(args, filename)
411 status, out, _ = git.diff(*args, **opts)
412 if status != 0:
413 # We probably don't have "$oid~" because this is the root commit.
414 # "git show" is clever enough to handle the root commit.
415 args = [end + '^!']
416 _add_filename(args, filename)
417 _, out, _ = git.show(pretty='format:', *args, **opts)
418 out = out.lstrip()
419 return out
422 def diff_info(context, oid, filename=None):
423 """Return the diff for the specified oid"""
424 return diff_range(context, oid + '~', oid, filename=filename)
427 def diff_range(context, start, end, filename=None):
428 """Return the diff for the specified commit range"""
429 git = context.git
430 decoded = log(git, '-1', end, '--', pretty='format:%b').strip()
431 if decoded:
432 decoded += '\n\n'
433 return decoded + oid_diff_range(context, start, end, filename=filename)
436 def diff_helper(
437 context,
438 commit=None,
439 ref=None,
440 endref=None,
441 filename=None,
442 cached=True,
443 deleted=False,
444 head=None,
445 amending=False,
446 with_diff_header=False,
447 suppress_header=True,
448 reverse=False,
449 untracked=False,
451 """Invoke git diff on a path"""
452 git = context.git
453 cfg = context.cfg
454 if commit:
455 ref, endref = commit + '^', commit
456 argv = []
457 if ref and endref:
458 argv.append(f'{ref}..{endref}')
459 elif ref:
460 argv.extend(utils.shell_split(ref.strip()))
461 elif head and amending and cached:
462 argv.append(head)
464 encoding = None
465 if untracked:
466 argv.append('--no-index')
467 argv.append(os.devnull)
468 argv.append(filename)
469 elif filename:
470 argv.append('--')
471 if isinstance(filename, (list, tuple)):
472 argv.extend(filename)
473 else:
474 argv.append(filename)
475 encoding = cfg.file_encoding(filename)
477 status, out, _ = git.diff(
478 R=reverse,
479 M=True,
480 cached=cached,
481 _encoding=encoding,
482 *argv,
483 **common_diff_opts(context),
486 success = status == 0
488 # Diff will return 1 when comparing untracked file and it has change,
489 # therefore we will check for diff header from output to differentiate
490 # from actual error such as file not found.
491 if untracked and status == 1:
492 try:
493 _, second, _ = out.split('\n', 2)
494 except ValueError:
495 second = ''
496 success = second.startswith('new file mode ')
498 if not success:
499 # git init
500 if with_diff_header:
501 return ('', '')
502 return ''
504 result = extract_diff_header(deleted, with_diff_header, suppress_header, out)
505 return core.UStr(result, out.encoding)
508 def extract_diff_header(deleted, with_diff_header, suppress_header, diffoutput):
509 """Split a diff into a header section and payload section"""
511 if diffoutput.startswith('Submodule'):
512 if with_diff_header:
513 return ('', diffoutput)
514 return diffoutput
516 start = False
517 del_tag = 'deleted file mode '
519 output = StringIO()
520 headers = StringIO()
522 for line in diffoutput.split('\n'):
523 if not start and line[:2] == '@@' and '@@' in line[2:]:
524 start = True
525 if start or (deleted and del_tag in line):
526 output.write(line + '\n')
527 else:
528 if with_diff_header:
529 headers.write(line + '\n')
530 elif not suppress_header:
531 output.write(line + '\n')
533 output_text = output.getvalue()
534 output.close()
536 headers_text = headers.getvalue()
537 headers.close()
539 if with_diff_header:
540 return (headers_text, output_text)
541 return output_text
544 def format_patchsets(context, to_export, revs, output='patches'):
546 Group contiguous revision selection into patch sets
548 Exists to handle multi-selection.
549 Multiple disparate ranges in the revision selection
550 are grouped into continuous lists.
554 outs = []
555 errs = []
557 cur_rev = to_export[0]
558 cur_rev_idx = revs.index(cur_rev)
560 patches_to_export = [[cur_rev]]
561 patchset_idx = 0
563 # Group the patches into continuous sets
564 for rev in to_export[1:]:
565 # Limit the search to the current neighborhood for efficiency
566 try:
567 rev_idx = revs[cur_rev_idx:].index(rev)
568 rev_idx += cur_rev_idx
569 except ValueError:
570 rev_idx = revs.index(rev)
572 if rev_idx == cur_rev_idx + 1:
573 patches_to_export[patchset_idx].append(rev)
574 cur_rev_idx += 1
575 else:
576 patches_to_export.append([rev])
577 cur_rev_idx = rev_idx
578 patchset_idx += 1
580 # Export each patch set
581 status = 0
582 for patchset in patches_to_export:
583 stat, out, err = export_patchset(
584 context,
585 patchset[0],
586 patchset[-1],
587 output=output,
588 n=len(patchset) > 1,
589 thread=True,
590 patch_with_stat=True,
592 outs.append(out)
593 if err:
594 errs.append(err)
595 status = max(stat, status)
596 return (status, '\n'.join(outs), '\n'.join(errs))
599 def export_patchset(context, start, end, output='patches', **kwargs):
600 """Export patches from start^ to end."""
601 git = context.git
602 return git.format_patch('-o', output, start + '^..' + end, **kwargs)
605 def reset_paths(context, head, items):
606 """Run "git reset" while preventing argument overflow"""
607 items = list(set(items))
608 func = context.git.reset
609 status, out, err = utils.slice_func(items, lambda paths: func(head, '--', *paths))
610 return (status, out, err)
613 def unstage_paths(context, args, head='HEAD'):
614 """Unstage paths while accounting for git init"""
615 status, out, err = reset_paths(context, head, args)
616 if status == 128:
617 # handle git init: we have to use 'git rm --cached'
618 # detect this condition by checking if the file is still staged
619 return untrack_paths(context, args)
620 return (status, out, err)
623 def untrack_paths(context, args):
624 if not args:
625 return (-1, N_('Nothing to do'), '')
626 git = context.git
627 return git.update_index('--', force_remove=True, *set(args))
630 def worktree_state(
631 context, head='HEAD', update_index=False, display_untracked=True, paths=None
633 """Return a dict of files in various states of being
635 :rtype: dict, keys are staged, unstaged, untracked, unmerged,
636 changed_upstream, and submodule.
638 git = context.git
639 if update_index:
640 git.update_index(refresh=True)
642 staged, unmerged, staged_deleted, staged_submods = diff_index(
643 context, head, paths=paths
645 modified, unstaged_deleted, modified_submods = diff_worktree(context, paths)
646 if display_untracked:
647 untracked = untracked_files(context, paths=paths)
648 else:
649 untracked = []
651 # Remove unmerged paths from the modified list
652 if unmerged:
653 unmerged_set = set(unmerged)
654 modified = [path for path in modified if path not in unmerged_set]
656 # Look for upstream modified files if this is a tracking branch
657 upstream_changed = diff_upstream(context, head)
659 # Keep stuff sorted
660 staged.sort()
661 modified.sort()
662 unmerged.sort()
663 untracked.sort()
664 upstream_changed.sort()
666 return {
667 'staged': staged,
668 'modified': modified,
669 'unmerged': unmerged,
670 'untracked': untracked,
671 'upstream_changed': upstream_changed,
672 'staged_deleted': staged_deleted,
673 'unstaged_deleted': unstaged_deleted,
674 'submodules': staged_submods | modified_submods,
678 def _parse_raw_diff(out):
679 while out:
680 info, path, out = out.split('\0', 2)
681 status = info[-1]
682 is_submodule = '160000' in info[1:14]
683 yield (path, status, is_submodule)
686 def diff_index(context, head, cached=True, paths=None):
687 git = context.git
688 staged = []
689 unmerged = []
690 deleted = set()
691 submodules = set()
693 if paths is None:
694 paths = []
695 args = [head, '--'] + paths
696 status, out, _ = git.diff_index(cached=cached, z=True, _readonly=True, *args)
697 if status != 0:
698 # handle git init
699 args[0] = EMPTY_TREE_OID
700 status, out, _ = git.diff_index(cached=cached, z=True, _readonly=True, *args)
702 for path, status, is_submodule in _parse_raw_diff(out):
703 if is_submodule:
704 submodules.add(path)
705 if status in 'DAMT':
706 staged.append(path)
707 if status == 'D':
708 deleted.add(path)
709 elif status == 'U':
710 unmerged.append(path)
712 return staged, unmerged, deleted, submodules
715 def diff_worktree(context, paths=None):
716 git = context.git
717 ignore_submodules_value = context.cfg.get('diff.ignoresubmodules', 'none')
718 ignore_submodules = ignore_submodules_value in {'all', 'dirty', 'untracked'}
719 modified = []
720 deleted = set()
721 submodules = set()
723 if paths is None:
724 paths = []
725 args = ['--'] + paths
726 status, out, _ = git.diff_files(z=True, _readonly=True, *args)
727 for path, status, is_submodule in _parse_raw_diff(out):
728 if is_submodule:
729 submodules.add(path)
730 if ignore_submodules:
731 continue
732 if status in 'DAMT':
733 modified.append(path)
734 if status == 'D':
735 deleted.add(path)
737 return modified, deleted, submodules
740 def diff_upstream(context, head):
741 """Given `ref`, return $(git merge-base ref HEAD)..ref."""
742 tracked = tracked_branch(context)
743 if not tracked:
744 return []
745 base = merge_base(context, head, tracked)
746 return diff_filenames(context, base, tracked)
749 def list_submodule(context):
750 """Return submodules in the format(state, sha_1, path, describe)"""
751 git = context.git
752 status, data, _ = git.submodule('status')
753 ret = []
754 if status == 0 and data:
755 data = data.splitlines()
756 # see git submodule status
757 for line in data:
758 state = line[0].strip()
759 sha1 = line[1 : OID_LENGTH + 1]
760 left_bracket = line.find('(', OID_LENGTH + 3)
761 if left_bracket == -1:
762 left_bracket = len(line) + 1
763 path = line[OID_LENGTH + 2 : left_bracket - 1]
764 describe = line[left_bracket + 1 : -1]
765 ret.append((state, sha1, path, describe))
766 return ret
769 def merge_base(context, head, ref):
770 """Return the merge-base of head and ref"""
771 git = context.git
772 return git.merge_base(head, ref, _readonly=True)[STDOUT]
775 def merge_base_parent(context, branch):
776 tracked = tracked_branch(context, branch=branch)
777 if tracked:
778 return tracked
779 return 'HEAD'
782 def ls_tree(context, path, ref='HEAD'):
783 """Return a parsed git ls-tree result for a single directory"""
784 git = context.git
785 result = []
786 status, out, _ = git.ls_tree(
787 ref, '--', path, z=True, full_tree=True, _readonly=True
789 if status == 0 and out:
790 path_offset = 6 + 1 + 4 + 1 + OID_LENGTH + 1
791 for line in out[:-1].split('\0'):
792 # 1 1 1
793 # .....6 ...4 ......................................40
794 # 040000 tree c127cde9a0c644a3a8fef449a244f47d5272dfa6 relative
795 # 100644 blob 139e42bf4acaa4927ec9be1ec55a252b97d3f1e2 relative/path
796 # 0..... 7... 12...................................... 53
797 # path_offset = 6 + 1 + 4 + 1 + OID_LENGTH(40) + 1
798 objtype = line[7:11]
799 relpath = line[path_offset:]
800 result.append((objtype, relpath))
802 return result
805 # A regex for matching the output of git(log|rev-list) --pretty=oneline
806 REV_LIST_REGEX = re.compile(r'^([0-9a-f]{40}) (.*)$')
809 def parse_rev_list(raw_revs):
810 """Parse `git log --pretty=online` output into (oid, summary) pairs."""
811 revs = []
812 for line in raw_revs.splitlines():
813 match = REV_LIST_REGEX.match(line)
814 if match:
815 rev_id = match.group(1)
816 summary = match.group(2)
817 revs.append((
818 rev_id,
819 summary,
821 return revs
824 def log_helper(context, all=False, extra_args=None):
825 """Return parallel arrays containing oids and summaries."""
826 revs = []
827 summaries = []
828 args = []
829 if extra_args:
830 args = extra_args
831 git = context.git
832 output = log(git, pretty='oneline', all=all, *args)
833 for line in output.splitlines():
834 match = REV_LIST_REGEX.match(line)
835 if match:
836 revs.append(match.group(1))
837 summaries.append(match.group(2))
838 return (revs, summaries)
841 def rev_list_range(context, start, end):
842 """Return (oid, summary) pairs between start and end."""
843 git = context.git
844 revrange = f'{start}..{end}'
845 out = git.rev_list(revrange, pretty='oneline', _readonly=True)[STDOUT]
846 return parse_rev_list(out)
849 def commit_message_path(context):
850 """Return the path to .git/GIT_COLA_MSG"""
851 git = context.git
852 path = git.git_path('GIT_COLA_MSG')
853 if core.exists(path):
854 return path
855 return None
858 def merge_message_path(context):
859 """Return the path to .git/MERGE_MSG or .git/SQUASH_MSG."""
860 git = context.git
861 for basename in ('MERGE_MSG', 'SQUASH_MSG'):
862 path = git.git_path(basename)
863 if core.exists(path):
864 return path
865 return None
868 def read_merge_commit_message(context, path):
869 """Read a merge commit message from disk while stripping commentary"""
870 content = core.read(path)
871 cleanup_mode = prefs.commit_cleanup(context)
872 if cleanup_mode in ('verbatim', 'scissors', 'whitespace'):
873 return content
874 comment_char = prefs.comment_char(context)
875 return '\n'.join(
876 line for line in content.splitlines() if not line.startswith(comment_char)
880 def prepare_commit_message_hook(context):
881 """Run the cola.preparecommitmessagehook to prepare the commit message"""
882 config = context.cfg
883 default_hook = config.hooks_path('cola-prepare-commit-msg')
884 return config.get('cola.preparecommitmessagehook', default=default_hook)
887 def cherry_pick(context, revs):
888 """Cherry-picks each revision into the current branch.
890 Returns (0, out, err) where stdout and stderr across all "git cherry-pick"
891 invocations are combined into single values when all cherry-picks succeed.
893 Returns a combined (status, out, err) of the first failing "git cherry-pick"
894 in the event of a non-zero exit status.
896 if not revs:
897 return []
898 outs = []
899 errs = []
900 status = 0
901 for rev in revs:
902 status, out, err = context.git.cherry_pick(rev)
903 if status != 0:
904 details = N_(
905 'Hint: The "Actions > Abort Cherry-Pick" menu action can be used to '
906 'cancel the current cherry-pick.'
908 output = f'# git cherry-pick {rev}\n# {details}\n\n{out}'
909 return (status, output, err)
910 outs.append(out)
911 errs.append(err)
912 return (0, '\n'.join(outs), '\n'.join(errs))
915 def abort_apply_patch(context):
916 """Abort a "git am" session."""
917 # Reset the worktree
918 git = context.git
919 status, out, err = git.am(abort=True)
920 return status, out, err
923 def abort_cherry_pick(context):
924 """Abort a cherry-pick."""
925 # Reset the worktree
926 git = context.git
927 status, out, err = git.cherry_pick(abort=True)
928 return status, out, err
931 def abort_merge(context):
932 """Abort a merge"""
933 # Reset the worktree
934 git = context.git
935 status, out, err = git.merge(abort=True)
936 return status, out, err
939 def strip_remote(remotes, remote_branch):
940 """Get branch names with the "<remote>/" prefix removed"""
941 for remote in remotes:
942 prefix = remote + '/'
943 if remote_branch.startswith(prefix):
944 return remote_branch[len(prefix) :]
945 return remote_branch.split('/', 1)[-1]
948 def parse_refs(context, argv):
949 """Parse command-line arguments into object IDs"""
950 git = context.git
951 status, out, _ = git.rev_parse(_readonly=True, *argv)
952 if status == 0:
953 oids = [oid for oid in out.splitlines() if oid]
954 else:
955 oids = argv
956 return oids
959 def prev_commitmsg(context, *args):
960 """Queries git for the latest commit message."""
961 git = context.git
962 return git.log(
963 '-1', no_color=True, pretty='format:%s%n%n%b', _readonly=True, *args
964 )[STDOUT]
967 def rev_parse(context, name):
968 """Call git rev-parse and return the output"""
969 git = context.git
970 status, out, _ = git.rev_parse(name, _readonly=True)
971 if status == 0:
972 result = out.strip()
973 else:
974 result = name
975 return result
978 def write_blob(context, oid, filename):
979 """Write a blob to a temporary file and return the path
981 Modern versions of Git allow invoking filters. Older versions
982 get the object content as-is.
985 if version.check_git(context, 'cat-file-filters-path'):
986 return cat_file_to_path(context, filename, oid)
987 return cat_file_blob(context, filename, oid)
990 def cat_file_blob(context, filename, oid):
991 """Write a blob from git to the specified filename"""
992 return cat_file(context, filename, 'blob', oid)
995 def cat_file_to_path(context, filename, oid):
996 """Extract a file from an commit ref and a write it to the specified filename"""
997 return cat_file(context, filename, oid, path=filename, filters=True)
1000 def cat_file(context, filename, *args, **kwargs):
1001 """Redirect git cat-file output to a path"""
1002 result = None
1003 git = context.git
1004 # Use the original filename in the suffix so that the generated filename
1005 # has the correct extension, and so that it resembles the original name.
1006 basename = os.path.basename(filename)
1007 suffix = '-' + basename # ensures the correct filename extension
1008 path = utils.tmp_filename('blob', suffix=suffix)
1009 with open(path, 'wb') as tmp_file:
1010 status, out, err = git.cat_file(
1011 _raw=True, _readonly=True, _stdout=tmp_file, *args, **kwargs
1013 Interaction.command(N_('Error'), 'git cat-file', status, out, err)
1014 if status == 0:
1015 result = path
1016 if not result:
1017 core.unlink(path)
1018 return result
1021 def write_blob_path(context, head, oid, filename):
1022 """Use write_blob() when modern git is available"""
1023 if version.check_git(context, 'cat-file-filters-path'):
1024 return write_blob(context, oid, filename)
1025 return cat_file_blob(context, filename, head + ':' + filename)
1028 def annex_path(context, head, filename):
1029 """Return the git-annex path for a filename at the specified commit"""
1030 git = context.git
1031 path = None
1032 annex_info = {}
1034 # unfortunately there's no way to filter this down to a single path
1035 # so we just have to scan all reported paths
1036 status, out, _ = git.annex('findref', '--json', head, _readonly=True)
1037 if status == 0:
1038 for line in out.splitlines():
1039 info = json.loads(line)
1040 try:
1041 annex_file = info['file']
1042 except (ValueError, KeyError):
1043 continue
1044 # we only care about this file so we can skip the rest
1045 if annex_file == filename:
1046 annex_info = info
1047 break
1048 key = annex_info.get('key', '')
1049 if key:
1050 status, out, _ = git.annex('contentlocation', key, _readonly=True)
1051 if status == 0 and os.path.exists(out):
1052 path = out
1054 return path
1057 def is_binary(context, filename):
1058 """A heuristic to determine whether `filename` contains (non-text) binary content"""
1059 cfg_is_binary = context.cfg.is_binary(filename)
1060 if cfg_is_binary is not None:
1061 return cfg_is_binary
1062 # This is the same heuristic as xdiff-interface.c:buffer_is_binary().
1063 size = 8000
1064 try:
1065 result = core.read(filename, size=size, encoding='bytes')
1066 except OSError:
1067 result = b''
1069 return b'\0' in result
1072 def is_valid_ref(context, ref):
1073 """Is the provided Git ref a valid refname?"""
1074 status, _, _ = context.git.rev_parse(ref, quiet=True, verify=True, _readonly=True)
1075 return status == 0