-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
177 lines (155 loc) · 4.4 KB
/
main.go
File metadata and controls
177 lines (155 loc) · 4.4 KB
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
// API Statistics example demonstrating multi-handler analysis with walker.
//
// This example shows how to:
// - Use multiple handlers to collect statistics in a single pass
// - Access Info, Operation, Schema, Parameter, and Tag nodes
// - Handle type as string or []string for OAS 3.1 compatibility
// - Build statistics using closure state
package main
import (
"fmt"
"log"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/erraggy/oastools/parser"
"github.com/erraggy/oastools/walker"
)
// APIStats holds collected statistics about an OpenAPI specification.
type APIStats struct {
Title string
Version string
OperationsByMethod map[string]int
SchemasByType map[string]int
ParametersByIn map[string]int
Tags []string
TotalOperations int
TotalSchemas int
TotalParameters int
}
func main() {
specPath := findSpecPath()
fmt.Println("API Statistics Report")
fmt.Println("=====================")
fmt.Println()
// Parse the specification
parseResult, err := parser.ParseWithOptions(
parser.WithFilePath(specPath),
parser.WithValidateStructure(true),
)
if err != nil {
log.Fatalf("Parse error: %v", err)
}
// Initialize statistics
stats := &APIStats{
OperationsByMethod: make(map[string]int),
SchemasByType: make(map[string]int),
ParametersByIn: make(map[string]int),
}
// Walk the document with multiple handlers
err = walker.Walk(parseResult,
// Extract API info
walker.WithInfoHandler(func(wc *walker.WalkContext, info *parser.Info) walker.Action {
stats.Title = info.Title
stats.Version = info.Version
return walker.Continue
}),
// Count operations by HTTP method
walker.WithOperationHandler(func(wc *walker.WalkContext, op *parser.Operation) walker.Action {
stats.TotalOperations++
stats.OperationsByMethod[strings.ToUpper(wc.Method)]++
return walker.Continue
}),
// Count schemas by type
walker.WithSchemaHandler(func(wc *walker.WalkContext, schema *parser.Schema) walker.Action {
stats.TotalSchemas++
// Handle type as string or []string (OAS 3.1 compatibility)
switch t := schema.Type.(type) {
case string:
if t != "" {
stats.SchemasByType[t]++
}
case []string:
for _, typeName := range t {
stats.SchemasByType[typeName]++
}
case []any:
for _, v := range t {
if typeName, ok := v.(string); ok {
stats.SchemasByType[typeName]++
}
}
}
return walker.Continue
}),
// Count parameters by location
walker.WithParameterHandler(func(wc *walker.WalkContext, param *parser.Parameter) walker.Action {
stats.TotalParameters++
if param.In != "" {
stats.ParametersByIn[param.In]++
}
return walker.Continue
}),
// Collect tag names
walker.WithTagHandler(func(wc *walker.WalkContext, tag *parser.Tag) walker.Action {
stats.Tags = append(stats.Tags, tag.Name)
return walker.Continue
}),
)
if err != nil {
log.Fatalf("Walk error: %v", err)
}
// Print the report
printReport(stats)
}
func printReport(stats *APIStats) {
fmt.Printf("API: %s v%s\n", stats.Title, stats.Version)
fmt.Println()
// Operations
fmt.Printf("Operations (%d total):\n", stats.TotalOperations)
methods := sortedKeys(stats.OperationsByMethod)
for _, method := range methods {
fmt.Printf(" %-8s %d\n", method+":", stats.OperationsByMethod[method])
}
fmt.Println()
// Schemas by type
fmt.Printf("Schemas by Type (%d total):\n", stats.TotalSchemas)
types := sortedKeys(stats.SchemasByType)
for _, t := range types {
fmt.Printf(" %-10s %d\n", t+":", stats.SchemasByType[t])
}
fmt.Println()
// Parameters by location
fmt.Println("Parameters by Location:")
locations := sortedKeys(stats.ParametersByIn)
for _, loc := range locations {
fmt.Printf(" %-10s %d\n", loc+":", stats.ParametersByIn[loc])
}
fmt.Println()
// Tags
fmt.Println("Tags:")
if len(stats.Tags) == 0 {
fmt.Println(" (none)")
} else {
for _, tag := range stats.Tags {
fmt.Printf(" - %s\n", tag)
}
}
}
func sortedKeys(m map[string]int) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// findSpecPath locates the petstore-3.0.yaml file relative to the source file.
func findSpecPath() string {
_, filename, _, ok := runtime.Caller(0)
if !ok {
log.Fatal("Cannot determine source file location")
}
return filepath.Join(filepath.Dir(filename), "..", "..", "..", "testdata", "petstore-3.0.yaml")
}