Debian Codegraph @

tools/metadata/openapi.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 "context"
10 "fmt"
11 "io"
12 "regexp"
13 "sort"
14 "strconv"
15
16 "github.com/getkin/kin-openapi/openapi3"
17 "github.com/google/go-github/v60/github"
18 "golang.org/x/sync/errgroup"
19 )
20
21 const (
22 descriptionsOwnerName = "github"
23 descriptionsRepoName = "rest-api-description"
24 descriptionsPath = "descriptions"
25 )
26
27 type openapiFile struct {
28 description *openapi3.T
29 filename string
30 plan string
31 planIdx int
32 releaseMajor int
33 releaseMinor int
34 }
35
36 func getOpsFromGithub(ctx context.Context, client *github.Client, gitRef string) ([]*operation, error) {
37 descs, err := getDescriptions(ctx, client, gitRef)
38 if err != nil {
39 return nil, err
40 }
41 var ops []*operation
42 for _, desc := range descs {
43 for p, pathItem := range desc.description.Paths.Map() {
44 for method, op := range pathItem.Operations() {
45 docURL := ""
46 if op.ExternalDocs != nil {
47 docURL = op.ExternalDocs.URL
48 }
49 ops = addOperation(ops, desc.filename, method+" "+p, docURL)
50 }
51 }
52 }
53 sortOperations(ops)
54 return ops, nil
55 }
56
57 func (o *openapiFile) loadDescription(ctx context.Context, client *github.Client, gitRef string) error {
58 contents, resp, err := client.Repositories.DownloadContents(
59 ctx,
60 descriptionsOwnerName,
61 descriptionsRepoName,
62 o.filename,
63 &github.RepositoryContentGetOptions{Ref: gitRef},
64 )
65 if err != nil {
66 return err
67 }
68 if resp.StatusCode != 200 {
69 return fmt.Errorf("unexpected status code: %s", resp.Status)
70 }
71 b, err := io.ReadAll(contents)
72 if err != nil {
73 return err
74 }
75 err = contents.Close()
76 if err != nil {
77 return err
78 }
79 o.description, err = openapi3.NewLoader().LoadFromData(b)
80 return err
81 }
82
83 // less sorts by the following rules:
84 // - planIdx ascending
85 // - releaseMajor descending
86 // - releaseMinor descending
87 func (o *openapiFile) less(other *openapiFile) bool {
88 if o.planIdx != other.planIdx {
89 return o.planIdx < other.planIdx
90 }
91 if o.releaseMajor != other.releaseMajor {
92 return o.releaseMajor > other.releaseMajor
93 }
94 return o.releaseMinor > other.releaseMinor
95 }
96
97 var dirPatterns = []*regexp.Regexp{
98 regexp.MustCompile(`^(?P<plan>api\.github\.com)(-(?P<major>\d+)\.(?P<minor>\d+))?$`),
99 regexp.MustCompile(`^(?P<plan>ghec)(-(?P<major>\d+)\.(?P<minor>\d+))?$`),
100 regexp.MustCompile(`^(?P<plan>ghes)(-(?P<major>\d+)\.(?P<minor>\d+))?$`),
101 }
102
103 // getDescriptions loads OpenapiFiles for all the OpenAPI 3.0 description files in github/rest-api-description.
104 // This assumes that all directories in "descriptions/" contain OpenAPI 3.0 description files with the same
105 // name as the directory (plus the ".json" extension). For example, "descriptions/api.github.com/api.github.com.json".
106 // Results are sorted by these rules:
107 // - Directories that don't match any of the patterns in dirPatterns are removed.
108 // - Directories are sorted by the pattern that matched in the same order they appear in dirPatterns.
109 // - Directories are then sorted by major and minor version in descending order.
110 func getDescriptions(ctx context.Context, client *github.Client, gitRef string) ([]*openapiFile, error) {
111 _, dir, resp, err := client.Repositories.GetContents(
112 ctx,
113 descriptionsOwnerName,
114 descriptionsRepoName,
115 descriptionsPath,
116 &github.RepositoryContentGetOptions{Ref: gitRef},
117 )
118 if err != nil {
119 return nil, err
120 }
121 if resp.StatusCode != 200 {
122 return nil, fmt.Errorf("unexpected status code: %s", resp.Status)
123 }
124 files := make([]*openapiFile, 0, len(dir))
125 for _, d := range dir {
126 for i, pattern := range dirPatterns {
127 m := pattern.FindStringSubmatch(d.GetName())
128 if m == nil {
129 continue
130 }
131 file := openapiFile{
132 filename: fmt.Sprintf("descriptions/%s/%s.json", d.GetName(), d.GetName()),
133 plan: m[pattern.SubexpIndex("plan")],
134 planIdx: i,
135 }
136 rawMajor := m[pattern.SubexpIndex("major")]
137 if rawMajor != "" {
138 file.releaseMajor, err = strconv.Atoi(rawMajor)
139 if err != nil {
140 return nil, err
141 }
142 }
143 rawMinor := m[pattern.SubexpIndex("minor")]
144 if rawMinor != "" {
145 file.releaseMinor, err = strconv.Atoi(rawMinor)
146 if err != nil {
147 return nil, err
148 }
149 }
150 if file.plan == "ghes" && file.releaseMajor < 3 {
151 continue
152 }
153 files = append(files, &file)
154 break
155 }
156 }
157 sort.Slice(files, func(i, j int) bool {
158 return files[i].less(files[j])
159 })
160 g, ctx := errgroup.WithContext(ctx)
161 for _, file := range files {
162 f := file
163 g.Go(func() error {
164 return f.loadDescription(ctx, client, gitRef)
165 })
166 }
167 err = g.Wait()
168 if err != nil {
169 return nil, err
170 }
171 return files, nil
172 }