-
Notifications
You must be signed in to change notification settings - Fork 4
/
namelen.go
102 lines (88 loc) · 1.64 KB
/
namelen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"unicode/utf8"
)
var (
descending = flag.Bool("d", false, "sort in descending order")
recursive = flag.Bool("r", false, "recursive")
status = 0
)
func main() {
log.SetFlags(0)
log.SetPrefix("namelen: ")
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
args = append(args, ".")
}
var fis []os.FileInfo
for _, path := range args {
fi, err := ln(path, *recursive)
if err != nil {
fmt.Fprintln(os.Stderr, "namelen:", err)
status = 1
continue
}
fis = append(fis, fi...)
}
sort.Slice(fis, func(i, j int) bool {
x := utf8.RuneCountInString(fis[i].Name())
y := utf8.RuneCountInString(fis[j].Name())
if *descending {
return x > y
}
return x < y
})
for _, fi := range fis {
fmt.Printf("%v %v", utf8.RuneCountInString(fi.Name()), fi.Name())
if fi.IsDir() {
fmt.Printf("/")
}
fmt.Println()
}
os.Exit(status)
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [options] [file/dir] ...")
flag.PrintDefaults()
os.Exit(2)
}
func ck(err error) {
if err != nil {
log.Fatal(err)
}
}
func ln(path string, recursive bool) ([]os.FileInfo, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
var fis []os.FileInfo
switch {
case !fi.IsDir():
fis = append(fis, fi)
case !recursive:
fis, err = f.Readdir(-1)
default:
filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
fis = append(fis, info)
return nil
})
}
return fis, nil
}