Merge pull request #25 from ulyssessouza/refactor-store-new

Refactor store.New to use vargs and get user home by default
This commit is contained in:
Djordje Lukic 2020-04-28 15:00:02 +02:00 committed by GitHub
commit 01cc77a09a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 8 deletions

View File

@ -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)
}

View File

@ -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

View File

@ -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