~f4814n/frost

ref: 1eee8169fcf6bda919ba018c6742f7b2d5268f15 frost/platform/platform_linux.go -rw-r--r-- 1.9 KiB
1eee8169Fabian Geiselhart platform: Colorful logs on linux 8 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//+build linux,!android

package platform

import (
	"encoding/json"
	"fmt"
	"os"

	"git.sr.ht/~f4814n/matrix"
	backend "git.sr.ht/~f4814n/matrix/backend/sqlite"
	"git.sr.ht/~f4814n/matrix/util/cache"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type platformLinux struct {
	dataDir, cacheDir, configFilePath string
}

func Init() (Platform, error) {
	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"

	// Create dataDir
	if _, err := os.Stat(dataDir); os.IsNotExist(err) {
		err := os.Mkdir(dataDir, os.ModePerm) // XXX Correct permissions
		if err != nil {
			return nil, err
		}
	}

	return platformLinux{
		dataDir:        dataDir,
		cacheDir:       cacheDir,
		configFilePath: configFilePath,
	}, nil
}

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

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

	return cache
}

func (p platformLinux) Logger() *zap.Logger {
	config := zap.NewDevelopmentConfig()
	config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	logger, err := config.Build()
	if err != nil {
		panic(err.Error())
	}

	return logger
}

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

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

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

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

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
}