Update swagger renderer to load external files properly

This commit is contained in:
Melon 2022-09-09 16:45:10 +01:00
parent 7d9b926eb4
commit 304fa4a99e
Signed by: melon
GPG Key ID: B0ADD5395BCDAAB6
3 changed files with 80 additions and 95 deletions

View File

@ -67,6 +67,7 @@ func (m *Module) SetupModule(router *mux.Router, f func(cb func(http.ResponseWri
} }
router.HandleFunc("/", m.getClient(m.homepage)) router.HandleFunc("/", m.getClient(m.homepage))
router.HandleFunc("/login", m.sessionWrapper(m.loginPage)) router.HandleFunc("/login", m.sessionWrapper(m.loginPage))
router.PathPrefix("/spec/{org}/{repo}/{sha}/{spec:.+}").HandlerFunc(m.getClient(m.specPage))
router.PathPrefix("/swagger").HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { router.PathPrefix("/swagger").HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
p := filepath.Join("swagger", filepath.Base(req.URL.Path)) p := filepath.Join("swagger", filepath.Base(req.URL.Path))
open, err := assets.SwaggerAssets.Open(p) open, err := assets.SwaggerAssets.Open(p)
@ -140,6 +141,7 @@ func (m *Module) homepage(rw http.ResponseWriter, req *http.Request, state *util
selModule := "" selModule := ""
selCommitTime := "" selCommitTime := ""
selCommitHash := "" selCommitHash := ""
selCommitHashShort := ""
mySpecs := make([]struct { mySpecs := make([]struct {
Name string Name string
Code int Code int
@ -196,54 +198,9 @@ func (m *Module) homepage(rw http.ResponseWriter, req *http.Request, state *util
return return
} }
if q.Has("spec") {
spec := q.Get("spec")
if q.Has("raw") && q.Get("raw") == "true" {
open, _, err := giteaClient.GetFile(myOrg, selRepo, ref.Object.SHA, spec)
if err != nil {
http.Error(rw, "OpenAPI spec raw: "+err.Error(), http.StatusInternalServerError)
return
}
http.ServeContent(rw, req, spec, repo.Updated, bytes.NewReader(open))
return
}
contents, _, err := giteaClient.GetContents(myOrg, selRepo, ref.Object.SHA, spec)
if err != nil {
http.Error(rw, "OpenAPI spec: "+err.Error(), http.StatusInternalServerError)
return
}
tmp, err := template.New("swagger").Parse(swaggerTemplate)
if err != nil {
fmt.Println("Template parse error:", err)
return
}
q2 := q
q2.Set("raw", "true")
err = tmp.Execute(rw, struct {
LoadUrls []struct {
Url string `json:"url"`
Name string `json:"name"`
}
LoadMain string
}{
LoadUrls: []struct {
Url string `json:"url"`
Name string `json:"name"`
}{
{Url: "/gitea/?" + q2.Encode(), Name: contents.Name},
},
LoadMain: contents.Name,
})
if err != nil {
fmt.Println("Template execute error:", err)
return
}
return
}
selCommitTime = commit.CommitMeta.Created.UTC().Format("20060102150405") selCommitTime = commit.CommitMeta.Created.UTC().Format("20060102150405")
selCommitHash = commit.CommitMeta.SHA[:12] selCommitHash = commit.CommitMeta.SHA
selCommitHashShort = commit.CommitMeta.SHA[:12]
goMod, resp, err := giteaClient.GetFile(myOrg, selRepo, ref.Object.SHA, "go.mod") goMod, resp, err := giteaClient.GetFile(myOrg, selRepo, ref.Object.SHA, "go.mod")
if err != nil { if err != nil {
if resp.StatusCode != http.StatusNotFound { if resp.StatusCode != http.StatusNotFound {
@ -310,33 +267,35 @@ func (m *Module) homepage(rw http.ResponseWriter, req *http.Request, state *util
Name string Name string
Private bool Private bool
} }
MyOrg string MyOrg string
SelOrg string SelOrg string
SelRepo string SelRepo string
ShowOrg bool ShowOrg bool
SelModule string SelModule string
ShowGoMod bool ShowGoMod bool
CommitTime string CommitTime string
CommitHash string CommitHash string
ShowSpec bool CommitHashShort string
Specs []struct { ShowSpec bool
Specs []struct {
Name string Name string
Code int Code int
} }
}{ }{
Username: myUser.UserName, Username: myUser.UserName,
Orgs: orgSimple, Orgs: orgSimple,
Repos: repoSimple, Repos: repoSimple,
MyOrg: myOrg, MyOrg: myOrg,
SelOrg: selOrg, SelOrg: selOrg,
SelRepo: selRepo, SelRepo: selRepo,
SelModule: selModule, SelModule: selModule,
ShowOrg: myOrg != "", ShowOrg: myOrg != "",
ShowGoMod: selModule != "", ShowGoMod: selModule != "",
CommitTime: selCommitTime, CommitTime: selCommitTime,
CommitHash: selCommitHash, CommitHash: selCommitHash,
ShowSpec: len(mySpecs) > 0, CommitHashShort: selCommitHashShort,
Specs: mySpecs, ShowSpec: len(mySpecs) > 0,
Specs: mySpecs,
}) })
if err != nil { if err != nil {
fmt.Println("Template execute error:", err) fmt.Println("Template execute error:", err)
@ -383,25 +342,51 @@ func (m *Module) loginPage(rw http.ResponseWriter, req *http.Request, state *uti
http.Redirect(rw, req, m.oauthClient.AuthCodeURL(flowState.String(), oauth2.AccessTypeOffline), http.StatusTemporaryRedirect) http.Redirect(rw, req, m.oauthClient.AuthCodeURL(flowState.String(), oauth2.AccessTypeOffline), http.StatusTemporaryRedirect)
} }
func (m *Module) fetchRepos(giteaClient *gitea.Client) { func (m *Module) specPage(rw http.ResponseWriter, req *http.Request, state *utils.State, giteaClient *gitea.Client) {
repos, _, err := giteaClient.ListOrgRepos("snow", gitea.ListOrgReposOptions{ListOptions: gitea.ListOptions{Page: 0, PageSize: 100}}) vars := mux.Vars(req)
if err != nil { myOrg := vars["org"]
fmt.Println(err) myRepo := vars["repo"]
return mySha := vars["sha"]
} mySpec := vars["spec"]
for _, myRepo := range repos {
refs, _, err := giteaClient.GetRepoRefs("snow", myRepo.Name, "heads") q := req.URL.Query()
if q.Has("raw") && q.Get("raw") == "true" {
open, _, err := giteaClient.GetFile(myOrg, myRepo, mySha, mySpec)
if err != nil { if err != nil {
fmt.Println(err) http.Error(rw, "OpenAPI spec raw: "+err.Error(), http.StatusInternalServerError)
return return
} }
fmt.Println(len(refs)) http.ServeContent(rw, req, mySpec, time.Now(), bytes.NewReader(open))
for _, myRef := range refs { return
if myRef.Ref == "refs/heads/"+myRepo.DefaultBranch { }
fmt.Println(myRef.Ref) contents, _, err := giteaClient.GetContents(myOrg, myRepo, mySha, mySpec)
return if err != nil {
} http.Error(rw, "OpenAPI spec: "+err.Error(), http.StatusInternalServerError)
return
}
tmp, err := template.New("swagger").Parse(swaggerTemplate)
if err != nil {
fmt.Println("Template parse error:", err)
return
}
err = tmp.Execute(rw, struct {
LoadUrls []struct {
Url string `json:"url"`
Name string `json:"name"`
} }
fmt.Println("Can't find default branch") LoadMain string
}{
LoadUrls: []struct {
Url string `json:"url"`
Name string `json:"name"`
}{
{Url: fmt.Sprintf("/gitea/spec/%s/%s/%s/%s?raw=true", myOrg, myRepo, mySha, mySpec), Name: contents.Name},
},
LoadMain: contents.Name,
})
if err != nil {
fmt.Println("Template execute error:", err)
return
} }
} }

View File

@ -57,7 +57,7 @@
<div> <div>
{{if .ShowGoMod}} {{if .ShowGoMod}}
<p>Repository details:</p> <p>Repository details:</p>
<p>Go import: go get {{.SelModule}}@v0.0.0-{{.CommitTime}}-{{.CommitHash}}</p> <p>Go import: go get {{.SelModule}}@v0.0.0-{{.CommitTime}}-{{.CommitHashShort}}</p>
{{end}} {{end}}
{{if .ShowSpec}} {{if .ShowSpec}}
<div> <div>
@ -68,7 +68,7 @@
{{if not (eq .Code 200)}} {{if not (eq .Code 200)}}
{{.Name}} ({{.Code}}) {{.Name}} ({{.Code}})
{{else}} {{else}}
<a href="?org={{$.SelOrg}}&repo={{$.SelRepo}}&spec={{.Name}}" target="_blank">{{.Name}}</a> <a href="/gitea/spec/{{$.SelOrg}}/{{$.SelRepo}}/{{$.CommitHash}}/{{.Name}}" target="_blank">{{.Name}}</a>
{{end}} {{end}}
</li> </li>
{{end}} {{end}}

View File

@ -4,16 +4,16 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Swagger | Gitea | Melon Tools</title> <title>Swagger | Gitea | Melon Tools</title>
<link rel="stylesheet" type="text/css" href="swagger/swagger-ui.css" /> <link rel="stylesheet" type="text/css" href="/gitea/swagger/swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="swagger/index.css" /> <link rel="stylesheet" type="text/css" href="/gitea/swagger/index.css" />
<link rel="icon" type="image/png" href="swagger/favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="/gitea/swagger/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="swagger/favicon-16x16.png" sizes="16x16" /> <link rel="icon" type="image/png" href="/gitea/swagger/favicon-16x16.png" sizes="16x16" />
</head> </head>
<body> <body>
<div id="swagger-ui"></div> <div id="swagger-ui"></div>
<script src="swagger/swagger-ui-bundle.js" charset="UTF-8"></script> <script src="/gitea/swagger/swagger-ui-bundle.js" charset="UTF-8"></script>
<script src="swagger/swagger-ui-standalone-preset.js" charset="UTF-8"></script> <script src="/gitea/swagger/swagger-ui-standalone-preset.js" charset="UTF-8"></script>
<script src="swagger/swagger-initializer-custom.js" charset="UTF-8"></script> <script src="/gitea/swagger/swagger-initializer-custom.js" charset="UTF-8"></script>
<script> <script>
window.loadUrls = {{.LoadUrls}}; window.loadUrls = {{.LoadUrls}};
window.loadMain = {{.LoadMain}}; window.loadMain = {{.LoadMain}};