1
0
mirror of https://github.com/rclone/rclone.git synced 2025-12-06 00:03:32 +00:00

Factor ShellExpand from sftp backend to lib/env

This commit is contained in:
Nick Craig-Wood
2019-05-10 22:07:36 +01:00
parent edda6d91cd
commit 5c0e5b85f7
3 changed files with 56 additions and 17 deletions

23
lib/env/env.go vendored Normal file
View File

@@ -0,0 +1,23 @@
// Package env contains functions for dealing with environment variables
package env
import (
"os"
homedir "github.com/mitchellh/go-homedir"
)
// ShellExpand replaces a leading "~" with the home directory" and
// expands all environment variables afterwards.
func ShellExpand(s string) string {
if s != "" {
if s[0] == '~' {
newS, err := homedir.Expand(s)
if err == nil {
s = newS
}
}
s = os.ExpandEnv(s)
}
return s
}

31
lib/env/env_test.go vendored Normal file
View File

@@ -0,0 +1,31 @@
package env
import (
"os"
"testing"
homedir "github.com/mitchellh/go-homedir"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestShellExpand(t *testing.T) {
home, err := homedir.Dir()
require.NoError(t, err)
require.NoError(t, os.Setenv("EXPAND_TEST", "potato"))
defer func() {
require.NoError(t, os.Unsetenv("EXPAND_TEST"))
}()
for _, test := range []struct {
in, want string
}{
{"", ""},
{"~", home},
{"~/dir/file.txt", home + "/dir/file.txt"},
{"/dir/~/file.txt", "/dir/~/file.txt"},
{"~/${EXPAND_TEST}", home + "/potato"},
} {
got := ShellExpand(test.in)
assert.Equal(t, test.want, got, test.in)
}
}