use format flag to handle json output

Signed-off-by: Meredith Lancaster <malancas@github.com>
This commit is contained in:
Meredith Lancaster 2024-03-18 10:35:10 -06:00
parent 172e4f6d6d
commit 09b11dbb11
3 changed files with 8 additions and 6 deletions

View file

@ -84,7 +84,7 @@ func NewInspectCmd(f *cmdutil.Factory, runF func(*Options) error) *cobra.Command
inspectCmd.Flags().StringVarP(&opts.BundlePath, "bundle", "b", "", "Path to bundle on disk, either a single bundle in a JSON file or a JSON lines file with multiple bundles")
inspectCmd.MarkFlagRequired("bundle") //nolint:errcheck
cmdutil.StringEnumFlag(inspectCmd, &opts.DigestAlgorithm, "digest-alg", "d", "sha256", []string{"sha256", "sha512"}, "The algorithm used to compute a digest of the artifact")
inspectCmd.Flags().BoolVarP(&opts.JsonResult, "json-result", "j", false, "Output inspect result as JSON lines")
cmdutil.AddFormatFlags(inspectCmd, &opts.exporter)
return inspectCmd
}
@ -125,8 +125,8 @@ func runInspect(opts *Options) error {
"Successfully verified all attestations against Sigstore!\n\n",
))
// If true, print results as a slice of JSON objects
if opts.JsonResult {
// If the user provides the --format=json flag, print the results in JSON format
if opts.exporter != nil {
details, err := getAttestationDetails(res.VerifyResults)
if err != nil {
return fmt.Errorf("failed to get attestation detail: %w", err)
@ -142,7 +142,9 @@ func runInspect(opts *Options) error {
jsonResults[i] = string(jsonBytes)
}
fmt.Fprintf(opts.Logger.IO.Out, "%v", jsonResults)
if err = opts.exporter.Write(opts.Logger.IO, jsonResults); err != nil {
return fmt.Errorf("failed to write JSON output")
}
return nil
}

View file

@ -115,7 +115,6 @@ func TestNewInspectCmd(t *testing.T) {
assert.Equal(t, tc.wants.ArtifactPath, opts.ArtifactPath)
assert.Equal(t, tc.wants.BundlePath, opts.BundlePath)
assert.Equal(t, tc.wants.DigestAlgorithm, opts.DigestAlgorithm)
assert.Equal(t, tc.wants.JsonResult, opts.JsonResult)
assert.NotNil(t, opts.OCIClient)
assert.NotNil(t, opts.Logger)
})

View file

@ -5,6 +5,7 @@ import (
"github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci"
"github.com/cli/cli/v2/pkg/cmd/attestation/io"
"github.com/cli/cli/v2/pkg/cmdutil"
)
// Options captures the options for the inspect command
@ -12,9 +13,9 @@ type Options struct {
ArtifactPath string
BundlePath string
DigestAlgorithm string
JsonResult bool
Logger *io.Handler
OCIClient oci.Client
exporter cmdutil.Exporter
}
// Clean cleans the file path option values