From d68510b9fcaff2deb218ce91f3f1812fa438bf55 Mon Sep 17 00:00:00 2001 From: Boris Bera Date: Mon, 14 Oct 2024 14:17:05 -0400 Subject: [PATCH] fix(backend): reuse ensure init feature in backend validation --- internal/backend.go | 18 +++++++----------- internal/backend_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/internal/backend.go b/internal/backend.go index 42f7b89..fd76990 100644 --- a/internal/backend.go +++ b/internal/backend.go @@ -131,20 +131,16 @@ func (b Backend) validate() error { return err } options := ExecuteOptions{Envs: env, Silent: true} - // Check if already initialized + + err = b.EnsureInit() + if err != nil { + return err + } + cmd := []string{"check"} cmd = append(cmd, combineBackendOptions("check", b)...) _, _, err = ExecuteResticCommand(options, cmd...) - if err == nil { - return nil - } else { - // If not initialize - colors.Body.Printf("Initializing backend \"%s\"...\n", b.name) - cmd := []string{"init"} - cmd = append(cmd, combineBackendOptions("init", b)...) - _, _, err := ExecuteResticCommand(options, cmd...) - return err - } + return err } // EnsureInit initializes the backend if it is not already initialized diff --git a/internal/backend_test.go b/internal/backend_test.go index 22f4975..508297f 100644 --- a/internal/backend_test.go +++ b/internal/backend_test.go @@ -266,6 +266,35 @@ func TestValidate(t *testing.T) { }) } +func TestValidateInitsRepo(t *testing.T) { + // This is normally initialized by the cobra commands but they don't run in + // this test so we do it ourselves. + flags.RESTIC_BIN = "restic" + + workDir := t.TempDir() + + b := Backend{ + name: "test", + Type: "local", + Path: path.Join(workDir, "backend"), + Key: "supersecret", + } + + config = &Config{Backends: map[string]Backend{"test": b}} + defer func() { config = nil }() + + // Check should fail because the repo doesn't exist + err := b.Exec([]string{"check"}) + assert.Error(t, err) + + err = b.validate() + assert.NoError(t, err) + + // Check should pass now + err = b.Exec([]string{"check"}) + assert.NoError(t, err) +} + func TestEnsureInit(t *testing.T) { // This is normally initialized by the cobra commands but they don't run in // this test so we do it ourselves.