support json output for init command

This commit is contained in:
Kyle Brennan 2020-11-28 01:54:21 -08:00 committed by Michael Eischer
parent fa20a78bb6
commit a6ae79b39e

View file

@ -1,7 +1,9 @@
package main package main
import ( import (
"bytes"
"context" "context"
"encoding/json"
"strconv" "strconv"
"github.com/restic/chunker" "github.com/restic/chunker"
@ -49,6 +51,12 @@ func init() {
} }
func runInit(ctx context.Context, opts InitOptions, gopts GlobalOptions, args []string) error { 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 var version uint
if opts.RepositoryVersion == "latest" || opts.RepositoryVersion == "" { if opts.RepositoryVersion == "latest" || opts.RepositoryVersion == "" {
version = restic.MaxRepoVersion version = restic.MaxRepoVersion
@ -100,15 +108,34 @@ func runInit(ctx context.Context, opts InitOptions, gopts GlobalOptions, args []
return errors.Fatalf("create key in repository at %s failed: %v\n", location.StripPassword(gopts.Repo), err) return errors.Fatalf("create key in repository at %s failed: %v\n", location.StripPassword(gopts.Repo), err)
} }
Verbosef("created restic repository %v at %s\n", s.Config().ID[:10], location.StripPassword(gopts.Repo)) if !gopts.JSON {
Verbosef("\n") Verbosef("created restic repository %v at %s\n", s.Config().ID[:10], location.StripPassword(gopts.Repo))
Verbosef("Please note that knowledge of your password is required to access\n") Verbosef("\n")
Verbosef("the repository. Losing your password means that your data is\n") Verbosef("Please note that knowledge of your password is required to access\n")
Verbosef("irrecoverably lost.\n") Verbosef("the repository. Losing your password means that your data is\n")
Verbosef("irrecoverably lost.\n")
} else {
status := JSONSuccess{
Status: "success",
ID: s.Config().ID,
Repository: location.StripPassword(gopts.Repo),
}
Verbosef(toJSONString(status))
}
return nil 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) { func maybeReadChunkerPolynomial(ctx context.Context, opts InitOptions, gopts GlobalOptions) (*chunker.Pol, error) {
if opts.CopyChunkerParameters { if opts.CopyChunkerParameters {
otherGopts, _, err := fillSecondaryGlobalOpts(opts.secondaryRepoOptions, gopts, "secondary") otherGopts, _, err := fillSecondaryGlobalOpts(opts.secondaryRepoOptions, gopts, "secondary")