From 2cfd9f146d042a1c30176ad91fea730df439704d Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Sun, 10 Dec 2017 15:43:58 +0100 Subject: Eliminate global variables --- env.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 env.go (limited to 'env.go') diff --git a/env.go b/env.go new file mode 100644 index 0000000..ad8cf9a --- /dev/null +++ b/env.go @@ -0,0 +1,74 @@ +package main + +import ( + "code.laria.me/petrific/cache" + "code.laria.me/petrific/config" + "code.laria.me/petrific/storage" + "code.laria.me/petrific/storage/registry" + "fmt" +) + +// Env provides commonly used objects for subcommands +type Env struct { + Conf config.Config + Store storage.Storage + IdCache cache.Cache +} + +func (e *Env) Close() { + if e.IdCache != nil { + e.IdCache.Close() + } + + if e.Store != nil { + e.Store.Close() + } +} + +func (env *Env) loadCache() error { + path := env.Conf.CachePath + if path == "" { + return nil + } + + file_cache := cache.NewFileCache(config.ExpandTilde(path)) + if err := file_cache.Load(); err != nil { + return fmt.Errorf("Loading cache %s: %s", path, err) + } + + env.IdCache = file_cache + return nil +} + +func NewEnv(confPath, storageName string) (*Env, error) { + env := new(Env) + + var err error + + // Load config + + env.Conf, err = config.LoadConfig(confPath) + if err != nil { + return nil, err + } + + // load storage + + if storageName == "" { + storageName = env.Conf.DefaultStorage + } + + env.Store, err = registry.LoadStorage(env.Conf, storageName) + if err != nil { + return nil, err + } + + // Load cache + + if err = env.loadCache(); err != nil { + env.Close() + return nil, err + } + + return env, nil +} -- cgit v1.2.3-54-g00ecf