1 """Git commands and queries for Git"""
2 from __future__
import absolute_import
, division
, print_function
, unicode_literals
6 from io
import StringIO
11 from .git
import STDOUT
12 from .git
import EMPTY_TREE_OID
13 from .git
import OID_LENGTH
15 from .interaction
import Interaction
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_fn(
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"""
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"""
35 return git
.apply(filename
)
38 def get_branch(context
, branch
):
39 """Get the current branch"""
41 branch
= current_branch(context
)
45 def upstream_remote(context
, branch
=None):
46 """Return the remote associated with the specified branch"""
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"""
55 url
= config
.get('remote.%s.url' % remote
, '')
57 url
= config
.get('remote.%s.pushurl' % remote
, url
)
61 def diff_index_filenames(context
, ref
):
63 Return a diff of filenames that have been modified relative to the index
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"""
74 name_only
=True, no_commit_id
=True, r
=True, z
=True, _readonly
=True, *args
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
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
)
93 if entry
[0][0] == 't': # tree
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])
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"
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
):
125 return out
[:-1].split('\0')
129 def tracked_files(context
, *args
):
130 """Return the names of all files in the repository"""
132 out
= git
.ls_files('--', *args
, z
=True, _readonly
=True)[STDOUT
]
134 return sorted(out
[:-1].split('\0'))
138 def all_files(context
, *args
):
139 """Returns a sorted list of all files, including untracked files."""
141 ls_files
= git
.ls_files(
147 exclude_standard
=True,
150 return sorted([f
for f
in ls_files
.split('\0') if f
])
153 class CurrentBranchCache(object):
154 """Cache for current_branch()"""
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"""
168 head
= git
.git_path('HEAD')
170 key
= core
.stat(head
).st_mtime
171 if CurrentBranchCache
.key
== key
:
172 return CurrentBranchCache
.value
174 # OSError means we can't use the stat cache
177 status
, data
, _
= git
.rev_parse('HEAD', symbolic_full_name
=True, _readonly
=True)
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
192 def _read_git_head(context
, head
, default
='main'):
193 """Pure-python .git/HEAD reader"""
194 # Common .git/HEAD "ref: refs/heads/main" files
196 islink
= core
.islink(head
)
197 if core
.isfile(head
) and not islink
:
198 data
= core
.read(head
).rstrip()
200 if data
.startswith(ref_prefix
):
201 return data
[len(ref_prefix
) :]
204 # Legacy .git/HEAD symlinks
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 :]
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.
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'):
234 def for_each_ref_basename(context
, refs
):
235 """Return refs starting with 'refs'."""
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)."""
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
:])
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'."""
277 branch
= current_branch(context
)
281 remote
= config
.get('branch.%s.remote' % branch
)
284 merge_ref
= config
.get('branch.%s.merge' % branch
)
287 refs_heads
= 'refs/heads/'
288 if merge_ref
.startswith(refs_heads
):
289 return remote
+ '/' + merge_ref
[len(refs_heads
) :]
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
)
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."""
310 args
= ['--'] + paths
312 z
=True, others
=True, exclude_standard
=True, _readonly
=True, *args
, **kwargs
315 return out
[:-1].split('\0')
319 def tag_list(context
):
320 """Return a list of tags."""
321 result
= for_each_ref_basename(context
, 'refs/tags')
326 def log(git
, *args
, **kwargs
):
329 no_abbrev_commit
=True,
337 def commit_diff(context
, oid
):
339 return log(git
, '-1', oid
, '--') + '\n\n' + oid_diff(context
, oid
)
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
):
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')
358 'patience': patience
,
359 'submodule': submodule
,
362 'unified': config
.get('gui.diffcontext', default
=3),
365 opts
.update(_diff_overrides
)
369 def _add_filename(args
, filename
):
371 args
.extend(['--', filename
])
374 def oid_diff(context
, oid
, filename
=None):
375 """Return the diff for an oid"""
376 # Naively "$oid^!" is what we'd like to use but that doesn't
377 # give the correct result for merges--the diff is reversed.
378 # Be explicit and compare oid against its first parent.
379 return oid_diff_range(context
, oid
+ '~', oid
, filename
=filename
)
382 def oid_diff_range(context
, start
, end
, filename
=None):
383 """Reeturn the diff for a commit range"""
386 opts
= common_diff_opts(context
)
387 _add_filename(args
, filename
)
388 status
, out
, _
= git
.diff(*args
, **opts
)
390 # We probably don't have "$oid~" because this is the root commit.
391 # "git show" is clever enough to handle the root commit.
393 _add_filename(args
, filename
)
394 _
, out
, _
= git
.show(pretty
='format:', _readonly
=True, *args
, **opts
)
399 def diff_info(context
, oid
, filename
=None):
400 """Return the diff for the specified oid"""
401 return diff_range(context
, oid
+ '~', oid
, filename
=filename
)
404 def diff_range(context
, start
, end
, filename
=None):
405 """Return the diff for the specified commit range"""
407 decoded
= log(git
, '-1', end
, '--', pretty
='format:%b').strip()
410 return decoded
+ oid_diff_range(context
, start
, end
, filename
=filename
)
413 # pylint: disable=too-many-arguments
424 with_diff_header
=False,
425 suppress_header
=True,
429 "Invokes git diff on a filepath."
433 ref
, endref
= commit
+ '^', commit
436 argv
.append('%s..%s' % (ref
, endref
))
438 argv
.extend(utils
.shell_split(ref
.strip()))
439 elif head
and amending
and cached
:
444 argv
.append('--no-index')
445 argv
.append(os
.devnull
)
446 argv
.append(filename
)
449 if isinstance(filename
, (list, tuple)):
450 argv
.extend(filename
)
452 argv
.append(filename
)
453 encoding
= cfg
.file_encoding(filename
)
455 status
, out
, _
= git
.diff(
461 **common_diff_opts(context
)
464 success
= status
== 0
466 # Diff will return 1 when comparing untracked file and it has change,
467 # therefore we will check for diff header from output to differentiate
468 # from actual error such as file not found.
469 if untracked
and status
== 1:
471 _
, second
, _
= out
.split('\n', 2)
474 success
= second
.startswith('new file mode ')
482 result
= extract_diff_header(deleted
, with_diff_header
, suppress_header
, out
)
483 return core
.UStr(result
, out
.encoding
)
486 def extract_diff_header(deleted
, with_diff_header
, suppress_header
, diffoutput
):
487 """Split a diff into a header section and payload section"""
489 if diffoutput
.startswith('Submodule'):
491 return ('', diffoutput
)
495 del_tag
= 'deleted file mode '
500 for line
in diffoutput
.split('\n'):
501 if not start
and line
[:2] == '@@' and '@@' in line
[2:]:
503 if start
or (deleted
and del_tag
in line
):
504 output
.write(line
+ '\n')
507 headers
.write(line
+ '\n')
508 elif not suppress_header
:
509 output
.write(line
+ '\n')
511 output_text
= output
.getvalue()
514 headers_text
= headers
.getvalue()
518 return (headers_text
, output_text
)
522 def format_patchsets(context
, to_export
, revs
, output
='patches'):
524 Group contiguous revision selection into patchsets
526 Exists to handle multi-selection.
527 Multiple disparate ranges in the revision selection
528 are grouped into continuous lists.
535 cur_rev
= to_export
[0]
536 cur_rev_idx
= revs
.index(cur_rev
)
538 patches_to_export
= [[cur_rev
]]
541 # Group the patches into continuous sets
542 for rev
in to_export
[1:]:
543 # Limit the search to the current neighborhood for efficiency
545 rev_idx
= revs
[cur_rev_idx
:].index(rev
)
546 rev_idx
+= cur_rev_idx
548 rev_idx
= revs
.index(rev
)
550 if rev_idx
== cur_rev_idx
+ 1:
551 patches_to_export
[patchset_idx
].append(rev
)
554 patches_to_export
.append([rev
])
555 cur_rev_idx
= rev_idx
558 # Export each patchsets
560 for patchset
in patches_to_export
:
561 stat
, out
, err
= export_patchset(
568 patch_with_stat
=True,
573 status
= max(stat
, status
)
574 return (status
, '\n'.join(outs
), '\n'.join(errs
))
577 def export_patchset(context
, start
, end
, output
='patches', **kwargs
):
578 """Export patches from start^ to end."""
580 return git
.format_patch('-o', output
, start
+ '^..' + end
, **kwargs
)
583 def reset_paths(context
, head
, items
):
584 """Run "git reset" while preventing argument overflow"""
585 items
= list(set(items
))
586 fn
= context
.git
.reset
587 status
, out
, err
= utils
.slice_fn(items
, lambda paths
: fn(head
, '--', *paths
))
588 return (status
, out
, err
)
591 def unstage_paths(context
, args
, head
='HEAD'):
592 """Unstage paths while accounting for git init"""
593 status
, out
, err
= reset_paths(context
, head
, args
)
595 # handle git init: we have to use 'git rm --cached'
596 # detect this condition by checking if the file is still staged
597 return untrack_paths(context
, args
)
598 return (status
, out
, err
)
601 def untrack_paths(context
, args
):
603 return (-1, N_('Nothing to do'), '')
605 return git
.update_index('--', force_remove
=True, *set(args
))
609 context
, head
='HEAD', update_index
=False, display_untracked
=True, paths
=None
611 """Return a dict of files in various states of being
613 :rtype: dict, keys are staged, unstaged, untracked, unmerged,
614 changed_upstream, and submodule.
619 git
.update_index(refresh
=True)
621 staged
, unmerged
, staged_deleted
, staged_submods
= diff_index(
622 context
, head
, paths
=paths
624 modified
, unstaged_deleted
, modified_submods
= diff_worktree(context
, paths
)
625 if display_untracked
:
626 untracked
= untracked_files(context
, paths
=paths
)
630 # Remove unmerged paths from the modified list
632 unmerged_set
= set(unmerged
)
633 modified
= [path
for path
in modified
if path
not in unmerged_set
]
635 # Look for upstream modified files if this is a tracking branch
636 upstream_changed
= diff_upstream(context
, head
)
643 upstream_changed
.sort()
647 'modified': modified
,
648 'unmerged': unmerged
,
649 'untracked': untracked
,
650 'upstream_changed': upstream_changed
,
651 'staged_deleted': staged_deleted
,
652 'unstaged_deleted': unstaged_deleted
,
653 'submodules': staged_submods | modified_submods
,
657 def _parse_raw_diff(out
):
659 info
, path
, out
= out
.split('\0', 2)
661 is_submodule
= '160000' in info
[1:14]
662 yield (path
, status
, is_submodule
)
665 def diff_index(context
, head
, cached
=True, paths
=None):
674 args
= [head
, '--'] + paths
675 status
, out
, _
= git
.diff_index(cached
=cached
, z
=True, _readonly
=True, *args
)
678 args
[0] = EMPTY_TREE_OID
679 status
, out
, _
= git
.diff_index(cached
=cached
, z
=True, _readonly
=True, *args
)
681 for path
, status
, is_submodule
in _parse_raw_diff(out
):
689 unmerged
.append(path
)
691 return staged
, unmerged
, deleted
, submodules
694 def diff_worktree(context
, paths
=None):
696 ignore_submodules_value
= context
.cfg
.get('diff.ignoresubmodules', 'none')
697 ignore_submodules
= ignore_submodules_value
in {'all', 'dirty', 'untracked'}
704 args
= ['--'] + paths
705 status
, out
, _
= git
.diff_files(z
=True, _readonly
=True, *args
)
706 for path
, status
, is_submodule
in _parse_raw_diff(out
):
709 if ignore_submodules
:
712 modified
.append(path
)
716 return modified
, deleted
, submodules
719 def diff_upstream(context
, head
):
720 """Given `ref`, return $(git merge-base ref HEAD)..ref."""
721 tracked
= tracked_branch(context
)
724 base
= merge_base(context
, head
, tracked
)
725 return diff_filenames(context
, base
, tracked
)
728 def list_submodule(context
):
729 """Return submodules in the format(state, sha1, path, describe)"""
731 status
, data
, _
= git
.submodule('status')
733 if status
== 0 and data
:
734 data
= data
.splitlines()
735 # see git submodule status
736 # TODO better separation
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
))
749 def merge_base(context
, head
, ref
):
750 """Return the merge-base of head and ref"""
752 return git
.merge_base(head
, ref
, _readonly
=True)[STDOUT
]
755 def merge_base_parent(context
, branch
):
756 tracked
= tracked_branch(context
, branch
=branch
)
763 def parse_ls_tree(context
, rev
):
764 """Return a list of (mode, type, oid, path) tuples."""
767 lines
= git
.ls_tree(rev
, r
=True, _readonly
=True)[STDOUT
].splitlines()
768 regex
= re
.compile(r
'^(\d+)\W(\w+)\W(\w+)[ \t]+(.*)$')
770 match
= regex
.match(line
)
772 mode
= match
.group(1)
773 objtype
= match
.group(2)
775 filename
= match
.group(4)
788 def ls_tree(context
, path
, ref
='HEAD'):
789 """Return a parsed git ls-tree result for a single directory"""
792 status
, out
, _
= git
.ls_tree(
793 ref
, '--', path
, z
=True, full_tree
=True, _readonly
=True
795 if status
== 0 and out
:
796 path_offset
= 6 + 1 + 4 + 1 + OID_LENGTH
+ 1
797 for line
in out
[:-1].split('\0'):
799 # .....6 ...4 ......................................40
800 # 040000 tree c127cde9a0c644a3a8fef449a244f47d5272dfa6 relative
801 # 100644 blob 139e42bf4acaa4927ec9be1ec55a252b97d3f1e2 relative/path
802 # 0..... 7... 12...................................... 53
803 # path_offset = 6 + 1 + 4 + 1 + OID_LENGTH(40) + 1
805 relpath
= line
[path_offset
:]
806 result
.append((objtype
, relpath
))
811 # A regex for matching the output of git(log|rev-list) --pretty=oneline
812 REV_LIST_REGEX
= re
.compile(r
'^([0-9a-f]{40}) (.*)$')
815 def parse_rev_list(raw_revs
):
816 """Parse `git log --pretty=online` output into (oid, summary) pairs."""
818 for line
in raw_revs
.splitlines():
819 match
= REV_LIST_REGEX
.match(line
)
821 rev_id
= match
.group(1)
822 summary
= match
.group(2)
832 # pylint: disable=redefined-builtin
833 def log_helper(context
, all
=False, extra_args
=None):
834 """Return parallel arrays containing oids and summaries."""
841 output
= log(git
, pretty
='oneline', all
=all
, *args
)
842 for line
in output
.splitlines():
843 match
= REV_LIST_REGEX
.match(line
)
845 revs
.append(match
.group(1))
846 summaries
.append(match
.group(2))
847 return (revs
, summaries
)
850 def rev_list_range(context
, start
, end
):
851 """Return (oid, summary) pairs between start and end."""
853 revrange
= '%s..%s' % (start
, end
)
854 out
= git
.rev_list(revrange
, pretty
='oneline', _readonly
=True)[STDOUT
]
855 return parse_rev_list(out
)
858 def commit_message_path(context
):
859 """Return the path to .git/GIT_COLA_MSG"""
861 path
= git
.git_path('GIT_COLA_MSG')
862 if core
.exists(path
):
867 def merge_message_path(context
):
868 """Return the path to .git/MERGE_MSG or .git/SQUASH_MSG."""
870 for basename
in ('MERGE_MSG', 'SQUASH_MSG'):
871 path
= git
.git_path(basename
)
872 if core
.exists(path
):
877 def prepare_commit_message_hook(context
):
878 """Run the cola.preparecommitmessagehook to prepare the commit message"""
880 default_hook
= config
.hooks_path('cola-prepare-commit-msg')
881 return config
.get('cola.preparecommitmessagehook', default
=default_hook
)
884 def cherry_pick(context
, revs
):
885 """Cherry-picks each revision into the current branch.
887 Returns (0, out, err) where stdout and stderr across all "git cherry-pick"
888 invocations are combined into single values when all cherry-picks succeed.
890 Returns a combined (status, out, err) of the first failing "git cherry-pick"
891 in the event of a non-zero exit status.
899 status
, out
, err
= context
.git
.cherry_pick(rev
)
902 'Hint: The "Actions > Abort Cherry-Pick" menu action can be used to '
903 'cancel the current cherry-pick.'
905 output
= '# git cherry-pick %s\n# %s\n\n%s' % (rev
, details
, out
)
906 return (status
, output
, err
)
909 return (0, '\n'.join(outs
), '\n'.join(errs
))
912 def abort_apply_patch(context
):
913 """Abort a "git am" session."""
916 status
, out
, err
= git
.am(abort
=True)
917 return status
, out
, err
920 def abort_cherry_pick(context
):
921 """Abort a cherry-pick."""
924 status
, out
, err
= git
.cherry_pick(abort
=True)
925 return status
, out
, err
928 def abort_merge(context
):
932 status
, out
, err
= git
.merge(abort
=True)
933 return status
, out
, err
936 def strip_remote(remotes
, remote_branch
):
937 """Get branch names with the "<remote>/" prefix removed"""
938 for remote
in remotes
:
939 prefix
= remote
+ '/'
940 if remote_branch
.startswith(prefix
):
941 return remote_branch
[len(prefix
) :]
942 return remote_branch
.split('/', 1)[-1]
945 def parse_refs(context
, argv
):
946 """Parse command-line arguments into object IDs"""
948 status
, out
, _
= git
.rev_parse(_readonly
=True, *argv
)
950 oids
= [oid
for oid
in out
.splitlines() if oid
]
956 def prev_commitmsg(context
, *args
):
957 """Queries git for the latest commit message."""
960 '-1', no_color
=True, pretty
='format:%s%n%n%b', _readonly
=True, *args
964 def rev_parse(context
, name
):
965 """Call git rev-parse and return the output"""
967 status
, out
, _
= git
.rev_parse(name
, _readonly
=True)
975 def write_blob(context
, oid
, filename
):
976 """Write a blob to a temporary file and return the path
978 Modern versions of Git allow invoking filters. Older versions
979 get the object content as-is.
982 if version
.check_git(context
, 'cat-file-filters-path'):
983 return cat_file_to_path(context
, filename
, oid
)
984 return cat_file_blob(context
, filename
, oid
)
987 def cat_file_blob(context
, filename
, oid
):
988 """Write a blob from git to the specified filename"""
989 return cat_file(context
, filename
, 'blob', oid
)
992 def cat_file_to_path(context
, filename
, oid
):
993 """Extract a file from an commit ref and a write it to the specified filename"""
994 return cat_file(context
, filename
, oid
, path
=filename
, filters
=True)
997 def cat_file(context
, filename
, *args
, **kwargs
):
998 """Redirect git cat-file output to a path"""
1001 # Use the original filename in the suffix so that the generated filename
1002 # has the correct extension, and so that it resembles the original name.
1003 basename
= os
.path
.basename(filename
)
1004 suffix
= '-' + basename
# ensures the correct filename extension
1005 path
= utils
.tmp_filename('blob', suffix
=suffix
)
1006 with
open(path
, 'wb') as tmp_file
:
1007 status
, out
, err
= git
.cat_file(
1008 _raw
=True, _readonly
=True, _stdout
=tmp_file
, *args
, **kwargs
1010 Interaction
.command(N_('Error'), 'git cat-file', status
, out
, err
)
1018 def write_blob_path(context
, head
, oid
, filename
):
1019 """Use write_blob() when modern git is available"""
1020 if version
.check_git(context
, 'cat-file-filters-path'):
1021 return write_blob(context
, oid
, filename
)
1022 return cat_file_blob(context
, filename
, head
+ ':' + filename
)
1025 def annex_path(context
, head
, filename
):
1026 """Return the git-annex path for a filename at the specified commit"""
1031 # unfortunately there's no way to filter this down to a single path
1032 # so we just have to scan all reported paths
1033 status
, out
, _
= git
.annex('findref', '--json', head
, _readonly
=True)
1035 for line
in out
.splitlines():
1036 info
= json
.loads(line
)
1038 annex_file
= info
['file']
1039 except (ValueError, KeyError):
1041 # we only care about this file so we can skip the rest
1042 if annex_file
== filename
:
1045 key
= annex_info
.get('key', '')
1047 status
, out
, _
= git
.annex('contentlocation', key
, _readonly
=True)
1048 if status
== 0 and os
.path
.exists(out
):
1054 def is_binary(context
, filename
):
1055 """A heustic to determine whether `filename` contains (non-text) binary content"""
1056 cfg_is_binary
= context
.cfg
.is_binary(filename
)
1057 if cfg_is_binary
is not None:
1058 return cfg_is_binary
1059 # This is the same heuristic as xdiff-interface.c:buffer_is_binary().
1062 result
= core
.read(filename
, size
=size
, encoding
='bytes')
1063 except (IOError, OSError):
1066 return b
'\0' in result
1069 def is_valid_ref(context
, ref
):
1070 """Is the provided Git ref a valid refname?"""
1071 status
, _
, _
= context
.git
.rev_parse(ref
, quiet
=True, verify
=True, _readonly
=True)