From 3380c9d459e54d2013a5ed85a1681728b316861d Mon Sep 17 00:00:00 2001 From: Ulysses Souza Date: Mon, 27 Apr 2020 18:16:46 +0200 Subject: [PATCH] Refactor store.New Signed-off-by: Ulysses Souza --- cli/main.go | 2 +- context/store/store.go | 27 +++++++++++++++++++++------ context/store/store_test.go | 2 +- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/cli/main.go b/cli/main.go index 0bd929cbc..6549b992c 100644 --- a/cli/main.go +++ b/cli/main.go @@ -118,7 +118,7 @@ func main() { logrus.Fatal(err) } - s, err := store.New(opts.Config) + s, err := store.New(store.WithRoot(opts.Config)) if err != nil { logrus.Fatal(err) } diff --git a/context/store/store.go b/context/store/store.go index 6f864d978..f09d36cc4 100644 --- a/context/store/store.go +++ b/context/store/store.go @@ -72,9 +72,27 @@ type store struct { root string } +type StoreOpt func(*store) + +func WithRoot(root string) StoreOpt { + return func(s *store) { + s.root = root + } +} + // New returns a configured context store -func New(root string) (Store, error) { - cd := filepath.Join(root, contextsDir) +func New(opts ...StoreOpt) (Store, error) { + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + s := &store { + root: home, + } + for _, opt := range opts { + opt(s) + } + cd := filepath.Join(s.root, contextsDir) if _, err := os.Stat(cd); os.IsNotExist(err) { if err = os.Mkdir(cd, 0755); err != nil { return nil, err @@ -86,10 +104,7 @@ func New(root string) (Store, error) { return nil, err } } - - return &store{ - root: root, - }, nil + return s, nil } // Get returns the context with the given name diff --git a/context/store/store_test.go b/context/store/store_test.go index d424e078b..39685c7b1 100644 --- a/context/store/store_test.go +++ b/context/store/store_test.go @@ -48,7 +48,7 @@ func (suite *StoreTestSuite) BeforeTest(suiteName, testName string) { dir, err := ioutil.TempDir("", "store") require.Nil(suite.T(), err) - store, err := New(dir) + store, err := New(WithRoot(dir)) require.Nil(suite.T(), err) suite.dir = dir