Skip to content

Commit

Permalink
fix(backend): reuse ensure init feature in backend validation
Browse files Browse the repository at this point in the history
  • Loading branch information
dotboris committed Oct 14, 2024
1 parent 3651c7c commit d68510b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
18 changes: 7 additions & 11 deletions internal/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions internal/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit d68510b

Please sign in to comment.