Created
May 22, 2021 08:17
-
-
Save Yapcheekian/3f2b5189160b51ca633af703531e1e74 to your computer and use it in GitHub Desktop.
Tree command implemented in go
This file contains 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/ioutil" | |
"log" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
args := []string{"."} | |
if len(os.Args) > 1 { | |
args = os.Args[1:] | |
} | |
for _, arg := range args { | |
err := tree(arg, "") | |
if err != nil { | |
log.Printf("tree %s: %v\n", arg, err) | |
} | |
} | |
} | |
func tree(root, indent string) error { | |
fi, err := os.Stat(root) | |
if err != nil { | |
return fmt.Errorf("could not stat %s: %v", root, err) | |
} | |
fmt.Println(fi.Name()) | |
if !fi.IsDir() { | |
return nil | |
} | |
fis, err := ioutil.ReadDir(root) | |
if err != nil { | |
return fmt.Errorf("could not read directory %s: %v", root, err) | |
} | |
for i, fi := range fis { | |
add := "│ " | |
if i == len(fis)-1 { | |
fmt.Printf(indent + "└──") | |
add = " " | |
} else { | |
fmt.Printf(indent + "├──") | |
} | |
if fi.Name()[0] == '.' { | |
continue | |
} | |
if err := tree(filepath.Join(root, fi.Name()), indent+add); err != nil { | |
return err | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment