Skip to content

Commit

Permalink
Expand ~/ in whitelist paths (#931)
Browse files Browse the repository at this point in the history
Expand a path string prefixed with ~/ to the current user's home directory.

Example: if current user is `user1` with home directory in `/home/user1`,
then `~/project` -> `/home/user1/project`

It's useful to allow paths with `~/`,  so that `direnv.toml` can be reused via
dotfiles repos across systems with different standard home paths
(compare Linux `/home` and macOS `/Users`).

Feedback is welcome e.g. if/how this should be tested. For now manual
testing of prefix & exact has been done confirming that full paths as
well as `~/`-paths works.

I looked here for how to expand tilde:
 https://gist.github.com/miguelmota/9ab72c5e342f833123c0b5cfd5aca468

I also found a third party module that expands tilde
https://github.com/prep/tilde
that we can swap in instead of the `expandTildePath` method in this PR
if desired. I assumed the project would like to minimize dependencies
and made this simple function instead.

Fixes #926
  • Loading branch information
erikw committed Apr 17, 2022
1 parent 829f9a4 commit d2c5d88
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions internal/cmd/config.go
Expand Up @@ -61,6 +61,22 @@ type tomlWhitelist struct {
Exact []string
}

// Expand a path string prefixed with ~/ to the current user's home directory.
// Example: if current user is user1 with home directory in /home/user1, then
// ~/project -> /home/user1/project
// It's useful to allow paths with ~/, so that direnv.toml can be reused via
// dotfiles repos across systems with different standard home paths
// (compare Linux /home and macOS /Users).
func expandTildePath(path string) (pathExpanded string) {
pathExpanded = path
if strings.HasPrefix(path, "~/") {
if homedir, homedirErr := os.UserHomeDir(); homedirErr == nil {
pathExpanded = filepath.Join(homedir, path[2:])
}
}
return pathExpanded
}

// LoadConfig opens up the direnv configuration from the Env.
func LoadConfig(env Env) (config *Config, err error) {
config = &Config{
Expand Down Expand Up @@ -119,14 +135,16 @@ func LoadConfig(env Env) (config *Config, err error) {
return
}

config.WhitelistPrefix = append(config.WhitelistPrefix, tomlConf.Whitelist.Prefix...)
for _, path := range tomlConf.Whitelist.Prefix {
config.WhitelistPrefix = append(config.WhitelistPrefix, expandTildePath(path))
}

for _, path := range tomlConf.Whitelist.Exact {
if !(strings.HasSuffix(path, "/.envrc") || strings.HasSuffix(path, "/.env")) {
path = filepath.Join(path, ".envrc")
}

config.WhitelistExact[path] = true
config.WhitelistExact[expandTildePath(path)] = true
}

if tomlConf.SkipDotenv {
Expand Down

0 comments on commit d2c5d88

Please sign in to comment.