aboutsummaryrefslogtreecommitdiff
path: root/go/tools/builders/generate_nogo_main.go
blob: 872b9b0a6029792d02dbcd5aeeed595864a1f1ac (plain)
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
/* Copyright 2018 The Bazel Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Generates the nogo binary to analyze Go source code at build time.

package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"math"
	"os"
	"regexp"
	"strconv"
	"text/template"
)

const nogoMainTpl = `
package main


import (
{{- if .NeedRegexp }}
	"regexp"
{{- end}}
{{- range $import := .Imports}}
	{{$import.Name}} "{{$import.Path}}"
{{- end}}
	"golang.org/x/tools/go/analysis"
)

var analyzers = []*analysis.Analyzer{
{{- range $import := .Imports}}
	{{$import.Name}}.Analyzer,
{{- end}}
}

// configs maps analysis names to configurations.
var configs = map[string]config{
{{- range $name, $config := .Configs}}
	{{printf "%q" $name}}: config{
		{{- if $config.AnalyzerFlags }}
		analyzerFlags: map[string]string {
			{{- range $flagKey, $flagValue := $config.AnalyzerFlags}}
			{{printf "%q: %q" $flagKey $flagValue}},
			{{- end}}
		},
		{{- end -}}
		{{- if $config.OnlyFiles}}
		onlyFiles: []*regexp.Regexp{
			{{- range $path, $comment := $config.OnlyFiles}}
			{{- if $comment}}
			// {{$comment}}
			{{end -}}
			{{printf "regexp.MustCompile(%q)" $path}},
			{{- end}}
		},
		{{- end -}}
		{{- if $config.ExcludeFiles}}
		excludeFiles: []*regexp.Regexp{
			{{- range $path, $comment := $config.ExcludeFiles}}
			{{- if $comment}}
			// {{$comment}}
			{{end -}}
			{{printf "regexp.MustCompile(%q)" $path}},
			{{- end}}
		},
		{{- end}}
	},
{{- end}}
}
`

func genNogoMain(args []string) error {
	analyzerImportPaths := multiFlag{}
	flags := flag.NewFlagSet("generate_nogo_main", flag.ExitOnError)
	out := flags.String("output", "", "output file to write (defaults to stdout)")
	flags.Var(&analyzerImportPaths, "analyzer_importpath", "import path of an analyzer library")
	configFile := flags.String("config", "", "nogo config file")
	if err := flags.Parse(args); err != nil {
		return err
	}
	if *out == "" {
		return errors.New("must provide output file")
	}

	outFile := os.Stdout
	var cErr error
	outFile, err := os.Create(*out)
	if err != nil {
		return fmt.Errorf("os.Create(%q): %v", *out, err)
	}
	defer func() {
		if err := outFile.Close(); err != nil {
			cErr = fmt.Errorf("error closing %s: %v", outFile.Name(), err)
		}
	}()

	config, err := buildConfig(*configFile)
	if err != nil {
		return err
	}

	type Import struct {
		Path, Name string
	}
	// Create unique name for each imported analyzer.
	suffix := 1
	imports := make([]Import, 0, len(analyzerImportPaths))
	for _, path := range analyzerImportPaths {
		imports = append(imports, Import{
			Path: path,
			Name: "analyzer" + strconv.Itoa(suffix)})
		if suffix == math.MaxInt32 {
			return fmt.Errorf("cannot generate more than %d analyzers", suffix)
		}
		suffix++
	}
	data := struct {
		Imports    []Import
		Configs    Configs
		NeedRegexp bool
	}{
		Imports: imports,
		Configs: config,
	}
	for _, c := range config {
		if len(c.OnlyFiles) > 0 || len(c.ExcludeFiles) > 0 {
			data.NeedRegexp = true
			break
		}
	}

	tpl := template.Must(template.New("source").Parse(nogoMainTpl))
	if err := tpl.Execute(outFile, data); err != nil {
		return fmt.Errorf("template.Execute failed: %v", err)
	}
	return cErr
}

func buildConfig(path string) (Configs, error) {
	if path == "" {
		return Configs{}, nil
	}
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return Configs{}, fmt.Errorf("failed to read config file: %v", err)
	}
	configs := make(Configs)
	if err = json.Unmarshal(b, &configs); err != nil {
		return Configs{}, fmt.Errorf("failed to unmarshal config file: %v", err)
	}
	for name, config := range configs {
		for pattern := range config.OnlyFiles {
			if _, err := regexp.Compile(pattern); err != nil {
				return Configs{}, fmt.Errorf("invalid pattern for analysis %q: %v", name, err)
			}
		}
		for pattern := range config.ExcludeFiles {
			if _, err := regexp.Compile(pattern); err != nil {
				return Configs{}, fmt.Errorf("invalid pattern for analysis %q: %v", name, err)
			}
		}
		configs[name] = Config{
			// Description is currently unused.
			OnlyFiles:     config.OnlyFiles,
			ExcludeFiles:  config.ExcludeFiles,
			AnalyzerFlags: config.AnalyzerFlags,
		}
	}
	return configs, nil
}

type Configs map[string]Config

type Config struct {
	Description   string
	OnlyFiles     map[string]string `json:"only_files"`
	ExcludeFiles  map[string]string `json:"exclude_files"`
	AnalyzerFlags map[string]string `json:"analyzer_flags"`
}