Add command to check for swagger docs regeneration

This commit is contained in:
kolaente 2020-09-01 18:36:45 +02:00
parent 0d427711f9
commit deeaa13a72
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
1 changed files with 43 additions and 0 deletions

View File

@ -21,8 +21,10 @@ package main
import (
"bufio"
"bytes"
"crypto/sha256"
"fmt"
"github.com/magefile/mage/mg"
"io"
"os"
"os/exec"
"runtime"
@ -188,6 +190,22 @@ func checkAndInstallGoTool(tool, importPath string) {
}
}
// Calculates a hash of a file
func calculateHashOfFile(path string) (hash string, err error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// Cleans all build, executable and bindata files
func Clean() error {
if err := exec.Command("go", "clean", "./...").Run(); err != nil {
@ -262,8 +280,33 @@ func DoTheSwag() {
runAndStreamOutput("swag", "init", "-g", "./pkg/routes/routes.go", "--parseDependency", "-d", RootPath, "-o", RootPath+"/pkg/swagger")
}
// Checks if the swagger docs need to be re-generated from the code annotations
func GotSwag() {
// The check is pretty cheaply done: We take the hash of the swagger.json file, generate the docs,
// hash the file again and compare the two hashes to see if anything changed. If that's the case,
// regenerating the docs is nessecary.
// swag is not capable of just outputting the generated docs to stdout, therefore we need to do it this way.
// Another drawback of this is obviously it will only work once - we're not resetting the newly generated
// docs after the check. This behaviour is good enough for ci though.
oldHash, err := calculateHashOfFile(RootPath + "/pkg/swagger/swagger.json")
if err != nil {
fmt.Printf("Error getting old hash of the swagger docs: %s", err)
os.Exit(1)
}
DoTheSwag()
newHash, err := calculateHashOfFile(RootPath + "/pkg/swagger/swagger.json")
if err != nil {
fmt.Printf("Error getting new hash of the swagger docs: %s", err)
os.Exit(1)
}
if oldHash != newHash {
fmt.Println("Swagger docs are not up to date.")
fmt.Println("Please run 'mage do-the-swag' and commit the result.")
os.Exit(1)
}
}
func MisspellCheck() {