From 465327c62dc458a92a8e57f6363debcd3b5fe60b Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Wed, 18 Sep 2013 00:13:36 -0500 Subject: [PATCH] Expand environment variables in datadir. This commit adds environment variable expansion and path cleaning to the data directory. This allows the user to specify data paths in the config file such as datadir=~/.btcd/data and datadir=$SOMEVAR/btcd. It also adds usage instructions and an example to the sample btcd.conf file. --- config.go | 15 +++++++++++++++ sample-btcd.conf | 13 +++++++++++++ 2 files changed, 28 insertions(+) diff --git a/config.go b/config.go index 9dae6d1b..125d6584 100644 --- a/config.go +++ b/config.go @@ -85,6 +85,20 @@ func btcdHomeDir() string { return "." } +// cleanAndExpandPath expands environement variables and leading ~ in the +// passed path, cleans the result, and returns it. +func cleanAndExpandPath(path string) string { + // Expand initial ~ to OS specific home directory. + if strings.HasPrefix(path, "~") { + homeDir := filepath.Dir(btcdHomeDir()) + path = strings.Replace(path, "~", homeDir, 1) + } + + // NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%, + // but they variables can still be expanded via POSIX-style $VARIABLE. + return filepath.Clean(os.ExpandEnv(path)) +} + // validLogLevel returns whether or not logLevel is a valid debug log level. func validLogLevel(logLevel string) bool { switch logLevel { @@ -302,6 +316,7 @@ func loadConfig() (*config, []string, error) { // All data is specific to a network, so namespacing the data directory // means each individual piece of serialized data does not have to // worry about changing names per network and such. + cfg.DataDir = cleanAndExpandPath(cfg.DataDir) cfg.DataDir = filepath.Join(cfg.DataDir, activeNetParams.netName) // Don't allow ban durations that are too short. diff --git a/sample-btcd.conf b/sample-btcd.conf index f9e9896c..02e370b5 100644 --- a/sample-btcd.conf +++ b/sample-btcd.conf @@ -1,5 +1,18 @@ [Application Options] +; ------------------------------------------------------------------------------ +; Data settings +; ------------------------------------------------------------------------------ + +; The directory to store data such as the block chain and peer addresses. The +; block chain takes several GB, so this location must have a lot of free space. +; The default is ~/.btcd/data on POSIX OSes and $APPDATA/btcd/data on Windows. +; Environment variables are expanded so they may be used. NOTE: Windows +; environment variables are typically %VARIABLE%, but they must be accessed with +; $VARIABLE here. Also, ~ is expanded to $APPDATA on Windows. +; datadir=~/.btcd/data + + ; ------------------------------------------------------------------------------ ; Network settings ; ------------------------------------------------------------------------------