/
main.go
339 lines (290 loc) · 6.33 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"github.com/BurntSushi/toml"
"github.com/codegangsta/cli"
"github.com/skratchdot/open-golang/open"
)
const (
RC_FILE = ".chickenheadrc"
DEFAULT_SNIPPET_DIR = ".chickenhead"
)
var (
app *cli.App
conf *Config
)
type Config struct {
SnippetDirectory string
Editor string
}
func (c *Config) String() string {
return fmt.Sprintf("%#v\n", c)
}
func setSubCommands() {
app.Commands = []cli.Command{
{
Name: "add",
Aliases: []string{"a"},
Usage: "add a new snippet",
Action: add,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "s",
Usage: "read contents from Standard Input",
},
},
},
{
Name: "delete",
Aliases: []string{"d"},
Usage: "delete a snippet",
Action: delete,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "f",
Usage: "force delete",
},
},
},
{
Name: "edit",
Aliases: []string{"e"},
Usage: "edit a snippet",
Action: edit,
},
{
Name: "list",
Aliases: []string{"l"},
Usage: "list up available snippets",
Action: list,
},
{
Name: "view",
Aliases: []string{"v"},
Usage: "view a snippet",
Action: view,
},
{
Name: "search",
Aliases: []string{"s"},
Usage: "search snippets",
Action: search,
},
}
}
// add is a subcommand to create a new snippet.
func add(c *cli.Context) {
snippetName := c.Args().First()
if len(snippetName) == 0 {
log.Fatal("please enter snippet name")
}
s := NewSnippet(conf.SnippetDirectory, snippetName)
if s.Exists() {
log.Fatal("This snippet already exists.")
}
stdinFlag := c.Bool("s")
switch {
case stdinFlag:
// read contents from standard input
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
// write contents to snippet
s.Write(buf)
default:
f, err := s.Create()
if err != nil {
log.Fatal(err)
}
f.Close()
openSnippetWithEditor(s)
}
}
// delete is a subcommand to delete a snippet.
func delete(c *cli.Context) {
force := c.Bool("f")
snippetName := c.Args().First()
if len(snippetName) == 0 {
log.Fatal("please enter snippet name")
}
s := NewSnippet(conf.SnippetDirectory, snippetName)
if !s.Exists() {
log.Fatal("This snippet doesn't exists.")
}
if !force {
reader := bufio.NewReader(os.Stdin)
fmt.Print("sure you want to delete %s [yn]?")
ret, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
if ret != "y\n" {
return
}
}
if err := s.Delete(); err != nil {
log.Fatal(err)
}
fmt.Printf("%s has been deleted.\n", snippetName)
}
// edit is subcommand to edit a snippet with an editor.
func edit(c *cli.Context) {
snippetName := c.Args().First()
if len(snippetName) == 0 {
log.Fatal("please enter snippet name")
}
s := NewSnippet(conf.SnippetDirectory, snippetName)
if !s.Exists() {
log.Fatal("snippet not found :", s.Path)
}
openSnippetWithEditor(s)
}
// list is a subcommand to list up snippets.
// It just finds snippet files in the snippet directory and listed them.
func list(c *cli.Context) {
var pattern *regexp.Regexp
var err error
query := c.Args().First()
if len(query) > 0 {
pattern, err = regexp.Compile(fmt.Sprintf(".*%s.*", query))
if err != nil {
log.Fatal(err)
}
}
err = filepath.Walk(
conf.SnippetDirectory,
func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
rel, err := filepath.Rel(conf.SnippetDirectory, path)
if pattern != nil {
if pattern.MatchString(rel) {
fmt.Println(rel)
}
return nil
}
fmt.Println(rel)
return nil
},
)
if err != nil {
log.Fatal(err)
}
}
// view is a subcommand to show contents of a snippet.
func view(c *cli.Context) {
snippetName := c.Args().First()
if len(snippetName) == 0 {
log.Fatal("please enter snippet name")
}
s := NewSnippet(conf.SnippetDirectory, snippetName)
if !s.Exists() {
log.Fatal("snippet not found :", s.Path)
}
contents, err := s.ReadContents()
if err != nil {
log.Fatal(err)
}
fmt.Print(contents)
}
// serch is a subcommand to searche snippets whose contents contains the query with pt or ag.
func search(c *cli.Context) {
var cmd *exec.Cmd
query := c.Args().First()
if len(query) == 0 {
log.Fatal("please enter search query")
}
switch {
case commandExists("pt"):
cmd = exec.Command("pt", "-i", query, conf.SnippetDirectory)
case commandExists("ag"):
cmd = exec.Command("ag", query, conf.SnippetDirectory)
default:
log.Fatal("the_platinum_searcher(pt) or the_silver_searcher(ag) is required.")
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// When query is not matched, both commands return an error,
// so the error is ignored here.
_ = cmd.Run()
}
func loadConfig(homeDir string) *Config {
rcFilePath := filepath.Join(homeDir, RC_FILE)
cf := new(Config)
// read config values if a rc file exists.
if exists(rcFilePath) {
f, err := os.Open(rcFilePath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
if _, err := toml.Decode(string(b), cf); err != nil {
log.Fatal(err)
}
}
// set default values if empty.
if len(cf.SnippetDirectory) == 0 {
cf.SnippetDirectory = filepath.Join(homeDir, DEFAULT_SNIPPET_DIR)
}
return cf
}
func openSnippetWithEditor(s *Snippet) {
if len(conf.Editor) > 0 {
err := open.RunWith(s.Path, conf.Editor)
if err != nil {
log.Fatalf("can't open %s with %s. please check your settings.", s.Path, conf.Editor)
}
} else {
err := open.Run(s.Path)
if err != nil {
log.Fatalf("can't open %s. please check your settings.", s.Path)
}
}
}
func commandExists(cmdName string) bool {
_, err := exec.LookPath(cmdName)
return err == nil
}
// exists checks a file exists or not.
func exists(filePath string) bool {
_, err := os.Stat(filePath)
return err == nil
}
func mkDir(dirPath string) {
if err := os.MkdirAll(dirPath, 0777); err != nil {
if !os.IsExist(err) {
log.Fatal(err)
}
}
}
func getHomeDir() string {
var err error
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
return usr.HomeDir
}
func main() {
conf = loadConfig(getHomeDir())
app = cli.NewApp()
app.Name = "chickenhead"
app.Usage = "simple CLI snippet tool."
setSubCommands()
mkDir(conf.SnippetDirectory)
app.Run(os.Args)
}