From 9a9f559806a8c62ee6200792b95d0489a9d9ebbc Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Fri, 21 Oct 2022 22:32:11 +0200 Subject: [PATCH] init: cleanup json print code --- changelog/unreleased/issue-3124 | 6 +++--- cmd/restic/cmd_init.go | 26 ++++++++------------------ 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/changelog/unreleased/issue-3124 b/changelog/unreleased/issue-3124 index bfd75b93d..25d754eed 100644 --- a/changelog/unreleased/issue-3124 +++ b/changelog/unreleased/issue-3124 @@ -1,7 +1,7 @@ -Enhancement: Enable support for json output on init command - -Init command did not listen to the --json flag, it now outputs a struct depending on a successful or failed creation of a repository, with all relevant information +Enhancement: Support json output for the `init` command +The `init` command ignored the `--json` flag. It now outputs a JSON message if +the repository was created successfully. https://github.com/restic/restic/issues/3124 https://github.com/restic/restic/pull/3132 diff --git a/cmd/restic/cmd_init.go b/cmd/restic/cmd_init.go index 2e293e040..7df4a810c 100644 --- a/cmd/restic/cmd_init.go +++ b/cmd/restic/cmd_init.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "context" "encoding/json" "strconv" @@ -51,12 +50,6 @@ func init() { } func runInit(ctx context.Context, opts InitOptions, gopts GlobalOptions, args []string) error { - type JSONSuccess struct { - Status string `json:"status"` - ID string `json:"id"` - Repository string `json:"repository"` - } - var version uint if opts.RepositoryVersion == "latest" || opts.RepositoryVersion == "" { version = restic.MaxRepoVersion @@ -116,26 +109,17 @@ func runInit(ctx context.Context, opts InitOptions, gopts GlobalOptions, args [] Verbosef("irrecoverably lost.\n") } else { - status := JSONSuccess{ + status := initSuccess{ Status: "success", ID: s.Config().ID, Repository: location.StripPassword(gopts.Repo), } - Verbosef(toJSONString(status)) + return json.NewEncoder(gopts.stdout).Encode(status) } return nil } -func toJSONString(status interface{}) string { - buf := new(bytes.Buffer) - err := json.NewEncoder(buf).Encode(status) - if err != nil { - panic("ERROR: Could not encode JSON string") - } - return buf.String() -} - func maybeReadChunkerPolynomial(ctx context.Context, opts InitOptions, gopts GlobalOptions) (*chunker.Pol, error) { if opts.CopyChunkerParameters { otherGopts, _, err := fillSecondaryGlobalOpts(opts.secondaryRepoOptions, gopts, "secondary") @@ -157,3 +141,9 @@ func maybeReadChunkerPolynomial(ctx context.Context, opts InitOptions, gopts Glo } return nil, nil } + +type initSuccess struct { + Status string `json:"status"` // "success" + ID string `json:"id"` + Repository string `json:"repository"` +}