Last active
April 18, 2019 14:05
-
-
Save olivernadj/33d3c6af234cedc26d9f91b32ea594cb to your computer and use it in GitHub Desktop.
Simplified golang implementation of tree - the recursive directory listing program that produces a depth indented listing of files
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 ( | |
"flag" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"os" | |
"path" | |
) | |
type TaskConfig struct { | |
DirOnly bool | |
Dirname string | |
Level int64 | |
Writer io.Writer | |
} | |
func main() { | |
dirOnly := flag.Bool("d", false, "List directories only.") | |
level := flag.Int64("L", 0, "Max display depth of the directory tree.") | |
outfile := flag.String("o", "", "Send output to filename.") | |
usageInfo := flag.Bool("h", false, "Prints usage information") | |
flag.Usage = func() { | |
fmt.Fprintf(os.Stderr, "Usage: %s [options] [<dir>]\nOptions are:\n", os.Args[0]) | |
flag.PrintDefaults() | |
} | |
flag.Parse() | |
if *usageInfo == true { | |
flag.Usage() | |
os.Exit(0) | |
} | |
tc := TaskConfig{ | |
DirOnly:*dirOnly, | |
Level:*level, | |
} | |
if flag.NArg() == 0 { | |
tc.Dirname, _ = os.Getwd() | |
} else { | |
tc.Dirname = flag.Arg(0) | |
} | |
if *outfile != "" { | |
f, err := os.Create(*outfile) | |
check(err) | |
defer f.Close() | |
tc.Writer = f | |
} else { | |
tc.Writer = os.Stdout | |
} | |
tc.nestedList(1, tc.Dirname) | |
} | |
func (tc TaskConfig) nestedList(cl int64, cd string) { | |
if cl == 1 { | |
_, err := fmt.Fprintf(tc.Writer, "%s\n", cd) | |
check(err) | |
} | |
files, err := ioutil.ReadDir(cd) | |
check(err) | |
for _, f := range files { | |
if tc.DirOnly == false || f.IsDir() == true { | |
_, err := fmt.Fprintf(tc.Writer, "%s%s\n", spaces(cl*2), f.Name()) | |
check(err) | |
} | |
if f.IsDir() && (tc.Level == 0 || tc.Level > cl) { | |
tc.nestedList(cl+1, path.Join(cd, f.Name())) | |
} | |
} | |
} | |
func spaces(n int64) string { | |
b := make([]byte, n) | |
for i := range b { | |
b[i] = ' ' | |
} | |
return string(b) | |
} | |
func check(err error) { | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error: %v\n", err) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment