Skip to content

Commit

Permalink
common: add GetParentDir() function
Browse files Browse the repository at this point in the history
  • Loading branch information
romberli committed Jan 4, 2022
1 parent fdb92c7 commit 6e1eaa3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
17 changes: 17 additions & 0 deletions common/path.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package common

import (
"errors"
"fmt"
"path/filepath"
"strings"

Expand Down Expand Up @@ -47,3 +49,18 @@ func IsAbsWindows(path string) bool {

return false
}

// GetParentDir returns the parent directory of the given path, it will not change the separate character
func GetParentDir(absPath string) (string, error) {
if !IsAbs(absPath) {
return constant.EmptyString, errors.New(fmt.Sprintf("path must be an absolute path, %s is not valid", absPath))
}

for i := len(absPath) - 1; i > constant.ZeroInt; i-- {
if absPath[i] == '/' || absPath[i] == '\\' {
return absPath[:i], nil
}
}

return constant.SlashString, nil
}
18 changes: 17 additions & 1 deletion common/path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
const (
testUnixAbsPath = "/data/mysql/data/"
testUnixRelPath = "data/mysql/"
testWindowsAbsPathA = `C:\data\mysql\data\`
testWindowsAbsPathA = `C:\data\mysql\data`
testWindowsAbsPathB = `C:/data/mysql/data/`
testWindowsRelPath = `data\mysql\data\`
)
Expand Down Expand Up @@ -48,3 +48,19 @@ func TestIsAbsWindows(t *testing.T) {
asst.True(IsAbsWindows(testWindowsAbsPathB), "test IsAbsWindows() failed")
asst.False(IsAbsWindows(testWindowsRelPath), "test IsAbsWindows() failed")
}

func TestGetParentDir(t *testing.T) {
asst := assert.New(t)

dir, err := GetParentDir(testUnixRelPath)
asst.NotNil(err, "test GetParentDir() failed")
dir, err = GetParentDir(testUnixAbsPath)
asst.Nil(err, "test GetParentDir() failed")
t.Log(dir)
dir, err = GetParentDir(testWindowsAbsPathA)
asst.Nil(err, "test GetParentDir() failed")
t.Log(dir)
dir, err = GetParentDir(testWindowsAbsPathB)
asst.Nil(err, "test GetParentDir() failed")
t.Log(dir)
}

0 comments on commit 6e1eaa3

Please sign in to comment.