osbuild2: v2 Result writer

Implementing writer for osbuild2 Result type.
Since Go maps don't have stable ordering, sorting by the pipeline name
provides stable output.

Signed-off-by: Achilleas Koutsou <achilleas@koutsou.net>
This commit is contained in:
Achilleas Koutsou 2021-09-06 15:26:28 +02:00 committed by Ondřej Budai
parent 2004c71f89
commit 9eff6f1e95

View file

@ -2,6 +2,9 @@ package osbuild2
import (
"encoding/json"
"fmt"
"io"
"sort"
)
type PipelineResult []StageResult
@ -87,3 +90,43 @@ type Result struct {
Log map[string]PipelineResult `json:"log"`
Metadata map[string]PipelineMetadata `json:"metadata"`
}
func (cr *Result) Write(writer io.Writer) error {
if cr.Log == nil {
fmt.Fprintf(writer, "The compose result is empty.\n")
}
// The pipeline results don't have a stable order
// (see https://github.com/golang/go/issues/27179)
// Sort based on pipeline name to have a stable print order
pipelineNames := make([]string, 0, len(cr.Log))
for name := range cr.Log {
pipelineNames = append(pipelineNames, name)
}
sort.Strings(pipelineNames)
for _, pipelineName := range pipelineNames {
fmt.Fprintf(writer, "Pipeline %s\n", pipelineName)
pipelineMD := cr.Metadata[pipelineName]
for _, stage := range cr.Log[pipelineName] {
fmt.Fprintf(writer, "Stage %s\n", stage.Type)
fmt.Fprintf(writer, "Output:\n%s\n", stage.Output)
// print structured stage metadata if available
if pipelineMD != nil {
if md, ok := pipelineMD[stage.Type]; ok {
fmt.Fprint(writer, "Metadata:\n")
enc := json.NewEncoder(writer)
enc.SetIndent("", " ")
err := enc.Encode(md)
if err != nil {
return err
}
}
fmt.Fprint(writer, "\n")
}
}
}
return nil
}