aboutsummaryrefslogtreecommitdiffstats
path: root/config/general.go
blob: 2a462a3e6ff0d711bd6722d4abca887dbddef982 (plain) (blame)
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
package config

import (
	"fmt"
	"os"

	"git.sr.ht/~rjarry/aerc/logging"
	"github.com/go-ini/ini"
	"github.com/mattn/go-isatty"
	"github.com/mitchellh/go-homedir"
)

type GeneralConfig struct {
	DefaultSavePath    string           `ini:"default-save-path"`
	PgpProvider        string           `ini:"pgp-provider"`
	UnsafeAccountsConf bool             `ini:"unsafe-accounts-conf"`
	LogFile            string           `ini:"log-file"`
	LogLevel           logging.LogLevel `ini:"-"`
}

func defaultGeneralConfig() GeneralConfig {
	return GeneralConfig{
		PgpProvider:        "internal",
		UnsafeAccountsConf: false,
		LogLevel:           logging.INFO,
	}
}

func (config *AercConfig) parseGeneral(file *ini.File) error {
	var level *ini.Key
	var logFile *os.File

	gen, err := file.GetSection("general")
	if err != nil {
		goto end
	}
	if err := gen.MapTo(&config.General); err != nil {
		return err
	}
	level, err = gen.GetKey("log-level")
	if err == nil {
		l, err := logging.ParseLevel(level.String())
		if err != nil {
			return err
		}
		config.General.LogLevel = l
	}
	if err := config.General.validatePgpProvider(); err != nil {
		return err
	}
end:
	if !isatty.IsTerminal(os.Stdout.Fd()) {
		logFile = os.Stdout
		// redirected to file, force DEBUG level
		config.General.LogLevel = logging.DEBUG
	} else if config.General.LogFile != "" {
		path, err := homedir.Expand(config.General.LogFile)
		if err != nil {
			return fmt.Errorf("log-file: %w", err)
		}
		logFile, err = os.OpenFile(path,
			os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
		if err != nil {
			return fmt.Errorf("log-file: %w", err)
		}
	}
	logging.Init(logFile, config.General.LogLevel)
	logging.Debugf("aerc.conf: [general] %#v", config.General)
	return nil
}

func (gen *GeneralConfig) validatePgpProvider() error {
	switch gen.PgpProvider {
	case "gpg", "internal":
		return nil
	default:
		return fmt.Errorf("pgp-provider must be either gpg or internal")
	}
}