forked from sindrets/diffview.nvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
2165 lines (1873 loc) · 59.9 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local AsyncListStream = require("diffview.stream").AsyncListStream
local Commit = require("diffview.vcs.adapters.git.commit").GitCommit
local Diff2Hor = require("diffview.scene.layouts.diff_2_hor").Diff2Hor
local FileEntry = require("diffview.scene.file_entry").FileEntry
local FlagOption = require("diffview.vcs.flag_option").FlagOption
local GitRev = require("diffview.vcs.adapters.git.rev").GitRev
local Job = require("diffview.job").Job
local JobStatus = require("diffview.vcs.utils").JobStatus
local LogEntry = require("diffview.vcs.log_entry").LogEntry
local MultiJob = require("diffview.multi_job").MultiJob
local RevType = require("diffview.vcs.rev").RevType
local VCSAdapter = require("diffview.vcs.adapter").VCSAdapter
local arg_parser = require("diffview.arg_parser")
local async = require("diffview.async")
local config = require("diffview.config")
local lazy = require("diffview.lazy")
local oop = require("diffview.oop")
local utils = require("diffview.utils")
local vcs_utils = require("diffview.vcs.utils")
local api = vim.api
local await, pawait = async.await, async.pawait
local fmt = string.format
local logger = DiffviewGlobal.logger
local pl = lazy.access(utils, "path") ---@type PathLib
local uv = vim.loop
local M = {}
---@class GitAdapter : VCSAdapter
---@operator call : GitAdapter
local GitAdapter = oop.create_class("GitAdapter", VCSAdapter)
GitAdapter.Rev = GitRev
GitAdapter.config_key = "git"
GitAdapter.bootstrap = {
done = false,
ok = false,
version = {},
target_version = {
major = 2,
minor = 31,
patch = 0,
}
}
GitAdapter.COMMIT_PRETTY_FMT = (
"%H %P" -- Commit hash followed by parent hashes
.. "%n%an" -- Author name
.. "%n%at" -- Author date: UNIX timestamp
.. "%n%ai" -- Author date: ISO (gives us timezone)
.. "%n%ar" -- Author date: relative
.. "%n..%D" -- Ref names
.. "%n..%gd" -- Reflog selectors
.. "%n..%s" -- Subject
-- The leading dots here are only used for padding to ensure those lines
-- won't ever be completetely empty. This way the lines will be
-- distinguishable from other empty lines outputted by Git.
)
---@return string, string
function GitAdapter.pathspec_split(pathspec)
local magic = utils.str_match(pathspec, {
"^:[/!^]+:?",
"^:%b()",
"^:",
}) or ""
local pattern = pathspec:sub(1 + #magic, -1)
return magic or "", pattern or ""
end
function GitAdapter.pathspec_expand(toplevel, cwd, pathspec)
local magic, pattern = GitAdapter.pathspec_split(pathspec)
if not pl:is_abs(pattern) then
pattern = pl:join(pl:relative(cwd, toplevel), pattern)
end
return magic .. pl:convert(pattern)
end
function GitAdapter.pathspec_modify(pathspec, mods)
local magic, pattern = GitAdapter.pathspec_split(pathspec)
return magic .. pl:vim_fnamemodify(pattern, mods)
end
function GitAdapter.run_bootstrap()
local git_cmd = config.get_config().git_cmd
local bs = GitAdapter.bootstrap
bs.done = true
local function err(msg)
if msg then
bs.err = msg
logger:error("[GitAdapter] " .. bs.err)
end
end
if vim.fn.executable(git_cmd[1]) ~= 1 then
return err(fmt("Configured `git_cmd` is not executable: '%s'", git_cmd[1]))
end
local out = utils.job(utils.flatten({ git_cmd, "version" }))
bs.version_string = out[1] and out[1]:match("git version (%S+)") or nil
if not bs.version_string then
return err("Could not get Git version!")
end
-- Parse version string
local v, target = bs.version, bs.target_version
bs.target_version_string = fmt("%d.%d.%d", target.major, target.minor, target.patch)
local parts = vim.split(bs.version_string, "%.")
v.major = tonumber(parts[1])
v.minor = tonumber(parts[2]) or 0
v.patch = tonumber(parts[3]) or 0
local version_ok = vcs_utils.check_semver(v, target)
if not version_ok then
return err(string.format(
"Git version is outdated! Some functionality might not work as expected, "
.. "or not at all! Current: %s, wanted: %s",
bs.version_string,
bs.target_version_string
))
end
bs.ok = true
end
---@param path_args string[] # Raw path args
---@param cpath string? # Cwd path given by the `-C` flag option
---@return string[] path_args # Resolved path args
---@return string[] top_indicators # Top-level indicators
function GitAdapter.get_repo_paths(path_args, cpath)
local paths = {}
local top_indicators = {}
for _, path_arg in ipairs(path_args) do
for _, path in ipairs(pl:vim_expand(path_arg, false, true) --[[@as string[] ]]) do
local magic, pattern = GitAdapter.pathspec_split(path)
pattern = pl:readlink(pattern) or pattern
table.insert(paths, magic .. pattern)
end
end
local cfile = pl:vim_expand("%")
cfile = pl:readlink(cfile) or cfile
for _, path in ipairs(paths) do
if GitAdapter.pathspec_split(path) == "" then
table.insert(top_indicators, pl:absolute(path, cpath))
break
end
end
table.insert(top_indicators, cpath and pl:realpath(cpath) or (
vim.bo.buftype == ""
and pl:absolute(cfile)
or nil
))
if not cpath then
table.insert(top_indicators, pl:realpath("."))
end
return paths, top_indicators
end
---Get the git toplevel directory from a path to file or directory
---@param path string
---@return string?
local function get_toplevel(path)
local out, code = utils.job(utils.flatten({
config.get_config().git_cmd,
{ "rev-parse", "--path-format=absolute", "--show-toplevel" },
}), path)
if code ~= 0 then
return nil
end
return out[1] and vim.trim(out[1])
end
---Try to find the top-level of a working tree by using the given indicative
---paths.
---@param top_indicators string[] A list of paths that might indicate what working tree we are in.
---@return string? err
---@return string toplevel # as an absolute path
function GitAdapter.find_toplevel(top_indicators)
local toplevel
for _, p in ipairs(top_indicators) do
if not pl:is_dir(p) then
---@diagnostic disable-next-line: cast-local-type
p = pl:parent(p)
end
if p and pl:readable(p) then
toplevel = get_toplevel(p)
if toplevel then
return nil, toplevel
end
end
end
local msg_paths = vim.tbl_map(function(v)
local rel_path = pl:relative(v, ".")
return utils.str_quote(rel_path == "" and "." or rel_path)
end, top_indicators) --[[@as vector ]]
local err = fmt(
"Path not a git repo (or any parent): %s",
table.concat(msg_paths, ", ")
)
return err, ""
end
---@param toplevel string
---@param path_args string[]
---@param cpath string?
---@return string? err
---@return GitAdapter
function GitAdapter.create(toplevel, path_args, cpath)
local err
local adapter = GitAdapter({
toplevel = toplevel,
path_args = path_args,
cpath = cpath,
})
if not adapter.ctx.toplevel then
err = "Could not find the top-level of the repository!"
elseif not pl:is_dir(adapter.ctx.toplevel) then
err = "The top-level is not a readable directory: " .. adapter.ctx.toplevel
end
if not adapter.ctx.dir then
err = "Could not find the Git directory!"
elseif not pl:is_dir(adapter.ctx.dir) then
err = "The Git directory is not readable: " .. adapter.ctx.dir
end
return err, adapter
end
---@param opt vcs.adapter.VCSAdapter.Opt
function GitAdapter:init(opt)
opt = opt or {}
self:super(opt)
local cwd = opt.cpath or vim.loop.cwd()
self.ctx = {
toplevel = opt.toplevel,
dir = self:get_dir(opt.toplevel),
path_args = vim.tbl_map(function(pathspec)
return GitAdapter.pathspec_expand(opt.toplevel, cwd, pathspec)
end, opt.path_args or {}) --[[@as string[] ]]
}
self:init_completion()
end
function GitAdapter:get_command()
return config.get_config().git_cmd
end
---@param path string
---@param rev Rev?
function GitAdapter:get_show_args(path, rev)
return utils.vec_join(self:args(), "show", fmt("%s:%s", rev and rev:object_name() or "", path))
end
function GitAdapter:get_log_args(args)
return utils.vec_join("log", "--first-parent", "--stat", args)
end
function GitAdapter:get_dir(path)
local out, code = self:exec_sync({ "rev-parse", "--path-format=absolute", "--git-dir" }, path)
if code ~= 0 then
return nil
end
return out[1] and vim.trim(out[1])
end
---Verify that a given git rev is valid.
---@param rev_arg string
---@return boolean ok, string[] output
function GitAdapter:verify_rev_arg(rev_arg)
local out, code = self:exec_sync({ "rev-parse", "--revs-only", rev_arg }, {
log_opt = { label = "GitAdapter:verify_rev_arg()" },
cwd = self.ctx.toplevel,
})
return code == 0 and (out[2] ~= nil or out[1] and out[1] ~= ""), out
end
---@return vcs.MergeContext?
function GitAdapter:get_merge_context()
local their_head
for _, name in ipairs({ "MERGE_HEAD", "REBASE_HEAD", "REVERT_HEAD", "CHERRY_PICK_HEAD" }) do
if pl:readable(pl:join(self.ctx.dir, name)) then
their_head = name
break
end
end
if not their_head then
-- We were unable to find THEIR head. Merge could be a result of an applied
-- stash (or something else?). Either way, we can't proceed.
return
end
local ret = {}
local out, code = self:exec_sync({ "show", "-s", "--pretty=format:%H%n%D", "HEAD", "--" }, self.ctx.toplevel)
ret.ours = code ~= 0 and {} or {
hash = out[1],
ref_names = out[2],
}
out, code = self:exec_sync({ "show", "-s", "--pretty=format:%H%n%D", their_head, "--" }, self.ctx.toplevel)
ret.theirs = code ~= 0 and {} or {
hash = out[1],
rev_names = out[2],
}
out, code = self:exec_sync({ "merge-base", "HEAD", their_head }, self.ctx.toplevel)
assert(code == 0)
ret.base = {
hash = out[1],
ref_names = self:exec_sync({ "show", "-s", "--pretty=format:%D", out[1] }, self.ctx.toplevel)[1],
}
return ret
end
---@class GitAdapter.PreparedLogOpts
---@field rev_range string
---@field base Rev
---@field path_args string[]
---@field flags string[]
---@param log_options GitLogOptions
---@param single_file boolean
---@return GitAdapter.PreparedLogOpts
function GitAdapter:prepare_fh_options(log_options, single_file)
local o = log_options
local line_trace = vim.tbl_map(function(v)
if not v:match("^-L") then
return "-L" .. v
end
return v
end, o.L or {})
local rev_range, base
if log_options.rev_range then
local ok, _ = self:verify_rev_arg(log_options.rev_range)
if not ok then
utils.warn(fmt("Bad range revision, ignoring: %s", utils.str_quote(log_options.rev_range)))
else
rev_range = log_options.rev_range
end
end
if log_options.base then
if log_options.base == "LOCAL" then
base = GitRev(RevType.LOCAL)
else
local ok, out = self:verify_rev_arg(log_options.base)
if not ok then
utils.warn(fmt("Bad base revision, ignoring: %s", utils.str_quote(log_options.base)))
else
base = GitRev(RevType.COMMIT, out[1])
end
end
end
return {
rev_range = rev_range,
base = base,
path_args = log_options.path_args,
flags = utils.vec_join(
line_trace,
(o.follow and single_file) and { "--follow" } or nil,
o.first_parent and { "--first-parent" } or nil,
o.show_pulls and { "--show-pulls" } or nil,
o.reflog and { "--reflog" } or nil,
o.walk_reflogs and { "--walk-reflogs" } or nil,
o.all and { "--all" } or nil,
o.merges and { "--merges" } or nil,
o.no_merges and { "--no-merges" } or nil,
o.reverse and { "--reverse" } or nil,
o.cherry_pick and { "--cherry-pick" } or nil,
o.left_only and { "--left-only" } or nil,
o.right_only and { "--right-only" } or nil,
o.max_count and { "-n" .. o.max_count } or nil,
o.diff_merges and { "--diff-merges=" .. o.diff_merges } or nil,
o.author and { "-E", "--author=" .. o.author } or nil,
o.grep and { "-E", "--grep=" .. o.grep } or nil,
o.G and { "-E", "-G" .. o.G } or nil,
o.S and { "-S" .. o.S, "--pickaxe-regex" } or nil,
o.after and { "--after=" .. o.after } or nil,
o.before and { "--before=" .. o.before } or nil
)
}
end
-- The stat data may appear intertwined, like:
--
-- :100644 100644 5755178b18 cb8f8ce44d M src/nvim/eval/typval.c
-- :100644 100644 84e4067f9d 767fd706b3 M src/nvim/eval/typval.h
-- :100644 100644 5231ec0841 4e521b14f7 M src/nvim/strings.c
-- 22 0 src/nvim/eval/typval.c
-- 0 4 src/nvim/eval/typval.h
-- 25 12 src/nvim/strings.c
-- :100644 100644 ea6555f005 2fd0aed601 M runtime/syntax/checkhealth.vim
-- 1 1 runtime/syntax/checkhealth.vim
---@param data string[]
---@param seek? integer
---@return string[] namestat
---@return string[] numstat
---@return integer data_end # First unprocessed data index. Marks the last index of stat data +1.
local function structure_stat_data(data, seek)
local namestat, numstat = {}, {}
local i = seek or 1
while data[i] do
if data[i]:match("^:+[0-7]") then
namestat[#namestat + 1] = data[i]
elseif data[i]:match("^[%d-]+\t[%d-]+\t") then
numstat[#numstat + 1] = data[i]
else
-- We have hit unrelated data
break
end
i = i + 1
end
return namestat, numstat, i
end
---@class GitAdapter.LogData
---@field left_hash? string
---@field right_hash string
---@field merge_hash? string
---@field author string
---@field time integer
---@field time_offset string
---@field rel_date string
---@field ref_names string
---@field reflog_selector string
---@field subject string
---@field namestat string[]
---@field numstat string[]
---@field diff? diff.FileEntry[]
---@field valid boolean
---@param stat_data string[]
---@param keep_diff? boolean
---@return GitAdapter.LogData data
local function structure_fh_data(stat_data, keep_diff)
local right_hash, left_hash, merge_hash = unpack(utils.str_split(stat_data[1]))
local time_offset = utils.str_split(stat_data[4])[3]
---@type GitAdapter.LogData
local ret = {
left_hash = left_hash ~= "" and left_hash or nil,
right_hash = right_hash,
merge_hash = merge_hash,
author = stat_data[2],
time = tonumber(stat_data[3]),
time_offset = time_offset,
rel_date = stat_data[5],
ref_names = stat_data[6] and stat_data[6]:sub(3) or "",
reflog_selector = stat_data[7] and stat_data[7]:sub(3) or "",
subject = stat_data[8] and stat_data[8]:sub(3) or "",
}
local namestat, numstat = structure_stat_data(stat_data, 9)
ret.namestat = namestat
ret.numstat = numstat
if keep_diff then
ret.diff = vcs_utils.parse_diff(stat_data)
end
-- Soft validate the data
ret.valid = #namestat == #numstat and pcall(
vim.validate,
{
left_hash = { ret.left_hash, "string", true },
right_hash = { ret.right_hash, "string" },
merge_hash = { ret.merge_hash, "string", true },
author = { ret.author, "string" },
time = { ret.time, "number" },
time_offset = { ret.time_offset, "string" },
rel_date = { ret.rel_date, "string" },
ref_names = { ret.ref_names, "string" },
reflog_selector = { ret.reflog_selector, "string" },
subject = { ret.subject, "string" },
}
)
return ret
end
---@param state GitAdapter.FHState
function GitAdapter:stream_fh_data(state)
---@type diffview.Job, AsyncListStream
local job, stream
---@type string[]?
local data
local function on_stdout(_, line)
if line == "\0" then
if data then
local log_data = structure_fh_data(data)
stream:push({ JobStatus.PROGRESS, log_data })
end
data = {}
else
data[#data + 1] = line
end
end
stream = AsyncListStream({
---@param shutdown? SignalConsumer Shutdown signal
on_close = function(shutdown)
if shutdown and shutdown:check() then
if job:is_running() then
logger:warn("Received shutdown signal. Killing file history jobs...")
job:kill(64)
else
logger:warn("Received shutdown signal, but no jobs are running. Nothing to do.")
end
stream:push({ JobStatus.KILLED })
return
end
local ok, err = job:is_success()
if job:is_done() and ok and job.code == 0 then on_stdout(nil, "\0") end
if not ok then
stream:push({
JobStatus.ERROR,
nil,
table.concat(utils.vec_join(err, job.stderr), "\n")
})
else
stream:push({ JobStatus.SUCCESS })
end
end
})
job = Job({
command = self:bin(),
args = utils.vec_join(
self:args(),
"-P",
"-c",
"gc.auto=0",
"-c",
"core.quotePath=false",
"log",
"--pretty=format:%x00%n" .. GitAdapter.COMMIT_PRETTY_FMT,
"--numstat",
"--raw",
state.prepared_log_opts.flags,
state.prepared_log_opts.rev_range,
"--",
state.path_args
),
cwd = self.ctx.toplevel,
log_opt = { label = "GitAdapter:incremental_fh_data()" },
on_stdout = on_stdout,
on_exit = utils.hard_bind(stream.close, stream),
})
job:start()
return stream
end
---@param state GitAdapter.FHState
function GitAdapter:stream_line_trace_data(state)
---@type diffview.Job, AsyncListStream
local job, stream
---@type string[]?
local data
local function on_stdout(_, line)
if line == "\0" then
if data then
local log_data = structure_fh_data(data, true)
stream:push({ JobStatus.PROGRESS, log_data })
end
data = {}
else
data[#data + 1] = line
end
end
stream = AsyncListStream({
---@param kill? boolean Shutdown signal
on_close = function(kill)
if kill then
if job:is_running() then
logger:warn("Received shutdown signal. Killing file history jobs...")
job:kill(64)
else
logger:warn("Received shutdown signal, but no jobs are running. Nothing to do.")
end
stream:push({ JobStatus.KILLED })
return
end
local ok, err = job:is_success()
if job:is_done() and ok and job.code == 0 then on_stdout(nil, "\0") end
if not ok then
stream:push({
JobStatus.ERROR,
nil,
table.concat(utils.vec_join(err, job.stderr), "\n")
})
else
stream:push({ JobStatus.SUCCESS })
end
end
})
job = Job({
command = self:bin(),
args = utils.vec_join(
self:args(),
"-P",
"-c",
"gc.auto=0",
"-c",
"core.quotePath=false",
"log",
"--color=never",
"--no-ext-diff",
"--pretty=format:%x00%n" .. GitAdapter.COMMIT_PRETTY_FMT,
state.prepared_log_opts.flags,
state.prepared_log_opts.rev_range,
"--"
),
cwd = self.ctx.toplevel,
log_opt = { label = "GitAdapter:incremental_line_trace_data()" },
on_stdout = on_stdout,
on_exit = utils.hard_bind(stream.close, stream),
})
job:start()
return stream
end
---@param path_args string[]
---@param lflags string[]
---@return boolean
function GitAdapter:is_single_file(path_args, lflags)
if lflags and #lflags > 0 then
local seen = {}
for i, v in ipairs(lflags) do
local path = v:match(".*:(.*)")
if i > 1 and not seen[path] then
return false
end
seen[path] = true
end
elseif path_args and self.ctx.toplevel then
return #path_args == 1
and not pl:is_dir(path_args[1])
and #self:exec_sync({ "ls-files", "--", path_args }, self.ctx.toplevel) < 2
end
return true
end
---@param log_opt GitLogOptions
---@return boolean ok, string description
function GitAdapter:file_history_dry_run(log_opt)
local single_file = self:is_single_file(log_opt.path_args, log_opt.L)
local log_options = config.get_log_options(single_file, log_opt, "git") --[[@as GitLogOptions ]]
local options = vim.tbl_map(function(v)
return vim.fn.shellescape(v)
end, self:prepare_fh_options(log_options, single_file).flags) --[[@as vector ]]
local description = utils.vec_join(
fmt("Top-level path: '%s'", pl:vim_fnamemodify(self.ctx.toplevel, ":~")),
log_options.rev_range and fmt("Revision range: '%s'", log_options.rev_range) or nil,
fmt("Flags: %s", table.concat(options, " "))
)
log_options = utils.tbl_clone(log_options) --[[@as GitLogOptions ]]
log_options.max_count = 1
options = self:prepare_fh_options(log_options, single_file).flags
local context = "GitAdapter:file_history_dry_run()"
local cmd
if #log_options.L > 0 then
-- cmd = utils.vec_join("-P", "log", log_options.rev_range, "--no-ext-diff", "--color=never", "--pretty=format:%H", "-s", options, "--")
-- NOTE: Running the dry-run for line tracing is slow. Just skip for now.
return true, table.concat(description, ", ")
else
cmd = utils.vec_join(
"log",
"--pretty=format:%H",
"--name-status",
options,
log_options.rev_range,
"--",
log_options.path_args
)
end
local out, code = self:exec_sync(cmd, {
cwd = self.ctx.toplevel,
log_opt = { label = context },
})
local ok = code == 0 and #out > 0
if not ok then
logger:fmt_debug("[%s] Dry run failed.", context)
end
return ok, table.concat(description, ", ")
end
---@param range? { [1]: integer, [2]: integer }
---@param paths string[]
---@param argo ArgObject
function GitAdapter:file_history_options(range, paths, argo)
local cfile = pl:vim_expand("%")
cfile = pl:readlink(cfile) or cfile
logger:fmt_debug("Found git top-level: %s", utils.str_quote(self.ctx.toplevel))
local rel_paths = vim.tbl_map(function(v)
return v == "." and "." or pl:relative(v, ".")
end, paths) --[[@as string[] ]]
---@type string
local range_arg = argo:get_flag("range", { no_empty = true })
if range_arg then
local ok = self:verify_rev_arg(range_arg)
if not ok then
utils.err(fmt("Bad revision: %s", utils.str_quote(range_arg)))
return
end
logger:fmt_debug("Verified range rev: %s", range_arg)
end
local log_flag_names = {
{ "follow" },
{ "first-parent" },
{ "show-pulls" },
{ "reflog" },
{ "walk-reflogs", "g" },
{ "all" },
{ "merges" },
{ "no-merges" },
{ "reverse" },
{ "cherry-pick" },
{ "left-only" },
{ "right-only" },
{ "max-count", "n" },
{ "L" },
{ "diff-merges" },
{ "author" },
{ "grep" },
{ "base" },
{ "G" },
{ "S" },
{ "after", "since" },
{ "before", "until" },
}
local log_options = { rev_range = range_arg } --[[@as GitLogOptions ]]
for _, names in ipairs(log_flag_names) do
local key, _ = names[1]:gsub("%-", "_")
local v = argo:get_flag(names, {
expect_string = type(config.log_option_defaults[self.config_key][key]) ~= "boolean",
expect_list = names[1] == "L",
})
log_options[key] = v
end
if range then
paths, rel_paths = {}, {}
log_options.L = {
fmt("%d,%d:%s", range[1], range[2], pl:relative(pl:absolute(cfile), self.ctx.toplevel))
}
end
if log_options.L and next(log_options.L) then
log_options.follow = false -- '--follow' is not compatible with '-L'
end
log_options.path_args = paths
local ok, opt_description = self:file_history_dry_run(log_options)
if not ok then
local msg = "No git history for the target(s) given the current options! Targets: %s\n"
.. "Current options: [ %s ]"
if #rel_paths == 0 then
utils.info(fmt(msg, "':(top)'", opt_description))
else
local msg_paths = vim.tbl_map(utils.str_quote, rel_paths)
utils.info(fmt(msg, table.concat(msg_paths, ", "), opt_description))
end
return
end
if not self.ctx.dir then
utils.err(
fmt(
"Failed to find the git dir for the repository: %s",
utils.str_quote(self.ctx.toplevel)
)
)
return
end
return log_options
end
---@class GitAdapter.FHState
---@field path_args string[]
---@field log_options GitLogOptions
---@field prepared_log_opts GitAdapter.PreparedLogOpts
---@field layout_opt vcs.adapter.LayoutOpt
---@field single_file boolean
---@field old_path string?
---@param self GitAdapter
---@param out_stream AsyncListStream
---@param opt vcs.adapter.FileHistoryWorkerSpec
GitAdapter.file_history_worker = async.void(function(self, out_stream, opt)
local single_file = self:is_single_file(
opt.log_opt.single_file.path_args,
opt.log_opt.single_file.L
)
---@type GitLogOptions
local log_options = config.get_log_options(
single_file,
single_file and opt.log_opt.single_file or opt.log_opt.multi_file,
"git"
)
local is_trace = #log_options.L > 0
---@type GitAdapter.FHState
local state = {
path_args = opt.log_opt.single_file.path_args,
log_options = log_options,
prepared_log_opts = self:prepare_fh_options(log_options, single_file),
layout_opt = opt.layout_opt,
single_file = single_file,
}
logger:info(
"[FileHistory] Updating with options:",
vim.inspect(state.prepared_log_opts, { newline = " ", indent = "" })
)
---@type AsyncListStream
local in_stream
if is_trace then
in_stream = self:stream_line_trace_data(state)
else
in_stream = self:stream_fh_data(state)
end
---@param shutdown? SignalConsumer
out_stream:on_close(function(shutdown)
if shutdown then in_stream:close(shutdown) end
end)
local last_wait = uv.hrtime()
local interval = (1000 / 15) * 1E6
for _, item in in_stream:iter() do
---@type JobStatus, GitAdapter.LogData?, string?
local status, new_data, msg = unpack(item, 1, 3)
-- Make sure to yield to the scheduler periodically to keep the editor
-- responsive.
local now = uv.hrtime()
if (now - last_wait > interval) then
last_wait = now
await(async.schedule_now())
end
if status == JobStatus.KILLED then
logger:warn("File history processing was killed.")
out_stream:push({ status })
out_stream:close()
return
elseif status == JobStatus.ERROR then
out_stream:push({ status, nil, msg })
out_stream:close()
return
elseif status == JobStatus.SUCCESS then
out_stream:push({ status })
out_stream:close()
return
elseif status ~= JobStatus.PROGRESS then
error("Unexpected state!")
end
-- Status is PROGRESS
assert(new_data, "No data received from scheduler!")
if not new_data.valid then
-- Sometimes git fails to provide stat data for a commit. This seems to
-- happen with commits that have a large number of changes. Merge commits
-- will also often be missing status data depending on the value of
-- `--diff-merges`. Attempt recovery here by retrying entries that have
-- data deemed invalid.
local err
local rev_arg = new_data.right_hash
local is_merge = new_data.merge_hash ~= nil
if is_trace and is_merge then goto continue end
logger:fmt_warn("Received malformed or insufficient data for '%s'! Retrying...", rev_arg)
logger:debug(new_data)
err, new_data = await(
self:fh_retry_commit(rev_arg, state, {
is_merge = is_merge,
retry_count = not is_merge and 2,
keep_diff = is_trace,
})
)
if err then
if err.name == "job_fail" then
logger:error(err.msg)
out_stream:push({ JobStatus.ERROR, nil, err.msg })
out_stream:close()
return
elseif err.name == "bad_data" then
logger:warn(err.msg)
utils.warn(
fmt(
"Encountered malformed data while parsing commit '%s'!"
.. " This commit will be missing from the displayed history."
.. " Call :DiffviewRefresh to try again. See :DiffviewLog for details.",
rev_arg:sub(1, 10)
),
true
)
-- Skip commit
goto continue
end
end
end
local commit = Commit({
hash = new_data.right_hash,
author = new_data.author,
time = tonumber(new_data.time),
time_offset = new_data.time_offset,
rel_date = new_data.rel_date,
ref_names = new_data.ref_names,
reflog_selector = new_data.reflog_selector,
subject = new_data.subject,
diff = new_data.diff,
})
---@type boolean, (LogEntry|string)?
local ok, entry
if is_trace then
ok, entry = self:parse_fh_line_trace_data(new_data, commit, state)