Debian Codegraph @

tools/metadata/metadata.go

raw
1 // Copyright 2023 The go-github AUTHORS. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package main
7
8 import (
9 "bytes"
10 "context"
11 "errors"
12 "fmt"
13 "go/ast"
14 "go/format"
15 "go/parser"
16 "go/printer"
17 "go/token"
18 "net/url"
19 "os"
20 "path"
21 "path/filepath"
22 "regexp"
23 "sort"
24 "strings"
25 "sync"
26
27 "github.com/google/go-github/v60/github"
28 "gopkg.in/yaml.v3"
29 )
30
31 type operation struct {
32 Name string `yaml:"name,omitempty" json:"name,omitempty"`
33 DocumentationURL string `yaml:"documentation_url,omitempty" json:"documentation_url,omitempty"`
34 OpenAPIFiles []string `yaml:"openapi_files,omitempty" json:"openapi_files,omitempty"`
35 }
36
37 func (o *operation) equal(other *operation) bool {
38 if o.Name != other.Name || o.DocumentationURL != other.DocumentationURL {
39 return false
40 }
41 if len(o.OpenAPIFiles) != len(other.OpenAPIFiles) {
42 return false
43 }
44 for i := range o.OpenAPIFiles {
45 if o.OpenAPIFiles[i] != other.OpenAPIFiles[i] {
46 return false
47 }
48 }
49 return true
50 }
51
52 func (o *operation) clone() *operation {
53 return &operation{
54 Name: o.Name,
55 DocumentationURL: o.DocumentationURL,
56 OpenAPIFiles: append([]string{}, o.OpenAPIFiles...),
57 }
58 }
59
60 func operationsEqual(a, b []*operation) bool {
61 if len(a) != len(b) {
62 return false
63 }
64 for i := range a {
65 if !a[i].equal(b[i]) {
66 return false
67 }
68 }
69 return true
70 }
71
72 func sortOperations(ops []*operation) {
73 sort.Slice(ops, func(i, j int) bool {
74 leftVerb, leftURL := parseOpName(ops[i].Name)
75 rightVerb, rightURL := parseOpName(ops[j].Name)
76 if leftURL != rightURL {
77 return leftURL < rightURL
78 }
79 return leftVerb < rightVerb
80 })
81 }
82
83 // normalizeOpPath returns an endpoint with all templated path parameters replaced with *.
84 func normalizeOpPath(opPath string) string {
85 if !strings.ContainsAny(opPath, "{%") {
86 return opPath
87 }
88 segments := strings.Split(opPath, "/")
89 for i, segment := range segments {
90 if len(segment) == 0 {
91 continue
92 }
93 if segment[0] == '{' || segment[0] == '%' {
94 segments[i] = "*"
95 }
96 }
97 return strings.Join(segments, "/")
98 }
99
100 func normalizedOpName(name string) string {
101 verb, u := parseOpName(name)
102 return strings.TrimSpace(verb + " " + normalizeOpPath(u))
103 }
104
105 // matches something like "GET /some/path"
106 var opNameRe = regexp.MustCompile(`(?i)(\S+)(?:\s+(\S.*))?`)
107
108 func parseOpName(id string) (verb, url string) {
109 match := opNameRe.FindStringSubmatch(id)
110 if match == nil {
111 return "", ""
112 }
113 u := strings.TrimSpace(match[2])
114 if !strings.HasPrefix(u, "/") {
115 u = "/" + u
116 }
117 return strings.ToUpper(match[1]), u
118 }
119
120 type operationsFile struct {
121 ManualOps []*operation `yaml:"operations,omitempty"`
122 OverrideOps []*operation `yaml:"operation_overrides,omitempty"`
123 GitCommit string `yaml:"openapi_commit,omitempty"`
124 OpenapiOps []*operation `yaml:"openapi_operations,omitempty"`
125
126 mu sync.Mutex
127 resolvedOps map[string]*operation
128 }
129
130 func (m *operationsFile) resolve() {
131 m.mu.Lock()
132 defer m.mu.Unlock()
133 if m.resolvedOps != nil {
134 return
135 }
136 m.resolvedOps = map[string]*operation{}
137 for _, op := range m.OpenapiOps {
138 m.resolvedOps[op.Name] = op.clone()
139 }
140 for _, op := range m.ManualOps {
141 m.resolvedOps[op.Name] = op.clone()
142 }
143 for _, override := range m.OverrideOps {
144 _, ok := m.resolvedOps[override.Name]
145 if !ok {
146 continue
147 }
148 override = override.clone()
149 if override.DocumentationURL != "" {
150 m.resolvedOps[override.Name].DocumentationURL = override.DocumentationURL
151 }
152 if len(override.OpenAPIFiles) > 0 {
153 m.resolvedOps[override.Name].OpenAPIFiles = override.OpenAPIFiles
154 }
155 }
156 }
157
158 func (m *operationsFile) saveFile(filename string) (errOut error) {
159 sortOperations(m.ManualOps)
160 sortOperations(m.OverrideOps)
161 sortOperations(m.OpenapiOps)
162 f, err := os.Create(filename)
163 if err != nil {
164 return err
165 }
166 defer func() {
167 e := f.Close()
168 if errOut == nil {
169 errOut = e
170 }
171 }()
172 enc := yaml.NewEncoder(f)
173 enc.SetIndent(2)
174 defer func() {
175 e := enc.Close()
176 if errOut == nil {
177 errOut = e
178 }
179 }()
180 return enc.Encode(m)
181 }
182
183 func (m *operationsFile) updateFromGithub(ctx context.Context, client *github.Client, ref string) error {
184 commit, resp, err := client.Repositories.GetCommit(ctx, descriptionsOwnerName, descriptionsRepoName, ref, nil)
185 if err != nil {
186 return err
187 }
188 if resp.StatusCode != 200 {
189 return fmt.Errorf("unexpected status code: %s", resp.Status)
190 }
191 ops, err := getOpsFromGithub(ctx, client, ref)
192 if err != nil {
193 return err
194 }
195 if !operationsEqual(m.OpenapiOps, ops) {
196 m.OpenapiOps = ops
197 m.GitCommit = commit.GetSHA()
198 }
199 return nil
200 }
201
202 func loadOperationsFile(filename string) (*operationsFile, error) {
203 b, err := os.ReadFile(filename)
204 if err != nil {
205 return nil, err
206 }
207 var opsFile operationsFile
208 err = yaml.Unmarshal(b, &opsFile)
209 if err != nil {
210 return nil, err
211 }
212 return &opsFile, nil
213 }
214
215 func addOperation(ops []*operation, filename, opName, docURL string) []*operation {
216 for _, op := range ops {
217 if opName != op.Name {
218 continue
219 }
220 if len(op.OpenAPIFiles) == 0 {
221 op.OpenAPIFiles = append(op.OpenAPIFiles, filename)
222 op.DocumentationURL = docURL
223 return ops
224 }
225 // just append to files, but only add the first ghes file
226 if !strings.Contains(filename, "/ghes") {
227 op.OpenAPIFiles = append(op.OpenAPIFiles, filename)
228 return ops
229 }
230 for _, f := range op.OpenAPIFiles {
231 if strings.Contains(f, "/ghes") {
232 return ops
233 }
234 }
235 op.OpenAPIFiles = append(op.OpenAPIFiles, filename)
236 return ops
237 }
238 return append(ops, &operation{
239 Name: opName,
240 OpenAPIFiles: []string{filename},
241 DocumentationURL: docURL,
242 })
243 }
244
245 func unusedOps(opsFile *operationsFile, dir string) ([]*operation, error) {
246 var usedOps map[string]bool
247 err := visitServiceMethods(dir, false, func(_ string, fn *ast.FuncDecl, cmap ast.CommentMap) error {
248 ops, err := methodOps(opsFile, cmap, fn)
249 if err != nil {
250 return err
251 }
252 for _, op := range ops {
253 if usedOps == nil {
254 usedOps = map[string]bool{}
255 }
256 usedOps[op.Name] = true
257 }
258 return nil
259 })
260 if err != nil {
261 return nil, err
262 }
263 var result []*operation
264 opsFile.resolve()
265 for opName, op := range opsFile.resolvedOps {
266 if !usedOps[opName] {
267 result = append(result, op)
268 }
269 }
270 sortOperations(result)
271 return result, nil
272 }
273
274 func updateDocsVisitor(opsFile *operationsFile) nodeVisitor {
275 return func(serviceMethod string, fn *ast.FuncDecl, cmap ast.CommentMap) error {
276 linksMap := map[string]struct{}{}
277 undocMap := map[string]bool{}
278
279 ops, err := methodOps(opsFile, cmap, fn)
280 if err != nil {
281 return err
282 }
283 if len(ops) == 0 {
284 return fmt.Errorf("no operations defined for %s", serviceMethod)
285 }
286
287 for _, op := range ops {
288 if op.DocumentationURL == "" {
289 undocMap[op.Name] = true
290 continue
291 }
292 linksMap[op.DocumentationURL] = struct{}{}
293 }
294 var undocumentedOps []string
295 for op := range undocMap {
296 undocumentedOps = append(undocumentedOps, op)
297 }
298 sort.Strings(undocumentedOps)
299
300 // Find the group that comes before the function
301 var group *ast.CommentGroup
302 for _, g := range cmap[fn] {
303 if g.End() == fn.Pos()-1 {
304 group = g
305 }
306 }
307
308 // If there is no group, create one
309 if group == nil {
310 group = &ast.CommentGroup{
311 List: []*ast.Comment{{Text: "//", Slash: fn.Pos() - 1}},
312 }
313 cmap[fn] = append(cmap[fn], group)
314 }
315
316 origList := group.List
317 group.List = nil
318 for _, comment := range origList {
319 if metaOpRe.MatchString(comment.Text) ||
320 docLineRE.MatchString(comment.Text) ||
321 undocRE.MatchString(comment.Text) {
322 continue
323 }
324 group.List = append(group.List, comment)
325 }
326
327 // add an empty line before adding doc links
328 group.List = append(group.List, &ast.Comment{Text: "//"})
329
330 var docLinks []string
331 for link := range linksMap {
332 docLinks = append(docLinks, link)
333 }
334 sort.Strings(docLinks)
335
336 for _, dl := range docLinks {
337 group.List = append(
338 group.List,
339 &ast.Comment{
340 Text: "// GitHub API docs: " + cleanURLPath(dl),
341 },
342 )
343 }
344 _, methodName, _ := strings.Cut(serviceMethod, ".")
345 for _, opName := range undocumentedOps {
346 line := fmt.Sprintf("// Note: %s uses the undocumented GitHub API endpoint %q.", methodName, opName)
347 group.List = append(group.List, &ast.Comment{Text: line})
348 }
349 for _, op := range ops {
350 group.List = append(group.List, &ast.Comment{
351 Text: fmt.Sprintf("//meta:operation %s", op.Name),
352 })
353 }
354 group.List[0].Slash = fn.Pos() - 1
355 for i := 1; i < len(group.List); i++ {
356 group.List[i].Slash = token.NoPos
357 }
358 return nil
359 }
360 }
361
362 // updateDocs updates the code comments in dir with doc urls from metadata.
363 func updateDocs(opsFile *operationsFile, dir string) error {
364 return visitServiceMethods(dir, true, updateDocsVisitor(opsFile))
365 }
366
367 type nodeVisitor func(serviceMethod string, fn *ast.FuncDecl, cmap ast.CommentMap) error
368
369 // visitServiceMethods runs visit on the ast.Node of every service method in dir. When writeFiles is true it will
370 // save any changes back to the original file.
371 func visitServiceMethods(dir string, writeFiles bool, visit nodeVisitor) error {
372 dirEntries, err := os.ReadDir(dir)
373 if err != nil {
374 return err
375 }
376 for _, dirEntry := range dirEntries {
377 filename := filepath.Join(dir, dirEntry.Name())
378 if dirEntry.IsDir() ||
379 !strings.HasSuffix(filename, ".go") ||
380 strings.HasSuffix(filename, "_test.go") {
381 continue
382 }
383 err = errors.Join(err, visitFileMethods(writeFiles, filename, visit))
384 }
385 return err
386 }
387
388 func visitFileMethods(updateFile bool, filename string, visit nodeVisitor) error {
389 content, err := os.ReadFile(filename)
390 if err != nil {
391 return err
392 }
393 content = bytes.ReplaceAll(content, []byte("\r\n"), []byte("\n"))
394
395 fset := token.NewFileSet()
396 fileNode, err := parser.ParseFile(fset, "", content, parser.ParseComments)
397 if err != nil {
398 return err
399 }
400 cmap := ast.NewCommentMap(fset, fileNode, fileNode.Comments)
401
402 ast.Inspect(fileNode, func(n ast.Node) bool {
403 fn, ok := n.(*ast.FuncDecl)
404 if !ok {
405 return true
406 }
407 serviceMethod := nodeServiceMethod(fn)
408 if serviceMethod == "" {
409 return true
410 }
411 e := visit(serviceMethod, fn, cmap)
412 err = errors.Join(err, e)
413 return true
414 })
415 if err != nil {
416 return err
417 }
418 if !updateFile {
419 return nil
420 }
421 fileNode.Comments = cmap.Filter(fileNode).Comments()
422 var buf bytes.Buffer
423 err = printer.Fprint(&buf, fset, fileNode)
424 if err != nil {
425 return err
426 }
427 updatedContent, err := format.Source(buf.Bytes())
428 if err != nil {
429 return err
430 }
431 if bytes.Equal(content, updatedContent) {
432 return nil
433 }
434 return os.WriteFile(filename, updatedContent, 0600)
435 }
436
437 var (
438 metaOpRe = regexp.MustCompile(`(?i)\s*//\s*meta:operation\s+(\S.+)`)
439 undocRE = regexp.MustCompile(`(?i)\s*//\s*Note:\s+\S.+ uses the undocumented GitHub API endpoint`)
440 docLineRE = regexp.MustCompile(`(?i)\s*//\s*GitHub\s+API\s+docs:`)
441 )
442
443 // methodOps parses a method's comments for //meta:operation lines and returns the corresponding operations.
444 func methodOps(opsFile *operationsFile, cmap ast.CommentMap, fn *ast.FuncDecl) ([]*operation, error) {
445 var ops []*operation
446 var err error
447 seen := map[string]bool{}
448 for _, g := range cmap[fn] {
449 for _, c := range g.List {
450 match := metaOpRe.FindStringSubmatch(c.Text)
451 if match == nil {
452 continue
453 }
454 opName := strings.TrimSpace(match[1])
455 opsFile.resolve()
456 var found []*operation
457 norm := normalizedOpName(opName)
458 for n := range opsFile.resolvedOps {
459 if normalizedOpName(n) == norm {
460 found = append(found, opsFile.resolvedOps[n])
461 }
462 }
463 switch len(found) {
464 case 0:
465 err = errors.Join(err, fmt.Errorf("could not find operation %q in openapi_operations.yaml", opName))
466 case 1:
467 name := found[0].Name
468 if seen[name] {
469 err = errors.Join(err, fmt.Errorf("duplicate operation: %s", name))
470 }
471 seen[name] = true
472 ops = append(ops, found[0])
473 default:
474 var foundNames []string
475 for _, op := range found {
476 foundNames = append(foundNames, op.Name)
477 }
478 sort.Strings(foundNames)
479 err = errors.Join(err, fmt.Errorf("ambiguous operation %q could match any of: %v", opName, foundNames))
480 }
481 }
482 }
483 sortOperations(ops)
484 return ops, err
485 }
486
487 // cleanURLPath runs path.Clean on the url path. This is to remove the unsightly double slashes from some
488 // of the urls in github's openapi descriptions.
489 func cleanURLPath(docURL string) string {
490 u, err := url.Parse(docURL)
491 if err != nil {
492 return docURL
493 }
494 u.Path = path.Clean(u.Path)
495 return u.String()
496 }
497
498 // nodeServiceMethod returns the name of the service method represented by fn, or "" if fn is not a service method.
499 // Name is in the form of "Receiver.Function", for example "IssuesService.Create".
500 func nodeServiceMethod(fn *ast.FuncDecl) string {
501 if fn.Recv == nil || len(fn.Recv.List) != 1 {
502 return ""
503 }
504 recv := fn.Recv.List[0]
505 se, ok := recv.Type.(*ast.StarExpr)
506 if !ok {
507 return ""
508 }
509 id, ok := se.X.(*ast.Ident)
510 if !ok {
511 return ""
512 }
513
514 // We only want exported methods on exported types where the type name ends in "Service".
515 if !id.IsExported() || !fn.Name.IsExported() || !strings.HasSuffix(id.Name, "Service") {
516 return ""
517 }
518
519 return id.Name + "." + fn.Name.Name
520 }