-
Notifications
You must be signed in to change notification settings - Fork 0
/
notes.go
345 lines (301 loc) · 7.62 KB
/
notes.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
340
341
342
343
344
345
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"github.com/urfave/cli"
)
// Note holds parsed explanation and commands
type Note struct {
Explanation []string
Command []string
}
// Print outputs an indivial note explanation and command to STDOUT.
func (n *Note) Print() {
for _, line := range n.Explanation {
colorizeComment(line)
}
for _, line := range n.Command {
fmt.Println(line)
}
// Add empty newline
fmt.Println()
}
// hasData checks if there is an explanation and command set for this note.
func (n *Note) hasData() bool {
if len(n.Explanation) > 0 && len(n.Command) > 0 {
return true
}
return false
}
// findNotes looks for <query> in all notes passed in, returns matching notes.
func findNotes(notes []Note, query string) []Note {
var results []Note
Loop:
for _, note := range notes {
queryRegexp := fmt.Sprintf("(?i)%s", query)
searchRegexp, _ := regexp.Compile(queryRegexp)
for _, line := range note.Explanation {
if searchRegexp.MatchString(line) == true {
results = append(results, note)
// We already found a match, continue with the next note
continue Loop
}
}
for _, line := range note.Command {
if searchRegexp.MatchString(line) == true {
results = append(results, note)
// We already found a match, continue with the next note
continue Loop
}
}
}
return results
}
// searchAllNotes looks through all note files and prints matching notes.
func searchAllNotes(query string) {
filenames := getAllNotes()
var matchedNotes []Note
for _, filename := range filenames {
// parse filename and get a []Note
note, err := parseNoteFile(filename)
if err != nil {
log.Fatal("note did not exist")
}
// check if the notes contain our query
matches := findNotes(note, query)
for _, match := range matches {
matchedNotes = append(matchedNotes, match)
}
}
for _, note := range matchedNotes {
note.Print()
}
}
// getAllNotes returns all .txt files in the notes dir, with the extension
// removed.
func getAllNotes() []string {
path := fmt.Sprintf("%v/*.txt", getNotesDir())
matches, err := filepath.Glob(path)
if err != nil {
fmt.Printf("%v\n", err)
}
for i := 0; i < len(matches); i++ {
match := matches[i]
filename := filepath.Base(match)
baseSize := len(filename) - 4 // Strip .txt from note filenames
matches[i] = filename[:baseSize]
}
return matches
}
// showAllNotes prints out all note filenames.
func showAllNotes() {
notes := getAllNotes()
for _, note := range notes {
fmt.Println(note)
}
}
// parseNoteFile reads a file from `note` and converts that to a slice of
// `Note`s. It will return an err if the file can not be opened (for now I'm
// assuming that always means it does not exist yet).
func parseNoteFile(note string) ([]Note, error) {
path := getNote(note)
file, err := os.Open(path)
if err != nil {
// File does not exist
return nil, err
}
defer file.Close()
var notes []Note
var n Note
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
}
commentRegexp, _ := regexp.Compile("^#")
previousLine := ""
for i := 0; i < len(lines); i++ {
line := lines[i]
if i > 0 {
previousLine = lines[i-1]
}
if commentRegexp.MatchString(line) == true {
// We found a # with the preceding string being blank, which means the
// start of a new note.
if previousLine == "" {
// Only add it when it contains an explanation and command, so we don't
// add a blank note.
if n.hasData() {
notes = append(notes, n)
}
n = Note{}
}
n.Explanation = append(n.Explanation, line)
} else {
n.Command = append(n.Command, line)
}
}
// We are done going over all the lines. If the file ended without a blank
// line it was not appended yet in the loop, so do that here.
if n.hasData() {
notes = append(notes, n)
}
// Strip off ending newlines
for i, note := range notes {
// Start at the end and loop through to the first line
for iC := len(note.Command) - 1; iC > 0; iC-- {
line := note.Command[iC]
if line == "" {
note.Command = note.Command[0:iC]
notes[i] = note
} else {
// We found a non-blank string, on to the next note
break
}
}
}
return notes, nil
}
// showNote prints out a complete note file with all notes, adding a newline in
// between and leveraging colorizeComment to pretty print the explanation.
func showNote(params ...string) {
note := params[0]
notes, err := parseNoteFile(note)
if err != nil {
editOrCreateNote(note)
}
// If we received multiple parameters, the second one will be the query, we
// filter our parsed notes here.
if len(params) > 1 {
query := params[1]
notes = findNotes(notes, query)
}
for _, note := range notes {
note.Print()
}
}
// colorizeComment pretty prints a note, the comment description gets a
// different color.
func colorizeComment(line string) {
highlight := "\033[33m"
reset := "\033[0m"
fmt.Printf("%v%v%v\n", highlight, line, reset)
}
// editOrCreateNote opens <note> in your editor.
func editOrCreateNote(note string) {
path := getNote(note)
command := exec.Command(getEditor(), path)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
command.Run()
}
// getEditor checks your environment variables to see which editor you use,
// falling back to vi.
func getEditor() string {
editor := os.Getenv("EDITOR")
if len(editor) == 0 {
editor = "vi"
}
return editor
}
// getNotesDir returns the path to the configured notes
// dir, without a trailing slash
func getNotesDir() string {
notesdir := os.Getenv("NOTESDIR")
var dir string
if notesdir != "" {
dir = notesdir
} else {
// Use default location, ~/dotfiles/notes/
homedir := os.Getenv("HOME")
dir = fmt.Sprintf("%v/dotfiles/notes/", homedir)
}
return filepath.Clean(dir)
}
// getNote returns the path to the note given
func getNote(path string) string {
return fmt.Sprintf("%s/%s.txt", getNotesDir(), path)
}
func main() {
app := cli.NewApp()
app.Name = "notes"
app.Version = "0.7.0"
app.Usage = "Store your thoughts on all sorts of subjects"
app.EnableBashCompletion = true
app.BashComplete = func(c *cli.Context) {
notes := getAllNotes()
for _, note := range notes {
fmt.Println(note)
}
}
app.Action = func(c *cli.Context) error {
note := c.Args().First()
if len(c.Args()) == 0 {
// We received no arguments, equal to:
// $ notes
showAllNotes()
} else if len(c.Args()) == 1 {
// We received 1 argument, to open a specific note, equal to:
// $ notes <note>
showNote(note)
} else {
// We received 2 arguments, to open a specific note and search, equal to:
// $ notes <note> <query>
showNote(note, c.Args()[1])
}
return nil
}
app.Commands = []cli.Command{
{
Name: "list",
ShortName: "l",
Usage: "List all notes",
Action: func(c *cli.Context) error {
// $ notes list
showAllNotes()
return nil
},
},
{
Name: "new",
ShortName: "n",
Usage: "Create new note",
Action: func(c *cli.Context) error {
// $ notes new <note>
editOrCreateNote(c.Args().First())
return nil
},
},
{
Name: "edit",
ShortName: "e",
Usage: "Edit a note",
Action: func(c *cli.Context) error {
// $ notes edit <note>
// $ notes e <note>
editOrCreateNote(c.Args().First())
return nil
},
},
{
Name: "search",
ShortName: "s",
Usage: "Search through all your notes",
Action: func(c *cli.Context) error {
// $ notes search <query>
// $ notes s <query>
query := c.Args().First()
searchAllNotes(query)
return nil
},
},
}
app.Run(os.Args)
}