1 """Git commands and queries for Git"""
5 from io
import StringIO
10 from .git
import STDOUT
11 from .git
import EMPTY_TREE_OID
12 from .git
import OID_LENGTH
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"""
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"""
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
)
81 status
, out
, _
= diff_tree(context
, EMPTY_TREE_OID
, oid
)
83 result
= _parse_diff_filenames(out
)
89 def diff_tree(context
, *args
):
90 """Return a list of filenames that have been modified"""
92 return git_diff_tree(git
, *args
)
95 def git_diff_tree(git
, *args
):
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
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])
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])
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"
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
):
147 return out
[:-1].split('\0')
151 def tracked_files(context
, *args
):
152 """Return the names of all files in the repository"""
154 out
= git
.ls_files('--', *args
, z
=True, _readonly
=True)[STDOUT
]
156 return sorted(out
[:-1].split('\0'))
160 def all_files(context
, *args
):
161 """Returns a sorted list of all files, including untracked files."""
163 ls_files
= git
.ls_files(
169 exclude_standard
=True,
172 return sorted([f
for f
in ls_files
.split('\0') if f
])
175 class CurrentBranchCache
:
176 """Cache for current_branch()"""
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"""
190 head
= git
.git_path('HEAD')
192 key
= core
.stat(head
).st_mtime
193 if CurrentBranchCache
.key
== key
:
194 return CurrentBranchCache
.value
196 # OSError means we can't use the stat cache
199 status
, data
, _
= git
.rev_parse('HEAD', symbolic_full_name
=True, _readonly
=True)
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
214 def _read_git_head(context
, head
, default
='main'):
215 """Pure-python .git/HEAD reader"""
216 # Common .git/HEAD "ref: refs/heads/main" files
218 islink
= core
.islink(head
)
219 if core
.isfile(head
) and not islink
:
220 data
= core
.read(head
).rstrip()
222 if data
.startswith(ref_prefix
):
223 return data
[len(ref_prefix
) :]
226 # Legacy .git/HEAD symlinks
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 :]
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.
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'):
256 def for_each_ref_basename(context
, refs
):
257 """Return refs starting with 'refs'."""
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)."""
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
:])
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'."""
299 branch
= current_branch(context
)
303 remote
= config
.get('branch.%s.remote' % branch
)
306 merge_ref
= config
.get('branch.%s.merge' % branch
)
309 refs_heads
= 'refs/heads/'
310 if merge_ref
.startswith(refs_heads
):
311 return remote
+ '/' + merge_ref
[len(refs_heads
) :]
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
)
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."""
332 args
= ['--'] + paths
334 z
=True, others
=True, exclude_standard
=True, _readonly
=True, *args
, **kwargs
337 return out
[:-1].split('\0')
341 def tag_list(context
):
342 """Return a list of tags."""
343 result
= for_each_ref_basename(context
, 'refs/tags')
348 def log(git
, *args
, **kwargs
):
351 no_abbrev_commit
=True,
359 def commit_diff(context
, oid
):
361 return log(git
, '-1', oid
, '--') + '\n\n' + oid_diff(context
, oid
)
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
):
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')
380 'patience': patience
,
381 'submodule': submodule
,
384 'unified': config
.get('gui.diffcontext', default
=3),
388 opts
.update(_diff_overrides
)
392 def _add_filename(args
, 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"""
409 opts
= common_diff_opts(context
)
410 _add_filename(args
, filename
)
411 status
, out
, _
= git
.diff(*args
, **opts
)
413 # We probably don't have "$oid~" because this is the root commit.
414 # "git show" is clever enough to handle the root commit.
416 _add_filename(args
, filename
)
417 _
, out
, _
= git
.show(pretty
='format:', *args
, **opts
)
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"""
430 decoded
= log(git
, '-1', end
, '--', pretty
='format:%b').strip()
433 return decoded
+ oid_diff_range(context
, start
, end
, filename
=filename
)
446 with_diff_header
=False,
447 suppress_header
=True,
451 """Invoke git diff on a path"""
455 ref
, endref
= commit
+ '^', commit
458 argv
.append(f
'{ref}..{endref}')
460 argv
.extend(utils
.shell_split(ref
.strip()))
461 elif head
and amending
and cached
:
466 argv
.append('--no-index')
467 argv
.append(os
.devnull
)
468 argv
.append(filename
)
471 if isinstance(filename
, (list, tuple)):
472 argv
.extend(filename
)
474 argv
.append(filename
)
475 encoding
= cfg
.file_encoding(filename
)
477 status
, out
, _
= git
.diff(
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:
493 _
, second
, _
= out
.split('\n', 2)
496 success
= second
.startswith('new file mode ')
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'):
513 return ('', diffoutput
)
517 del_tag
= 'deleted file mode '
522 for line
in diffoutput
.split('\n'):
523 if not start
and line
[:2] == '@@' and '@@' in line
[2:]:
525 if start
or (deleted
and del_tag
in line
):
526 output
.write(line
+ '\n')
529 headers
.write(line
+ '\n')
530 elif not suppress_header
:
531 output
.write(line
+ '\n')
533 output_text
= output
.getvalue()
536 headers_text
= headers
.getvalue()
540 return (headers_text
, 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.
557 cur_rev
= to_export
[0]
558 cur_rev_idx
= revs
.index(cur_rev
)
560 patches_to_export
= [[cur_rev
]]
563 # Group the patches into continuous sets
564 for rev
in to_export
[1:]:
565 # Limit the search to the current neighborhood for efficiency
567 rev_idx
= revs
[cur_rev_idx
:].index(rev
)
568 rev_idx
+= cur_rev_idx
570 rev_idx
= revs
.index(rev
)
572 if rev_idx
== cur_rev_idx
+ 1:
573 patches_to_export
[patchset_idx
].append(rev
)
576 patches_to_export
.append([rev
])
577 cur_rev_idx
= rev_idx
580 # Export each patch set
582 for patchset
in patches_to_export
:
583 stat
, out
, err
= export_patchset(
590 patch_with_stat
=True,
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."""
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
)
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
):
625 return (-1, N_('Nothing to do'), '')
627 return git
.update_index('--', force_remove
=True, *set(args
))
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.
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
)
651 # Remove unmerged paths from the modified list
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
)
664 upstream_changed
.sort()
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
):
680 info
, path
, out
= out
.split('\0', 2)
682 is_submodule
= '160000' in info
[1:14]
683 yield (path
, status
, is_submodule
)
686 def diff_index(context
, head
, cached
=True, paths
=None):
695 args
= [head
, '--'] + paths
696 status
, out
, _
= git
.diff_index(cached
=cached
, z
=True, _readonly
=True, *args
)
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
):
710 unmerged
.append(path
)
712 return staged
, unmerged
, deleted
, submodules
715 def diff_worktree(context
, paths
=None):
717 ignore_submodules_value
= context
.cfg
.get('diff.ignoresubmodules', 'none')
718 ignore_submodules
= ignore_submodules_value
in {'all', 'dirty', 'untracked'}
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
):
730 if ignore_submodules
:
733 modified
.append(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
)
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)"""
752 status
, data
, _
= git
.submodule('status')
754 if status
== 0 and data
:
755 data
= data
.splitlines()
756 # see git submodule status
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
))
769 def merge_base(context
, head
, ref
):
770 """Return the merge-base of head and ref"""
772 return git
.merge_base(head
, ref
, _readonly
=True)[STDOUT
]
775 def merge_base_parent(context
, branch
):
776 tracked
= tracked_branch(context
, branch
=branch
)
782 def ls_tree(context
, path
, ref
='HEAD'):
783 """Return a parsed git ls-tree result for a single directory"""
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'):
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
799 relpath
= line
[path_offset
:]
800 result
.append((objtype
, relpath
))
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."""
812 for line
in raw_revs
.splitlines():
813 match
= REV_LIST_REGEX
.match(line
)
815 rev_id
= match
.group(1)
816 summary
= match
.group(2)
824 def log_helper(context
, all
=False, extra_args
=None):
825 """Return parallel arrays containing oids and summaries."""
832 output
= log(git
, pretty
='oneline', all
=all
, *args
)
833 for line
in output
.splitlines():
834 match
= REV_LIST_REGEX
.match(line
)
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."""
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"""
852 path
= git
.git_path('GIT_COLA_MSG')
853 if core
.exists(path
):
858 def merge_message_path(context
):
859 """Return the path to .git/MERGE_MSG or .git/SQUASH_MSG."""
861 for basename
in ('MERGE_MSG', 'SQUASH_MSG'):
862 path
= git
.git_path(basename
)
863 if core
.exists(path
):
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'):
874 comment_char
= prefs
.comment_char(context
)
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"""
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.
902 status
, out
, err
= context
.git
.cherry_pick(rev
)
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
)
912 return (0, '\n'.join(outs
), '\n'.join(errs
))
915 def abort_apply_patch(context
):
916 """Abort a "git am" session."""
919 status
, out
, err
= git
.am(abort
=True)
920 return status
, out
, err
923 def abort_cherry_pick(context
):
924 """Abort a cherry-pick."""
927 status
, out
, err
= git
.cherry_pick(abort
=True)
928 return status
, out
, err
931 def abort_merge(context
):
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"""
951 status
, out
, _
= git
.rev_parse(_readonly
=True, *argv
)
953 oids
= [oid
for oid
in out
.splitlines() if oid
]
959 def prev_commitmsg(context
, *args
):
960 """Queries git for the latest commit message."""
963 '-1', no_color
=True, pretty
='format:%s%n%n%b', _readonly
=True, *args
967 def rev_parse(context
, name
):
968 """Call git rev-parse and return the output"""
970 status
, out
, _
= git
.rev_parse(name
, _readonly
=True)
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"""
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
)
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"""
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)
1038 for line
in out
.splitlines():
1039 info
= json
.loads(line
)
1041 annex_file
= info
['file']
1042 except (ValueError, KeyError):
1044 # we only care about this file so we can skip the rest
1045 if annex_file
== filename
:
1048 key
= annex_info
.get('key', '')
1050 status
, out
, _
= git
.annex('contentlocation', key
, _readonly
=True)
1051 if status
== 0 and os
.path
.exists(out
):
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().
1065 result
= core
.read(filename
, size
=size
, encoding
='bytes')
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)