PageRenderTime 11ms CodeModel.GetById 1ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/lsd/lsd.go

https://code.google.com/p/simple-shell-utils/
Go | 78 lines | 63 code | 9 blank | 6 comment | 19 complexity | 0e4f23d620abcd163ecce90d899b2f39 MD5 | raw file
 1//list directories
 2//
 3// lsd(1) lists all directories in the current directory, or in the directories
 4// specified on the command line. By default it does not display directories
 5// that begin with a . such as .hg.
 6package main
 7
 8import (
 9	"os"
10	path "path/filepath"
11	"fmt"
12	"flag"
13	"log"
14)
15
16var (
17	ShowDotFiles = flag.Bool(".", false, "list hidden files as well")
18	Invert       = flag.Bool("v", false,
19		"invert: show only files that are not directories")
20)
21
22func lsd(dir string, join, hidedot bool) {
23	f, err := os.Open(dir)
24	if err != nil {
25		log.Println(err)
26		return
27	}
28
29	for {
30		stats, err := f.Readdir(100)
31		if err != nil {
32			log.Println(err)
33		}
34		if len(stats) == 0 {
35			return
36		}
37
38		for _, stat := range stats {
39			show := stat.IsDirectory()
40			if *Invert {
41				show = !show
42			}
43			if !show {
44				continue
45			}
46			if hidedot && stat.Name[0] == '.' {
47				continue
48			}
49
50			name := stat.Name
51			if join {
52				name = path.Join(dir, name)
53			}
54			fmt.Println(name)
55		}
56	}
57}
58
59//Usage: %name %flags dirnames*
60func main() {
61	log.SetFlags(0)
62	flag.Parse()
63	hide := !*ShowDotFiles
64
65	dirs := flag.Args()
66	if len(dirs) == 0 {
67		pwd, err := os.Getwd()
68		if err != nil {
69			log.Fatalln(err)
70		}
71		lsd(pwd, false, hide)
72		return
73	}
74
75	for _, dir := range dirs {
76		lsd(dir, true, hide)
77	}
78}