feat: add output query param on serve mode & refactor output logic

Signed-off-by: Matthis Holleville <matthish29@gmail.com>
This commit is contained in:
Matthis Holleville
2023-04-15 21:55:46 +02:00
parent 0f88edf4e3
commit 9642202ed1
5 changed files with 88 additions and 55 deletions

View File

@@ -51,17 +51,12 @@ var AnalyzeCmd = &cobra.Command{
} }
// print results // print results
switch output { output, err := config.PrintOutput(output)
case "json":
output, err := config.JsonOutput()
if err != nil { if err != nil {
color.Red("Error: %v", err) color.Red("Error: %v", err)
os.Exit(1) os.Exit(1)
} }
fmt.Println(string(output)) fmt.Println(string(output))
default:
config.PrintOutput()
}
}, },
} }

View File

@@ -2,7 +2,6 @@ package analysis
import ( import (
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"os" "os"
@@ -149,45 +148,6 @@ func (a *Analysis) RunAnalysis() error {
return nil return nil
} }
func (a *Analysis) JsonOutput() ([]byte, error) {
var problems int
var status AnalysisStatus
for _, result := range a.Results {
problems += len(result.Error)
}
if problems > 0 {
status = StateProblemDetected
} else {
status = StateOK
}
result := JsonOutput{
Problems: problems,
Results: a.Results,
Status: status,
}
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
return nil, fmt.Errorf("error marshalling json: %v", err)
}
return output, nil
}
func (a *Analysis) PrintOutput() {
fmt.Println("")
if len(a.Results) == 0 {
fmt.Println(color.GreenString("No problems detected"))
}
for n, result := range a.Results {
fmt.Printf("%s %s(%s)\n", color.CyanString("%d", n),
color.YellowString(result.Name), color.CyanString(result.ParentObject))
for _, err := range result.Error {
fmt.Printf("- %s %s\n", color.RedString("Error:"), color.RedString(err.Text))
}
fmt.Println(color.GreenString(result.Details + "\n"))
}
}
func (a *Analysis) GetAIResults(output string, anonymize bool) error { func (a *Analysis) GetAIResults(output string, anonymize bool) error {
if len(a.Results) == 0 { if len(a.Results) == 0 {
return nil return nil

View File

@@ -22,7 +22,7 @@ func TestAnalysis_NoProblemJsonOutput(t *testing.T) {
Results: []common.Result{}, Results: []common.Result{},
} }
gotJson, err := analysis.JsonOutput() gotJson, err := analysis.PrintOutput("json")
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@@ -75,7 +75,7 @@ func TestAnalysis_ProblemJsonOutput(t *testing.T) {
}, },
} }
gotJson, err := analysis.JsonOutput() gotJson, err := analysis.PrintOutput("json")
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@@ -136,7 +136,7 @@ func TestAnalysis_MultipleProblemJsonOutput(t *testing.T) {
}, },
} }
gotJson, err := analysis.JsonOutput() gotJson, err := analysis.PrintOutput("json")
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }

72
pkg/analysis/output.go Normal file
View File

@@ -0,0 +1,72 @@
package analysis
import (
"encoding/json"
"fmt"
"strings"
"github.com/fatih/color"
)
var outputFormats = map[string]func(*Analysis) ([]byte, error){
"json": (*Analysis).jsonOutput,
"text": (*Analysis).textOutput,
}
func getOutputFormats() []string {
formats := make([]string, 0, len(outputFormats))
for format := range outputFormats {
formats = append(formats, format)
}
return formats
}
func (a *Analysis) PrintOutput(format string) ([]byte, error) {
outputFunc, ok := outputFormats[format]
if !ok {
return nil, fmt.Errorf("unsupported output format: %s. Available format %s", format, strings.Join(getOutputFormats(), ","))
}
return outputFunc(a)
}
func (a *Analysis) jsonOutput() ([]byte, error) {
var problems int
var status AnalysisStatus
for _, result := range a.Results {
problems += len(result.Error)
}
if problems > 0 {
status = StateProblemDetected
} else {
status = StateOK
}
result := JsonOutput{
Problems: problems,
Results: a.Results,
Status: status,
}
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
return nil, fmt.Errorf("error marshalling json: %v", err)
}
return output, nil
}
func (a *Analysis) textOutput() ([]byte, error) {
var output strings.Builder
output.WriteString("\n")
if len(a.Results) == 0 {
output.WriteString(color.GreenString("No problems detected\n"))
return []byte(output.String()), nil
}
for n, result := range a.Results {
output.WriteString(fmt.Sprintf("%s %s(%s)\n", color.CyanString("%d", n),
color.YellowString(result.Name), color.CyanString(result.ParentObject)))
for _, err := range result.Error {
output.WriteString(fmt.Sprintf("- %s %s\n", color.RedString("Error:"), color.RedString(err.Text)))
}
output.WriteString(color.GreenString(result.Details + "\n"))
}
return []byte(output.String()), nil
}

View File

@@ -42,6 +42,11 @@ func (s *Config) analyzeHandler(w http.ResponseWriter, r *http.Request) {
anonymize := getBoolParam(r.URL.Query().Get("anonymize")) anonymize := getBoolParam(r.URL.Query().Get("anonymize"))
nocache := getBoolParam(r.URL.Query().Get("nocache")) nocache := getBoolParam(r.URL.Query().Get("nocache"))
language := r.URL.Query().Get("language") language := r.URL.Query().Get("language")
s.Output = r.URL.Query().Get("output")
if s.Output == "" {
s.Output = "json"
}
config, err := analysis.NewAnalysis(s.Backend, language, []string{}, namespace, nocache, explain) config, err := analysis.NewAnalysis(s.Backend, language, []string{}, namespace, nocache, explain)
if err != nil { if err != nil {
@@ -65,14 +70,15 @@ func (s *Config) analyzeHandler(w http.ResponseWriter, r *http.Request) {
} }
} }
output, err := config.JsonOutput() out, err := config.PrintOutput(s.Output)
if err != nil { if err != nil {
color.Red("Error: %v", err) color.Red("Error: %v", err)
health.Failure++ health.Failure++
fmt.Fprintf(w, err.Error()) fmt.Fprintf(w, err.Error())
} }
health.Success++ health.Success++
fmt.Fprintf(w, string(output)) fmt.Fprintf(w, string(out))
} }
func (s *Config) Serve() error { func (s *Config) Serve() error {