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 { func (task *ListVolumeSubTask) Execute() error {
utils.HighlightPrint(fmt.Sprintf("Volume path: %s", task.Config.VolumePath)) utils.HighlightPrint(fmt.Sprintf("Volume path: %s", task.Config.VolumePath))
volumeLength := lenPath(task.Config.VolumePath)
volumeList := []string{" "} volumeList := []string{" "}
filepath.WalkDir(task.Config.VolumePath, func(path string, d fs.DirEntry, err error) error { filepath.WalkDir(task.Config.VolumePath, func(path string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
@ -35,8 +33,7 @@ func (task *ListVolumeSubTask) Execute() error {
} }
if d.IsDir() { if d.IsDir() {
dirLength := lenPath(path) if utils.MatchPathLength(task.Config.VolumePath, path, 1) {
if volumeLength+1 == dirLength {
volumeList = append(volumeList, d.Name()) volumeList = append(volumeList, d.Name())
} }
} }
@ -52,7 +49,3 @@ func (task *ListVolumeSubTask) Execute() error {
func (task *ListVolumeSubTask) String() string { func (task *ListVolumeSubTask) String() string {
return "List Volumes" 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
}