aboutsummaryrefslogtreecommitdiff
path: root/env.go
blob: 9ec74e8a4d6940a1ac45e8025970da827a3e6ac3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main

import (
	"code.laria.me/petrific/cache"
	"code.laria.me/petrific/config"
	"code.laria.me/petrific/logging"
	"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
	Log     *logging.Log
}

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(log *logging.Log, confPath, storageName string) (*Env, error) {
	env := new(Env)
	env.Log = log

	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
}