Skip to content

Commit

Permalink
✨ feat(fs): add new util func ToAbsPath() for convert path
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 16, 2023
1 parent 7797e83 commit 247c554
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
24 changes: 24 additions & 0 deletions fsutil/fsutil.go
Expand Up @@ -7,6 +7,8 @@ import (
"os"
"path/filepath"
"strings"

"github.com/gookit/goutil/internal/comfunc"
)

const (
Expand Down Expand Up @@ -97,3 +99,25 @@ func UnixPath(path string) string {
}
return strings.ReplaceAll(path, "\\", "/")
}

// ToAbsPath convert process.
//
// TIP: will don't check path
func ToAbsPath(p string) string {
if len(p) == 0 {
return ""
}
if filepath.IsAbs(p) {
return p
}

if p[0] == '~' {
return comfunc.ExpandHome(p)
}

wd, err := os.Getwd()
if err != nil {
return p
}
return filepath.Join(wd, p)
}
10 changes: 10 additions & 0 deletions fsutil/fsutil_test.go
Expand Up @@ -43,6 +43,16 @@ func TestSplitPath(t *testing.T) {
assert.Eq(t, "some.txt", file)
}

func TestToAbsPath(t *testing.T) {
assert.Eq(t, "", fsutil.ToAbsPath(""))
assert.Eq(t, "/path/to/dir/", fsutil.ToAbsPath("/path/to/dir/"))
assert.Neq(t, "~/path/to/dir", fsutil.ToAbsPath("~/path/to/dir"))
assert.Neq(t, ".", fsutil.ToAbsPath("."))
assert.Neq(t, "..", fsutil.ToAbsPath(".."))
assert.Neq(t, "./", fsutil.ToAbsPath("./"))
assert.Neq(t, "../", fsutil.ToAbsPath("../"))
}

func TestSlashPath(t *testing.T) {
assert.Eq(t, "/path/to/dir", fsutil.SlashPath("/path/to/dir"))
assert.Eq(t, "/path/to/dir", fsutil.UnixPath("/path/to/dir"))
Expand Down

0 comments on commit 247c554

Please sign in to comment.