Piecing together some basic directory walking techniques in Go (golang)
Python's method gives some level of completeness, Go's simpler setup means reaching for other libraries to do path operations.
Not hard, just needed to figure that out...
| package main | |
| /* Some experiments with basic directory walking in go | |
| * For my own future reference ... | |
| * | |
| * go run main.go [DIRS TO SKIP] | |
| * | |
| */ | |
| import ( | |
| "os" | |
| "fmt" | |
| "errors" | |
| "strings" | |
| "path/filepath" | |
| ) | |
| func main() { | |
| // Directory walker | |
| // NOTE: This walker will _specifically_ process folders first, then files | |
| err := filepath.Walk(os.Args[1], func(path string, info os.FileInfo, err error) error { | |
| if err != nil { | |
| return err | |
| } | |
| // Can get the base name straight fro mthe info object | |
| name := info.Name() | |
| if info.IsDir() { // Dircheck - not sure how it works for other non-dir non-file objects? | |
| for _, excname := range os.Args[2:] { | |
| if name == excname { | |
| // Do not descend into the directory | |
| return filepath.SkipDir | |
| } | |
| } | |
| for _, childpath := range []string{".git", "bin/activate"} { | |
| should_skip, err := skipIfChild(path, childpath) | |
| if err != nil { | |
| fmt.Printf("--> %v\n", err) | |
| return err | |
| } | |
| if should_skip { | |
| fmt.Printf("\n[ Skipping '%s' because it contains '%s' ]\n", path, childpath) | |
| return filepath.SkipDir | |
| } | |
| } | |
| //fmt.Printf("\n---- %s :\n", path) | |
| return nil | |
| } | |
| if strings.HasSuffix(path, ".py") || strings.HasSuffix(path, ".pyc") { | |
| return nil | |
| } | |
| // If we want to know the parent dir, need to use path splitting | |
| dirname := filepath.Dir(path) | |
| // Size in bytes | |
| fmt.Printf(" %s // %s : %v\n", dirname, name, info.Size()) | |
| return nil | |
| }) | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| } | |
| func childExists(path string, child string) (bool, error) { | |
| _, err := os.Stat(filepath.Join(path, child)) | |
| if err != nil { | |
| if errors.Is(err, os.ErrNotExist) { | |
| return false, nil | |
| } | |
| return false, fmt.Errorf("Could not stat '%s/%s' : \n", path, child, err) | |
| } | |
| return true, nil | |
| } | |
| func skipIfChild(path string, child string) (bool, error) { | |
| child_exists, err := childExists(path, child) | |
| if err != nil { | |
| return false, err | |
| } | |
| if child_exists { | |
| return true, nil | |
| } | |
| return false, nil | |
| } |