Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POSIX implementation of ExpandPath #36

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions pkg/utils/path.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package utils

import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
)
Expand All @@ -18,3 +20,61 @@ func ExpandPath(path string) (string, error) {
path = os.ExpandEnv(path)
return filepath.Abs(path)
}

func ExpandPathPOSIX(path string) (string, error) {
if len(path) == 0 {
return path, nil
}

if !strings.HasPrefix(path, "~") {
return filepath.Abs(os.ExpandEnv(path))
}

// [...] the characters in the tilde-prefix following the <tilde> are treated
// as a possible login name from the user database. [...].

parts := pathSegments(path)
if len(parts[0]) == 1 {
// If the login name is null (that is, the tilde-prefix contains only the tilde),
// the tilde-prefix is replaced by the value of the variable HOME. If HOME is
// unset, the results are unspecified. [continue]
home, err := os.UserHomeDir()
if err != nil {
return path, err
}

path = strings.Replace(path, "~", home, 1)

return filepath.Abs(os.ExpandEnv(path))
}

// Otherwise, the tilde-prefix shall be replaced
// by a pathname of the initial working directory associated with the login name
// obtained using the getpwnam() function as defined in the System Interfaces volume
// of POSIX.1-2017. If the system does not recognize the login name, the results are
// undefined.

// treat what follows the tilde as a potentially valid username

usr, err := user.Lookup(strings.TrimPrefix(parts[0], "~"))
if err == nil {
// replace the tilde-prefix with the user's home directory
return filepath.Abs(os.ExpandEnv(strings.Replace(path, parts[0], usr.HomeDir, 1)))
}

switch terr := err.(type) {
case user.UnknownUserError: // non existing user, move on
default: // unexpected error
return path, fmt.Errorf("ExpandPathPOSIX: got unexpected error %v", terr)
}

return os.ExpandEnv(path), nil
}

func pathSegments(path string) []string {
dir, last := filepath.Split(path)
if dir == "" {
return []string{last}
}
return append(pathSegments(filepath.Clean(dir)), last)
}
116 changes: 116 additions & 0 deletions pkg/utils/path_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package utils

import (
"fmt"
"log"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
)

func TestExpandPath(t *testing.T) {
home := getHomeDir(t)

tests := []struct {
name string
path string
want string
wantErr bool
}{
{"empty", "", "", false},
{"non existing user", "~NONEXISTING/", fmt.Sprintf("%sNONEXISTING", home), false},
{"home's subdir", "~/subdir", filepath.Join(home, "subdir"), false},
{"any path", "/patgh/to/file", "/patgh/to/file", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t2 *testing.T) {
got, err := ExpandPath(tt.path)

if tt.want == "" {
curdir, err := os.Getwd()
if err != nil {
t2.Skipf("couldn't2 get the current working directory")
}

tt.want = curdir
}

if tt.wantErr {
assert.NotNil(t2, err)
return
}

assert.Nil(t2, err)
assert.Equal(t2, tt.want, got)
})
}
}

func TestExpandPathPOSIX(t *testing.T) {
home := getHomeDir(t)

tests := []struct {
name string
path string
want string
wantErr bool
}{
{"empty", "", "", false},
{"non existing user", "~NONEXISTING/", "~NONEXISTING/", false},
{"home's subdir", "~/subdir", filepath.Join(home, "subdir"), false},
{"any path", "/patgh/to/file", "/patgh/to/file", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t2 *testing.T) {
got, err := ExpandPathPOSIX(tt.path)
if tt.wantErr {
assert.NotNil(t2, err)
return
}

assert.Nil(t2, err)
assert.Equal(t2, tt.want, got)
})
}
}

func ExampleExpandPathPOSIX() {
p, err := ExpandPathPOSIX("~/test")
if err != nil {
log.Fatal(err)
}

_, last := filepath.Split(p)
fmt.Println(last)

p, _ = ExpandPathPOSIX("~NONEXISTINGUSER/path/to/file")
fmt.Println(p)

p, _ = ExpandPathPOSIX("/path/to/file/tilde/~")
fmt.Println(p)

p, _ = ExpandPathPOSIX("")
fmt.Println(p)

p, _ = ExpandPathPOSIX("")
fmt.Println(p)

// Output:
// test
// ~NONEXISTINGUSER/path/to/file
// /path/to/file/tilde/~
//
}

func getHomeDir(t *testing.T) string {
t.Helper()

home, err := os.UserHomeDir()
if err != nil {
t.Skipf("couldn't get $HOME")
}

return home
}
Loading