ref: 2ac4a8e33181ae3b467644fd41a8c7dfbd6b76eb annotatego/main.go -rw-r--r-- 6.0 KiB View raw
                                                                                
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
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"go/token"
	"go/types"
	"golang.org/x/tools/go/packages"
	"log"
	"os"
	"os/exec"
	"strings"

	"git.sr.ht/~sircmpwn/getopt"
)

var cwd string

func init() {
	cwd, _ = os.Getwd()
}

type LinkAnnotation struct {
	Type   string  `json:"type"`
	Lineno int     `json:"lineno"`
	Colno  int     `json:"colno"`
	Len    int     `json:"len"`
	To     string  `json:"to"`
	Title  *string `json:"title,omitempty"`
	Color  *string `json:"color,omitempty"`
}

type MarkdownAnnotation struct {
	Type    string `json:"type"`
	Lineno  int    `json:"lineno"`
	Title   string `json:"title"`
	Content string `json:"content"`
}

func normalizePath(path string) string {
	path = strings.TrimPrefix(path, cwd)
	path = strings.TrimPrefix(path, "/")
	return path
}

func scanNulls(data []byte, atEOF bool) (int, []byte, error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, 0); i >= 0 {
		return i + 1, data[0:i], nil
	}
	if atEOF {
		return len(data), data, nil
	}
	return 0, nil, nil
}

// Returns a map of path to blob id
func crawlGitTree() map[string]string {
	cmd := exec.Command("git", "ls-tree", "-zr", "HEAD")
	pipe, err := cmd.StdoutPipe()
	if err != nil {
		panic(err)
	}
	defer pipe.Close()
	scanner := bufio.NewScanner(pipe)
	go func() {
		if err := cmd.Run(); err != nil {
			panic(err)
		}
	}()
	scanner.Split(scanNulls)
	m := make(map[string]string)
	for scanner.Scan() {
		fields := strings.FieldsFunc(scanner.Text(), func(r rune) bool {
			return r == ' ' || r == '\t'
		})
		oid := fields[2]
		path := strings.Join(fields[3:], " ")
		m[path] = oid
	}
	return m
}

func godocUrl(object types.Object) string {
	var receiver string
	pkg := object.Pkg()
	if sig, ok := object.Type().(*types.Signature); ok {
		if recv := sig.Recv(); recv != nil {
			if ptr, ok := recv.Type().(*types.Pointer); ok {
				if n, ok := ptr.Elem().(*types.Named); ok {
					receiver = n.Obj().Name()
				}
			} else if n, ok := recv.Type().(*types.Named); ok {
				receiver = n.Obj().Name()
			}
		}
	}
	if receiver != "" {
		return fmt.Sprintf("https://godoc.org/%s#%s.%s",
			pkg.Path(), receiver, object.Name())
	}
	return fmt.Sprintf("https://godoc.org/%s#%s", pkg.Path(), object.Name())
}

func main() {
	var (
		disableGodoc bool
		enableTests  bool
		enableVars   bool
	)
	getopt.BoolVar(&enableVars, "-v", false,
		"Enables linking of variables to their declarations")
	getopt.BoolVar(&disableGodoc, "-d", false,
		"Disables linking to external symbols via Godoc")
	getopt.BoolVar(&enableTests, "-T", false,
		"Enables scanning of test files as well as normal code")
	err := getopt.Parse()
	if err != nil {
		log.Fatalf("getopt: ", err)
	}

	log.SetFlags(0)
	fset := token.NewFileSet()
	conf := packages.Config{
		Tests: enableTests,
		Fset: fset,
		Mode: (packages.NeedName |
			packages.NeedSyntax |
			packages.NeedTypes |
			packages.NeedTypesInfo |
			packages.NeedFiles |
			packages.NeedDeps |
			packages.NeedImports),
	}
	pkgs, err := packages.Load(&conf, getopt.Args()...)
	if err != nil {
		log.Fatal(err)
	}
	tree := crawlGitTree()
	annotations := make(map[string][]interface{})
	references := make(map[token.Pos][]token.Pos)
	for _, pkg := range pkgs {
		log.Printf("Annotating %s...", pkg.ID)
		for ident, object := range pkg.TypesInfo.Uses {
			pos := fset.Position(ident.Pos())
			filename := pos.Filename
			if filename == "" {
				continue
			}
			length := ident.End() - ident.Pos()
			filename = normalizePath(filename)
			var ok bool
			if filename, ok = tree[filename]; !ok {
				continue
			}
			var (
				color string
				title string
				to    string
			)
			switch object := object.(type) {
			case *types.Func:
				fpos := fset.Position(object.Pos())
				if fpos.IsValid() && strings.HasPrefix(fpos.Filename, cwd) {
					if _, ok := references[object.Pos()]; !ok {
						references[object.Pos()] = nil
					}
					references[object.Pos()] = append(
						references[object.Pos()], ident.Pos())
					/* Internal reference */
					path := normalizePath(fpos.Filename)
					to = fmt.Sprintf("%s#L%d", path, fpos.Line)
					title = object.FullName()
				} else if object.Pkg() != nil && !disableGodoc {
					to = godocUrl(object)
					title = object.FullName() + " on Godoc"
				}
			case *types.Var:
				if !enableVars {
					break
				}
				tpos := fset.Position(object.Pos())
				if tpos.IsValid() && strings.HasPrefix(tpos.Filename, cwd) {
					/* Internal reference */
					path := normalizePath(tpos.Filename)
					to = fmt.Sprintf("%s#L%d", path, tpos.Line)
					title = object.Name()
				} else if object.Pkg() != nil && !disableGodoc {
					to = godocUrl(object)
					title = object.Name() + " on Godoc"
				}
				color = "transparent"
			}
			if to != "" {
				if _, ok := annotations[filename]; !ok {
					annotations[filename] = nil
				}
				anno := &LinkAnnotation{
					Type:   "link",
					Lineno: pos.Line,
					Colno:  pos.Column,
					Len:    int(length),
					To:     to,
				}
				if title != "" {
					anno.Title = &title
				}
				if color != "" {
					anno.Color = &color
				}
				annotations[filename] = append(annotations[filename], anno)
			}
		}
	}
	for target, refs := range references {
		pos := fset.Position(target)
		if !pos.IsValid() || !strings.HasPrefix(pos.Filename, cwd) {
			continue
		}
		var ok bool
		path := normalizePath(pos.Filename)
		if path, ok = tree[path]; !ok {
			continue
		}
		if _, ok = annotations[path]; !ok {
			annotations[path] = nil
		}
		var content bytes.Buffer
		for _, via := range refs {
			ref := fset.Position(via)
			refpath := normalizePath(ref.Filename)
			content.WriteString(fmt.Sprintf("- [%s:%d](%s#L%d)\n",
				refpath, ref.Line, refpath, ref.Line))
		}
		var title string
		if len(refs) == 1 {
			title = fmt.Sprintf("%d reference", 1)
		} else {
			title = fmt.Sprintf("%d references", len(refs))
		}
		anno := &MarkdownAnnotation{
			Type: "markdown",
			Title: title,
			Lineno: pos.Line,
			Content: content.String(),
		}
		annotations[path] = append(annotations[path], anno)
	}
	m, err := json.Marshal(annotations)
	if err != nil {
		panic(err)
	}
	os.Stdout.Write(m)
}