diff --git a/dir/dir.go b/dir/dir.go new file mode 100644 index 0000000..6a523b8 --- /dev/null +++ b/dir/dir.go @@ -0,0 +1,66 @@ +package dir + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" +) + +func check(err error) { + if err != nil { + panic(err) + } +} + +func createEmptyFile(p string) { + check(os.WriteFile(p, []byte(""), 0700)) +} + +func Dir() { + dirPath := "/tmp/gobyex-tempdir" + err := os.Mkdir(dirPath, 0700) + check(err) + defer os.RemoveAll(dirPath) + + createEmptyFile(filepath.Join(dirPath, "file1")) + + check(os.MkdirAll(filepath.Join(dirPath, "child", "grandchild"), 0700)) + + createEmptyFile(filepath.Join(dirPath, "child", "grandchild", "file1")) + createEmptyFile(filepath.Join(dirPath, "child", "grandchild", "file2")) + createEmptyFile(filepath.Join(dirPath, "child", "grandchild", "file3")) + + check(os.Mkdir(filepath.Join(dirPath, "child", "grandchild", "dir1"), 0700)) + + entries, err := os.ReadDir(filepath.Join(dirPath, "child", "grandchild")) + check(err) + + fmt.Println("Lisitng", filepath.Join(dirPath, "child", "grandchild")) + for _, entry := range entries { + fmt.Printf("%s, is dir? %t\n", entry.Name(), entry.IsDir()) + } + + check(os.Chdir(dirPath)) + + entries, err = os.ReadDir(".") + check(err) + + fmt.Println("Listing", dirPath) + for _, entry := range entries { + fmt.Printf("%s, is dir? %t\n", entry.Name(), entry.IsDir()) + } + + fmt.Println("Walking the file tree at", dirPath) + // WalkDir is more efficient than Walk + check(filepath.WalkDir(".", walk)) +} + +func walk(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + fmt.Println(" ", p, "is dir?", d.IsDir()) + return nil +} diff --git a/main.go b/main.go index b3ebc0b..5ec042c 100644 --- a/main.go +++ b/main.go @@ -37,7 +37,8 @@ package main // import "git.sangeeth.dev/gobyexample/files" // import "git.sangeeth.dev/gobyexample/linefilter" // import "git.sangeeth.dev/gobyexample/exit" -import "git.sangeeth.dev/gobyexample/filepath" +// import "git.sangeeth.dev/gobyexample/filepath" +import "git.sangeeth.dev/gobyexample/dir" func main() { // runes.Runes() @@ -77,5 +78,6 @@ func main() { // files.Files() // linefilter.LineFilter() // exit.Exit() - filepath.Filepath() + // filepath.Filepath() + dir.Dir() }