From e522a279f571ab0ca6b114628d039cbd4e79450a Mon Sep 17 00:00:00 2001 From: Shiwei Zhang Date: Wed, 14 Apr 2021 10:42:00 +0800 Subject: [PATCH] print in table (#258) Signed-off-by: Shiwei Zhang --- cmd/oras/discover.go | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/cmd/oras/discover.go b/cmd/oras/discover.go index 79aea971e..b3c284e84 100644 --- a/cmd/oras/discover.go +++ b/cmd/oras/discover.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "os" + "strings" ctxo "github.com/deislabs/oras/pkg/context" "github.com/deislabs/oras/pkg/oras" @@ -81,22 +82,43 @@ func runDiscover(opts discoverOptions) error { } if opts.outputJSON { - printDiscoveredReferences(desc, refs) + printDiscoveredReferencesJSON(desc, refs) } else { fmt.Println("Discovered", len(refs), "artifacts referencing", opts.targetRef) fmt.Println("Digest:", desc.Digest) - for _, ref := range refs { - fmt.Println("Reference:", ref.Digest) - if opts.verbose { - printJSON(ref.Artifact) - } + + if len(refs) != 0 { + fmt.Println() + printDiscoveredReferencesTable(refs, opts.verbose) } } return nil } -func printDiscoveredReferences(desc ocispec.Descriptor, refs []remotes.DiscoveredArtifact) { +func printDiscoveredReferencesTable(refs []remotes.DiscoveredArtifact, verbose bool) { + typeNameTitle := "Artifact Type" + typeNameLength := len(typeNameTitle) + for _, ref := range refs { + if length := len(ref.Artifact.ArtifactType); length > typeNameLength { + typeNameLength = length + } + } + + print := func(key string, value interface{}) { + fmt.Println(key, strings.Repeat(" ", typeNameLength-len(key)+1), value) + } + + print(typeNameTitle, "Digest") + for _, ref := range refs { + print(ref.Artifact.ArtifactType, ref.Digest) + if verbose { + printJSON(ref.Artifact) + } + } +} + +func printDiscoveredReferencesJSON(desc ocispec.Descriptor, refs []remotes.DiscoveredArtifact) { type reference struct { Digest digest.Digest `json:"digest"` Manifest artifactspec.Artifact `json:"manifest"`