-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (76 loc) · 1.3 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
93
94
95
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
)
func getStorageDirectory() string {
usr, _ := user.Current()
path := filepath.Join(usr.HomeDir, ".kv")
return path
}
func ensureDirectory() string {
path := getStorageDirectory()
os.MkdirAll(path, os.ModePerm)
return path
}
func list() {
path := ensureDirectory()
files, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
}
func set(key, value string) {
keyFile := filepath.Join(ensureDirectory(), key)
f, err := os.Create(keyFile)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if value == "" {
io.Copy(f, os.Stdin)
} else {
f.WriteString(value)
}
}
func get(key string) {
keyFile := filepath.Join(ensureDirectory(), key)
f, err := os.Open(keyFile)
if err != nil {
return
}
defer f.Close()
io.Copy(os.Stdout, f)
}
func main() {
var args = os.Args
fi, _ := os.Stdin.Stat()
if (fi.Mode() & os.ModeCharDevice) == 0 {
// if there is a piped stdin, assume its a set command.
if len(args) < 2 {
log.Fatal("specify a key")
} else {
set(args[1], "")
}
} else {
switch len(args) {
case 1:
// list
list()
case 2:
// get
get(args[1])
case 3:
// set
set(args[1], args[2])
}
}
}