~f4814n/frost

ref: 8ce23f36008a3001c34aac6bb8751d0d91bc336c frost/cmd/frost/platform_linux.go -rw-r--r-- 1.5 KiB
8ce23f36Fabian Geiselhart gofmt -w ./.. 10 months ago
                                                                                
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
78
// +build linux,!android

package main

import (
	"encoding/json"
	"fmt"
	"git.sr.ht/~f4814n/matrix"
	backend "git.sr.ht/~f4814n/matrix/backend/sqlite"
	"git.sr.ht/~f4814n/matrix/util/cache"
	"github.com/sirupsen/logrus"
	"os"
)

var (
	dataDir        = fmt.Sprintf("%s/frost", getenv("XDG_DATA_HOME", "~/.local/share"))
	cacheDir       = fmt.Sprintf("%s/frost", getenv("XDG_CACHE_HOME", "~/.cache"))
	configFilePath = dataDir + "/config.json"
)

type Platform struct {
	Logger *logrus.Logger
	Cache  cache.Cache
}

func InitPlatform() Platform {
	// Create b.Path directory
	if _, err := os.Stat(dataDir); os.IsNotExist(err) {
		os.Mkdir(dataDir, os.ModePerm) // XXX Correct permissions
	}

	// Create Cache
	cache, err := cache.NewFSCache(cacheDir)
	if err != nil {
		// XXX Fallback to memory cache, warn
		panic(err.Error())
	}

	return Platform{Cache: cache, Logger: logrus.New()}
}

func (p Platform) LoadConfig() (cfg AppConfig, err error) {
	f, err := os.Open(configFilePath)
	if err != nil {
		return
	}

	err = json.NewDecoder(f).Decode(&cfg)
	return
}

func (p Platform) FlushConfig(cfg AppConfig) (err error) {
	f, err := os.Create(configFilePath)
	if err != nil {
		return
	}

	err = json.NewEncoder(f).Encode(cfg)
	return
}

func (p Platform) NewBackend() matrix.Backend {
	return backend.New(dataDir)
}

func getenv(key, fallback string) (res string) {
	if val, ok := os.LookupEnv(key); ok {
		res = val
	} else {
		res = fallback
	}

	if res[0] == '~' {
		res = os.Getenv("HOME") + res[1:]
	}

	return
}