-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
92 lines (83 loc) · 1.72 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"sort"
"strings"
)
func plainList(m map[string][]string, v []string) {
for _, value := range v {
for _, file := range m[value] {
fmt.Println(file)
}
}
}
func nestedList(m map[string][]string, v []string) {
for i, value := range v {
fmt.Println(v[i])
for _, file := range m[value] {
fmt.Println(" - ", file)
}
}
}
func jsonList(m map[string][]string) {
j, err := json.Marshal(m)
if err != nil {
log.Panicf("Error marshalling JSON. %s", err)
}
fmt.Printf("%s", j)
}
func main() {
wd, err := os.Getwd()
if err != nil {
msg := fmt.Sprintf("An error occured getting the current working directory.\n%s", err)
fmt.Println(msg)
os.Exit(1)
}
dir, err := ioutil.ReadDir(wd)
if err != nil {
msg := fmt.Sprintf("An error occured reading the current working directory.\n%s", err)
fmt.Println(msg)
os.Exit(1)
}
var m = make(map[string][]string)
for _, file := range dir {
if !file.IsDir() {
fileName := file.Name()
ext := strings.Split(fileName, ".")
if len(ext) > 1 {
m[ext[len(ext)-1]] = append(m[ext[len(ext)-1]], fileName)
}
if len(ext) == 1 {
m["no-ext"] = append(m["no-ext"], fileName)
}
}
}
for ext := range m {
sort.Strings(m[ext])
}
values := reflect.ValueOf(m).MapKeys()
var extensions []string
for _, value := range values {
extensions = append(extensions, value.String())
}
sort.Strings(extensions)
if len(os.Args) > 1 {
switch arg := os.Args[1]; arg {
case "plain":
plainList(m, extensions)
case "nested":
nestedList(m, extensions)
case "json":
jsonList(m)
default:
fmt.Println("Usage: gls [plain|nested|json]")
}
} else {
nestedList(m, extensions)
}
}