/
plugconf.go
904 lines (815 loc) · 26.2 KB
/
plugconf.go
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
package plugconf
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
multierror "github.com/hashicorp/go-multierror"
"github.com/vim-volt/volt/httputil"
"github.com/vim-volt/volt/lockjson"
"github.com/vim-volt/volt/pathutil"
"github.com/haya14busa/go-vimlparser"
"github.com/haya14busa/go-vimlparser/ast"
"github.com/haya14busa/go-vimlparser/token"
)
type loadOnType string
// TODO: make this uint
const (
loadOnStart loadOnType = "(loadOnStart)"
loadOnFileType = "FileType"
loadOnExcmd = "(loadOnExcmd)"
)
const (
// TODO: Check duplicate variable for excmdLoadPlugin
excmdLoadPlugin = "s:__volt_excmd_load_plugin"
lazyLoadExcmdFunc = "s:__volt_lazy_load_excmd"
completeFunc = "s:__volt_complete"
)
func isProhibitedFuncName(name string) bool {
return name == lazyLoadExcmdFunc ||
name == completeFunc
}
// ParsedInfo represents parsed info of plugconf.
type ParsedInfo struct {
reposID int
reposPath pathutil.ReposPath
functions []string
onLoadPreFunc string
onLoadPostFunc string
loadOnFunc string
loadOn loadOnType
loadOnArg string
dependsFunc string
depends pathutil.ReposPathList
}
// ConvertConfigToOnLoadPreFunc converts s:config() function name to
// s:on_load_pre() (see 'volt migrate plugconf/config-func' function).
// If no s:config() function is found, returns false.
// If found, returns true.
func (pi *ParsedInfo) ConvertConfigToOnLoadPreFunc() bool {
newStr := rxFuncName.ReplaceAllString(pi.onLoadPreFunc, "${1}on_load_pre")
if pi.onLoadPreFunc != newStr {
return false
}
pi.onLoadPreFunc = newStr
return true
}
// GeneratePlugconf generates a plugconf file placed at
// "$VOLTPATH/plugconf/{repos}.vim".
func (pi *ParsedInfo) GeneratePlugconf() ([]byte, error) {
// Merge result and return it
var buf bytes.Buffer
// modeline
buf.WriteString("\" vim:et:sw=2:ts=2\n\n")
// s:on_load_pre()
if pi.onLoadPreFunc != "" {
buf.WriteString(pi.onLoadPreFunc)
} else {
buf.WriteString(skeletonPlugconfOnLoadPre)
}
buf.WriteString("\n\n")
// s:on_load_post()
if pi.onLoadPostFunc != "" {
buf.WriteString(pi.onLoadPostFunc)
} else {
buf.WriteString(skeletonPlugconfOnLoadPost)
}
buf.WriteString("\n\n")
// s:loaded_on()
if pi.loadOnFunc != "" {
buf.WriteString(pi.loadOnFunc)
} else {
buf.WriteString(skeletonPlugconfLoadOn)
}
buf.WriteString("\n\n")
// s:depends()
if pi.dependsFunc != "" {
buf.WriteString(pi.dependsFunc)
} else {
buf.WriteString(skeletonPlugconfDepends)
}
for _, f := range pi.functions {
buf.WriteString("\n\n")
buf.WriteString(f)
}
return buf.Bytes(), nil
}
// ParseError does not provide Error() because I don't want let it pretend like
// error type. Receivers of a value of this type must decide how to handle.
type ParseError struct {
path string
merr *multierror.Error
mwarn *multierror.Error
}
func newParseError(path string) *ParseError {
var e ParseError
e.path = path
e.merr = newParseErrorMultiError("parse errors in ", path)
e.mwarn = newParseErrorMultiError("parse warnings in ", path)
return &e
}
func newParseErrorMultiError(prefix, path string) *multierror.Error {
return &multierror.Error{
Errors: make([]error, 0, 8),
ErrorFormat: func(errs []error) string {
var buf bytes.Buffer
buf.WriteString(prefix)
buf.WriteString(path)
buf.WriteString(":")
for _, e := range errs {
buf.WriteString("\n* ")
buf.WriteString(e.Error())
}
return buf.String()
},
}
}
// HasErrsOrWarns returns true when 1 or more errors or warnings.
func (e *ParseError) HasErrsOrWarns() bool {
return e != nil && (e.merr.ErrorOrNil() != nil || e.mwarn.ErrorOrNil() != nil)
}
// HasErrs returns true when 1 or more errors.
func (e *ParseError) HasErrs() bool {
return e != nil && e.merr.ErrorOrNil() != nil
}
// HasWarns returns true when 1 or more warnings.
func (e *ParseError) HasWarns() bool {
return e != nil && e.mwarn.ErrorOrNil() != nil
}
// Errors returns multierror.Error of errors.
func (e *ParseError) Errors() *multierror.Error {
if e == nil {
return nil
}
return e.mwarn
}
// ErrorsAndWarns returns multierror.Error which errors and warnings are mixed in.
func (e *ParseError) ErrorsAndWarns() *multierror.Error {
if e == nil {
return nil
}
var result *multierror.Error
if e.merr.ErrorOrNil() != nil {
result = multierror.Append(result, e.merr.Errors...)
}
if e.mwarn.ErrorOrNil() != nil {
result = multierror.Append(result, e.mwarn.Errors...)
}
return result
}
func (e *ParseError) merge(e2 *ParseError) {
if e == nil || e2 == nil {
return
}
if e2.merr.ErrorOrNil() != nil {
e.merr = multierror.Append(e.merr, e2.merr.Errors...)
}
if e2.mwarn.ErrorOrNil() != nil {
e.mwarn = multierror.Append(e.mwarn, e2.mwarn.Errors...)
}
}
// MultiParseError holds multiple ParseError.
type MultiParseError []ParseError
// HasErrs returns true when any of holding ParseError.HasErrs() returns true.
func (errs MultiParseError) HasErrs() bool {
for _, e := range errs {
if e.HasErrs() {
return true
}
}
return false
}
// HasWarns returns true when any of holding ParseError.HasWarns() returns true.
func (errs MultiParseError) HasWarns() bool {
for _, e := range errs {
if e.HasWarns() {
return true
}
}
return false
}
// Errors returns all errors in holding ParseError.
func (errs MultiParseError) Errors() *multierror.Error {
return errs.concatErrors(false)
}
// Warns returns all warnings in holding ParseError.
func (errs MultiParseError) Warns() *multierror.Error {
return errs.concatErrors(true)
}
func (errs MultiParseError) concatErrors(showWarns bool) *multierror.Error {
result := &multierror.Error{
Errors: make([]error, 0, len(errs)),
ErrorFormat: func(errs []error) string {
var buf bytes.Buffer
for _, e := range errs {
buf.WriteString(e.Error())
buf.WriteString("\n")
}
return buf.String()
},
}
for _, e := range errs {
merr := e.merr
if showWarns {
merr = e.mwarn
}
if merr.ErrorOrNil() != nil {
// Call merr.Error() to apply error format func
result = multierror.Append(result, errors.New(merr.Error()))
}
}
return result
}
// ErrorsAndWarns returns errors and warnings in holding ParseError.
func (errs MultiParseError) ErrorsAndWarns() *multierror.Error {
var result *multierror.Error
for _, e := range errs {
merr := e.ErrorsAndWarns()
if merr.ErrorOrNil() != nil {
result = multierror.Append(result, merr.Errors...)
}
}
return result
}
// ParsePlugconfFile parses plugconf and returns parsed info and parse error and
// warnings.
// path is a filepath of plugconf.
// reposID is an ID of unsigned integer which identifies one plugconf.
// reposPath is an pathutil.ReposPath of plugconf.
func ParsePlugconfFile(path string, reposID int, reposPath pathutil.ReposPath) (result *ParsedInfo, parseErr *ParseError) {
// this function always returns non-nil parseErr
// (which may have empty errors / warns)
parseErr = new(ParseError)
content, err := ioutil.ReadFile(path)
if err != nil {
err = multierror.Append(nil, err)
return
}
file, err := vimlparser.ParseFile(bytes.NewReader(content), path, nil)
if err != nil {
err = multierror.Append(nil, err)
return
}
result, parseErr = ParsePlugconf(file, content, path)
if result != nil {
result.reposID = reposID
result.reposPath = reposPath
}
return
}
// ParsePlugconf always returns non-nil parseErr
// (which may have empty errors / warns)
func ParsePlugconf(file *ast.File, src []byte, path string) (*ParsedInfo, *ParseError) {
var loadOn = loadOnStart
var loadOnArg string
var loadOnFunc string
var onLoadPreFunc string
var onLoadPostFunc string
var functions []string
var dependsFunc string
var depends pathutil.ReposPathList
parseErr := newParseError(path)
// Inspect nodes and get above values from plugconf script
ast.Inspect(file, func(node ast.Node) bool {
// Cast to function node (return if it's not a function node)
fn, ok := node.(*ast.Function)
if !ok {
return true
}
// Get function name
ident, ok := fn.Name.(*ast.Ident)
if !ok {
return true
}
switch {
case ident.Name == "s:loaded_on":
if loadOnFunc != "" {
parseErr.merr = multierror.Append(parseErr.merr,
errors.New("duplicate s:loaded_on()"))
return true
}
if !isEmptyFunc(fn) {
loadOnFunc = string(extractBody(fn, src))
var err error
loadOn, loadOnArg, err = inspectReturnValue(fn)
if err != nil {
parseErr.merr = multierror.Append(parseErr.merr, err)
}
}
case ident.Name == "s:config":
if onLoadPreFunc != "" {
parseErr.merr = multierror.Append(parseErr.merr,
errors.New("duplicate s:on_load_pre() and s:config()"))
return true
}
parseErr.mwarn = multierror.Append(parseErr.mwarn,
errors.New("s:config() is deprecated. "+
"please use s:on_load_pre() instead, or run "+
"\"volt migrate plugconf/config-func\" to rewrite existing plugconf files"))
if !isEmptyFunc(fn) {
onLoadPreFunc = string(extractBody(fn, src))
onLoadPreFunc = rxFuncName.ReplaceAllString(
onLoadPreFunc, "${1}on_load_pre",
)
}
case ident.Name == "s:on_load_pre":
if onLoadPreFunc != "" {
parseErr.merr = multierror.Append(parseErr.merr,
errors.New("duplicate s:on_load_pre() and s:config()"))
return true
}
if !isEmptyFunc(fn) {
onLoadPreFunc = string(extractBody(fn, src))
}
case ident.Name == "s:on_load_post":
if onLoadPostFunc != "" {
parseErr.merr = multierror.Append(parseErr.merr,
errors.New("duplicate s:on_load_post()"))
return true
}
if !isEmptyFunc(fn) {
onLoadPostFunc = string(extractBody(fn, src))
}
case ident.Name == "s:depends":
if dependsFunc != "" {
parseErr.merr = multierror.Append(parseErr.merr,
errors.New("duplicate s:depends()"))
return true
}
if !isEmptyFunc(fn) {
dependsFunc = string(extractBody(fn, src))
var err error
depends, err = getDependencies(fn)
if err != nil {
parseErr.merr = multierror.Append(parseErr.merr, err)
}
}
case isProhibitedFuncName(ident.Name):
parseErr.merr = multierror.Append(parseErr.merr,
fmt.Errorf(
"'%s' is prohibited function name. please use other function name", ident.Name))
default:
functions = append(functions, string(extractBody(fn, src)))
}
return true
})
if parseErr.HasErrs() {
return nil, parseErr
}
return &ParsedInfo{
functions: functions,
onLoadPreFunc: onLoadPreFunc,
onLoadPostFunc: onLoadPostFunc,
loadOnFunc: loadOnFunc,
loadOn: loadOn,
loadOnArg: loadOnArg,
dependsFunc: dependsFunc,
depends: depends,
}, parseErr
}
// Inspect return value of s:loaded_on() function in plugconf
func inspectReturnValue(fn *ast.Function) (loadOnType, string, error) {
var loadOn loadOnType
var loadOnArg string
var err error
ast.Inspect(fn, func(node ast.Node) bool {
// Cast to return node (return if it's not a return node)
ret, ok := node.(*ast.Return)
if !ok {
return true
}
// Parse the argument of :return
rhs, ok := ret.Result.(*ast.BasicLit)
if ok && rhs.Kind == token.STRING {
value := rhs.Value[1 : len(rhs.Value)-1]
if value == "start" {
loadOn = loadOnStart
} else if strings.HasPrefix(value, "filetype=") {
loadOn = loadOnFileType
loadOnArg = strings.TrimPrefix(value, "filetype=")
} else if strings.HasPrefix(value, "excmd=") {
loadOn = loadOnExcmd
loadOnArg = strings.TrimPrefix(value, "excmd=")
} else {
err = errors.New("Invalid rhs of ':return': " + rhs.Value)
}
}
return true
})
if string(loadOn) == "" {
return "", "", errors.New("can't detect return value of s:loaded_on()")
}
return loadOn, loadOnArg, err
}
// Returns true if fn.Body is empty or has only comment nodes
func isEmptyFunc(fn *ast.Function) bool {
for i := range fn.Body {
empty := true
ast.Inspect(fn.Body[i], func(node ast.Node) bool {
if _, ok := node.(*ast.Comment); ok {
return true
}
empty = false
return false
})
if !empty {
return false
}
}
return true
}
func extractBody(fn *ast.Function, src []byte) []byte {
pos := fn.Pos()
endpos := fn.EndFunction.Pos()
endfunc := fn.EndFunction.ExArg
cmdlen := endfunc.Argpos.Offset - endfunc.Cmdpos.Offset
endpos.Offset += cmdlen
return src[pos.Offset:endpos.Offset]
}
func getDependencies(fn *ast.Function) (pathutil.ReposPathList, error) {
var deps pathutil.ReposPathList
var parseErr error
ast.Inspect(fn, func(node ast.Node) bool {
// Cast to return node (return if it's not a return node)
ret, ok := node.(*ast.Return)
if !ok {
return true
}
if list, ok := ret.Result.(*ast.List); ok {
for i := range list.Values {
if str, ok := list.Values[i].(*ast.BasicLit); ok {
if deps == nil {
deps = make(pathutil.ReposPathList, 0, len(list.Values))
}
if str.Kind == token.STRING {
reposPath, err := pathutil.NormalizeRepos(str.Value[1 : len(str.Value)-1])
if err != nil {
parseErr = err
return false
}
deps = append(deps, reposPath)
}
}
}
}
return true
})
return deps, parseErr
}
// rxFuncName is a pattern which matches to function name.
// Note that $2 is a function name.
// $1 is a string before a function name.
var rxFuncName = regexp.MustCompile(`\A(fu\w+!?\s+s:)(\w+)`)
func convertToDecodableFunc(funcBody string, reposPath pathutil.ReposPath, reposID int) string {
// Change function name (e.g. s:loaded_on() -> s:loaded_on_1())
funcBody = rxFuncName.ReplaceAllString(funcBody, fmt.Sprintf("${1}${2}_%d", reposID))
// Add repos path as comment
funcBody = "\" " + reposPath.String() + "\n" + funcBody
return funcBody
}
type reposDepTree struct {
// The nodes' dependTo are nil. These repos's ranks are always 0.
leaves []reposDepNode
}
type reposDepNode struct {
repos *lockjson.Repos
dependTo []reposDepNode
dependedBy []reposDepNode
}
// ParseMultiPlugconf parses plugconfs of given reposList.
func ParseMultiPlugconf(reposList []lockjson.Repos) (*MultiParsedInfo, MultiParseError) {
plugconfMap, parseErr := parsePlugconfAsMap(reposList)
if parseErr.HasErrs() {
return nil, parseErr
}
sortByDepends(reposList, plugconfMap)
return &MultiParsedInfo{
plugconfMap: plugconfMap,
reposList: reposList,
}, parseErr
}
type parsedInfoMap map[pathutil.ReposPath]*ParsedInfo
// MultiParsedInfo holds multiple ParsedInfo.
// This value is generated by ParseMultiPlugconf.
type MultiParsedInfo struct {
plugconfMap parsedInfoMap
reposList []lockjson.Repos
}
// GenerateBundlePlugconf generates bundled plugconf content.
// Generated content does not include s:loaded_on() function.
// vimrcPath and gvimrcPath are fullpath of vimrc and gvimrc.
// They become an empty string when each path does not exist.
func (mp *MultiParsedInfo) GenerateBundlePlugconf(vimrcPath, gvimrcPath string) ([]byte, error) {
functions := make([]string, 0, 64)
loadCmds := make([]string, 0, len(mp.reposList))
lazyExcmd := make(map[string]string, len(mp.reposList))
for _, repos := range mp.reposList {
p, hasPlugconf := mp.plugconfMap[repos.Path]
// :packadd <repos>
optName := filepath.Base(repos.Path.EncodeToPlugDirName())
packadd := fmt.Sprintf("packadd %s", optName)
// s:on_load_pre(), invoked command, s:on_load_post()
var invokedCmd string
if hasPlugconf {
cmds := make([]string, 0, 3)
if p.onLoadPreFunc != "" {
functions = append(functions, convertToDecodableFunc(p.onLoadPreFunc, p.reposPath, p.reposID))
cmds = append(cmds, fmt.Sprintf("call s:on_load_pre_%d()", p.reposID))
}
cmds = append(cmds, packadd)
if p.onLoadPostFunc != "" {
functions = append(functions, convertToDecodableFunc(p.onLoadPostFunc, p.reposPath, p.reposID))
cmds = append(cmds, fmt.Sprintf("call s:on_load_post_%d()", p.reposID))
}
invokedCmd = strings.Join(cmds, " | ")
} else {
invokedCmd = packadd
}
// Bootstrap statements
switch {
case !hasPlugconf || p.loadOn == loadOnStart:
loadCmds = append(loadCmds, " "+invokedCmd)
case p.loadOn == loadOnFileType:
loadCmds = append(loadCmds,
fmt.Sprintf(" autocmd %s %s %s", string(p.loadOn), p.loadOnArg, invokedCmd))
case p.loadOn == loadOnExcmd:
// Define dummy Ex commands
for _, excmd := range strings.Split(p.loadOnArg, ",") {
lazyExcmd[excmd] = invokedCmd
loadCmds = append(loadCmds,
fmt.Sprintf(" command -complete=customlist,%[1]s -bang -bar -range -nargs=* %[3]s call %[2]s('%[3]s', <q-args>, expand('<bang>'), expand('<line1>'), expand('<line2>'))", completeFunc, lazyLoadExcmdFunc, excmd))
}
}
// User defined functions in plugconf
if hasPlugconf {
functions = append(functions, p.functions...)
}
}
var buf bytes.Buffer
buf.WriteString(`if exists('g:loaded_volt_system_bundled_plugconf')
finish
endif
let g:loaded_volt_system_bundled_plugconf = 1`)
if len(functions) > 0 {
buf.WriteString("\n\n")
buf.WriteString(strings.Join(functions, "\n\n"))
}
if len(lazyExcmd) > 0 {
lazyExcmdJSON, err := json.Marshal(lazyExcmd)
if err != nil {
return nil, err
}
// * dein#autoload#_on_cmd()
// https://github.com/Shougo/dein.vim/blob/2adba7655b23f2fc1ddcd35e15d380c5069a3712/autoload/dein/autoload.vim#L157-L175
// * dein#autoload#_dummy_complete()
// https://github.com/Shougo/dein.vim/blob/2adba7655b23f2fc1ddcd35e15d380c5069a3712/autoload/dein/autoload.vim#L216-L232
buf.WriteString(`
let ` + excmdLoadPlugin + ` = ` + string(lazyExcmdJSON) + `
function ` + lazyLoadExcmdFunc + `(command, args, bang, line1, line2) abort
if exists(':' . a:command) is# 2
execute 'delcommand' a:command
endif
execute get(` + excmdLoadPlugin + `, a:command, '')
if exists(':' . a:command) isnot# 2
echohl ErrorMsg
echomsg printf('[volt] Lazy loading of Ex command ''%s'' failed: ''%s'' is not found', a:command, a:command)
echohl None
return
endif
let range = (a:line1 is# a:line2) ? '' :
\ (a:line1 is# line("'<") && a:line2 is# line("'>")) ?
\ "'<,'>" : a:line1 . ',' . a:line2
try
execute range . a:command . a:bang a:args
catch /^Vim\%((\a\+)\)\=:E481/
" E481: No range allowed
execute a:command . a:bang a:args
endtry
endfunction
function ` + completeFunc + `(arglead, cmdline, cursorpos) abort
let command = matchstr(a:cmdline, '\h\w*')
if exists(':' . command) is# 2
execute 'delcommand' command
endif
execute get(` + excmdLoadPlugin + `, command, '')
if exists(':' . command) is# 2
call feedkeys("\<C-d>", 'n')
endif
return [a:arglead]
endfunction
`)
}
if len(loadCmds) > 0 {
buf.WriteString("\n\n")
buf.WriteString(`augroup volt-bundled-plugconf
autocmd!
`)
buf.WriteString(strings.Join(loadCmds, "\n"))
buf.WriteString("\naugroup END")
}
if vimrcPath != "" || gvimrcPath != "" {
buf.WriteString("\n\n")
if vimrcPath != "" {
vimrcPath = strings.Replace(vimrcPath, "'", "''", -1)
buf.WriteString("let $MYVIMRC = '" + vimrcPath + "'")
}
if gvimrcPath != "" {
gvimrcPath = strings.Replace(gvimrcPath, "'", "''", -1)
buf.WriteString("let $MYGVIMRC = '" + gvimrcPath + "'")
}
}
return buf.Bytes(), nil
}
// Each iterates each repository by given func.
func (mp *MultiParsedInfo) Each(f func(pathutil.ReposPath, *ParsedInfo)) {
for reposPath, info := range mp.plugconfMap {
f(reposPath, info)
}
}
// RdepsOf returns depended (required) plugins of reposPath.
// reposList is used to calculate dependency of reposPath.
func RdepsOf(reposPath pathutil.ReposPath, reposList []lockjson.Repos) (pathutil.ReposPathList, error) {
plugconfMap, parseErr := parsePlugconfAsMap(reposList)
if parseErr.HasErrs() {
return nil, parseErr.ErrorsAndWarns()
}
_, _, rdepsMap := getDepMaps(reposList, plugconfMap)
rdeps := rdepsMap[reposPath]
if rdeps == nil {
rdeps = make(pathutil.ReposPathList, 0)
}
return rdeps, nil
}
// Parse plugconf of reposList and return parsed plugconf info as map
func parsePlugconfAsMap(reposList []lockjson.Repos) (map[pathutil.ReposPath]*ParsedInfo, MultiParseError) {
parseErrAll := make(MultiParseError, 0, len(reposList))
plugconfMap := make(parsedInfoMap, len(reposList))
reposID := 1
for _, repos := range reposList {
path := repos.Path.Plugconf()
if !pathutil.Exists(path) {
continue
}
result, parseErr := ParsePlugconfFile(path, reposID, repos.Path)
if parseErr.HasErrsOrWarns() {
parseErrAll = append(parseErrAll, *parseErr)
}
if result != nil {
plugconfMap[repos.Path] = result
reposID++
}
}
return plugconfMap, parseErrAll
}
// Move the plugins which was depended to previous plugin which depends to them.
// reposList is sorted in-place.
func sortByDepends(reposList []lockjson.Repos, plugconfMap map[pathutil.ReposPath]*ParsedInfo) {
reposMap, depsMap, rdepsMap := getDepMaps(reposList, plugconfMap)
rank := make(map[pathutil.ReposPath]int, len(reposList))
for i := range reposList {
if _, exists := rank[reposList[i].Path]; !exists {
tree := makeDepTree(reposList[i].Path, reposMap, depsMap, rdepsMap)
for i := range tree.leaves {
makeRank(rank, &tree.leaves[i], 0)
}
}
}
sort.Slice(reposList, func(i, j int) bool {
return rank[reposList[i].Path] < rank[reposList[j].Path]
})
}
func getDepMaps(reposList []lockjson.Repos, plugconfMap map[pathutil.ReposPath]*ParsedInfo) (map[pathutil.ReposPath]*lockjson.Repos, map[pathutil.ReposPath]pathutil.ReposPathList, map[pathutil.ReposPath]pathutil.ReposPathList) {
reposMap := make(map[pathutil.ReposPath]*lockjson.Repos, len(reposList))
depsMap := make(map[pathutil.ReposPath]pathutil.ReposPathList, len(reposList))
rdepsMap := make(map[pathutil.ReposPath]pathutil.ReposPathList, len(reposList))
for i := range reposList {
reposPath := reposList[i].Path
reposMap[reposPath] = &reposList[i]
if p, exists := plugconfMap[reposPath]; exists {
depsMap[reposPath] = p.depends
for _, dep := range p.depends {
rdepsMap[dep] = append(rdepsMap[dep], reposPath)
}
}
}
return reposMap, depsMap, rdepsMap
}
func makeDepTree(reposPath pathutil.ReposPath, reposMap map[pathutil.ReposPath]*lockjson.Repos, depsMap map[pathutil.ReposPath]pathutil.ReposPathList, rdepsMap map[pathutil.ReposPath]pathutil.ReposPathList) *reposDepTree {
visitedNodes := make(map[pathutil.ReposPath]*reposDepNode, len(reposMap))
node := makeNodes(reposPath, reposMap, depsMap, rdepsMap, visitedNodes)
leaves := make([]reposDepNode, 0, 10)
visitedMarks := make(map[pathutil.ReposPath]bool, 10)
visitNode(node, func(n *reposDepNode) {
if len(n.dependTo) == 0 {
leaves = append(leaves, *n)
}
}, visitedMarks)
return &reposDepTree{leaves: leaves}
}
func makeNodes(reposPath pathutil.ReposPath, reposMap map[pathutil.ReposPath]*lockjson.Repos, depsMap map[pathutil.ReposPath]pathutil.ReposPathList, rdepsMap map[pathutil.ReposPath]pathutil.ReposPathList, visited map[pathutil.ReposPath]*reposDepNode) *reposDepNode {
if node, exists := visited[reposPath]; exists {
return node
}
node := &reposDepNode{repos: reposMap[reposPath]}
visited[reposPath] = node
for i := range depsMap[reposPath] {
dep := makeNodes(depsMap[reposPath][i], reposMap, depsMap, rdepsMap, visited)
node.dependTo = append(node.dependTo, *dep)
}
for i := range rdepsMap[reposPath] {
rdep := makeNodes(rdepsMap[reposPath][i], reposMap, depsMap, rdepsMap, visited)
node.dependedBy = append(node.dependedBy, *rdep)
}
return node
}
func visitNode(node *reposDepNode, callback func(*reposDepNode), visited map[pathutil.ReposPath]bool) {
if node == nil || node.repos == nil || visited[node.repos.Path] {
return
}
visited[node.repos.Path] = true
callback(node)
for i := range node.dependTo {
visitNode(&node.dependTo[i], callback, visited)
}
for i := range node.dependedBy {
visitNode(&node.dependedBy[i], callback, visited)
}
}
func makeRank(rank map[pathutil.ReposPath]int, node *reposDepNode, value int) {
rank[node.repos.Path] = value
for i := range node.dependedBy {
makeRank(rank, &node.dependedBy[i], value+1)
}
}
// Template is a content of plugconf template.
type Template struct {
template []byte
}
// FetchPlugconfTemplate fetches reposPath's plugconf from vim-volt/plugconf-templates
// repository.
// Fetched URL: https://raw.githubusercontent.com/vim-volt/plugconf-templates/master/templates/{reposPath}.vim
func FetchPlugconfTemplate(reposPath pathutil.ReposPath) (*Template, error) {
url := path.Join("https://raw.githubusercontent.com/vim-volt/plugconf-templates/master/templates", reposPath.String()+".vim")
content, err := httputil.GetContent(url)
if err != nil {
return nil, err
}
return &Template{content}, nil
}
const skeletonPlugconfOnLoadPre = `function! s:on_load_pre()
" Plugin configuration like the code written in vimrc.
" This configuration is executed *before* a plugin is loaded.
endfunction`
const skeletonPlugconfOnLoadPost = `function! s:on_load_post()
" Plugin configuration like the code written in vimrc.
" This configuration is executed *after* a plugin is loaded.
endfunction`
const skeletonPlugconfLoadOn = `function! s:loaded_on()
" This function determines when a plugin is loaded.
"
" Possible values are:
" * 'start' (a plugin will be loaded at VimEnter event)
" * 'filetype=<filetypes>' (a plugin will be loaded at FileType event)
" * 'excmd=<excmds>' (a plugin will be loaded at CmdUndefined event)
" <filetypes> and <excmds> can be multiple values separated by comma.
"
" This function must contain 'return "<str>"' code.
" (the argument of :return must be string literal)
return 'start'
endfunction`
const skeletonPlugconfDepends = `function! s:depends()
" Dependencies of this plugin.
" The specified dependencies are loaded after this plugin is loaded.
"
" This function must contain 'return [<repos>, ...]' code.
" (the argument of :return must be list literal, and the elements are string)
" e.g. return ['github.com/tyru/open-browser.vim']
return []
endfunction`
// Generate generates plugconf content from Template.
func (pt *Template) Generate(path string) ([]byte, *multierror.Error) {
result := &ParsedInfo{}
if pt != nil {
// Parse fetched plugconf
tmpl, err := vimlparser.ParseFile(bytes.NewReader(pt.template), path, nil)
if err != nil {
return nil, multierror.Append(nil, err)
}
var parseErr *ParseError
result, parseErr = ParsePlugconf(tmpl, pt.template, path)
if parseErr.HasErrs() {
return nil, parseErr.ErrorsAndWarns()
}
}
content, err := result.GeneratePlugconf()
if err != nil {
return nil, multierror.Append(nil, err)
}
return content, nil
}