-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathgitv.vim
More file actions
2689 lines (2595 loc) · 86.2 KB
/
gitv.vim
File metadata and controls
2689 lines (2595 loc) · 86.2 KB
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
"AUTHOR: Greg Sexton <gregsexton@gmail.com>
"MAINTAINER: Roger Bongers <r.l.bongers@gmail.com>
"WEBSITE: http://www.gregsexton.org/portfolio/gitv/
"LICENSE: Same terms as Vim itself (see :help license).
"NOTES: Much of the credit for gitv goes to Tim Pope and the fugitive plugin
" where this plugin either uses functionality directly or was inspired heavily.
if exists("g:loaded_gitv") || v:version < 700
finish
endif
let g:loaded_gitv = 1
let s:savecpo = &cpo
set cpo&vim
"configurable options:
"g:Gitv_CommitStep - int
"g:Gitv_OpenHorizontal - {0,1,'AUTO'}
"g:Gitv_WipeAllOnClose - int
"g:Gitv_WrapLines - {0,1}
"g:Gitv_TruncateCommitSubjects - {0,1}
"g:Gitv_OpenPreviewOnLaunch - {0,1}
"g:Gitv_PromptToDeleteMergeBranch - {0,1}
if !exists("g:Gitv_CommitStep")
let g:Gitv_CommitStep = &lines
endif
if !exists('g:Gitv_WipeAllOnClose')
let g:Gitv_WipeAllOnClose = 0 "default for safety
endif
if !exists('g:Gitv_WrapLines')
let g:Gitv_WrapLines = 0
endif
if !exists('g:Gitv_TruncateCommitSubjects')
let g:Gitv_TruncateCommitSubjects = 0
endif
if !exists('g:Gitv_OpenPreviewOnLaunch')
let g:Gitv_OpenPreviewOnLaunch = 1
endif
if !exists('g:Gitv_PromptToDeleteMergeBranch')
let g:Gitv_PromptToDeleteMergeBranch = 0
endif
if !exists('g:Gitv_CustomMappings')
let g:Gitv_CustomMappings = {}
endif
if !exists('g:Gitv_DisableShellEscape')
let g:Gitv_DisableShellEscape = 0
endif
if !exists('g:Gitv_DoNotMapCtrlKey')
let g:Gitv_DoNotMapCtrlKey = 0
endif
if !exists('g:Gitv_PreviewOptions')
let g:Gitv_PreviewOptions = ''
endif
if !exists('g:Gitv_QuietBisect')
let g:Gitv_QuietBisect = 0
endif
" create a temporary file for working
let s:workingFile = tempname()
"this counts up each time gitv is opened to ensure a unique file name
let g:Gitv_InstanceCounter = 0
let s:localUncommitedMsg = 'Local uncommitted changes, not checked in to index.'
let s:localCommitedMsg = 'Local changes checked in to index but not committed.'
let s:pendingRebaseMsg = 'View pending rebase instructions'
let s:rebaseMsg = 'Edit rebase todo'
command! -nargs=* -range -bang -complete=custom,s:CompleteGitv Gitv call s:OpenGitv(s:EscapeGitvArgs(<q-args>), <bang>0, <line1>, <line2>)
cabbrev gitv <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'Gitv' : 'gitv')<CR>
"Public API:"{{{
fu! Gitv_OpenGitCommand(command, windowCmd, ...) "{{{
"returns 1 if command succeeded with output
"optional arg is a flag, if present runs command verbatim
"this function is not limited to script scope as is useful for running other commands.
"e.g call Gitv_OpenGitCommand("diff --no-color", 'vnew') is useful for getting an overall git diff.
let [result, finalCmd] = s:RunGitCommand(a:command, a:0)
if type(result) == type(0)
return 0
endif
if type(result) == type("") && result == ""
echom "No output."
return 0
else
if a:windowCmd == ''
silent setlocal modifiable
silent setlocal noreadonly
1,$ d _
else
let goBackTo = winnr()
let dir = fugitive#repo().dir()
let workingDir = fugitive#repo().tree()
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let bufferDir = getcwd()
let tempSplitBelow = &splitbelow
let tempSplitRight = &splitright
try
set nosplitbelow
set nosplitright
execute cd.'`=workingDir`'
exec a:windowCmd
let newWindow = winnr()
finally
exec goBackTo . 'wincmd w'
execute cd.'`=bufferDir`'
if exists('newWindow')
exec newWindow . 'wincmd w'
endif
exec 'set '. (tempSplitBelow ? '' : 'no') . 'splitbelow'
exec 'set '. (tempSplitRight ? '' : 'no') . 'splitright'
endtry
endif
if !(&modifiable)
return 0
endif
let b:Git_Command = finalCmd
silent setlocal ft=git
silent setlocal buftype=nofile
silent setlocal nobuflisted
silent setlocal noswapfile
silent setlocal bufhidden=wipe
silent setlocal nonumber
if exists('+relativenumber')
silent setlocal norelativenumber
endif
if g:Gitv_WrapLines
silent setlocal wrap
else
silent setlocal nowrap
endif
silent setlocal fdm=syntax
nnoremap <buffer> <silent> q :q!<CR>
nnoremap <buffer> <silent> u :if exists('b:Git_Command')<bar>call Gitv_OpenGitCommand(b:Git_Command, '', 1)<bar>endif<cr>
call append(0, split(result, '\n')) "system converts eols to \n regardless of os.
silent setlocal nomodifiable
silent setlocal readonly
1
return 1
endif
endf "}}}
fu! Gitv_GetDebugInfo() "{{{
if has('clipboard')
redir @+
endif
echo '## Gitv debug output'
echo ''
echo '### Basic information'
echo ''
echo '```'
echo 'Version: 1.3.1.22'
echo ''
echo strftime('%c')
echo '```'
echo ''
echo '### Settings'
echo ''
echo '```'
set
echo '```'
echo ''
echo '### Vim version'
echo ''
echo '```'
version
echo '```'
echo ''
echo '### Git output'
echo ''
echo '```'
try
echo '$ git --version'
echo s:RunCommandRelativeToGitRepo('git --version')[0]
echo '$ git status'
echo s:RunCommandRelativeToGitRepo('git status')[0]
echo '$ git remote --verbose'
echo s:RunCommandRelativeToGitRepo('git remote --verbose')[0]
catch
echo 'Gitv_GetDebugInfo exception:'
echo v:exception
endtry
echo '```'
echo ''
echo '### Fugitive version'
echo ''
echo '```'
try
let filename = s:GetFugitiveInfo()[1]
" Make sure redirection is still set up
if has('clipboard')
redir @+
endif
for line in readfile(filename)
if line =~ 'Version:' || line =~ 'GetLatestVimScripts:'
echo line
endif
endfor
catch
echo 'Gitv_GetDebugInfo exception:'
echo v:exception
endtry
echo '```'
echo ''
redir END
if has('clipboard')
echo 'Debug information has been copied to your clipboard. Please attach this information to your submitted issue.'
else
echo 'Please copy the contents above and add them to your submitted issue.'
endif
endf "}}} }}}
"General Git Functions: "{{{
fu! s:RunGitCommand(command, verbatim) "{{{
"if verbatim returns result of system command, else
"switches to the buffer repository before running the command and switches back after.
if !a:verbatim
"switches to the buffer repository before running the command and switches back after.
let cmd = FugitiveShellCommand() .' '. a:command
let [result, finalCmd] = s:RunCommandRelativeToGitRepo(cmd)
else
let result = system(a:command)
let finalCmd = a:command
endif
return [result, finalCmd]
endfu "}}}
fu! s:RunCommandRelativeToGitRepo(command) abort "{{{
" Runs the command verbatim but first changing to the root git dir.
" Input commands should include a --git-dir argument to git (see
" FugitiveShellCommand()).
let workingDir = fugitive#repo().tree()
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let bufferDir = getcwd()
try
execute cd.'`=workingDir`'
let result = system(a:command)
finally
execute cd.'`=bufferDir`'
endtry
return [result, a:command]
endfu "}}} }}}
"Open And Update Gitv:"{{{
fu! s:SanitizeReservedArgs(extraArgs) "{{{
let sanitizedArgs = a:extraArgs
if sanitizedArgs[0] =~ "[\"']" && sanitizedArgs[:-1] =~ "[\"']"
let sanitizedArgs = sanitizedArgs[1:-2]
endif
" store bisect
if match(sanitizedArgs, ' --bisect') >= 0
let sanitizedArgs = substitute(sanitizedArgs, ' --bisect', '', 'g')
if s:BisectHasStarted()
let b:Gitv_Bisecting = 1
endif
endif
" store files
let selectedFiles = []
let splitArgs = split(sanitizedArgs, ' ')
let index = len(splitArgs)
let root = fugitive#repo().tree().'/'
while index
let index -= 1
let path = splitArgs[index]
if !empty(globpath('.', path))
" transform the path relative to the git directory
let path = fnamemodify(path, ':p')
let splitPath = split(path, root)
if splitPath[0] == path
echoerr "Not in git repo:" path
break
endif
" join the relroot back in case we split more than one off
let path = join(splitPath, root)
let selectedFiles += [path]
else
break
endif
endwhile
let selectedFiles = sort(selectedFiles)
return [join(splitArgs[0:-len(selectedFiles) - 1], ' '), join(selectedFiles, ' ')]
endfu "}}}
fu! s:ReapplyReservedArgs(extraArgs) "{{{
let options = a:extraArgs[0]
if s:RebaseIsEnabled()
return [options, '']
endif
if s:BisectIsEnabled()
if !s:IsBisectingCurrentFiles()
echoerr "Not bisecting specified files."
let b:Gitv_Bisecting = 0
else
let options .= " --bisect"
let options = s:FilterArgs(options, ['--all', '--first-parent'])
endif
endif
return [options, a:extraArgs[1]]
endfu "}}}
fu! s:EscapeGitvArgs(extraArgs) "{{{
" TODO: test whether shellescape is really needed on windows.
if g:Gitv_DisableShellEscape == 0
return shellescape(a:extraArgs)
else
return a:extraArgs
endif
endfu "}}}
fu! s:OpenGitv(extraArgs, fileMode, rangeStart, rangeEnd) "{{{
if !exists('s:fugitiveSid')
let s:fugitiveSid = s:GetFugitiveSid()
endif
let sanitizedArgs = s:SanitizeReservedArgs(a:extraArgs)
let g:Gitv_InstanceCounter += 1
if !s:IsCompatible() "this outputs specific errors
return
endif
try
if a:fileMode
call s:OpenFileMode(sanitizedArgs, a:rangeStart, a:rangeEnd)
else
call s:OpenBrowserMode(sanitizedArgs)
endif
catch /not a git repository/
echom 'Not a git repository.'
return
endtry
endf "}}}
fu! s:IsCompatible() "{{{
if !exists('g:loaded_fugitive')
echoerr "gitv requires the fugitive plugin to be installed."
endif
return exists('g:loaded_fugitive')
endfu "}}}
fu! s:CompleteGitv(arglead, cmdline, pos) "{{{
if match( a:arglead, '^-' ) >= 0
return "\n--after\n--all-match\n--ancestry-path\n--author-date-order"
\ . "\n--author=\n--author=\n--before=\n--bisect\n--boundary"
\ . "\n--branches\n--cherry-mark\n--cherry-pick\n--committer="
\ . "\n--date-order\n--dense\n--exclude=\n--first-parent"
\ . "\n--fixed-strings\n--follow\n--glob\n--grep-reflog"
\ . "\n--grep=\n--max-age=\n--max-count=\n--merges\n--no-merges"
\ . "\n--min-age=\n--min-parents=\n--not\n--pickaxe-all"
\ . "\n--pickaxe-regex\n--regexp-ignore-case\n--remotes"
\ . "\n--remove-empty\n--since=\n--skip\n--tags\n--topo-order"
\ . "\n--until=\n--use-mailmap"
else
if match(a:arglead, '\/$') >= 0
let paths = "\n".globpath(a:arglead, '*')
else
let paths = "\n".glob(a:arglead.'*')
endif
let refs = fugitive#repo().git_chomp('rev-parse', '--symbolic', '--branches', '--tags', '--remotes')
let refs .= "\nHEAD\nFETCH_HEAD\nORIG_HEAD"
" Complete ref names preceded by a ^ or anything followed by 2-3 dots
let prefix = matchstr( a:arglead, '\v^(\^|.*\.\.\.?)' )
if prefix == ''
return refs.paths
else
return substitute( refs, "\\v(^|\n)\\zs", prefix, 'g' ).paths
endif
endf "}}}
fu! s:OpenBrowserMode(extraArgs) "{{{
"this throws an exception if not a git repo which is caught immediately
silent Gtabedit HEAD:
if s:IsHorizontal()
let direction = 'new gitv'.'-'.g:Gitv_InstanceCounter
else
let direction = 'vnew gitv'.'-'.g:Gitv_InstanceCounter
endif
if !s:LoadGitv(direction, 0, g:Gitv_CommitStep, a:extraArgs, '', [])
return 0
endif
call s:SetupBufferCommands(0)
let b:Gitv_RebaseInstructions = {}
"open the first commit
if g:Gitv_OpenPreviewOnLaunch
silent call s:OpenGitvCommit("Gedit", 0)
else
call s:MoveIntoPreviewAndExecute('bdelete', 0)
endif
endf "}}}
fu! s:OpenFileMode(extraArgs, rangeStart, rangeEnd) "{{{
let relPath = fugitive#Path(@%, a:0 ? a:1 : '')
pclose!
let range = a:rangeStart != a:rangeEnd ? s:GetRegexRange(a:rangeStart, a:rangeEnd) : []
if !s:LoadGitv(&previewheight . "new gitv".'-'.g:Gitv_InstanceCounter, 0, g:Gitv_CommitStep, a:extraArgs, relPath, range)
return 0
endif
set previewwindow
set winfixheight
let b:Gitv_FileMode = 1
let b:Gitv_FileModeRelPath = relPath
let b:Gitv_FileModeRange = range
call s:SetupBufferCommands(1)
endf "}}}
fu! s:LoadGitv(direction, reload, commitCount, extraArgs, filePath, range) "{{{
call s:RebaseUpdate()
call s:BisectUpdate()
if a:reload
let jumpTo = line('.') "this is for repositioning the cursor after reload
endif
"precondition: a:range should be of the form [a, b] or []
" where a,b are integers && a<b
if !s:ConstructAndExecuteCmd(a:direction, a:commitCount, a:extraArgs, a:filePath, a:range)
return 0
endif
call s:SetupBuffer(a:commitCount, a:extraArgs, a:filePath, a:range)
exec exists('jumpTo') ? jumpTo : '1'
call s:SetupMappings() "redefines some of the mappings made by Gitv_OpenGitCommand
call s:ResizeWindow(a:filePath!='')
echom "Loaded up to " . a:commitCount . " commits."
return 1
endf "}}}
fu! s:FilterArgs(args, sanitize) "{{{
let newArgs = a:args
for arg in a:sanitize
let newArgs = substitute(newArgs, '\( \|^\)' . arg, '', 'g')
endfor
return newArgs
endf "}}}
fu! s:ToggleArg(args, toggle) "{{{
if matchstr(a:args[0], a:toggle) == ''
let NewArgs = a:args[0] . ' ' . a:toggle
else
let NewArgs = substitute(a:args[0], '\( \|^\)' . a:toggle, '', '')
endif
let b:Gitv_ExtraArgs = [NewArgs, a:args[1]]
return [NewArgs, a:args[1]]
endf "}}}
fu! s:ConstructAndExecuteCmd(direction, commitCount, extraArgs, filePath, range) "{{{
if a:range == [] "no range, setup and execute the command
let extraArgs = s:ReapplyReservedArgs(a:extraArgs)
let cmd = "log "
let cmd .= " --no-color --decorate=full --pretty=format:\"%d__START__ %s__SEP__%ar__SEP__%an__SEP__[%h]\" --graph -"
let cmd .= a:commitCount
let cmd .= " " . extraArgs[0]
if a:filePath != ''
let cmd .= ' -- ' . a:filePath
elseif extraArgs[1] != ''
let cmd .= ' -- ' . extraArgs[1]
endif
let g:cmd = cmd
silent let res = Gitv_OpenGitCommand(cmd, a:direction)
return res
else "range applies, setup a trivial buffer and then modify it with custom logic
let cmd = "--version" "arbitrary command intended to setup the buffer
"and act as a check everything is ok
let g:cmd = cmd
silent let res = Gitv_OpenGitCommand(cmd, a:direction)
if !res | return res | endif
silent let res = s:ConstructRangeBuffer(a:commitCount, a:extraArgs, a:filePath, a:range)
return res
endif
endf "}}}
"Range Commands: {{{
fu! s:ConstructRangeBuffer(commitCount, extraArgs, filePath, range) "{{{
silent setlocal modifiable
silent setlocal noreadonly
%delete
"necessary as order is important; can't just iterate over keys(slices)
let extraArgs = s:ReapplyReservedArgs(a:extraArgs)
let hashCmd = "log " . extraArgs[0]
let hashCmd .= " --no-color --pretty=format:%H -".a:commitCount." -- " . a:filePath
let [result, cmd] = s:RunGitCommand(hashCmd, 0)
let hashes = split(result, '\n')
let slices = s:GetFileSlices(a:range, a:filePath, a:commitCount, a:extraArgs)
if s:AllSlicesBlank(slices)
call append(0, 'No commits matched the range. Try altering the search.')
else
let modHashes = []
for i in range(len(hashes))
let hash1 = hashes[i]
let hash2 = get(hashes, i+1, "")
if (hash2 == "" && has_key(slices, hash1)) || s:CompareFileAtCommits(slices, hash1, hash2)
let modHashes = add(modHashes, hash1)
endif
endfor
let output = s:GetFinalOutputForHashes(modHashes)
call append(0, output)
endif
silent setlocal nomodifiable
silent setlocal readonly
return 1
endf "}}}
fu! s:GetFileSlices(range, filePath, commitCount, extraArgs) "{{{
"this returns a dictionary, indexed by commit sha, of all slices of range lines of filePath
"NOTE: this could get massive for a large repo and large range
let range = a:range[0] . ',' . a:range[1]
let range = substitute(range, "'", "'\\\\''", 'g') "force unix style escaping even on windows
let git = FugitiveShellCommand()
let sliceCmd = "for hash in `".git." log " . a:extraArgs[0]
let sliceCmd .= " --no-color --pretty=format:%H -".a:commitCount." -- " . a:filePath . '`; '
let sliceCmd .= "do "
let sliceCmd .= 'echo "****${hash}"; '
let sliceCmd .= git." --no-pager blame -s -L '" . range . "' ${hash} " . a:filePath . "; "
let sliceCmd .= "done"
let finalCmd = "bash -c " . shellescape(sliceCmd)
let [result, cmd] = s:RunCommandRelativeToGitRepo(finalCmd)
let slicesLst = split(result, '\(^\|\n\)\zs\*\{4}')
let slices = {}
for slice in slicesLst
let key = matchstr(slice, '^.\{-}\ze\n')
let val = matchstr(slice, '\n\zs.*')
if val !~? '^fatal: .*$'
"remove the commit sha and line number to stop them affecting the comparisons
let lines = split(val, '\n')
call map(lines, "matchstr(v:val, '\\x\\{-} \\d\\+) \\zs.*')")
let finalVal = join(lines)
let slices[key] = finalVal
endif
endfor
return slices
endfu "}}}
fu! s:AllSlicesBlank(slices) "{{{
for i in keys(a:slices)
if a:slices[i] != ''
return 0
endif
endfor
return 1
endfu "}}}
fu! s:CompareFileAtCommits(slices, c1sha, c2sha) "{{{
"returns 1 if lineRange for filePath in commits: c1sha and c2sha are different
"else returns 0
if has_key(a:slices, a:c1sha) && !has_key(a:slices, a:c2sha)
return 1
endif
if has_key(a:slices, a:c1sha) && has_key(a:slices, a:c2sha)
return a:slices[a:c1sha] != a:slices[a:c2sha]
else
return 0
endif
endfu "}}}
fu! s:GetFinalOutputForHashes(hashes) "{{{
if len(a:hashes) > 0
let extraArgs = s:ReapplyReservedArgs(['', ''])
let git = FugitiveShellCommand()
let cmd = 'for hash in ' . join(a:hashes, " ") . '; '
let cmd .= "do "
let cmd .= git.' log'
let cmd .= extraArgs[0]
let cmd .=' --no-color --decorate=full --pretty=format:"%d__START__ %s__SEP__%ar__SEP__%an__SEP__[%h]%n" --graph -1 ${hash}; '
let cmd .= 'done'
let finalCmd = "bash -c " . shellescape(cmd)
let [result, cmd] = s:RunCommandRelativeToGitRepo(finalCmd)
return split(result, '\n')
else
return ""
endif
endfu "}}}
fu! s:GetRegexRange(rangeStart, rangeEnd) "{{{
let rangeS = getline(a:rangeStart)
let rangeS = escape(rangeS, '.^$*\/[]')
let rangeS = matchstr(rangeS, '\v^\s*\zs.{-}\ze\s*$') "trim whitespace
let rangeE = getline(a:rangeEnd)
let rangeE = escape(rangeE, '.^$*\/[]')
let rangeE = matchstr(rangeE, '\v^\s*\zs.{-}\ze\s*$') "trim whitespace
let rangeS = rangeS =~ '^\s*$' ? '^[:blank:]*$' : rangeS
let rangeE = rangeE =~ '^\s*$' ? '^[:blank:]*$' : rangeE
return ['/'.rangeS.'/', '/'.rangeE.'/']
endfu "}}} }}}
fu! s:SetupBuffer(commitCount, extraArgs, filePath, range) "{{{
silent set filetype=gitv
let b:Gitv_CommitCount = a:commitCount
let b:Gitv_ExtraArgs = a:extraArgs
silent setlocal modifiable
silent setlocal noreadonly
silent %s/refs\/tags\//t:/ge
silent %s/refs\/remotes\//r:/ge
silent %s/refs\/heads\///ge
call s:AddLoadMore()
call s:AddLocalNodes(a:filePath)
call s:AddFileModeSpecific(a:filePath, a:range, a:commitCount)
call s:AddRebaseMessage(a:filePath)
" run any autocmds the user may have defined to hook in here
silent doautocmd User GitvSetupBuffer
silent call s:InsertRebaseInstructions()
silent %call s:Align("__SEP__", a:filePath)
silent %s/\s\+$//e
silent setlocal nomodifiable
silent setlocal readonly
silent setlocal cursorline
endf "}}}
fu! s:InsertRebaseInstructions() "{{{
if s:RebaseHasInstructions()
for key in keys(b:Gitv_RebaseInstructions)
let search = '__START__\ze.*\['.key.'\]$'
let replace = ' ['.b:Gitv_RebaseInstructions[key].instruction
if exists('b:Gitv_RebaseInstructions[key].cmd')
let replace .= 'x'
endif
let replace .= ']'
exec '%s/'.search.'/'.replace
endfor
endif
%s/__START__//
endf "}}}
fu! s:CleanupRebasePreview() "{{{
if &syntax == 'gitrebase'
bdelete
endif
endf "}}}
fu! s:AddRebaseMessage(filePath) "{{{
if a:filePath != ''
return
endif
if s:RebaseHasInstructions()
call append(0, '= '.s:pendingRebaseMsg)
elseif s:RebaseIsEnabled()
call append(0, '= '.s:rebaseMsg)
else
" TODO: this will fail if there's no preview window
call s:MoveIntoPreviewAndExecute('call s:CleanupRebasePreview()', 0)
endif
endf "}}}
fu! s:AddLocalNodes(filePath) "{{{
let suffix = a:filePath == '' ? '' : ' -- '.a:filePath
let gitCmd = "diff --no-color" . suffix
let [result, cmd] = s:RunGitCommand(gitCmd, 0)
let headLine = search('^\(\(|\|\/\|\\\|\*\)\s\?\)*\s*([^)]*HEAD', 'cnw')
let headLine = headLine == 0 ? 1 : headLine
if result != ""
let line = s:AlignWithRefs(headLine, s:localUncommitedMsg)
call append(headLine-1, substitute(line, '*', '=', ''))
let headLine += 1
endif
let gitCmd = "diff --no-color --cached" . suffix
let [result, cmd] = s:RunGitCommand(gitCmd, 0)
if result != ""
let line = s:AlignWithRefs(headLine, s:localCommitedMsg)
call append(headLine-1, substitute(line, '*', '+', ''))
endif
endfu
fu! s:AlignWithRefs(targetLine, targetStr)
"returns the targetStr prefixed with enough whitespace to align with
"the first asterisk on targetLine
if a:targetLine == 0
return '* '.a:targetStr
endif
let line = getline(a:targetLine)
let idx = stridx(line, '(')
if idx == -1
return '* '.a:targetStr
endif
return strpart(line, 0, idx) . a:targetStr
endfu "}}}
fu! s:AddLoadMore() "{{{
call append(line('$'), '-- Load More --')
endfu "}}}
fu! s:AddFileModeSpecific(filePath, range, commitCount) "{{{
if a:filePath != ''
call append(0, '-- ['.a:filePath.'] --')
if a:range != []
call append(1, '-- Showing (up to '.a:commitCount.') commits affecting lines in the range:')
call append(2, '-- ' . a:range[0])
call append(3, '-- ' . a:range[1])
endif
endif
endfu "}}}
"Mapping: "{{{
fu! s:SetDefaultMappings() "{{{
" creates the script-scoped dictionary of mapping descriptors
" the dictionary will optionally include ctrl based commands
" sets s:defaultMappings to the dictionary
let s:defaultMappings = {}
" convenience
let s:defaultMappings.quit = {
\'cmd': ':<C-U>call <SID>CloseGitv()<cr>', 'bindings': 'q'
\}
let s:defaultMappings.update = {
\'cmd': ':<C-U>call <SID>LoadGitv("", 1, b:Gitv_CommitCount, b:Gitv_ExtraArgs, <SID>GetRelativeFilePath(), <SID>GetRange())<cr>',
\'bindings': 'u'
\}
let s:defaultMappings.toggleAll = {
\'cmd': ':<C-U>call <SID>LoadGitv("", 0, b:Gitv_CommitCount, <SID>ToggleArg(b:Gitv_ExtraArgs, "--all"), <SID>GetRelativeFilePath(), <SID>GetRange())<cr>',
\'bindings': 'a'
\}
" movement
let s:defaultMappings.nextBranch = {
\'cmd': ':call <SID>JumpToBranch(0)<cr>',
\'bindings': 'x'
\}
let s:defaultMappings.prevBranch = {
\'cmd': ':call <SID>JumpToBranch(1)<cr>',
\'bindings': 'X'
\}
let s:defaultMappings.nextRef = {
\'cmd': ':call <SID>JumpToRef(0)<cr>',
\'bindings': 'r'
\}
let s:defaultMappings.prevRef = {
\'cmd': ':call <SID>JumpToRef(1)<cr>',
\'bindings': 'R'
\}
let s:defaultMappings.head = {
\'cmd': ':<C-U>call <SID>JumpToHead()<cr>',
\'bindings': 'P'
\}
let s:defaultMappings.parent = {
\'cmd': ':<C-U>call <SID>JumpToParent()<cr>',
\'bindings': 'p'
\}
let s:defaultMappings.toggleWindow = {
\'cmd': ':<C-U>call <SID>SwitchBetweenWindows()<cr>',
\'bindings': 'gw'
\}
" viewing commits
let s:defaultMappings.editCommit = {
\'cmd': ':<C-U>call <SID>OpenGitvCommit("Gedit", 0)<cr>',
\'bindings': [
\'<cr>', { 'keys': '<LeftMouse>', 'prefix': '<LeftMouse>' }
\],
\}
" <Plug>(gitv-*) are fuzzyfinder style keymappings
let s:defaultMappings.splitCommit = {
\'cmd': ':<C-U>call <SID>OpenGitvCommit("Gsplit", 0)<cr>',
\'bindings': 'o',
\'permanentBindings': '<Plug>(gitv-split)'
\}
let s:defaultMappings.tabeCommit = {
\'cmd': ':<C-U>call <SID>OpenGitvCommit("Gtabedit", 0)<cr>',
\'bindings': 'O' ,
\'permanentBindings': '<Plug>(gitv-tabedit)'
\}
let s:defaultMappings.vertSplitCommit = {
\'cmd': ':<C-U>call <SID>OpenGitvCommit("Gvsplit", 0)<cr>',
\'bindings': 's',
\'permanentBindings': '<Plug>(gitv-vsplit)'
\}
let s:defaultMappings.prevCommit = {
\'cmd': ':<C-U>call <SID>JumpToCommit(0)<cr>',
\'bindings': 'J',
\'permanentBindings': '<Plug>(gitv-previous-commit)'
\}
let s:defaultMappings.nextCommit = {
\'cmd': ':<C-U>call <SID>JumpToCommit(1)<cr>',
\'bindings': 'K',
\'permanentBindings': '<Plug>(gitv-next-commit)'
\}
" force opening the fugitive buffer for the commit
let s:defaultMappings.editCommitDetails = {
\'cmd': ':<C-U>call <SID>OpenGitvCommit("Gedit", 1)<cr>',
\'bindings': 'i',
\'permanentBindings': '<Plug>(gitv-edit)'
\}
let s:defaultMappings.diff = {
\'cmd': ':<C-U>call <SID>DiffGitvCommit()<cr>',
\'bindings': 'D'
\}
let s:defaultMappings.vdiff = {
\'mapCmd': 'vnoremap',
\'cmd': ':call <SID>DiffGitvCommit()<cr>',
\'bindings': 'D'
\}
let s:defaultMappings.stat = {
\'cmd': ':<C-U>call <SID>StatGitvCommit()<cr>',
\'bindings': 'S'
\}
let s:defaultMappings.vstat = {
\'mapCmd': 'vnoremap',
\'cmd': ':call <SID>StatGitvCommit()<cr>',
\'bindings': 'S'
\}
" general git commands
let s:defaultMappings.checkout = {
\'cmd': ':<C-U>call <SID>CheckOutGitvCommit()<cr>', 'bindings': 'co'
\}
let s:defaultMappings.merge = {
\'cmd': ':<C-U>call <SID>MergeToCurrent()<cr>', 'bindings': '<leader>m'
\}
let s:defaultMappings.vmerge = {
\'mapCmd': 'vnoremap',
\'cmd': ':call <SID>MergeBranches()<cr>',
\'bindings': 'm'
\}
let s:defaultMappings.cherryPick = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>CherryPick()<cr>',
\'bindings': 'cp'
\}
let s:defaultMappings.vcherryPick = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>CherryPick()<cr>',
\'bindings': 'cp'
\}
let s:defaultMappings.reset = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>ResetBranch("--mixed")<cr>',
\'bindings': 'rb'
\}
let s:defaultMappings.vreset = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>ResetBranch("--mixed")<cr>',
\'bindings': 'rb'
\}
let s:defaultMappings.resetSoft = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>ResetBranch("--soft")<cr>',
\'bindings': 'rbs'
\}
let s:defaultMappings.vresetSoft = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>ResetBranch("--soft")<cr>',
\'bindings': 'rbs'
\}
let s:defaultMappings.resetHard = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>ResetBranch("--hard")<cr>',
\'bindings': 'rbh'
\}
let s:defaultMappings.vresetHard = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>ResetBranch("--hard")<cr>',
\'bindings': 'rbh'
\}
let s:defaultMappings.revert = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>Revert()<cr>',
\'bindings': 'rev'
\}
let s:defaultMappings.vrevert = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>Revert()<cr>',
\'bindings': 'rev'
\}
let s:defaultMappings.delete = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>DeleteRef()<cr>',
\'bindings': 'd'
\}
let s:defaultMappings.vdelete = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>DeleteRef()<cr>',
\'bindings': 'd'
\}
" rebasing
let s:defaultMappings.rebase = {
\'cmd': ':<C-U>call <SID>Rebase()<cr>',
\'bindings': 'grr'
\}
let s:defaultMappings.vrebase = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>Rebase()<cr>',
\'bindings': 'grr'
\}
let s:defaultMappings.rebasePick = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("p")<cr>',
\'bindings': 'grP'
\}
let s:defaultMappings.vrebasePick = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("p")<cr>',
\'bindings': 'grP'
\}
let s:defaultMappings.rebaseReword = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("r")<cr>',
\'bindings': 'grR'
\}
let s:defaultMappings.vrebaseReword = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("r")<cr>',
\'bindings': 'grR'
\}
let s:defaultMappings.rebaseMarkEdit = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("e")<cr>',
\'bindings': 'grE'
\}
let s:defaultMappings.vrebaseMarkEdit = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("e")<cr>',
\'bindings': 'grE'
\}
let s:defaultMappings.rebaseSquash = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("s")<cr>',
\'bindings': 'grS'
\}
let s:defaultMappings.vrebaseSquash = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("s")<cr>',
\'bindings': 'grS'
\}
let s:defaultMappings.rebaseFixup = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("f")<cr>',
\'bindings': 'grF'
\}
let s:defaultMappings.vrebaseFixup = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("f")<cr>',
\'bindings': 'grF'
\}
let s:defaultMappings.rebaseExec = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("x")<cr>',
\'bindings': 'grX'
\}
let s:defaultMappings.vrebaseExec = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("x")<cr>',
\'bindings': 'grX'
\}
let s:defaultMappings.rebaseDrop = {
\'cmd': ':<C-U>call <SID>RebaseSetInstruction("d")<cr>',
\'bindings': 'grD'
\}
let s:defaultMappings.vrebaseDrop = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseSetInstruction("d")<cr>',
\'bindings': 'grD'
\}
let s:defaultMappings.rebaseAbort = {
\'cmd': ':<C-U>call <SID>RebaseAbort()<cr>',
\'bindings': 'gra'
\}
let s:defaultMappings.rebaseToggle = {
\'cmd': ':<C-U>call <SID>RebaseToggle()<cr>',
\'bindings': 'grs'
\}
let s:defaultMappings.vrebaseToggle = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>RebaseToggle()<cr>',
\'bindings': 'grs'
\}
let s:defaultMappings.rebaseSkip = {
\'cmd': ':call <SID>RebaseSkip()<cr>',
\'bindings': 'grn'
\}
let s:defaultMappings.rebaseContinue = {
\'cmd': ':<C-U>call <SID>RebaseContinue()<cr>',
\'bindings': 'grc'
\}
" bisecting
let s:defaultMappings.bisectStart = {
\'mapCmd': 'nmap',
\'cmd': ':<C-U>call <SID>BisectStart("n")<cr>',
\'bindings': 'gbs'
\}
let s:defaultMappings.vbisectStart = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>BisectStart("v")<cr>',
\'bindings': 'gbs'
\}
let s:defaultMappings.bisectGood = {
\'mapCmd': 'nmap',
\'cmd': ':call <SID>BisectGoodBad("good")<cr>',
\'bindings': 'gbg'
\}
let s:defaultMappings.vbisectGood = {
\'mapCmd': 'vmap',
\'cmd': ':call <SID>BisectGoodBad("good")<cr>',
\'bindings': 'gbg'
\}
let s:defaultMappings.bisectBad = {
\'mapCmd': 'nmap',
\'cmd': ':call <SID>BisectGoodBad("bad")<cr>',
\'bindings': 'gbb'