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.
This commit is contained in:
Dave Collins 2013-09-18 00:13:36 -05:00
parent f2190d21dd
commit 465327c62d
2 changed files with 28 additions and 0 deletions

View File

@ -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.

View File

@ -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
; ------------------------------------------------------------------------------