-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
fugitive.vim
3126 lines (2883 loc) · 103 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
" fugitive.vim - A Git wrapper so awesome, it should be illegal
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 2.2
" GetLatestVimScripts: 2975 1 :AutoInstall: fugitive.vim
if exists('g:loaded_fugitive') || &cp
finish
endif
let g:loaded_fugitive = 1
if !exists('g:fugitive_git_executable')
let g:fugitive_git_executable = 'git'
endif
" Section: Utility
function! s:function(name) abort
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<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:winshell() abort
return &shell =~? 'cmd' || exists('+shellslash') && !&shellslash
endfunction
function! s:shellesc(arg) abort
if 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
function! s:fnameescape(file) abort
if exists('*fnameescape')
return fnameescape(a:file)
else
return escape(a:file," \t\n*?[{`$\\%#'\"|!<")
endif
endfunction
function! s:throw(string) abort
let v:errmsg = 'fugitive: '.a:string
throw v:errmsg
endfunction
function! s:warn(str) abort
echohl WarningMsg
echomsg a:str
echohl None
let v:warningmsg = a:str
endfunction
function! s:shellslash(path) abort
if s:winshell()
return s:gsub(a:path,'\\','/')
else
return a:path
endif
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
let s:git_versions = {}
function! s:git_command() abort
return get(g:, 'fugitive_git_command', g:fugitive_git_executable)
endfunction
function! fugitive#git_version(...) abort
if !has_key(s:git_versions, g:fugitive_git_executable)
let s:git_versions[g:fugitive_git_executable] = matchstr(system(g:fugitive_git_executable.' --version'), "\\S\\+\n")
endif
return s:git_versions[g:fugitive_git_executable]
endfunction
function! s:recall() abort
let rev = s:sub(s:buffer().rev(), '^/', '')
if rev ==# ':'
return matchstr(getline('.'),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$\|^\d\{6} \x\{40\} \d\t\zs.*')
elseif s:buffer().type('tree')
let file = matchstr(getline('.'), '\t\zs.*')
if empty(file) && line('.') > 2
let file = s:sub(getline('.'), '/$', '')
endif
if !empty(file) && rev !~# ':$'
return rev . '/' . file
else
return rev . file
endif
endif
return rev
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
let s:commands = []
function! s:command(definition) abort
let s:commands += [a:definition]
endfunction
function! s:define_commands() abort
for command in s:commands
exe 'command! -buffer '.command
endfor
endfunction
let s:abstract_prototype = {}
" Section: Initialization
function! fugitive#is_git_dir(path) abort
let path = s:sub(a:path, '[\/]$', '') . '/'
return getfsize(path.'HEAD') > 10 && (
\ isdirectory(path.'objects') && isdirectory(path.'refs') ||
\ getftype(path.'commondir') ==# 'file')
endfunction
function! fugitive#extract_git_dir(path) abort
if s:shellslash(a:path) =~# '^fugitive://.*//'
return matchstr(s:shellslash(a:path), '\C^fugitive://\zs.\{-\}\ze//')
endif
if isdirectory(a:path)
let path = fnamemodify(a:path, ':p:s?[\/]$??')
else
let path = fnamemodify(a:path, ':p:h:s?[\/]$??')
endif
let root = s:shellslash(resolve(path))
let previous = ""
while root !=# previous
if root =~# '\v^//%([^/]+/?)?$'
" This is for accessing network shares from Cygwin Vim. There won't be
" any git directory called //.git or //serverName/.git so let's avoid
" checking for them since such checks are extremely slow.
break
endif
if index(split($GIT_CEILING_DIRECTORIES, ':'), root) >= 0
break
endif
if root ==# $GIT_WORK_TREE && fugitive#is_git_dir($GIT_DIR)
return simplify(fnamemodify(expand($GIT_DIR), ':p:s?[\/]$??'))
endif
if fugitive#is_git_dir($GIT_DIR)
" Ensure that we've cached the worktree
call s:configured_tree(simplify(fnamemodify(expand($GIT_DIR), ':p:s?[\/]$??')))
if has_key(s:dir_for_worktree, root)
return s:dir_for_worktree[root]
endif
endif
let dir = s:sub(root, '[\/]$', '') . '/.git'
let type = getftype(dir)
if type ==# 'dir' && fugitive#is_git_dir(dir)
return dir
elseif type ==# 'link' && fugitive#is_git_dir(dir)
return resolve(dir)
elseif type !=# '' && filereadable(dir)
let line = get(readfile(dir, '', 1), 0, '')
if line =~# '^gitdir: \.' && fugitive#is_git_dir(root.'/'.line[8:-1])
return simplify(root.'/'.line[8:-1])
elseif line =~# '^gitdir: ' && fugitive#is_git_dir(line[8:-1])
return line[8:-1]
endif
elseif fugitive#is_git_dir(root)
return root
endif
let previous = root
let root = fnamemodify(root, ':h')
endwhile
return ''
endfunction
function! fugitive#detect(path) abort
if exists('b:git_dir') && (b:git_dir ==# '' || b:git_dir =~# '/$')
unlet b:git_dir
endif
if !exists('b:git_dir')
let dir = fugitive#extract_git_dir(a:path)
if dir !=# ''
let b:git_dir = dir
if empty(fugitive#buffer().path())
silent! exe haslocaldir() ? 'lcd .' : 'cd .'
endif
endif
endif
if exists('b:git_dir')
if exists('#User#FugitiveBoot')
try
let [save_mls, &modelines] = [&mls, 0]
doautocmd User FugitiveBoot
finally
let &mls = save_mls
endtry
endif
if !exists('g:fugitive_no_maps')
cnoremap <buffer> <expr> <C-R><C-G> fnameescape(<SID>recall())
nnoremap <buffer> <silent> y<C-G> :call setreg(v:register, <SID>recall())<CR>
endif
let buffer = fugitive#buffer()
if expand('%:p') =~# '://'
call buffer.setvar('&path', s:sub(buffer.getvar('&path'), '^\.%(,|$)', ''))
endif
if stridx(buffer.getvar('&tags'), escape(b:git_dir, ', ')) == -1
if filereadable(b:git_dir.'/tags')
call buffer.setvar('&tags', escape(b:git_dir.'/tags', ', ').','.buffer.getvar('&tags'))
endif
if &filetype !=# '' && filereadable(b:git_dir.'/'.&filetype.'.tags')
call buffer.setvar('&tags', escape(b:git_dir.'/'.&filetype.'.tags', ', ').','.buffer.getvar('&tags'))
endif
endif
try
let [save_mls, &modelines] = [&mls, 0]
call s:define_commands()
doautocmd User Fugitive
finally
let &mls = save_mls
endtry
endif
endfunction
augroup fugitive
autocmd!
autocmd BufNewFile,BufReadPost * call fugitive#detect(expand('%:p'))
autocmd FileType netrw call fugitive#detect(expand('%:p'))
autocmd User NERDTreeInit,NERDTreeNewRoot call fugitive#detect(b:NERDTreeRoot.path.str())
autocmd VimEnter * if expand('<amatch>')==''|call fugitive#detect(getcwd())|endif
autocmd CmdWinEnter * call fugitive#detect(expand('#:p'))
autocmd BufWinLeave * execute getwinvar(+bufwinnr(+expand('<abuf>')), 'fugitive_leave')
augroup END
" Section: Repository
let s:repo_prototype = {}
let s:repos = {}
let s:worktree_for_dir = {}
let s:dir_for_worktree = {}
function! s:repo(...) abort
let dir = a:0 ? a:1 : (exists('b:git_dir') && b:git_dir !=# '' ? b:git_dir : fugitive#extract_git_dir(expand('%:p')))
if dir !=# ''
if has_key(s:repos, dir)
let repo = get(s:repos, dir)
else
let repo = {'git_dir': dir}
let s:repos[dir] = repo
endif
return extend(extend(repo, s:repo_prototype, 'keep'), s:abstract_prototype, 'keep')
endif
call s:throw('not a git repository: '.expand('%:p'))
endfunction
function! fugitive#repo(...) abort
return call('s:repo', a:000)
endfunction
function! s:repo_dir(...) dict abort
return join([self.git_dir]+a:000,'/')
endfunction
function! s:configured_tree(git_dir) abort
if !has_key(s:worktree_for_dir, a:git_dir)
let s:worktree_for_dir[a:git_dir] = ''
let config_file = a:git_dir . '/config'
if filereadable(config_file)
let config = readfile(config_file,'',10)
call filter(config,'v:val =~# "^\\s*worktree *="')
if len(config) == 1
let worktree = matchstr(config[0], '= *\zs.*')
endif
elseif filereadable(a:git_dir . '/gitdir')
let worktree = fnamemodify(readfile(a:git_dir . '/gitdir')[0], ':h')
if worktree ==# '.'
unlet! worktree
endif
endif
if exists('worktree')
let s:worktree_for_dir[a:git_dir] = worktree
let s:dir_for_worktree[s:worktree_for_dir[a:git_dir]] = a:git_dir
endif
endif
if s:worktree_for_dir[a:git_dir] =~# '^\.'
return simplify(a:git_dir . '/' . s:worktree_for_dir[a:git_dir])
else
return s:worktree_for_dir[a:git_dir]
endif
endfunction
function! s:repo_tree(...) dict abort
if self.dir() =~# '/\.git$'
let dir = self.dir()[0:-6]
if dir !~# '/'
let dir .= '/'
endif
else
let dir = s:configured_tree(self.git_dir)
endif
if dir ==# ''
call s:throw('no work tree')
else
return join([dir]+a:000,'/')
endif
endfunction
function! s:repo_bare() dict abort
if self.dir() =~# '/\.git$'
return 0
else
return s:configured_tree(self.git_dir) ==# ''
endif
endfunction
function! s:repo_translate(spec) dict abort
let refs = self.dir('refs/')
if filereadable(self.dir('commondir'))
let refs = simplify(self.dir(get(readfile(self.dir('commondir'), 1), 0, ''))) . '/refs/'
endif
if a:spec ==# '.' || a:spec ==# '/.'
return self.bare() ? self.dir() : self.tree()
elseif a:spec =~# '^/\=\.git$' && self.bare()
return self.dir()
elseif a:spec =~# '^/\=\.git/'
return self.dir(s:sub(a:spec, '^/=\.git/', ''))
elseif a:spec =~# '^/'
return self.tree().a:spec
elseif a:spec =~# '^:[0-3]:'
return 'fugitive://'.self.dir().'//'.a:spec[1].'/'.a:spec[3:-1]
elseif a:spec ==# ':'
if $GIT_INDEX_FILE =~# '/[^/]*index[^/]*\.lock$' && fnamemodify($GIT_INDEX_FILE,':p')[0:strlen(self.dir())] ==# self.dir('') && filereadable($GIT_INDEX_FILE)
return fnamemodify($GIT_INDEX_FILE,':p')
else
return self.dir('index')
endif
elseif a:spec =~# '^:/'
let ref = self.rev_parse(matchstr(a:spec,'.[^:]*'))
return 'fugitive://'.self.dir().'//'.ref
elseif a:spec =~# '^:'
return 'fugitive://'.self.dir().'//0/'.a:spec[1:-1]
elseif a:spec ==# '@'
return self.dir('HEAD')
elseif a:spec =~# 'HEAD\|^refs/' && a:spec !~ ':' && filereadable(refs . '../' . a:spec)
return simplify(refs . '../' . a:spec)
elseif filereadable(refs.a:spec)
return refs.a:spec
elseif filereadable(refs.'tags/'.a:spec)
return refs.'tags/'.a:spec
elseif filereadable(refs.'heads/'.a:spec)
return refs.'heads/'.a:spec
elseif filereadable(refs.'remotes/'.a:spec)
return refs.'remotes/'.a:spec
elseif filereadable(refs.'remotes/'.a:spec.'/HEAD')
return refs.'remotes/'.a:spec.'/HEAD'
else
try
let ref = self.rev_parse(matchstr(a:spec,'[^:]*'))
let path = s:sub(matchstr(a:spec,':.*'),'^:','/')
return 'fugitive://'.self.dir().'//'.ref.path
catch /^fugitive:/
return self.tree(a:spec)
endtry
endif
endfunction
function! s:repo_head(...) dict abort
let head = s:repo().head_ref()
if head =~# '^ref: '
let branch = s:sub(head,'^ref: %(refs/%(heads/|remotes/|tags/)=)=','')
elseif head =~# '^\x\{40\}$'
" truncate hash to a:1 characters if we're in detached head mode
let len = a:0 ? a:1 : 0
let branch = len ? head[0:len-1] : ''
else
return ''
endif
return branch
endfunction
call s:add_methods('repo',['dir','tree','bare','translate','head'])
function! s:repo_git_command(...) dict abort
let git = s:git_command() . ' --git-dir='.s:shellesc(self.git_dir)
return git.join(map(copy(a:000),'" ".s:shellesc(v:val)'),'')
endfunction
function! s:repo_git_chomp(...) dict abort
let git = g:fugitive_git_executable . ' --git-dir='.s:shellesc(self.git_dir)
let output = git.join(map(copy(a:000),'" ".s:shellesc(v:val)'),'')
return s:sub(system(output),'\n$','')
endfunction
function! s:repo_git_chomp_in_tree(...) dict abort
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd' : 'cd'
let dir = getcwd()
try
execute cd s:fnameescape(s:repo().tree())
return call(s:repo().git_chomp, a:000, s:repo())
finally
execute cd s:fnameescape(dir)
endtry
endfunction
function! s:repo_rev_parse(rev) dict abort
let hash = self.git_chomp('rev-parse','--verify',a:rev)
if hash =~ '\<\x\{40\}$'
return matchstr(hash,'\<\x\{40\}$')
endif
call s:throw('rev-parse '.a:rev.': '.hash)
endfunction
call s:add_methods('repo',['git_command','git_chomp','git_chomp_in_tree','rev_parse'])
function! s:repo_dirglob(base) dict abort
let base = s:sub(a:base,'^/','')
let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*/')),"\n")
call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]')
return matches
endfunction
function! s:repo_superglob(base) dict abort
if a:base =~# '^/' || a:base !~# ':'
let results = []
if a:base !~# '^/'
let heads = ["HEAD","ORIG_HEAD","FETCH_HEAD","MERGE_HEAD"]
let heads += sort(split(s:repo().git_chomp("rev-parse","--symbolic","--branches","--tags","--remotes"),"\n"))
" Add any stashes.
if filereadable(s:repo().dir('refs/stash'))
let heads += ["stash"]
let heads += sort(split(s:repo().git_chomp("stash","list","--pretty=format:%gd"),"\n"))
endif
call filter(heads,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base')
let results += heads
endif
if !self.bare()
let base = s:sub(a:base,'^/','')
let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*')),"\n")
call map(matches,'s:shellslash(v:val)')
call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val')
call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]')
let results += matches
endif
return results
elseif a:base =~# '^:'
let entries = split(self.git_chomp('ls-files','--stage'),"\n")
call map(entries,'s:sub(v:val,".*(\\d)\\t(.*)",":\\1:\\2")')
if a:base !~# '^:[0-3]\%(:\|$\)'
call filter(entries,'v:val[1] == "0"')
call map(entries,'v:val[2:-1]')
endif
call filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base')
return entries
else
let tree = matchstr(a:base,'.*[:/]')
let entries = split(self.git_chomp('ls-tree',tree),"\n")
call map(entries,'s:sub(v:val,"^04.*\\zs$","/")')
call map(entries,'tree.s:sub(v:val,".*\t","")')
return filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base')
endif
endfunction
call s:add_methods('repo',['dirglob','superglob'])
function! s:repo_config(conf) dict abort
return matchstr(s:repo().git_chomp('config',a:conf),"[^\r\n]*")
endfun
function! s:repo_user() dict abort
let username = s:repo().config('user.name')
let useremail = s:repo().config('user.email')
return username.' <'.useremail.'>'
endfun
function! s:repo_aliases() dict abort
if !has_key(self,'_aliases')
let self._aliases = {}
for line in split(self.git_chomp('config','-z','--get-regexp','^alias[.]'),"\1")
let self._aliases[matchstr(line, '\.\zs.\{-}\ze\n')] = matchstr(line, '\n\zs.*')
endfor
endif
return self._aliases
endfunction
call s:add_methods('repo',['config', 'user', 'aliases'])
function! s:repo_keywordprg() dict abort
let args = ' --git-dir='.escape(self.dir(),"\\\"' ")
if has('gui_running') && !has('win32')
return s:git_command() . ' --no-pager' . args . ' log -1'
else
return s:git_command() . args . ' show'
endif
endfunction
call s:add_methods('repo',['keywordprg'])
" Section: Buffer
let s:buffer_prototype = {}
function! s:buffer(...) abort
let buffer = {'#': bufnr(a:0 ? a:1 : '%')}
call extend(extend(buffer,s:buffer_prototype,'keep'),s:abstract_prototype,'keep')
if buffer.getvar('git_dir') !=# ''
return buffer
endif
call s:throw('not a git repository: '.expand('%:p'))
endfunction
function! fugitive#buffer(...) abort
return s:buffer(a:0 ? a:1 : '%')
endfunction
function! s:buffer_getvar(var) dict abort
return getbufvar(self['#'],a:var)
endfunction
function! s:buffer_setvar(var,value) dict abort
return setbufvar(self['#'],a:var,a:value)
endfunction
function! s:buffer_getline(lnum) dict abort
return get(getbufline(self['#'], a:lnum), 0, '')
endfunction
function! s:buffer_repo() dict abort
return s:repo(self.getvar('git_dir'))
endfunction
function! s:buffer_type(...) dict abort
if self.getvar('fugitive_type') != ''
let type = self.getvar('fugitive_type')
elseif fnamemodify(self.spec(),':p') =~# '.\git/refs/\|\.git/\w*HEAD$'
let type = 'head'
elseif self.getline(1) =~ '^tree \x\{40\}$' && self.getline(2) == ''
let type = 'tree'
elseif self.getline(1) =~ '^\d\{6\} \w\{4\} \x\{40\}\>\t'
let type = 'tree'
elseif self.getline(1) =~ '^\d\{6\} \x\{40\}\> \d\t'
let type = 'index'
elseif isdirectory(self.spec())
let type = 'directory'
elseif self.spec() == ''
let type = 'null'
else
let type = 'file'
endif
if a:0
return !empty(filter(copy(a:000),'v:val ==# type'))
else
return type
endif
endfunction
if has('win32')
function! s:buffer_spec() dict abort
let bufname = bufname(self['#'])
let retval = ''
for i in split(bufname,'[^:]\zs\\')
let retval = fnamemodify((retval==''?'':retval.'\').i,':.')
endfor
return s:shellslash(fnamemodify(retval,':p'))
endfunction
else
function! s:buffer_spec() dict abort
let bufname = bufname(self['#'])
return s:shellslash(bufname == '' ? '' : fnamemodify(bufname,':p'))
endfunction
endif
function! s:buffer_name() dict abort
return self.spec()
endfunction
function! s:buffer_commit() dict abort
return matchstr(self.spec(),'^fugitive://.\{-\}//\zs\w*')
endfunction
function! s:cpath(path) abort
if exists('+fileignorecase') && &fileignorecase
return tolower(a:path)
else
return a:path
endif
endfunction
function! s:buffer_path(...) dict abort
let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*')
if rev != ''
let rev = s:sub(rev,'\w*','')
elseif s:cpath(self.spec()[0 : len(self.repo().dir())]) ==#
\ s:cpath(self.repo().dir() . '/')
let rev = '/.git'.self.spec()[strlen(self.repo().dir()) : -1]
elseif !self.repo().bare() &&
\ s:cpath(self.spec()[0 : len(self.repo().tree())]) ==#
\ s:cpath(self.repo().tree() . '/')
let rev = self.spec()[strlen(self.repo().tree()) : -1]
endif
return s:sub(s:sub(rev,'.\zs/$',''),'^/',a:0 ? a:1 : '')
endfunction
function! s:buffer_rev() dict abort
let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*')
if rev =~ '^\x/'
return ':'.rev[0].':'.rev[2:-1]
elseif rev =~ '.'
return s:sub(rev,'/',':')
elseif self.spec() =~ '\.git/index$'
return ':'
elseif self.spec() =~ '\.git/refs/\|\.git/.*HEAD$'
return self.spec()[strlen(self.repo().dir())+1 : -1]
else
return self.path('/')
endif
endfunction
function! s:buffer_sha1() dict abort
if self.spec() =~ '^fugitive://' || self.spec() =~ '\.git/refs/\|\.git/.*HEAD$'
return self.repo().rev_parse(self.rev())
else
return ''
endif
endfunction
function! s:buffer_expand(rev) dict abort
if a:rev =~# '^:[0-3]$'
let file = a:rev.self.path(':')
elseif a:rev =~# '^[-:]/$'
let file = '/'.self.path()
elseif a:rev =~# '^-'
let file = 'HEAD^{}'.a:rev[1:-1].self.path(':')
elseif a:rev =~# '^@{'
let file = 'HEAD'.a:rev.self.path(':')
elseif a:rev =~# '^[~^]'
let commit = s:sub(self.commit(),'^\d=$','HEAD')
let file = commit.a:rev.self.path(':')
else
let file = a:rev
endif
return s:sub(s:sub(file,'\%$',self.path()),'\.\@<=/$','')
endfunction
function! s:buffer_containing_commit() dict abort
if self.commit() =~# '^\d$'
return ':'
elseif self.commit() =~# '.'
return self.commit()
else
return 'HEAD'
endif
endfunction
function! s:buffer_up(...) dict abort
let rev = self.rev()
let c = a:0 ? a:1 : 1
while c
if rev =~# '^[/:]$'
let rev = 'HEAD'
elseif rev =~# '^:'
let rev = ':'
elseif rev =~# '^refs/[^^~:]*$\|^[^^~:]*HEAD$'
let rev .= '^{}'
elseif rev =~# '^/\|:.*/'
let rev = s:sub(rev, '.*\zs/.*', '')
elseif rev =~# ':.'
let rev = matchstr(rev, '^[^:]*:')
elseif rev =~# ':$'
let rev = rev[0:-2]
else
return rev.'~'.c
endif
let c -= 1
endwhile
return rev
endfunction
call s:add_methods('buffer',['getvar','setvar','getline','repo','type','spec','name','commit','path','rev','sha1','expand','containing_commit','up'])
" Section: Git
call s:command("-bang -nargs=? -complete=customlist,s:GitComplete Git :execute s:Git(<bang>0,<q-args>)")
function! s:ExecuteInTree(cmd) abort
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd' : 'cd'
let dir = getcwd()
try
execute cd s:fnameescape(s:repo().tree())
execute a:cmd
finally
execute cd s:fnameescape(dir)
endtry
endfunction
function! s:Git(bang, args) abort
if a:bang
return s:Edit('edit', 1, a:args)
endif
let git = s:git_command()
if has('gui_running') && !has('win32')
let git .= ' --no-pager'
endif
let args = matchstr(a:args,'\v\C.{-}%($|\\@<!%(\\\\)*\|)@=')
if exists(':terminal')
let dir = s:repo().tree()
if expand('%') != ''
-tabedit %
else
-tabnew
endif
execute 'lcd' fnameescape(dir)
execute 'terminal' git args
else
call s:ExecuteInTree('!'.git.' '.args)
if has('win32')
call fugitive#reload_status()
endif
endif
return matchstr(a:args, '\v\C\\@<!%(\\\\)*\|\zs.*')
endfunction
function! fugitive#git_commands() abort
if !exists('s:exec_path')
let s:exec_path = s:sub(system(g:fugitive_git_executable.' --exec-path'),'\n$','')
endif
return map(split(glob(s:exec_path.'/git-*'),"\n"),'s:sub(v:val[strlen(s:exec_path)+5 : -1],"\\.exe$","")')
endfunction
function! s:GitComplete(A, L, P) abort
if strpart(a:L, 0, a:P) !~# ' [[:alnum:]-]\+ '
let cmds = fugitive#git_commands()
return filter(sort(cmds+keys(s:repo().aliases())), 'strpart(v:val, 0, strlen(a:A)) ==# a:A')
else
return s:repo().superglob(a:A)
endif
endfunction
" Section: Gcd, Glcd
function! s:DirComplete(A,L,P) abort
let matches = s:repo().dirglob(a:A)
return matches
endfunction
call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Gcd :exe 'cd<bang>' s:fnameescape(s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>))")
call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Glcd :exe 'lcd<bang>' s:fnameescape(s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>))")
" Section: Gstatus
call s:command("-bar Gstatus :execute s:Status()")
augroup fugitive_status
autocmd!
if !has('win32')
autocmd FocusGained,ShellCmdPost * call fugitive#reload_status()
autocmd BufDelete term://* call fugitive#reload_status()
endif
augroup END
function! s:Status() abort
try
Gpedit :
wincmd P
setlocal foldmethod=syntax foldlevel=1
nnoremap <buffer> <silent> q :<C-U>bdelete<CR>
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
return ''
endfunction
function! fugitive#reload_status() abort
if exists('s:reloading_status')
return
endif
try
let s:reloading_status = 1
let mytab = tabpagenr()
for tab in [mytab] + range(1,tabpagenr('$'))
for winnr in range(1,tabpagewinnr(tab,'$'))
if getbufvar(tabpagebuflist(tab)[winnr-1],'fugitive_type') ==# 'index'
execute 'tabnext '.tab
if winnr != winnr()
execute winnr.'wincmd w'
let restorewinnr = 1
endif
try
if !&modified
call s:BufReadIndex()
endif
finally
if exists('restorewinnr')
wincmd p
endif
execute 'tabnext '.mytab
endtry
endif
endfor
endfor
finally
unlet! s:reloading_status
endtry
endfunction
function! s:stage_info(lnum) abort
let filename = matchstr(getline(a:lnum),'^#\t\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$')
let lnum = a:lnum
if has('multi_byte_encoding')
let colon = '\%(:\|\%uff1a\)'
else
let colon = ':'
endif
while lnum && getline(lnum) !~# colon.'$'
let lnum -= 1
endwhile
if !lnum
return ['', '']
elseif (getline(lnum+1) =~# '^# .*\<git \%(reset\|rm --cached\) ' && getline(lnum+2) ==# '#') || getline(lnum) ==# '# Changes to be committed:'
return [matchstr(filename, colon.' *\zs.*'), 'staged']
elseif (getline(lnum+1) =~# '^# .*\<git add ' && getline(lnum+2) ==# '#' && getline(lnum+3) !~# colon.' ') || getline(lnum) ==# '# Untracked files:'
return [filename, 'untracked']
elseif getline(lnum+2) =~# '^# .*\<git checkout ' || getline(lnum) ==# '# Changes not staged for commit:'
return [matchstr(filename, colon.' *\zs.*'), 'unstaged']
elseif getline(lnum+2) =~# '^# .*\<git \%(add\|rm\)' || getline(lnum) ==# '# Unmerged paths:'
return [matchstr(filename, colon.' *\zs.*'), 'unmerged']
else
return ['', 'unknown']
endif
endfunction
function! s:StageNext(count) abort
for i in range(a:count)
call search('^#\t.*','W')
endfor
return '.'
endfunction
function! s:StagePrevious(count) abort
if line('.') == 1 && exists(':CtrlP') && get(g:, 'ctrl_p_map') =~? '^<c-p>$'
return 'CtrlP '.fnameescape(s:repo().tree())
else
for i in range(a:count)
call search('^#\t.*','Wbe')
endfor
return '.'
endif
endfunction
function! s:StageReloadSeek(target,lnum1,lnum2) abort
let jump = a:target
let f = matchstr(getline(a:lnum1-1),'^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\zs.*')
if f !=# '' | let jump = f | endif
let f = matchstr(getline(a:lnum2+1),'^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\zs.*')
if f !=# '' | let jump = f | endif
silent! edit!
1
redraw
call search('^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\V'.jump.'\%( ([^()[:digit:]]\+)\)\=\$','W')
endfunction
function! s:StageUndo() abort
let [filename, section] = s:stage_info(line('.'))
if empty(filename)
return ''
endif
let repo = s:repo()
let hash = repo.git_chomp('hash-object', '-w', filename)
if !empty(hash)
if section ==# 'untracked'
call repo.git_chomp_in_tree('clean', '-f', '--', filename)
elseif section ==# 'unmerged'
call repo.git_chomp_in_tree('rm', '--', filename)
elseif section ==# 'unstaged'
call repo.git_chomp_in_tree('checkout', '--', filename)
else
call repo.git_chomp_in_tree('checkout', 'HEAD', '--', filename)
endif
call s:StageReloadSeek(filename, line('.'), line('.'))
let @" = hash
return 'checktime|redraw|echomsg ' .
\ string('To restore, :Git cat-file blob '.hash[0:6].' > '.filename)
endif
endfunction
function! s:StageDiff(diff) abort
let [filename, section] = s:stage_info(line('.'))
if filename ==# '' && section ==# 'staged'
return 'Git! diff --no-ext-diff --cached'
elseif filename ==# ''
return 'Git! diff --no-ext-diff'
elseif filename =~# ' -> '
let [old, new] = split(filename,' -> ')
execute 'Gedit '.s:fnameescape(':0:'.new)
return a:diff.' HEAD:'.s:fnameescape(old)
elseif section ==# 'staged'
execute 'Gedit '.s:fnameescape(':0:'.filename)
return a:diff.' -'
else
execute 'Gedit '.s:fnameescape('/'.filename)
return a:diff
endif
endfunction
function! s:StageDiffEdit() abort
let [filename, section] = s:stage_info(line('.'))
let arg = (filename ==# '' ? '.' : filename)
if section ==# 'staged'
return 'Git! diff --no-ext-diff --cached '.s:shellesc(arg)
elseif section ==# 'untracked'
let repo = s:repo()
call repo.git_chomp_in_tree('add','--intent-to-add',arg)
if arg ==# '.'
silent! edit!
1
if !search('^# .*:\n#.*\n# .*"git checkout \|^# Changes not staged for commit:$','W')
call search('^# .*:$','W')
endif
else
call s:StageReloadSeek(arg,line('.'),line('.'))
endif
return ''
else
return 'Git! diff --no-ext-diff '.s:shellesc(arg)
endif
endfunction
function! s:StageToggle(lnum1,lnum2) abort
if a:lnum1 == 1 && a:lnum2 == 1
return 'Gedit /.git|call search("^index$", "wc")'
endif
try
let output = ''
for lnum in range(a:lnum1,a:lnum2)
let [filename, section] = s:stage_info(lnum)
let repo = s:repo()
if getline('.') =~# '^# .*:$'
if section ==# 'staged'
call repo.git_chomp_in_tree('reset','-q')
silent! edit!
1
if !search('^# .*:\n# .*"git add .*\n#\n\|^# Untracked files:$','W')
call search('^# .*:$','W')
endif
return ''
elseif section ==# 'unstaged'
call repo.git_chomp_in_tree('add','-u')
silent! edit!
1
if !search('^# .*:\n# .*"git add .*\n#\n\|^# Untracked files:$','W')
call search('^# .*:$','W')
endif
return ''
else
call repo.git_chomp_in_tree('add','.')
silent! edit!
1
call search('^# .*:$','W')
return ''
endif
endif
if filename ==# ''
continue
endif
execute lnum
if section ==# 'staged'
if filename =~ ' -> '
let files_to_unstage = split(filename,' -> ')
else
let files_to_unstage = [filename]
endif
let filename = files_to_unstage[-1]
let cmd = ['reset','-q','--'] + files_to_unstage
elseif getline(lnum) =~# '^#\tdeleted:'
let cmd = ['rm','--',filename]
elseif getline(lnum) =~# '^#\tmodified:'
let cmd = ['add','--',filename]
else
let cmd = ['add','-A','--',filename]