hack for cleaning circular refs in swagger definition

This commit is contained in:
Owen Diehl
2021-03-03 22:01:07 -05:00
parent b80b89e309
commit d815bf4a4c
2 changed files with 72 additions and 5 deletions
+10 -5
View File
@@ -1,13 +1,18 @@
.DEFAULT_GOAL := openapi
PKG_DIR = pkg
GO_PKG_FILES = $(shell find $(PKG_DIR) -name *.go -print)
API_DIR = pkg/api
GO_PKG_FILES = $(shell find $(API_DIR) -name *.go -print)
spec.json: $(GO_PKG_FILES)
swagger generate spec -m -w $(PKG_DIR) -o $@
swagger generate spec -m -w $(API_DIR) -o $@
post.json: spec.json
go run cmd/clean-swagger/main.go -if $(<) -of $@
.PHONY: server
server: post.json
swagger generate server --exclude-main -t pkg/gen --with-flatten=full --with-flatten=remove-unused -f $(<)
.PHONY: openapi
openapi: spec.json
openapi: post.json
docker run --rm -p 80:8080 -v $$(pwd):/tmp -e SWAGGER_FILE=/tmp/$(<) swaggerapi/swagger-editor
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"strings"
)
const RefKey = "$ref"
func main() {
var input, output string
flag.StringVar(&input, "if", "", "input file")
flag.StringVar(&output, "of", "", "output file")
flag.Parse()
if input == "" || output == "" {
log.Fatal("no file specified, input", input, ", output", output)
}
b, err := ioutil.ReadFile(input)
if err != nil {
log.Fatal(err)
}
data := make(map[string]interface{})
if err := json.Unmarshal(b, &data); err != nil {
log.Fatal(err)
}
definitions, ok := data["definitions"]
if !ok {
log.Fatal("no definitions")
}
defs := definitions.(map[string]interface{})
for k, v := range defs {
vMap := v.(map[string]interface{})
refKey, ok := vMap[RefKey]
if !ok {
continue
}
if strings.TrimPrefix(refKey.(string), "#/definitions/") == k {
log.Println("removing circular ref key", refKey)
delete(vMap, RefKey)
}
}
out, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(output, out, 0644)
if err != nil {
log.Fatal(err)
}
}