Debian Codegraph @

lua/gitsigns/git/repo.lua

raw
1 local async = require('gitsigns.async')
2 local git_command = require('gitsigns.git.cmd')
3 local config = require('gitsigns.config').config
4 local log = require('gitsigns.debug.log')
5 local util = require('gitsigns.util')
6 local Path = util.Path
7 local errors = require('gitsigns.git.errors')
8 local Watcher = require('gitsigns.git.repo.watcher')
9
10 local check_version = require('gitsigns.git.version').check
11
12 local uv = vim.uv or vim.loop ---@diagnostic disable-line: deprecated
13
14 --- @class Gitsigns.RepoInfo
15 --- @field gitdir string
16 --- @field toplevel string
17 --- @field detached boolean
18 --- @field abbrev_head string
19
20 --- @class Gitsigns.Repo : Gitsigns.RepoInfo
21 ---
22 --- Username configured for the repo.
23 --- Needed for to determine "You" in current line blame.
24 --- @field username string
25 --- @field private _lock Gitsigns.async.Semaphore
26 --- @field private _watcher? Gitsigns.Repo.Watcher
27 --- @field head_oid? string
28 --- @field head_ref? string
29 --- @field commondir string
30 local M = {}
31
32 --- @param gitdir string
33 --- @return boolean
34 local function is_rebasing(gitdir)
35 return Path.exists(Path.join(gitdir, 'rebase-merge'))
36 or Path.exists(Path.join(gitdir, 'rebase-apply'))
37 end
38
39 --- @param value string?
40 --- @return string?
41 local function trim(value)
42 if not value then
43 -- Preserve nil to signal "no value".
44 return
45 end
46 -- Normalize line endings/whitespace from ref files.
47 local trimmed = vim.trim(value)
48 -- Treat whitespace-only lines as absent.
49 return trimmed ~= '' and trimmed or nil
50 end
51
52 --- @param path string
53 --- @return string?
54 local function read_first_line(path)
55 local f = io.open(path, 'r')
56 if not f then
57 return
58 end
59 local line = f:read('*l')
60 f:close()
61 return trim(line)
62 end
63
64 --- @param path string
65 local function wait_for_unlock(path)
66 -- Git updates refs by taking `<ref>.lock` and then renaming into place.
67 -- Wait briefly so we don't read transient state when reacting to fs events.
68 --
69 -- TODO(lewis6991): should this be async?
70 vim.wait(1000, function()
71 return not Path.exists(path .. '.lock')
72 end, 10, true)
73 end
74
75 --- Wait for `<path>.lock` to clear then read the first line of a file.
76 --- @param path string
77 --- @return string?
78 local function read_first_line_wait(path)
79 wait_for_unlock(path)
80 return read_first_line(path)
81 end
82
83 --- @param gitdir string
84 --- @return string?
85 local function read_head(gitdir)
86 return read_first_line_wait(Path.join(gitdir, 'HEAD'))
87 end
88
89 --- @param head string?
90 --- @return string?
91 local function parse_head_ref(head)
92 return head and head:match('^ref:%s*(.+)$') or nil
93 end
94
95 --- Return the abbreviated ref for HEAD (or short SHA if detached).
96 --- Equivalent to `git rev-parse --abbrev-ref HEAD`
97 --- @param gitdir string Must be an absolute path to the .git directory
98 --- @param head? string
99 --- @return string abbrev_head
100 local function get_abbrev_head(gitdir, head)
101 head = head or assert(read_head(gitdir))
102 -- HEAD content is either:
103 -- "ref: refs/heads/<branch>"
104 -- "<commitsha>" (detached HEAD)
105 local refpath = parse_head_ref(head)
106 if refpath then
107 return refpath:match('^refs/heads/(.+)$') or refpath
108 end
109
110 assert(head:find('^[%x]+$'), 'Invalid HEAD content: ' .. head)
111
112 -- Detached HEAD -> like `git rev-parse --abbrev-ref HEAD`, return literal "HEAD"
113 local short_sha = log.debug_mode() and 'HEAD' or head:sub(1, 7)
114
115 if is_rebasing(gitdir) then
116 short_sha = short_sha .. '(rebasing)'
117 end
118 return short_sha
119 end
120
121 --- @param gitdir string
122 --- @return string
123 local function get_commondir(gitdir)
124 -- In linked worktrees, `gitdir` points at `.git/worktrees/<name>` while most
125 -- refs live under the main `.git` directory (the "commondir").
126 local commondir = read_first_line(Path.join(gitdir, 'commondir'))
127 if not commondir then
128 return gitdir
129 end
130 local abs = Path.join(gitdir, commondir)
131 return uv.fs_realpath(abs) or abs
132 end
133
134 --- @param commondir string
135 --- @param refname string
136 --- @return string?
137 local function read_packed_ref(commondir, refname)
138 local packed_refs_path = Path.join(commondir, 'packed-refs')
139 wait_for_unlock(packed_refs_path)
140 -- `packed-refs` is a flat map from refname to OID (with optional peeled
141 -- entries). Read it linearly as this is only used on debounced fs events.
142 local f = io.open(packed_refs_path, 'r')
143 if not f then
144 return
145 end
146 for line in f:lines() do
147 --- @cast line string
148 if line:sub(1, 1) ~= '#' and line:sub(1, 1) ~= '^' then
149 local oid, name = line:match('^(%x+)%s+(.+)$')
150 if name == refname then
151 f:close()
152 return oid
153 end
154 end
155 end
156 f:close()
157 end
158
159 --- @param gitdir string
160 --- @param commondir? string
161 --- @param refname string
162 --- @return string?
163 local function resolve_ref(gitdir, commondir, refname)
164 -- Resolve a refname to an OID by following symbolic refs and checking:
165 -- - worktree-local loose refs in `gitdir/`
166 -- - shared loose refs in `commondir/`
167 -- - `commondir/packed-refs`
168 local seen = {} --- @type table<string, true>
169 local current = refname
170
171 while current and current ~= '' do
172 if seen[current] then
173 log.dprintf('cycle detected in symbolic refs: %s', vim.inspect(vim.tbl_keys(seen)))
174 return
175 end
176 seen[current] = true
177
178 local line = read_first_line_wait(Path.join(gitdir, current))
179
180 if not line and commondir and commondir ~= gitdir then
181 line = read_first_line_wait(Path.join(commondir, current))
182 end
183
184 if not line then
185 log.dprintf('Ref %s not found as loose ref; checking packed-refs', current)
186 break
187 elseif line:match('^%x+$') then
188 return line
189 end
190
191 local symref = line:match('^ref:%s*(.+)$')
192 if symref then
193 current = symref
194 else
195 log.dprintf('Ref %s has invalid contents (%s); checking packed-refs', current, line)
196 break
197 end
198 end
199
200 if commondir and current then
201 -- Some refs are only stored in packed-refs.
202 local packed = read_packed_ref(commondir, current)
203 if packed and packed:match('^%x+$') then
204 return packed
205 end
206 end
207 end
208
209 --- Manual implementation of `git rev-parse HEAD`.
210 --- @param gitdir string
211 --- @param commondir string
212 --- @return string? oid
213 --- @return string? err
214 local function get_head_oid0(gitdir, commondir)
215 -- `.git/HEAD` can remain unchanged while its target ref moves (e.g. `git pull`
216 -- updating the checked-out branch). Resolve `HEAD` through loose refs and
217 -- packed-refs so we can detect branch moves without spawning `git`.
218 local head = read_head(gitdir)
219 if not head then
220 -- Unable to read HEAD.
221 return nil, 'unable to read HEAD file'
222 end
223
224 if head:match('^%x+$') then
225 -- Detached HEAD contains an OID directly.
226 return head
227 end
228
229 local ref = parse_head_ref(head)
230 if not ref then
231 -- Unrecognized HEAD format.
232 return nil, ('unrecognized HEAD contents: %s'):format(head)
233 end
234
235 local oid = resolve_ref(gitdir, commondir, ref)
236 if oid then
237 -- Resolved via loose refs or packed-refs.
238 return oid
239 end
240
241 -- Reftable stores refs in a different backend (no loose/packed refs).
242 if Path.exists(Path.join(commondir, 'reftable')) then
243 return nil, 'reftable'
244 end
245
246 -- Reftable cannot be parsed via loose refs/packed-refs. Keep a synchronous
247 -- fallback for correctness (rare setup). Some other backends or transient
248 -- states can also cause resolution to fail, so keep this as a general
249 -- fallback.
250 return nil, ('unable to resolve %s via loose refs/packed-refs'):format(ref)
251 end
252
253 --- Manual implementation of `git rev-parse HEAD` with command fallback.
254 --- @param gitdir string
255 --- @param commondir string
256 --- @return string? oid
257 local function get_head_oid(gitdir, commondir)
258 local oid0, err = get_head_oid0(gitdir, commondir)
259 if oid0 then
260 return oid0
261 end
262
263 log.dprintf('Falling back to `git rev-parse HEAD`: %s', err)
264
265 local stdout, stderr, code = async
266 .run(git_command, { '--git-dir', gitdir, 'rev-parse', 'HEAD' }, { ignore_error = true })
267 :wait()
268
269 local oid = stdout[1]
270
271 if code ~= 0 or not oid or not oid:match('^%x+$') then
272 log.dprintf('Fallback `git rev-parse HEAD` failed: code=%s oid=%s stderr=%s', code, oid, stderr)
273 return
274 end
275 return oid
276 end
277
278 --- Registers a callback to be invoked on update events.
279 ---
280 --- The provided callback function `cb` will be stored and called when an update
281 --- occurs. Returns a deregister function that, when called, will remove the
282 --- callback from the watcher.
283 ---
284 --- @param callback fun() Callback function to be invoked on update.
285 --- @return fun() deregister Function to remove the callback from the watcher.
286 function M:on_update(callback)
287 assert(self._watcher, 'Watcher not initialized')
288 return self._watcher:on_update(callback)
289 end
290
291 --- Run a function while holding the repo lock.
292 --- This serializes git operations that mutate repo state such as the index.
293 --- @async
294 --- @generic R
295 --- @param fn async fun(): R...
296 --- @return R...
297 function M:lock(fn)
298 return self._lock:with(fn)
299 end
300
301 --- Run git command the with the objects gitdir and toplevel
302 --- @async
303 --- @param args table<any,any>
304 --- @param spec? Gitsigns.Git.JobSpec
305 --- @return string[] stdout
306 --- @return string? stderr
307 --- @return integer code
308 function M:command(args, spec)
309 spec = spec or {}
310 spec.cwd = self.toplevel
311
312 local args0 = { '--git-dir', self.gitdir }
313
314 if self.detached then
315 -- If detached, we need to set the work tree to the toplevel so that git
316 -- commands work correctly.
317 args0 = vim.list_extend(args0, { '--work-tree', self.toplevel })
318 end
319
320 vim.list_extend(args0, args)
321
322 return git_command(args0, spec)
323 end
324
325 --- @async
326 --- @param base string?
327 --- @param include_untracked? boolean
328 --- @return {path:string, oldpath?:string}[]
329 function M:files_changed(base, include_untracked)
330 local ret = {} --- @type {path:string, oldpath?:string}[]
331
332 if base and base ~= ':0' then
333 local results = self:command({ 'diff', '--name-status', base })
334 for _, result in ipairs(results) do
335 local parts = vim.split(result, '\t', { plain = true })
336 local status = parts[1]
337 local path = parts[#parts]
338 local renamed = status and (vim.startswith(status, 'R') or vim.startswith(status, 'C'))
339 if path then
340 ret[#ret + 1] = {
341 path = path,
342 oldpath = renamed and parts[2] or nil,
343 }
344 end
345 end
346 if include_untracked then
347 local untracked = self:command({ 'ls-files', '--others', '--exclude-standard' })
348 for _, path in ipairs(untracked) do
349 ret[#ret + 1] = { path = path }
350 end
351 end
352 return ret
353 end
354
355 local results = self:command({ 'status', '--porcelain', '--ignore-submodules' })
356
357 for _, line in ipairs(results) do
358 local status = line:sub(1, 2)
359 if status:match('^.M') or (include_untracked and status == '??') then
360 ret[#ret + 1] = { path = line:sub(4, -1) }
361 end
362 end
363 return ret
364 end
365
366 --- @async
367 --- @param attr string
368 --- @param files string[]
369 --- @return table<string,'set'|'unset'|'unspecified'|string>
370 function M:check_attr(attr, files)
371 local ret = {} --- @type table<string,'set'|'unset'|'unspecified'|string>
372
373 if #files == 0 then
374 return ret
375 end
376
377 for _, f in ipairs(files) do
378 ret[f] = 'unspecified'
379 end
380
381 local output = self:command({ 'check-attr', attr, '--stdin' }, { stdin = files })
382 local sep = ': ' .. attr .. ': '
383
384 for _, line in ipairs(output) do
385 local parts = vim.split(line, sep, { plain = true })
386 local file = parts[1]
387 if file and #parts >= 2 then
388 local value = table.concat(parts, sep, 2)
389 ret[file] = value
390 end
391 end
392
393 return ret
394 end
395
396 --- @param encoding string
397 --- @return boolean
398 local function iconv_supported(encoding)
399 -- TODO(lewis6991): needs https://github.com/neovim/neovim/pull/21924
400 if vim.startswith(encoding, 'utf-16') or vim.startswith(encoding, 'utf-32') then
401 return false
402 end
403 return true
404 end
405
406 --- @async
407 --- Get version of file in the index, return array lines
408 --- @param object string
409 --- @param encoding? string
410 --- @return string[] stdout, string? stderr
411 function M:get_show_text(object, encoding)
412 local stdout, stderr = self:command({ 'show', object }, { text = false, ignore_error = true })
413
414 if encoding and encoding ~= 'utf-8' and iconv_supported(encoding) then
415 for i, l in ipairs(stdout) do
416 stdout[i] = vim.iconv(l, encoding, 'utf-8')
417 end
418 end
419
420 return stdout, stderr
421 end
422
423 --- @async
424 --- Get version of file at revision. If the path was renamed after `revision`,
425 --- resolve the old path before reading the blob.
426 --- @param revision string
427 --- @param relpath string
428 --- @param encoding? string
429 --- @return string[] stdout, string? stderr
430 function M:get_show_text_at_revision(revision, relpath, encoding)
431 local stdout, stderr = self:get_show_text(revision .. ':' .. relpath, encoding)
432
433 if
434 stderr
435 and (
436 stderr:match(errors.e.path_does_not_exist)
437 or stderr:match(errors.e.path_exist_on_disk_but_not_in)
438 )
439 then
440 log.dprintf('%s not found in %s looking for renames', relpath, revision)
441 local old_path = self:diff_rename_status(revision, true)[relpath]
442 or self:log_rename_status(revision, relpath)
443 if old_path then
444 log.dprintf('found rename %s -> %s', old_path, relpath)
445 stdout, stderr = self:get_show_text(revision .. ':' .. old_path, encoding)
446 end
447 end
448
449 return stdout, stderr
450 end
451
452 --- @type table<string,Gitsigns.Repo?>
453 local repo_cache = setmetatable({}, { __mode = 'v' })
454
455 --- @async
456 --- @private
457 --- @param info Gitsigns.RepoInfo
458 --- @return Gitsigns.Repo
459 function M._new(info)
460 --- @type Gitsigns.Repo
461 local self = setmetatable(info, { __index = M })
462 self._lock = async.semaphore(1)
463 self.username = self:command({ 'config', 'user.name' }, { ignore_error = true })[1]
464
465 self.commondir = get_commondir(self.gitdir)
466
467 if config.watch_gitdir.enable then
468 local head = read_head(self.gitdir)
469 self.head_ref = parse_head_ref(head)
470 self.head_oid = get_head_oid(self.gitdir, self.commondir)
471 self._watcher = Watcher.new(self.gitdir, self.commondir)
472 self._watcher:set_head_ref(self.head_ref)
473 self._watcher:on_update(function()
474 -- Recompute on every debounced tick. The checked-out branch can move
475 -- without `HEAD` changing (e.g. `refs/heads/main` update).
476 local head2 = read_head(self.gitdir)
477 if not head2 then
478 return
479 end
480
481 self.head_oid = get_head_oid(self.gitdir, self.commondir)
482 -- Set abbrev_head to empty string if head_oid is unavailable (.e.g repo
483 -- with no commits). This is consistent with `git rev-parse --abrev-ref
484 -- HEAD` which returns "HEAD" in this case.
485 local abbrev_head = self.head_oid and get_abbrev_head(self.gitdir, head2) or ''
486 if self.abbrev_head ~= abbrev_head then
487 self.abbrev_head = abbrev_head
488 log.dprintf('HEAD changed, updating abbrev_head to %s', self.abbrev_head)
489 end
490
491 local head_ref = parse_head_ref(head2)
492 if self.head_ref ~= head_ref then
493 self.head_ref = head_ref
494 self._watcher:set_head_ref(self.head_ref)
495 end
496 end)
497 end
498
499 return self
500 end
501
502 function M:has_watcher()
503 return self._watcher ~= nil
504 end
505
506 local sem = async.semaphore(1)
507
508 --- @async
509 --- @param cwd? string
510 --- @param gitdir? string
511 --- @param toplevel? string
512 --- @return Gitsigns.Repo? repo
513 --- @return string? err
514 function M.get(cwd, gitdir, toplevel)
515 --- EmmyLuaLs/emmylua-analyzer-rust#659
516 --- @return Gitsigns.Repo? repo
517 --- @return string? err
518 return sem:with(function()
519 local info, err = M.get_info(cwd, gitdir, toplevel)
520 if not info then
521 return nil, err
522 end
523
524 local repo = repo_cache[info.gitdir]
525 if repo then
526 -- Keep cached repo metadata in sync with git's current state.
527 -- Without this, branch/rebase transitions can leave abbrev_head stale
528 -- until a watcher callback runs.
529 repo.abbrev_head = info.abbrev_head
530 repo.detached = info.detached
531 else
532 repo = M._new(info)
533 repo_cache[info.gitdir] = repo
534 end
535 return repo
536 end)
537 end
538
539 local has_win_cygpath = vim.fn.has('win32') == 1 and vim.fn.executable('cygpath') == 1
540
541 --- Normalize repo discovery paths for comparisons and returned repo metadata.
542 --- On Windows with MSYS/Cygwin Git, convert `/c/...` style paths to mixed
543 --- Windows form before applying `vim.fs.normalize()`.
544 --- @async
545 --- @param path? string
546 --- @return string?
547 local function normalize_path(path)
548 if not path then
549 return
550 end
551 if has_win_cygpath then
552 path = util.cygpath(path, 'mixed')
553 end
554 return vim.fs.normalize(path)
555 end
556
557 --- @async
558 --- @param gitdir string
559 --- @param head_str string
560 --- @param cwd string
561 --- @return string
562 local function process_abbrev_head(gitdir, head_str, cwd)
563 if head_str ~= 'HEAD' then
564 return head_str
565 end
566
567 local short_sha = git_command({ 'rev-parse', '--short', 'HEAD' }, {
568 ignore_error = true,
569 cwd = cwd,
570 })[1] or ''
571
572 -- Make tests easier
573 if short_sha ~= '' and log.debug_mode() then
574 short_sha = 'HEAD'
575 end
576
577 if is_rebasing(gitdir) then
578 return short_sha .. '(rebasing)'
579 end
580
581 return short_sha
582 end
583
584 --- @async
585 --- @param dir? string
586 --- @param gitdir? string
587 --- @param worktree? string
588 --- @return Gitsigns.RepoInfo? info, string? err
589 function M.get_info(dir, gitdir, worktree)
590 -- Does git rev-parse have --absolute-git-dir, added in 2.13:
591 -- https://public-inbox.org/git/[email protected]/
592 local has_abs_gd = check_version(2, 13)
593
594 -- Wait for internal scheduler to settle before running command (#215)
595 async.schedule()
596
597 if dir and not uv.fs_stat(dir) then
598 -- Cwd can be deleted externally, so check if it exists (see #1331)
599 log.dprintf("dir '%s' does not exist", dir)
600 return
601 end
602
603 -- Explicitly fallback to env vars for better debug
604 gitdir = gitdir or vim.env.GIT_DIR
605 worktree = worktree or vim.env.GIT_WORK_TREE or vim.fs.dirname(gitdir)
606
607 -- gitdir and worktree must be provided together from `man git`:
608 -- > Specifying the location of the ".git" directory using this option (or GIT_DIR environment
609 -- > variable) turns off the repository discovery that tries to find a directory with ".git"
610 -- > subdirectory (which is how the repository and the top-level of the working tree are
611 -- > discovered), and tells Git that you are at the top level of the working tree. If you are
612 -- > not at the top-level directory of the working tree, you should tell Git where the
613 -- > top-level of the working tree is, with the --work-tree=<path> option (or GIT_WORK_TREE
614 -- > environment variable)
615 local stdout, stderr, code = git_command(
616 util.flatten({
617 gitdir and { '--git-dir', gitdir },
618 worktree and { '--work-tree', worktree },
619 'rev-parse',
620 '--show-toplevel',
621 has_abs_gd and '--absolute-git-dir' or '--git-dir',
622 '--abbrev-ref',
623 'HEAD',
624 }),
625 {
626 ignore_error = true,
627 -- Worktree may be a relative path, so don't set cwd when it is provided.
628 cwd = not worktree and dir or nil,
629 }
630 )
631
632 -- If the repo has no commits yet, rev-parse will fail. Ignore this error.
633 if code > 0 and stderr and stderr:match(errors.e.ambiguous_head) then
634 code = 0
635 end
636
637 if code > 0 then
638 return nil, string.format('got stderr: %s', stderr or '')
639 end
640
641 if #stdout < 3 then
642 return nil, string.format('incomplete stdout: %s', table.concat(stdout, '\n'))
643 end
644 --- @cast stdout [string, string, string]
645
646 local toplevel_r = assert(normalize_path(stdout[1]))
647 local gitdir_r = assert(normalize_path(stdout[2]))
648 dir = normalize_path(dir)
649 gitdir = normalize_path(gitdir)
650
651 -- On windows, git will emit paths with `/` but dir may contain `\` so need to
652 -- normalize.
653 if dir and not vim.startswith(dir, toplevel_r) then
654 log.dprintf("'%s' is outside worktree '%s'", dir, toplevel_r)
655 -- outside of worktree
656 return
657 end
658
659 if not has_abs_gd then
660 gitdir_r = assert(normalize_path(uv.fs_realpath(gitdir_r)))
661 end
662
663 if gitdir and not worktree and gitdir ~= gitdir_r then
664 log.eprintf('expected gitdir to be %s, got %s', gitdir, gitdir_r)
665 end
666
667 return {
668 toplevel = toplevel_r,
669 gitdir = gitdir_r,
670 abbrev_head = process_abbrev_head(gitdir_r, stdout[3], toplevel_r),
671 detached = gitdir_r ~= assert(normalize_path(Path.join(toplevel_r, '.git'))),
672 }
673 end
674
675 --- @class (exact) Gitsigns.Repo.LsTree.Result
676 --- @field relpath string
677 --- @field mode_bits? string
678 --- @field object_name? string
679 --- @field object_type? 'blob'|'tree'|'commit'
680
681 --- @async
682 --- @param path string
683 --- @param revision string
684 --- @return Gitsigns.Repo.LsTree.Result? info
685 --- @return string? err
686 function M:ls_tree(path, revision)
687 local results, stderr, code = self:command({
688 '-c',
689 'core.quotepath=off',
690 'ls-tree',
691 revision,
692 path,
693 }, { ignore_error = true })
694
695 if code > 0 then
696 return nil, stderr or tostring(code)
697 end
698
699 local res = results[1]
700
701 if not res then
702 -- Not found, see if it was renamed
703 log.dprintf('%s not found in %s looking for renames', path, revision)
704 local old_path = self:diff_rename_status(revision, true)[path]
705 if old_path then
706 log.dprintf('found rename %s -> %s', old_path, path)
707 return self:ls_tree(old_path, revision)
708 end
709
710 return nil, ('%s not found in %s'):format(path, revision)
711 end
712
713 local info, relpath = unpack(vim.split(res, '\t'))
714 assert(info and relpath)
715 local mode_bits, object_type, object_name = unpack(vim.split(info, '%s+'))
716 --- @cast object_type 'blob'|'tree'|'commit'
717
718 return {
719 relpath = relpath,
720 mode_bits = mode_bits,
721 object_name = object_name,
722 object_type = object_type,
723 }
724 end
725
726 --- @class (exact) Gitsigns.Repo.LsFiles.Result
727 --- @field relpath? string nil if file is not in working tree
728 --- @field mode_bits? string
729 --- @field object_name? string nil if file is untracked
730 --- @field i_crlf? boolean (requires git version >= 2.9)
731 --- @field w_crlf? boolean (requires git version >= 2.9)
732 --- @field has_conflicts? true
733
734 --- @async
735 --- Get information about files in the index and the working tree
736 --- @param file string
737 --- @return Gitsigns.Repo.LsFiles.Result? info
738 --- @return string? err
739 function M:ls_files(file)
740 local has_eol = check_version(2, 9)
741
742 -- --others + --exclude-standard means ignored files won't return info, but
743 -- untracked files will. Unlike file_info_tree which won't return untracked
744 -- files.
745 local results, stderr, code = self:command(
746 util.flatten({
747 '-c',
748 'core.quotepath=off',
749 'ls-files',
750 '--stage',
751 '--others',
752 '--exclude-standard',
753 has_eol and '--eol',
754 file,
755 }),
756 { ignore_error = true }
757 )
758
759 -- ignore_error for the cases when we run:
760 -- git ls-files --others exists/nonexist
761 if code > 0 and (not stderr or not stderr:match(errors.e.path_does_not_exist)) then
762 return nil, stderr or tostring(code)
763 end
764
765 local relpath_idx = has_eol and 2 or 1
766
767 local result = {}
768 for _, line in ipairs(results) do
769 local parts = vim.split(line, '\t')
770 if #parts > relpath_idx then -- tracked file
771 local attrs = vim.split(assert(parts[1]), '%s+')
772 local stage = tonumber(attrs[3])
773 if stage <= 1 then
774 result.mode_bits = attrs[1]
775 result.object_name = attrs[2]
776 else
777 result.has_conflicts = true
778 end
779
780 if has_eol then
781 result.relpath = parts[3]
782 local eol = vim.split(assert(parts[2]), '%s+')
783 result.i_crlf = eol[1] == 'i/crlf'
784 result.w_crlf = eol[2] == 'w/crlf'
785 else
786 result.relpath = parts[2]
787 end
788 else -- untracked file
789 result.relpath = parts[relpath_idx]
790 end
791 end
792
793 return result
794 end
795
796 --- @param revision? string
797 --- @return boolean
798 function M.from_tree(revision)
799 return revision ~= nil and not vim.startswith(revision, ':')
800 end
801
802 --- @async
803 --- @param file string
804 --- @param revision? string
805 --- @return Gitsigns.Repo.LsFiles.Result? info
806 --- @return string? err
807 function M:file_info(file, revision)
808 if M.from_tree(revision) then
809 local info, err = self:ls_tree(file, assert(revision))
810 if err then
811 return nil, err
812 end
813
814 if info and info.object_type == 'blob' then
815 return {
816 relpath = info.relpath,
817 mode_bits = info.mode_bits,
818 object_name = info.object_name,
819 }
820 end
821 else
822 local info, err = self:ls_files(file)
823 if err then
824 return nil, err
825 end
826
827 return info
828 end
829 end
830
831 --- @async
832 --- @param mode_bits string
833 --- @param object string
834 --- @param path string
835 --- @param add? boolean
836 function M:update_index(mode_bits, object, path, add)
837 self:command(util.flatten({
838 'update-index',
839 add and '--add',
840 '--cacheinfo',
841 ('%s,%s,%s'):format(mode_bits, object, path),
842 }))
843 end
844
845 --- @async
846 --- @param path string
847 --- @param lines string[]
848 --- @return string
849 function M:hash_object(path, lines)
850 -- Concatenate the lines into a single string to ensure EOL
851 -- is respected
852 local text = table.concat(lines, '\n')
853 local res = self:command({ 'hash-object', '-w', '--path', path, '--stdin' }, { stdin = text })[1]
854 return assert(res)
855 end
856
857 --- @param line string?
858 --- @return string? status
859 --- @return string? path
860 --- @return string? path2
861 local function parse_name_status_line(line)
862 if not line then
863 return
864 end
865
866 local parts = vim.split(line, '\t', { plain = true })
867 if #parts < 2 then
868 return
869 end
870
871 local status = parts[1]
872 if not status then
873 return
874 end
875
876 if vim.startswith(status, 'R') or vim.startswith(status, 'C') then
877 return status, parts[2], parts[3]
878 end
879
880 return status, parts[2]
881 end
882
883 --- @async
884 --- @param revision string
885 --- @param path string
886 --- @return string?
887 function M:log_rename_status(revision, path)
888 local out = self:command({
889 'log',
890 '--follow',
891 '--name-status',
892 '--diff-filter=R',
893 '--format=',
894 revision .. '..HEAD',
895 '--',
896 path,
897 })
898 local _, old_path = parse_name_status_line(out[#out])
899 return old_path
900 end
901
902 --- @async
903 --- @param revision? string
904 --- @param invert? boolean
905 --- @return table<string,string>
906 function M:diff_rename_status(revision, invert)
907 local out = self:command({
908 'diff',
909 '--name-status',
910 '--find-renames',
911 '--find-copies',
912 '--cached',
913 revision,
914 })
915 local ret = {} --- @type table<string,string>
916 for _, l in ipairs(out) do
917 local stat, orig_file, new_file = parse_name_status_line(l)
918 if stat and vim.startswith(stat, 'R') and orig_file and new_file then
919 if invert then
920 ret[new_file] = orig_file
921 else
922 ret[orig_file] = new_file
923 end
924 end
925 end
926 return ret
927 end
928
929 return M