Created
March 4, 2023 10:10
-
-
Save stevel705/c5a1428e22c97f3f410f99a485df2564 to your computer and use it in GitHub Desktop.
prints the directory tree
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
| package main | |
| import ( | |
| "fmt" | |
| "io" | |
| "io/ioutil" | |
| "os" | |
| "path/filepath" | |
| ) | |
| // listFiles() is a recursive function that prints the directory tree | |
| func listFiles(out io.Writer, path string, printFiles bool, indent string) error { | |
| //Reading contents of the directory | |
| files, err := ioutil.ReadDir(path) | |
| // error handling | |
| if err != nil { | |
| return err | |
| } | |
| // Filter files only directories | |
| if !printFiles { | |
| var files_only_dir []os.FileInfo | |
| for _, file := range files { | |
| if file.IsDir() { | |
| files_only_dir = append(files_only_dir, file) | |
| } | |
| } | |
| files = files_only_dir | |
| } | |
| // get last element in files | |
| var last os.FileInfo | |
| if len(files) > 0 { | |
| last = files[len(files)-1] | |
| } else { | |
| last = nil | |
| } | |
| for _, file := range files { | |
| if file.IsDir() { | |
| subDirectoryPath := filepath.Join(path, file.Name()) // path of the subdirectory | |
| // printing the directoty name | |
| if file == last { | |
| fmt.Fprintln(out, indent+"└───"+file.Name()) | |
| } else { | |
| fmt.Fprintln(out, indent+"├───"+file.Name()) | |
| } | |
| var new_indent string | |
| if file == last { | |
| new_indent = indent + "\t" | |
| } else { | |
| new_indent = indent + "│\t" | |
| } | |
| listFiles(out, subDirectoryPath, printFiles, new_indent) // calling listFiles() again for subdirectory | |
| } else { | |
| if printFiles { | |
| // printing the file size | |
| var sizeByte string | |
| if file.Size() == 0 { | |
| sizeByte = "(empty)" | |
| } else { | |
| sizeByte = "(" + fmt.Sprint(file.Size()) + "b)" | |
| } | |
| if file == last { | |
| fmt.Fprintln(out, indent+"└───"+file.Name()+" "+sizeByte) | |
| } else { | |
| fmt.Fprintln(out, indent+"├───"+file.Name()+" "+sizeByte) | |
| } | |
| } | |
| } | |
| } | |
| return nil | |
| } | |
| // dirTree() is a wrapper function for listFiles() | |
| func dirTree(out io.Writer, path string, printFiles bool) error { | |
| err := listFiles(out, path, printFiles, "") | |
| if err != nil { | |
| return err | |
| } | |
| return nil | |
| } | |
| func main() { | |
| out := os.Stdout | |
| if !(len(os.Args) == 2 || len(os.Args) == 3) { | |
| panic("usage go run main.go . [-f]") | |
| } | |
| path := os.Args[1] | |
| printFiles := len(os.Args) == 3 && os.Args[2] == "-f" | |
| err := dirTree(out, path, printFiles) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment