diff options
author | Laria Carolin Chabowski <laria@laria.me> | 2017-12-10 15:43:58 +0100 |
---|---|---|
committer | Laria Carolin Chabowski <laria@laria.me> | 2017-12-11 08:13:52 +0100 |
commit | 2cfd9f146d042a1c30176ad91fea730df439704d (patch) | |
tree | c3df2c321b8b8b5d409d2e2f4601da5af0d117a5 /env.go | |
parent | 0a4929876c1606abf2a599c6561affba368ab5fb (diff) | |
download | petrific-2cfd9f146d042a1c30176ad91fea730df439704d.tar.gz petrific-2cfd9f146d042a1c30176ad91fea730df439704d.tar.bz2 petrific-2cfd9f146d042a1c30176ad91fea730df439704d.zip |
Eliminate global variables
Diffstat (limited to 'env.go')
-rw-r--r-- | env.go | 74 |
1 files changed, 74 insertions, 0 deletions
@@ -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 +} |