-
-
Save caojunxyz/25459b227a10cf1cfd8568c42bc766a4 to your computer and use it in GitHub Desktop.
Two methods of traverse directory with golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func exclude(dir, path string) bool { | |
rel, _ := filepath.Rel(dir, path) | |
segs := strings.Split(rel, fmt.Sprintf("%c", os.PathSeparator)) | |
if segs[0] == ".git" || segs[0] == ".idea" { | |
return true | |
} | |
name := filepath.Base(path) | |
if name == ".DS_Store" { | |
return true | |
} | |
return false | |
} | |
func getFileList(dir string) []string { | |
list := make([]string, 0) | |
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if info.IsDir() { | |
return nil | |
} | |
if exclude(dir, path) { | |
return nil | |
} | |
list = append(list, path) | |
return nil | |
}) | |
return list | |
} | |
func readDirAll(dir string) []string { | |
list := make([]string, 0) | |
var f func(string, string) | |
f = func(root string, rel string) { | |
files, err := ioutil.ReadDir(filepath.Join(root, rel)) | |
if err != nil { | |
panic(err) | |
} | |
for _, file := range files { | |
if file.IsDir() { | |
f(root, filepath.Join(rel, file.Name())) | |
continue | |
} | |
path := filepath.Join(root, rel, file.Name()) | |
if exclude(root, path) { | |
continue | |
} | |
list = append(list, path) | |
} | |
} | |
f(dir, ".") | |
return list | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment