-
Notifications
You must be signed in to change notification settings - Fork 27
/
config.go
306 lines (265 loc) · 9.94 KB
/
config.go
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package main
import (
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"sort"
"strings"
"gioui.org/app"
"github.com/crypto-power/cryptopower/appos"
libutils "github.com/crypto-power/cryptopower/libwallet/utils"
"github.com/crypto-power/cryptopower/version"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/slog"
flags "github.com/jessevdk/go-flags"
)
const (
defaultConfigFileName = "cryptopower.conf"
defaultLogFilename = "cryptopower.log"
defaultLogDirname = "logs"
)
type config struct {
Network string `long:"network" description:"Network to use (mainnet, simnet, testnet, dextest). Default is mainnet. Cannot be changed from the app once set."`
HomeDir string `long:"appdata" description:"Directory where the app configuration file and wallet data is stored"`
ConfigFile string `long:"configfile" description:"Filename of the config file in the app directory"`
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
MaxLogZips int `long:"max-log-zips" description:"The number of zipped log files created by the log rotator to be retained. Setting to 0 will keep all."`
LogDir string `long:"logdir" description:"Directory to log output."`
DebugLevel string `short:"d" long:"debuglevel" description:"Logging level {trace, debug, info, warn, error, critical, off}"`
Quiet bool `short:"q" long:"quiet" description:"Easy way to set debuglevel to error"`
SpendUnconfirmed bool `long:"spendunconfirmed" description:"Allow the assetsManager to use transactions that have not been confirmed"`
Profile int `long:"profile" description:"Runs local web server for profiling"`
DEXTestAddr string `long:"dextestaddr" description:"If using the dextest network, set an address for the dex harness to be used as a persistant peer for all new wallets."`
net libutils.NetworkType
}
func defaultConfig(defaultHomeDir string) config {
return config{
HomeDir: defaultHomeDir,
ConfigFile: filepath.Join(defaultHomeDir, defaultConfigFileName),
LogDir: filepath.Join(defaultHomeDir, defaultLogDirname),
}
}
// validLogLevel returns whether or not logLevel is a valid debug log level.
func validLogLevel(logLevel string) bool {
_, ok := slog.LevelFromString(logLevel)
return ok
}
// supportedSubsystems returns a sorted slice of the supported subsystems for
// logging purposes.
func supportedSubsystems() []string {
// Convert the subsystemLoggers map keys to a slice.
subsystems := make([]string, 0, len(subsystemSLoggers)+len(subsystemBLoggers))
for subsysID := range subsystemSLoggers {
subsystems = append(subsystems, subsysID)
}
for subsysID := range subsystemBLoggers {
subsystems = append(subsystems, subsysID)
}
// Sort the subsystems for stable display.
sort.Strings(subsystems)
return subsystems
}
// parseAndSetDebugLevels attempts to parse the specified debug level and set
// the levels accordingly. An appropriate error is returned if anything is
// invalid.
func parseAndSetDebugLevels(debugLevel string) error {
// When the specified string doesn't have any delimiters, treat it as
// the log level for all subsystems.
debugLeveSet := debugLevel != ""
if debugLeveSet && !strings.Contains(debugLevel, ",") && !strings.Contains(debugLevel, "=") {
// Validate debug log level.
if !validLogLevel(debugLevel) {
str := "the specified debug level [%v] is invalid"
return fmt.Errorf(str, debugLevel)
}
return nil
}
return nil
}
// loadConfig initializes and parses the config using a config file and command
// line options.
func loadConfig() (*config, error) {
loadConfigError := func(err error) (*config, error) {
return nil, err
}
// Default config
defaultHomeDir := dcrutil.AppDataDir("cryptopower", false)
if appos.Current().IsMobile() {
homeDir, err := app.DataDir()
if err != nil {
return nil, fmt.Errorf("unable to get android home dir: %v", err)
}
defaultHomeDir = homeDir // something like /data/user/0/com.github.cryptopower/files
}
cfg := defaultConfig(defaultHomeDir)
defaultCfg := defaultConfig(defaultHomeDir)
// Pre-parse the command line options to see if an alternative config file
// or the version flag was specified. Override any environment variables
// with parsed command line flags.
preParser := flags.NewParser(&cfg, flags.HelpFlag|flags.PassDoubleDash)
_, err := preParser.Parse()
if err != nil {
e, ok := err.(*flags.Error)
if !ok || e.Type != flags.ErrHelp {
preParser.WriteHelp(os.Stderr)
}
if ok && e.Type == flags.ErrHelp {
preParser.WriteHelp(os.Stdout)
os.Exit(0)
}
return loadConfigError(err)
}
// Show the version and exit if the version flag was specified.
appName := filepath.Base(os.Args[0])
appName = strings.TrimSuffix(appName, filepath.Ext(appName))
if cfg.ShowVersion {
fmt.Printf("%s version %s (Go version %s)\n", appName,
version.Version(), runtime.Version())
os.Exit(0)
}
// If a non-default appdata folder is specified on the command line, it may
// be necessary adjust the config file location. If the the config file
// location was not specified on the command line, the default location
// should be under the non-default appdata directory. However, if the config
// file was specified on the command line, it should be used regardless of
// the appdata directory.
if defaultCfg.HomeDir != cfg.HomeDir && defaultCfg.ConfigFile == cfg.ConfigFile {
cfg.ConfigFile = filepath.Join(cfg.HomeDir, defaultConfigFileName)
// Update the defaultConfig to avoid an error if the config file in this
// "new default" location does not exist.
defaultCfg.ConfigFile = cfg.ConfigFile
}
// Load additional config from file.
var configFileError error
// Config file name for logging.
configFile := "NONE (defaults)"
parser := flags.NewParser(&cfg, flags.Default)
// Do not error default config file is missing.
if _, err := os.Stat(cfg.ConfigFile); os.IsNotExist(err) {
// Non-default config file must exist
if defaultCfg.ConfigFile != cfg.ConfigFile {
return loadConfigError(err)
}
// Warn about missing default config file, but continue
fmt.Printf("Config file (%s) does not exist. Using defaults.\n",
cfg.ConfigFile)
} else {
// The config file exists, so attempt to parse it.
err = flags.NewIniParser(parser).ParseFile(cfg.ConfigFile)
if err != nil {
if _, ok := err.(*os.PathError); !ok {
parser.WriteHelp(os.Stderr)
return loadConfigError(err)
}
configFileError = err
}
configFile = cfg.ConfigFile
}
// Parse command line options again to ensure they take precedence.
_, err = parser.Parse()
if err != nil {
if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {
parser.WriteHelp(os.Stderr)
}
return loadConfigError(err)
}
// Create the home directory if it doesn't already exist.
funcName := "loadConfig"
err = os.MkdirAll(cfg.HomeDir, libutils.UserFilePerm)
if err != nil {
// Show a nicer error message if it's because a symlink is linked to a
// directory that does not exist (probably because it's not mounted).
if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt.Errorf(str, e.Path, link)
}
}
return nil, fmt.Errorf("%s: failed to create home directory: %v", funcName, err)
}
// If a non-default appdata folder is specified, it may be necessary to
// adjust the LogDir.
if defaultCfg.HomeDir != cfg.HomeDir {
if defaultCfg.LogDir == cfg.LogDir {
cfg.LogDir = filepath.Join(cfg.HomeDir, defaultLogDirname)
}
}
// Warn about missing config file after the final command line parse
// succeeds. This prevents the warning on help messages and invalid
// options.
if configFileError != nil {
return loadConfigError(configFileError)
}
logRotators = nil
cfg.LogDir = cleanAndExpandPath(cfg.LogDir)
// Initialize log rotation. After log rotation has been initialized, the
// logger variables may be used. This creates the LogDir if needed.
if cfg.MaxLogZips < 0 {
cfg.MaxLogZips = 0
}
if cfg.Network != "" && libutils.ToNetworkType(cfg.Network) == libutils.Unknown {
return loadConfigError(fmt.Errorf("network type is not supported: %s", cfg.Network))
}
// Parse, validate, and set debug log level(s).
if cfg.Quiet {
cfg.DebugLevel = "error"
}
// Special show command to list supported subsystems and exit.
if cfg.DebugLevel == "show" {
fmt.Println("Supported subsystems", supportedSubsystems())
os.Exit(0)
}
// Parse, validate, and set debug log level(s).
if err := parseAndSetDebugLevels(cfg.DebugLevel); err != nil {
err = fmt.Errorf("%s: %v", funcName, err.Error())
parser.WriteHelp(os.Stderr)
return loadConfigError(err)
}
log.Debugf("Log folder: %s", cfg.LogDir)
log.Debugf("Config file: %s", configFile)
return &cfg, nil
}
// cleanAndExpandPath expands environment variables and leading ~ in the passed
// path, cleans the result, and returns it.
func cleanAndExpandPath(path string) string {
// NOTE: The os.ExpandEnv doesn't work with Windows cmd.exe-style
// %VARIABLE%, but the variables can still be expanded via POSIX-style
// $VARIABLE.
path = os.ExpandEnv(path)
if !strings.HasPrefix(path, "~") {
return filepath.Clean(path)
}
// Expand initial ~ to the current user's home directory, or ~otheruser to
// otheruser's home directory. On Windows, both forward and backward
// slashes can be used.
path = path[1:]
var pathSeparators string
if runtime.GOOS == "windows" {
pathSeparators = string(os.PathSeparator) + "/"
} else {
pathSeparators = string(os.PathSeparator)
}
userName := ""
if i := strings.IndexAny(path, pathSeparators); i != -1 {
userName = path[:i]
path = path[i:]
}
homeDir := ""
var u *user.User
var err error
if userName == "" {
u, err = user.Current()
} else {
u, err = user.Lookup(userName)
}
if err == nil {
homeDir = u.HomeDir
}
// Fallback to CWD if user lookup fails or user has no home directory.
if homeDir == "" {
homeDir = "."
}
return filepath.Join(homeDir, path)
}