-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
imports.go
69 lines (54 loc) · 1.34 KB
/
imports.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
package internal
import (
"bytes"
"fmt"
"go/format"
"os"
"path/filepath"
"text/template"
)
const importsTemplate = `
package main
import (
{{range .Imports -}}
_ "{{.}}"
{{end -}}
)
`
func (b Builder) updatePluginsFile() error {
importsDest := filepath.Join(b.repo, "cmd", "golangci-lint", "plugins.go")
info, err := os.Stat(importsDest)
if err != nil {
return fmt.Errorf("file %s not found: %w", importsDest, err)
}
source, err := generateImports(b.cfg)
if err != nil {
return fmt.Errorf("generate imports: %w", err)
}
b.log.Infof("generated imports info %s:\n%s\n", importsDest, source)
err = os.WriteFile(filepath.Clean(importsDest), source, info.Mode())
if err != nil {
return fmt.Errorf("write file %s: %w", importsDest, err)
}
return nil
}
func generateImports(cfg *Configuration) ([]byte, error) {
impTmpl, err := template.New("plugins.go").Parse(importsTemplate)
if err != nil {
return nil, fmt.Errorf("parse template: %w", err)
}
var imps []string
for _, plugin := range cfg.Plugins {
imps = append(imps, plugin.Import)
}
buf := &bytes.Buffer{}
err = impTmpl.Execute(buf, map[string]any{"Imports": imps})
if err != nil {
return nil, fmt.Errorf("execute template: %w", err)
}
source, err := format.Source(buf.Bytes())
if err != nil {
return nil, fmt.Errorf("format source: %w", err)
}
return source, nil
}