-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
fugitive.vim
8091 lines (7570 loc) · 270 KB
/
fugitive.vim
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
" Location: autoload/fugitive.vim
" Maintainer: Tim Pope <http://tpo.pe/>
" The functions contained within this file are for internal use only. For the
" official API, see the commented functions in plugin/fugitive.vim.
if exists('g:autoloaded_fugitive')
finish
endif
let g:autoloaded_fugitive = 1
" Section: Utility
function! s:function(name) abort
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '.*\zs<SNR>\d\+_'),''))
endfunction
function! s:sub(str,pat,rep) abort
return substitute(a:str,'\v\C'.a:pat,a:rep,'')
endfunction
function! s:gsub(str,pat,rep) abort
return substitute(a:str,'\v\C'.a:pat,a:rep,'g')
endfunction
function! s:Uniq(list) abort
let i = 0
let seen = {}
while i < len(a:list)
let str = string(a:list[i])
if has_key(seen, str)
call remove(a:list, i)
else
let seen[str] = 1
let i += 1
endif
endwhile
return a:list
endfunction
function! s:JoinChomp(list) abort
if empty(a:list[-1])
return join(a:list[0:-2], "\n")
else
return join(a:list, "\n")
endif
endfunction
function! s:winshell() abort
return has('win32') && &shellcmdflag !~# '^-'
endfunction
function! s:WinShellEsc(arg) abort
if type(a:arg) == type([])
return join(map(copy(a:arg), 's:WinShellEsc(v:val)'))
elseif a:arg =~# '^[A-Za-z0-9_/:.-]\+$'
return a:arg
else
return '"' . s:gsub(s:gsub(a:arg, '"', '""'), '\%', '"%"') . '"'
endif
endfunction
function! s:shellesc(arg) abort
if type(a:arg) == type([])
return join(map(copy(a:arg), 's:shellesc(v:val)'))
elseif a:arg =~# '^[A-Za-z0-9_/:.-]\+$'
return a:arg
elseif s:winshell()
return '"' . s:gsub(s:gsub(a:arg, '"', '""'), '\%', '"%"') . '"'
else
return shellescape(a:arg)
endif
endfunction
let s:fnameescape = " \t\n*?[{`$\\%#'\"|!<"
function! s:fnameescape(file) abort
if type(a:file) == type([])
return join(map(copy(a:file), 's:fnameescape(v:val)'))
elseif exists('*fnameescape')
return fnameescape(a:file)
else
return escape(a:file, s:fnameescape)
endif
endfunction
function! s:throw(string) abort
throw 'fugitive: '.a:string
endfunction
function! s:VersionCheck() abort
if v:version < 703
return 'return ' . string('echoerr "fugitive: Vim 7.3 or newer required"')
elseif empty(fugitive#GitVersion())
let exe = get(s:GitCmd(), 0, '')
if len(exe) && !executable(exe)
return 'return ' . string('echoerr "fugitive: cannot find ' . string(exe) . ' in PATH"')
endif
return 'return ' . string('echoerr "fugitive: cannot execute Git"')
elseif !fugitive#GitVersion(1, 8, 5)
return 'return ' . string('echoerr "fugitive: Git 1.8.5 or newer required"')
else
return ''
endif
endfunction
let s:worktree_error = "core.worktree is required when using an external Git dir"
function! s:DirCheck(...) abort
let vcheck = s:VersionCheck()
if !empty(vcheck)
return vcheck
endif
let dir = call('FugitiveGitDir', a:000)
if !empty(dir) && FugitiveWorkTree(dir, 1) is# 0
return 'return ' . string('echoerr "fugitive: ' . s:worktree_error . '"')
elseif !empty(dir)
return ''
elseif empty(bufname(''))
return 'return ' . string('echoerr "fugitive: working directory does not belong to a Git repository"')
else
return 'return ' . string('echoerr "fugitive: file does not belong to a Git repository"')
endif
endfunction
function! s:Mods(mods, ...) abort
let mods = substitute(a:mods, '\C<mods>', '', '')
let mods = mods =~# '\S$' ? mods . ' ' : mods
if a:0 && mods !~# '\<\%(aboveleft\|belowright\|leftabove\|rightbelow\|topleft\|botright\|tab\)\>'
if a:1 ==# 'Edge'
if mods =~# '\<vertical\>' ? &splitright : &splitbelow
let mods = 'botright ' . mods
else
let mods = 'topleft ' . mods
endif
else
let mods = a:1 . ' ' . mods
endif
endif
return substitute(mods, '\s\+', ' ', 'g')
endfunction
if exists('+shellslash')
function! s:Slash(path) abort
return tr(a:path, '\', '/')
endfunction
else
function! s:Slash(path) abort
return a:path
endfunction
endif
function! s:AbsoluteVimPath(...) abort
if a:0 && type(a:1) == type('')
let path = a:1
else
let path = bufname(a:0 && a:1 > 0 ? a:1 : '')
if getbufvar(a:0 && a:1 > 0 ? a:1 : '', '&buftype') !~# '^\%(nowrite\|acwrite\)\=$'
return path
endif
endif
if s:Slash(path) =~# '^/\|^\a\+:'
return path
else
return getcwd() . matchstr(getcwd(), '[\\/]') . path
endif
endfunction
function! s:Resolve(path) abort
let path = resolve(a:path)
if has('win32')
let path = FugitiveVimPath(fnamemodify(fnamemodify(path, ':h'), ':p') . fnamemodify(path, ':t'))
endif
return path
endfunction
function! s:FileIgnoreCase(for_completion) abort
return (exists('+fileignorecase') && &fileignorecase)
\ || (a:for_completion && exists('+wildignorecase') && &wildignorecase)
endfunction
function! s:cpath(path, ...) abort
if s:FileIgnoreCase(0)
let path = FugitiveVimPath(tolower(a:path))
else
let path = FugitiveVimPath(a:path)
endif
return a:0 ? path ==# s:cpath(a:1) : path
endfunction
let s:executables = {}
function! s:executable(binary) abort
if !has_key(s:executables, a:binary)
let s:executables[a:binary] = executable(a:binary)
endif
return s:executables[a:binary]
endfunction
if !exists('s:temp_scripts')
let s:temp_scripts = {}
endif
function! s:TempScript(...) abort
let body = join(a:000, "\n")
if !has_key(s:temp_scripts, body)
let s:temp_scripts[body] = tempname() . '.sh'
endif
let temp = s:temp_scripts[body]
if !filereadable(temp)
call writefile(['#!/bin/sh'] + a:000, temp)
endif
return FugitiveGitPath(temp)
endfunction
function! s:DoAutocmd(...) abort
if v:version >= 704 || (v:version == 703 && has('patch442'))
return join(map(copy(a:000), "'doautocmd <nomodeline>' . v:val"), '|')
elseif &modelines > 0
return 'try|set modelines=0|' . join(map(copy(a:000), "'doautocmd ' . v:val"), '|') . '|finally|set modelines=' . &modelines . '|endtry'
else
return join(map(copy(a:000), "'doautocmd ' . v:val"), '|')
endif
endfunction
let s:nowait = v:version >= 704 ? '<nowait>' : ''
function! s:Map(mode, lhs, rhs, ...) abort
let maps = []
let defer = a:0 && a:1 =~# '<unique>' || get(g:, 'fugitive_defer_to_existing_maps')
let flags = substitute(a:0 ? a:1 : '', '<unique>', '', '') . (a:rhs =~# '<Plug>' ? '' : '<script>') . s:nowait
for mode in split(a:mode, '\zs')
if a:0 <= 1
call add(maps, mode.'map <buffer>' . substitute(flags, '<unique>', '', '') . ' <Plug>fugitive:' . a:lhs . ' ' . a:rhs)
endif
let skip = 0
let head = a:lhs
let tail = ''
let keys = get(g:, mode.'remap', {})
if type(keys) == type([])
continue
endif
while !empty(head)
if has_key(keys, head)
let head = keys[head]
let skip = empty(head)
break
endif
let tail = matchstr(head, '<[^<>]*>$\|.$') . tail
let head = substitute(head, '<[^<>]*>$\|.$', '', '')
endwhile
if !skip && (!defer || empty(mapcheck(head.tail, mode)))
call add(maps, mode.'map <buffer>' . flags . ' ' . head.tail . ' ' . a:rhs)
if a:0 > 1 && a:2
let b:undo_ftplugin = get(b:, 'undo_ftplugin', 'exe') .
\ '|sil! exe "' . mode . 'unmap <buffer> ' . head.tail . '"'
endif
endif
endfor
exe join(maps, '|')
return ''
endfunction
function! fugitive#Autowrite() abort
if &autowrite || &autowriteall
try
if &confirm
let reconfirm = 1
setglobal noconfirm
endif
silent! wall
finally
if exists('reconfirm')
setglobal confirm
endif
endtry
endif
return ''
endfunction
function! fugitive#Wait(job_or_jobs, ...) abort
let original = type(a:job_or_jobs) == type([]) ? copy(a:job_or_jobs) : [a:job_or_jobs]
let jobs = map(copy(original), 'type(v:val) ==# type({}) ? get(v:val, "job", "") : v:val')
call filter(jobs, 'type(v:val) !=# type("")')
let timeout_ms = a:0 ? a:1 : -1
if exists('*jobwait')
call map(copy(jobs), 'chanclose(v:val, "stdin")')
call jobwait(jobs, timeout_ms)
let jobs = map(copy(original), 'type(v:val) ==# type({}) ? get(v:val, "job", "") : v:val')
call filter(jobs, 'type(v:val) !=# type("")')
if len(jobs)
sleep 1m
endif
else
let sleep = has('patch-8.2.2366') ? 'sleep! 1m' : 'sleep 1m'
for job in jobs
if ch_status(job) !=# 'closed'
call ch_close_in(job)
endif
endfor
let i = 0
for job in jobs
while ch_status(job) !=# 'closed' || job_status(job) ==# 'run'
if i == timeout_ms
break
endif
let i += 1
exe sleep
endwhile
endfor
endif
return a:job_or_jobs
endfunction
function! s:JobVimExit(dict, callback, temp, job, status) abort
let a:dict.exit_status = a:status
let a:dict.stderr = readfile(a:temp . '.err', 'b')
call delete(a:temp . '.err')
let a:dict.stdout = readfile(a:temp . '.out', 'b')
call delete(a:temp . '.out')
call delete(a:temp . '.in')
call remove(a:dict, 'job')
call call(a:callback[0], [a:dict] + a:callback[1:-1])
endfunction
function! s:JobNvimExit(dict, callback, job, data, type) dict abort
let a:dict.stdout = self.stdout
let a:dict.stderr = self.stderr
let a:dict.exit_status = a:data
call remove(a:dict, 'job')
call call(a:callback[0], [a:dict] + a:callback[1:-1])
endfunction
function! s:JobExecute(argv, jopts, stdin, callback, ...) abort
let dict = a:0 ? a:1 : {}
let cb = len(a:callback) ? a:callback : [function('len')]
if exists('*jobstart')
call extend(a:jopts, {
\ 'stdout_buffered': v:true,
\ 'stderr_buffered': v:true,
\ 'on_exit': function('s:JobNvimExit', [dict, cb])})
let dict.job = jobstart(a:argv, a:jopts)
if !empty(a:stdin)
call chansend(dict.job, a:stdin)
call chanclose(dict.job, 'stdin')
endif
elseif exists('*ch_close_in')
let temp = tempname()
call extend(a:jopts, {
\ 'out_io': 'file',
\ 'out_name': temp . '.out',
\ 'err_io': 'file',
\ 'err_name': temp . '.err',
\ 'exit_cb': function('s:JobVimExit', [dict, cb, temp])})
if a:stdin ==# ['']
let a:jopts.in_io = 'null'
elseif !empty(a:stdin)
let a:jopts.in_io = 'file'
let a:jopts.in_name = temp . '.in'
call writefile(a:stdin, a:jopts.in_name, 'b')
endif
let dict.job = job_start(a:argv, a:jopts)
elseif &shell !~# 'sh' || &shell =~# 'fish\|\%(powershell\|pwsh\)\%(\.exe\)\=$'
throw 'fugitive: Vim 8 or higher required to use ' . &shell
else
let cmd = s:shellesc(a:argv)
let outfile = tempname()
try
if len(a:stdin)
call writefile(a:stdin, outfile . '.in', 'b')
let cmd = ' (' . cmd . ' >' . outfile . ' <' . outfile . '.in) '
else
let cmd = ' (' . cmd . ' >' . outfile . ') '
endif
let dict.stderr = split(system(cmd), "\n", 1)
let dict.exit_status = v:shell_error
let dict.stdout = readfile(outfile, 'b')
call call(cb[0], [dict] + cb[1:-1])
finally
call delete(outfile)
call delete(outfile . '.in')
endtry
endif
if empty(a:callback)
call fugitive#Wait(dict)
endif
return dict
endfunction
function! s:add_methods(namespace, method_names) abort
for name in a:method_names
let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name)
endfor
endfunction
" Section: Git
let s:run_jobs = (exists('*ch_close_in') || exists('*jobstart')) && exists('*bufwinid')
function! s:GitCmd() abort
if !exists('g:fugitive_git_executable')
return ['git']
elseif type(g:fugitive_git_executable) == type([])
return g:fugitive_git_executable
else
let dquote = '"\%([^"]\|""\|\\"\)*"\|'
let string = g:fugitive_git_executable
let list = []
if string =~# '^\w\+='
call add(list, '/usr/bin/env')
endif
while string =~# '\S'
let arg = matchstr(string, '^\s*\%(' . dquote . '''[^'']*''\|\\.\|[^[:space:] |]\)\+')
let string = strpart(string, len(arg))
let arg = substitute(arg, '^\s\+', '', '')
let arg = substitute(arg,
\ '\(' . dquote . '''\%(''''\|[^'']\)*''\|\\[' . s:fnameescape . ']\|^\\[>+-]\|!\d*\)\|' . s:expand,
\ '\=submatch(0)[0] ==# "\\" ? submatch(0)[1] : submatch(0)[1:-2]', 'g')
call add(list, arg)
endwhile
return list
endif
endfunction
function! s:GitShellCmd() abort
if !exists('g:fugitive_git_executable')
return 'git'
elseif type(g:fugitive_git_executable) == type([])
return s:shellesc(g:fugitive_git_executable)
else
return g:fugitive_git_executable
endif
endfunction
function! s:UserCommandCwd(dir) abort
let tree = s:Tree(a:dir)
return len(tree) ? FugitiveVimPath(tree) : getcwd()
endfunction
function! s:UserCommandList(...) abort
if !fugitive#GitVersion(1, 8, 5)
throw 'fugitive: Git 1.8.5 or higher required'
endif
if !exists('g:fugitive_git_command')
let git = s:GitCmd()
elseif type(g:fugitive_git_command) == type([])
let git = g:fugitive_git_command
else
let git = split(g:fugitive_git_command, '\s\+')
endif
let flags = []
if a:0 && type(a:1) == type({})
let git = copy(get(a:1, 'git', git))
let flags = get(a:1, 'flags', flags)
let dir = a:1.git_dir
elseif a:0
let dir = s:GitDir(a:1)
else
let dir = ''
endif
if len(dir)
let tree = s:Tree(dir)
if empty(tree)
call add(git, '--git-dir=' . FugitiveGitPath(dir))
else
if !s:cpath(tree . '/.git', dir) || len($GIT_DIR)
call add(git, '--git-dir=' . FugitiveGitPath(dir))
endif
if !s:cpath(tree, getcwd())
call extend(git, ['-C', FugitiveGitPath(tree)])
endif
endif
endif
return git + flags
endfunction
let s:git_versions = {}
function! fugitive#GitVersion(...) abort
let git = s:GitShellCmd()
if !has_key(s:git_versions, git)
let s:git_versions[git] = matchstr(get(s:JobExecute(s:GitCmd() + ['--version'], {}, [], [], {}).stdout, 0, ''), '\d[^[:space:]]\+')
endif
if !a:0
return s:git_versions[git]
endif
let components = split(s:git_versions[git], '\D\+')
if empty(components)
return -1
endif
for i in range(len(a:000))
if a:000[i] > +get(components, i)
return 0
elseif a:000[i] < +get(components, i)
return 1
endif
endfor
return a:000[i] ==# get(components, i)
endfunction
function! s:Dir(...) abort
return a:0 ? FugitiveGitDir(a:1) : FugitiveGitDir()
endfunction
function! s:GitDir(...) abort
return a:0 ? FugitiveGitDir(a:1) : FugitiveGitDir()
endfunction
function! s:DirUrlPrefix(...) abort
return 'fugitive://' . call('s:GitDir', a:000) . '//'
endfunction
function! s:Tree(...) abort
return a:0 ? FugitiveWorkTree(a:1) : FugitiveWorkTree()
endfunction
function! s:HasOpt(args, ...) abort
let args = a:args[0 : index(a:args, '--')]
let opts = copy(a:000)
if type(opts[0]) == type([])
if empty(args) || index(opts[0], args[0]) == -1
return 0
endif
call remove(opts, 0)
endif
for opt in opts
if index(args, opt) != -1
return 1
endif
endfor
endfunction
function! s:PreparePathArgs(cmd, dir, literal, explicit) abort
if !a:explicit
call insert(a:cmd, '--literal-pathspecs')
endif
let split = index(a:cmd, '--')
for i in range(split < 0 ? len(a:cmd) : split)
if type(a:cmd[i]) == type(0)
if a:literal
let a:cmd[i] = fugitive#Path(bufname(a:cmd[i]), './', a:dir)
else
let a:cmd[i] = fugitive#Path(bufname(a:cmd[i]), ':(top,literal)', a:dir)
endif
endif
endfor
if split < 0
return a:cmd
endif
for i in range(split + 1, len(a:cmd) - 1)
if type(a:cmd[i]) == type(0)
if a:literal
let a:cmd[i] = fugitive#Path(bufname(a:cmd[i]), './', a:dir)
else
let a:cmd[i] = fugitive#Path(bufname(a:cmd[i]), ':(top,literal)', a:dir)
endif
elseif !a:explicit
let a:cmd[i] = fugitive#Path(a:cmd[i], './', a:dir)
endif
endfor
return a:cmd
endfunction
function! s:PrepareEnv(env, dir) abort
if len($GIT_INDEX_FILE) && len(s:Tree(a:dir)) && !has_key(a:env, 'GIT_INDEX_FILE')
let index_dir = substitute($GIT_INDEX_FILE, '[^/]\+$', '', '')
let our_dir = fugitive#Find('.git/', a:dir)
if !s:cpath(index_dir, our_dir) && !s:cpath(resolve(FugitiveVimPath(index_dir)), our_dir)
let a:env['GIT_INDEX_FILE'] = FugitiveGitPath(fugitive#Find('.git/index', a:dir))
endif
endif
if len($GIT_WORK_TREE)
let a:env['GIT_WORK_TREE'] = '.'
endif
endfunction
let s:prepare_env = {
\ 'sequence.editor': 'GIT_SEQUENCE_EDITOR',
\ 'core.editor': 'GIT_EDITOR',
\ 'core.askpass': 'GIT_ASKPASS',
\ }
function! fugitive#PrepareDirEnvGitFlagsArgs(...) abort
if !fugitive#GitVersion(1, 8, 5)
throw 'fugitive: Git 1.8.5 or higher required'
endif
let git = s:GitCmd()
if a:0 == 1 && type(a:1) == type({}) && has_key(a:1, 'git_dir') && has_key(a:1, 'flags') && has_key(a:1, 'args')
let cmd = a:1.flags + a:1.args
let dir = a:1.git_dir
if has_key(a:1, 'git')
let git = a:1.git
endif
let env = get(a:1, 'env', {})
else
let list_args = []
let cmd = []
for arg in a:000
if type(arg) ==# type([])
call extend(list_args, arg)
else
call add(cmd, arg)
endif
endfor
call extend(cmd, list_args)
let env = {}
endif
let autoenv = {}
let explicit_pathspec_option = 0
let literal_pathspecs = 1
let i = 0
let arg_count = 0
while i < len(cmd)
if type(cmd[i]) == type({})
if has_key(cmd[i], 'git_dir')
let dir = cmd[i].git_dir
endif
if has_key(cmd[i], 'git')
let git = cmd[i].git
endif
if has_key(cmd[i], 'env')
call extend(env, cmd[i].env)
endif
call remove(cmd, i)
elseif cmd[i] =~# '^$\|[\/.]' && cmd[i] !~# '^-'
let dir = remove(cmd, i)
elseif cmd[i] =~# '^--git-dir='
let dir = remove(cmd, i)[10:-1]
elseif type(cmd[i]) ==# type(0)
let dir = s:Dir(remove(cmd, i))
elseif cmd[i] ==# '-c' && len(cmd) > i + 1
let key = matchstr(cmd[i+1], '^[^=]*')
if has_key(s:prepare_env, tolower(key))
let var = s:prepare_env[tolower(key)]
let val = matchstr(cmd[i+1], '=\zs.*')
let autoenv[var] = val
endif
let i += 2
elseif cmd[i] =~# '^--.*pathspecs$'
let literal_pathspecs = (cmd[i] ==# '--literal-pathspecs')
let explicit_pathspec_option = 1
let i += 1
elseif cmd[i] !~# '^-'
let arg_count = len(cmd) - i
break
else
let i += 1
endif
endwhile
if !exists('dir')
let dir = s:Dir()
endif
call extend(autoenv, env)
call s:PrepareEnv(autoenv, dir)
if len($GPG_TTY) && !has_key(autoenv, 'GPG_TTY')
let autoenv.GPG_TTY = ''
endif
call s:PreparePathArgs(cmd, dir, literal_pathspecs, explicit_pathspec_option)
return [s:GitDir(dir), env, extend(autoenv, env), git, cmd[0 : -arg_count-1], arg_count ? cmd[-arg_count : -1] : []]
endfunction
function! s:BuildEnvPrefix(env) abort
let pre = ''
let env = items(a:env)
if empty(env)
return ''
elseif &shell =~# '\%(powershell\|pwsh\)\%(\.exe\)\=$'
return join(map(env, '"$Env:" . v:val[0] . " = ''" . substitute(v:val[1], "''", "''''", "g") . "''; "'), '')
elseif s:winshell()
return join(map(env, '"set " . substitute(join(v:val, "="), "[&|<>^]", "^^^&", "g") . "& "'), '')
else
return '/usr/bin/env ' . s:shellesc(map(env, 'join(v:val, "=")')) . ' '
endif
endfunction
function! s:JobOpts(cmd, env) abort
if empty(a:env)
return [a:cmd, {}]
elseif has('patch-8.2.0239') ||
\ has('nvim') && api_info().version.api_level - api_info().version.api_prerelease >= 7 ||
\ has('patch-8.0.0902') && !has('nvim') && (!has('win32') || empty(filter(keys(a:env), 'exists("$" . v:val)')))
return [a:cmd, {'env': a:env}]
endif
let envlist = map(items(a:env), 'join(v:val, "=")')
if !has('win32')
return [['/usr/bin/env'] + envlist + a:cmd, {}]
else
let pre = join(map(envlist, '"set " . substitute(v:val, "[&|<>^]", "^^^&", "g") . "& "'), '')
if len(a:cmd) == 3 && a:cmd[0] ==# 'cmd.exe' && a:cmd[1] ==# '/c'
return [a:cmd[0:1] + [pre . a:cmd[2]], {}]
else
return [['cmd.exe', '/c', pre . s:WinShellEsc(a:cmd)], {}]
endif
endif
endfunction
function! s:PrepareJob(opts) abort
let dict = {'argv': a:opts.argv}
if has_key(a:opts, 'env')
let dict.env = a:opts.env
endif
let [argv, jopts] = s:JobOpts(a:opts.argv, get(a:opts, 'env', {}))
if has_key(a:opts, 'cwd')
if has('patch-8.0.0902')
let jopts.cwd = a:opts.cwd
let dict.cwd = a:opts.cwd
else
throw 'fugitive: cwd unsupported'
endif
endif
return [argv, jopts, dict]
endfunction
function! fugitive#PrepareJob(...) abort
if a:0 == 1 && type(a:1) == type({}) && has_key(a:1, 'argv') && !has_key(a:1, 'args')
return s:PrepareJob(a:1)
endif
let [dir, user_env, exec_env, git, flags, args] = call('fugitive#PrepareDirEnvGitFlagsArgs', a:000)
let dict = {'git': git, 'git_dir': dir, 'flags': flags, 'args': args}
if len(user_env)
let dict.env = user_env
endif
let cmd = flags + args
let tree = s:Tree(dir)
if empty(tree) || index(cmd, '--') == len(cmd) - 1
let dict.cwd = getcwd()
call extend(cmd, ['--git-dir=' . FugitiveGitPath(dir)], 'keep')
else
let dict.cwd = FugitiveVimPath(tree)
call extend(cmd, ['-C', FugitiveGitPath(tree)], 'keep')
if !s:cpath(tree . '/.git', dir) || len($GIT_DIR)
call extend(cmd, ['--git-dir=' . FugitiveGitPath(dir)], 'keep')
endif
endif
call extend(cmd, git, 'keep')
return s:JobOpts(cmd, exec_env) + [dict]
endfunction
function! fugitive#Execute(...) abort
let cb = copy(a:000)
let cmd = []
let stdin = []
while len(cb) && type(cb[0]) !=# type(function('tr'))
if type(cb[0]) ==# type({}) && has_key(cb[0], 'stdin')
if type(cb[0].stdin) == type([])
call extend(stdin, cb[0].stdin)
elseif type(cb[0].stdin) == type('')
call extend(stdin, readfile(cb[0].stdin, 'b'))
endif
if len(keys(cb[0])) == 1
call remove(cb, 0)
continue
endif
endif
call add(cmd, remove(cb, 0))
endwhile
let [argv, jopts, dict] = call('fugitive#PrepareJob', cmd)
return s:JobExecute(argv, jopts, stdin, cb, dict)
endfunction
function! s:BuildShell(dir, env, git, args) abort
let cmd = copy(a:args)
let tree = s:Tree(a:dir)
let pre = s:BuildEnvPrefix(a:env)
if empty(tree) || index(cmd, '--') == len(cmd) - 1
call insert(cmd, '--git-dir=' . FugitiveGitPath(a:dir))
else
call extend(cmd, ['-C', FugitiveGitPath(tree)], 'keep')
if !s:cpath(tree . '/.git', a:dir) || len($GIT_DIR)
call extend(cmd, ['--git-dir=' . FugitiveGitPath(a:dir)], 'keep')
endif
endif
return pre . join(map(a:git + cmd, 's:shellesc(v:val)'))
endfunction
function! s:JobNvimCallback(lines, job, data, type) abort
let a:lines[-1] .= remove(a:data, 0)
call extend(a:lines, a:data)
endfunction
function! s:SystemList(cmd) abort
let exit = []
if exists('*jobstart')
let lines = ['']
let jopts = {
\ 'on_stdout': function('s:JobNvimCallback', [lines]),
\ 'on_stderr': function('s:JobNvimCallback', [lines]),
\ 'on_exit': { j, code, _ -> add(exit, code) }}
let job = jobstart(a:cmd, jopts)
call chanclose(job, 'stdin')
call jobwait([job])
if empty(lines[-1])
call remove(lines, -1)
endif
return [lines, exit[0]]
elseif exists('*ch_close_in')
let lines = []
let jopts = {
\ 'out_cb': { j, str -> add(lines, str) },
\ 'err_cb': { j, str -> add(lines, str) },
\ 'exit_cb': { j, code -> add(exit, code) }}
let job = job_start(a:cmd, jopts)
call ch_close_in(job)
let sleep = has('patch-8.2.2366') ? 'sleep! 1m' : 'sleep 1m'
while ch_status(job) !=# 'closed' || job_status(job) ==# 'run'
exe sleep
endwhile
return [lines, exit[0]]
else
let [output, exec_error] = s:SystemError(s:shellesc(a:cmd))
let lines = split(output, "\n", 1)
if empty(lines[-1])
call remove(lines, -1)
endif
return [lines, v:shell_error]
endif
endfunction
function! fugitive#ShellCommand(...) abort
let [dir, _, env, git, flags, args] = call('fugitive#PrepareDirEnvGitFlagsArgs', a:000)
return s:BuildShell(dir, env, git, flags + args)
endfunction
function! fugitive#Prepare(...) abort
return call('fugitive#ShellCommand', a:000)
endfunction
function! s:SystemError(cmd, ...) abort
let cmd = type(a:cmd) == type([]) ? s:shellesc(a:cmd) : a:cmd
try
if &shellredir ==# '>' && &shell =~# 'sh\|cmd'
let shellredir = &shellredir
if &shell =~# 'csh'
set shellredir=>&
else
set shellredir=>%s\ 2>&1
endif
endif
if exists('+guioptions') && &guioptions =~# '!'
let guioptions = &guioptions
set guioptions-=!
endif
let out = call('system', [cmd] + a:000)
return [out, v:shell_error]
catch /^Vim\%((\a\+)\)\=:E484:/
let opts = ['shell', 'shellcmdflag', 'shellredir', 'shellquote', 'shellxquote', 'shellxescape', 'shellslash']
call filter(opts, 'exists("+".v:val) && !empty(eval("&".v:val))')
call map(opts, 'v:val."=".eval("&".v:val)')
call s:throw('failed to run `' . cmd . '` with ' . join(opts, ' '))
finally
if exists('shellredir')
let &shellredir = shellredir
endif
if exists('guioptions')
let &guioptions = guioptions
endif
endtry
endfunction
function! s:ChompStderr(...) abort
let r = call('fugitive#Execute', a:000)
return !r.exit_status ? '' : len(r.stderr) > 1 ? s:JoinChomp(r.stderr) : 'unknown Git error' . string(r)
endfunction
function! s:ChompDefault(default, ...) abort
let r = call('fugitive#Execute', a:000)
return r.exit_status ? a:default : s:JoinChomp(r.stdout)
endfunction
function! s:LinesError(...) abort
let r = call('fugitive#Execute', a:000)
if empty(r.stdout[-1])
call remove(r.stdout, -1)
endif
return [r.exit_status ? [] : r.stdout, r.exit_status]
endfunction
function! s:NullError(cmd) abort
let r = fugitive#Execute(a:cmd)
let list = r.exit_status ? [] : split(tr(join(r.stdout, "\1"), "\1\n", "\n\1"), "\1", 1)[0:-2]
return [list, s:JoinChomp(r.stderr), r.exit_status]
endfunction
function! s:TreeChomp(...) abort
let r = call('fugitive#Execute', a:000)
if !r.exit_status
return s:JoinChomp(r.stdout)
endif
throw 'fugitive: error running `' . call('fugitive#ShellCommand', a:000) . '`: ' . s:JoinChomp(r.stderr)
endfunction
function! s:StdoutToFile(out, cmd, ...) abort
let [argv, jopts, _] = fugitive#PrepareJob(a:cmd)
let exit = []
if exists('*jobstart')
call extend(jopts, {
\ 'stdout_buffered': v:true,
\ 'stderr_buffered': v:true,
\ 'on_exit': { j, code, _ -> add(exit, code) }})
let job = jobstart(argv, jopts)
if a:0
call chansend(job, a:1)
endif
call chanclose(job, 'stdin')
call jobwait([job])
if len(a:out)
call writefile(jopts.stdout, a:out, 'b')
endif
return [join(jopts.stderr, "\n"), exit[0]]
elseif exists('*ch_close_in')
try
let err = tempname()
call extend(jopts, {
\ 'out_io': len(a:out) ? 'file' : 'null',
\ 'out_name': a:out,
\ 'err_io': 'file',
\ 'err_name': err,
\ 'exit_cb': { j, code -> add(exit, code) }})
let job = job_start(argv, jopts)
if a:0
call ch_sendraw(job, a:1)
endif
call ch_close_in(job)
while ch_status(job) !=# 'closed' || job_status(job) ==# 'run'
exe has('patch-8.2.2366') ? 'sleep! 1m' : 'sleep 1m'
endwhile
return [join(readfile(err, 'b'), "\n"), exit[0]]
finally
call delete(err)
endtry
elseif s:winshell() || &shell !~# 'sh' || &shell =~# 'fish\|\%(powershell\|pwsh\)\%(\.exe\)\=$'
throw 'fugitive: Vim 8 or higher required to use ' . &shell
else
let cmd = fugitive#ShellCommand(a:cmd)
return s:SystemError(' (' . cmd . ' >' . a:out . ') ')
endif
endfunction
let s:head_cache = {}
function! fugitive#Head(...) abort
let dir = a:0 > 1 ? a:2 : s:Dir()
if empty(dir)
return ''
endif
let file = fugitive#Find('.git/HEAD', dir)
let ftime = getftime(file)
if ftime == -1
return ''
elseif ftime != get(s:head_cache, file, [-1])[0]
let s:head_cache[file] = [ftime, readfile(file)[0]]
endif
let head = s:head_cache[file][1]
let len = a:0 ? a:1 : 0
if head =~# '^ref: '
if len < 0
return strpart(head, 5)
else
return substitute(head, '\C^ref: \%(refs/\%(heads/\|remotes/\|tags/\)\=\)\=', '', '')
endif
elseif head =~# '^\x\{40,\}$'
return len < 0 ? head : strpart(head, 0, len)
else
return ''
endif
endfunction
function! fugitive#head(...) abort
throw 'Third party code is using fugitive#head() which has been removed. Change it to FugitiveHead()'
endfunction
function! fugitive#RevParse(rev, ...) abort
let hash = s:ChompDefault('', [a:0 ? a:1 : s:Dir(), 'rev-parse', '--verify', a:rev, '--'])
if hash =~# '^\x\{40,\}$'
return hash
endif
throw 'fugitive: failed to parse revision ' . a:rev
endfunction
" Section: Git config
function! s:ConfigTimestamps(dir, dict) abort
let files = ['/etc/gitconfig', '~/.gitconfig',
\ len($XDG_CONFIG_HOME) ? $XDG_CONFIG_HOME . '/git/config' : '~/.config/git/config']
if len(a:dir)
call add(files, fugitive#Find('.git/config', a:dir))
endif
call extend(files, get(a:dict, 'include.path', []))
return join(map(files, 'getftime(expand(v:val))'), ',')
endfunction
function! s:ConfigCallback(r, into) abort
let dict = a:into[1]
if has_key(dict, 'job')
call remove(dict, 'job')
endif
let lines = a:r.exit_status ? [] : split(tr(join(a:r.stdout, "\1"), "\1\n", "\n\1"), "\1", 1)[0:-2]
for line in lines
let key = matchstr(line, "^[^\n]*")
if !has_key(dict, key)
let dict[key] = []
endif
if len(key) ==# len(line)
call add(dict[key], 1)
else