From c28641d2906bcf811ed57007725961534d21bc5b Mon Sep 17 00:00:00 2001 From: Alex Vanin Date: Tue, 20 Oct 2020 15:34:13 +0300 Subject: [PATCH] [#95] Support `--json` flag in container.get command Signed-off-by: Alex Vanin --- cmd/neofs-cli/modules/container.go | 39 ++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/cmd/neofs-cli/modules/container.go b/cmd/neofs-cli/modules/container.go index 0444b874..805a8226 100644 --- a/cmd/neofs-cli/modules/container.go +++ b/cmd/neofs-cli/modules/container.go @@ -299,12 +299,24 @@ var getContainerInfoCmd = &cobra.Command{ } } - prettyPrintContainer(cnr) + prettyPrintContainer(cnr, containerJSON) if containerPathTo != "" { - data, err := cnr.ToV2().StableMarshal(nil) - if err != nil { - return errors.New("can't marshal container") + var ( + data []byte + err error + ) + + if containerJSON { + data = v2container.ContainerToJSON(cnr.ToV2()) + if len(data) == 0 { + return errors.New("can't JSON encode container") + } + } else { + data, err = cnr.ToV2().StableMarshal(nil) + if err != nil { + return errors.New("can't binary encode container") + } } err = ioutil.WriteFile(containerPathTo, data, 0644) @@ -475,8 +487,9 @@ func init() { // container get getContainerInfoCmd.Flags().StringVar(&containerID, "cid", "", "container ID") - getContainerInfoCmd.Flags().StringVar(&containerPathTo, "to", "", "path to dump binary encoded container") - getContainerInfoCmd.Flags().StringVar(&containerPathFrom, "from", "", "path to file with binary encoded container") + getContainerInfoCmd.Flags().StringVar(&containerPathTo, "to", "", "path to dump encoded container") + getContainerInfoCmd.Flags().StringVar(&containerPathFrom, "from", "", "path to file with encoded container") + getContainerInfoCmd.Flags().BoolVar(&containerJSON, "json", false, "print or dump container in JSON format") // container get-eacl getExtendedACLCmd.Flags().StringVar(&containerID, "cid", "", "container ID") @@ -588,11 +601,23 @@ func parseContainerID(cid string) (*container.ID, error) { return id, nil } -func prettyPrintContainer(cnr *container.Container) { +func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) { if cnr == nil { return } + if jsonEncoding { + data := v2container.ContainerToJSON(cnr.ToV2()) + buf := new(bytes.Buffer) + if err := json.Indent(buf, data, "", " "); err != nil { + printVerbose("Can't pretty print json: %w", err) + } + + fmt.Println(buf) + + return + } + id := container.CalculateID(cnr) fmt.Println("container ID:", id)