Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
135 lines (114 loc) · 4.07 KB
/
Copy pathmain.go
File metadata and controls
135 lines (114 loc) · 4.07 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
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/spf13/cobra"
)
func main() {
var (
inputFile string
outputFile string
paths []string
pathsFile string
verbose bool
)
rootCmd := &cobra.Command{
Use: "go-openapi-subset",
Short: "Create a subset of an OpenAPI JSON by keeping only specified paths",
RunE: func(cmd *cobra.Command, args []string) error {
if pathsFile != "" {
filePaths, err := loadPathsFile(pathsFile)
if err != nil {
return fmt.Errorf("error reading paths file: %w", err)
}
paths = append(paths, filePaths...)
}
if inputFile == "" || outputFile == "" || len(paths) == 0 {
return fmt.Errorf("flags -i, -o, and at least one of -p or --paths-file are required")
}
// Read input file
data, err := os.ReadFile(inputFile)
if err != nil {
return fmt.Errorf("error reading input file: %w", err)
}
// Parse OpenAPI spec
var spec OpenAPISpec
if err := json.Unmarshal(data, &spec); err != nil {
return fmt.Errorf("error parsing OpenAPI JSON: %w", err)
}
if verbose {
fmt.Printf("Loaded spec with %d paths and %d components\n",
len(spec.Paths), len(spec.Components.Schemas))
}
// Filter paths
include, exclude := FilterPatterns(paths)
filteredPaths, pathResult := FilterPaths(&spec, include, exclude)
spec.Paths = filteredPaths
// Find used components
usedComponents := FindUsedComponents(&spec, filteredPaths)
// Filter components
filteredSchemas, compResult := FilterComponents(&spec, usedComponents)
spec.Components.Schemas = filteredSchemas
// Combine results
result := MatchResult{
KeptPaths: pathResult.KeptPaths,
RemovedPaths: pathResult.RemovedPaths,
KeptComponents: compResult.KeptComponents,
RemovedComponents: compResult.RemovedComponents,
}
PrintMatchResult(result)
// Write output file
outputData, err := json.MarshalIndent(spec, "", " ")
if err != nil {
return fmt.Errorf("error marshaling output: %w", err)
}
if err := os.WriteFile(outputFile, outputData, 0644); err != nil {
return fmt.Errorf("error writing output file: %w", err)
}
// Calculate size reduction
originalSize := len(data)
newSize := len(outputData)
reduction := float64(originalSize-newSize) / float64(originalSize) * 100
fmt.Printf("Output written to %s\n", outputFile)
fmt.Printf("Size reduction: %.2f%% (%d → %d bytes)\n", reduction, originalSize, newSize)
return nil
},
}
rootCmd.Flags().StringVarP(&inputFile, "in", "i", "", "Input OpenAPI JSON file (required)")
rootCmd.Flags().StringVarP(&outputFile, "out", "o", "", "Output OpenAPI JSON file (required)")
rootCmd.Flags().StringArrayVarP(&paths, "path", "p", nil, "Path pattern to keep; supports wildcards (repeatable, e.g. -p /api/v1/* -p /users)")
rootCmd.Flags().StringVar(&pathsFile, "paths-file", "", "JSON file containing path patterns to include/exclude")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
// loadPathsFile reads path patterns from a JSON file.
// Accepted formats: array of strings ["path1", "!path2"] or object {"include": [...], "exclude": [...]}.
// Exclude entries from the object form are prefixed with "!" to match CLI convention.
func loadPathsFile(filename string) ([]string, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
// Try object form first
var obj struct {
Include []string `json:"include"`
Exclude []string `json:"exclude"`
}
if err := json.Unmarshal(data, &obj); err == nil && (len(obj.Include) > 0 || len(obj.Exclude) > 0) {
patterns := make([]string, 0, len(obj.Include)+len(obj.Exclude))
patterns = append(patterns, obj.Include...)
for _, p := range obj.Exclude {
patterns = append(patterns, "!"+p)
}
return patterns, nil
}
// Fall back to plain array
var list []string
if err := json.Unmarshal(data, &list); err != nil {
return nil, fmt.Errorf("invalid paths file format: expected array or {\"include\": [], \"exclude\": []}")
}
return list, nil
}