utils: add common function to match the directory layer

This commit is contained in:
oscarzhou 2022-12-28 14:38:14 +13:00
parent 7f2afd1bdb
commit 889b7a4ca2
2 changed files with 19 additions and 8 deletions

View File

@ -22,8 +22,6 @@ func NewListVolumeSubTask(cfg *configs.Config) *ListVolumeSubTask {
func (task *ListVolumeSubTask) Execute() error {
utils.HighlightPrint(fmt.Sprintf("Volume path: %s", task.Config.VolumePath))
volumeLength := lenPath(task.Config.VolumePath)
volumeList := []string{" "}
filepath.WalkDir(task.Config.VolumePath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
@ -35,8 +33,7 @@ func (task *ListVolumeSubTask) Execute() error {
}
if d.IsDir() {
dirLength := lenPath(path)
if volumeLength+1 == dirLength {
if utils.MatchPathLength(task.Config.VolumePath, path, 1) {
volumeList = append(volumeList, d.Name())
}
}
@ -52,7 +49,3 @@ func (task *ListVolumeSubTask) Execute() error {
func (task *ListVolumeSubTask) String() string {
return "List Volumes"
}
func lenPath(path string) int {
return len(strings.Split(path, string(filepath.Separator)))
}

18
go/utils/path.go Normal file
View File

@ -0,0 +1,18 @@
package utils
import (
"path/filepath"
"strings"
)
// MatchPathLength matches the length of target path separated by path separator
// to the length of base path separated by path separator plus offset
func MatchPathLength(basePath, targetPath string, offset int) bool {
basePathLength := len(strings.Split(basePath, string(filepath.Separator)))
targetPathLength := len(strings.Split(targetPath, string(filepath.Separator)))
if basePathLength+offset == targetPathLength {
return true
}
return false
}