PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 6ms RepoModel.GetById 34ms app.codeStats 0ms

/lsr/lsr.go

https://code.google.com/p/rbits/
Go | 88 lines | 63 code | 10 blank | 15 comment | 14 complexity | e5c243f494ca89daddaa74df5b9e001c MD5 | raw file
 1// Permission to use, copy, modify, and/or distribute this software for
 2// any purpose is hereby granted, provided this notice appear in all copies.
 3
 4/*
 5Lsr: list recursively.
 6	lsr [-d | -fd] [name ...]
 7
 8For each directory argument, lsr recursively lists the contents of the
 9directory; for each file argument, lsr repeats its name. When no argument
10is given, the current directory is listed.
11
12Options:
13    -d  only print directories
14    -fd print both files and directories
15    -l  list in long format; name mode mtime size
16*/
17package main
18
19import (
20	"flag"
21	"fmt"
22	"log"
23	"os"
24	"path/filepath"
25
26	_ "code.google.com/p/rbits/log"
27)
28
29var (
30	flagD  = flag.Bool("d", false, "only print directories")
31	flagFD = flag.Bool("fd", false, "print both files and directories")
32	flagL  = flag.Bool("l", false, "long format")
33)
34
35var usageString = `usage: lsr [-d | -fd | -l] [name ...]
36Options:
37`
38
39func usage() {
40	fmt.Fprint(os.Stderr, usageString)
41	flag.PrintDefaults()
42	os.Exit(1)
43}
44
45func prname(path string, f os.FileInfo) error {
46	if f.IsDir() && path[len(path)-1] != '/' {
47		path = path + "/"
48	}
49	if *flagL {
50		mode := f.Mode() & 0x1FF
51		size := f.Size()
52		mtime := f.ModTime().Unix()
53		fmt.Printf("%s %o %v %v\n", path, mode, mtime, size)
54		return nil
55	}
56	fmt.Println(path)
57	return nil
58}
59
60func pr(path string, f os.FileInfo, err error) error {
61	if err != nil {
62		log.Println(err)
63		return nil
64	}
65	if *flagFD {
66		return prname(path, f)
67	}
68	if *flagD && f.IsDir() {
69		return prname(path, f)
70	}
71	if !*flagD && !f.IsDir() {
72		return prname(path, f)
73	}
74	return nil
75}
76
77func main() {
78	flag.Usage = usage
79	flag.Parse()
80
81	if flag.NArg() == 0 {
82		filepath.Walk(".", pr)
83		return
84	}
85	for _, v := range flag.Args() {
86		filepath.Walk(v, pr)
87	}
88}