-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
350 lines (304 loc) · 8.86 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
340
341
342
343
344
345
346
347
348
349
350
package main
import (
"bufio"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
)
const (
journalDirName = "notes"
tagsDirName = "tags"
defaultEditor = "nano"
)
func main() {
// Create command
createCmd := flag.NewFlagSet("create", flag.ExitOnError)
createTitle := createCmd.String("title", "", "title of the note (required)")
createBody := createCmd.String("body", "", "body of the note")
createTags := createCmd.String("tags", "", "comma-separated list of tags")
// List command
listCmd := flag.NewFlagSet("list", flag.ExitOnError)
listTag := listCmd.String("tag", "", "list entries for a specific tag")
// Tags command
tagsCmd := flag.NewFlagSet("tags", flag.ExitOnError)
tagsSearch := tagsCmd.String("search", "", "search entries by tag")
if len(os.Args) == 2 && os.Args[1] == "--help" {
printUsage()
os.Exit(0)
}
if len(os.Args) < 2 {
fmt.Println("Expected 'create', 'list', or 'tags' subcommands")
fmt.Println("Use --help for more information")
os.Exit(1)
}
switch os.Args[1] {
case "create":
createCmd.Parse(os.Args[2:])
if createCmd.Parsed() {
if *createTitle == "" && len(createCmd.Args()) == 0 {
fmt.Println("Usage: journal create [options]")
createCmd.PrintDefaults()
os.Exit(0)
}
createNote(*createTitle, *createBody, *createTags)
}
case "list":
listCmd.Parse(os.Args[2:])
if listCmd.Parsed() {
if len(listCmd.Args()) == 0 && *listTag == "" {
fmt.Println("Usage: journal list [options]")
listCmd.PrintDefaults()
os.Exit(0)
}
if *listTag != "" {
listEntriesByTag(*listTag)
} else {
listEntries()
}
}
case "tags":
tagsCmd.Parse(os.Args[2:])
if tagsCmd.Parsed() {
if len(tagsCmd.Args()) == 0 && *tagsSearch == "" {
fmt.Println("Usage: journal tags [options]")
tagsCmd.PrintDefaults()
os.Exit(0)
}
if *tagsSearch != "" {
searchEntriesByTag(*tagsSearch)
} else {
listAllTags()
}
}
default:
fmt.Println("Expected 'create', 'list', or 'tags' subcommands")
fmt.Println("Use --help for more information")
os.Exit(1)
}
}
func createNote(title, body, tags string) {
if title == "" {
fmt.Println("Error: Title is required")
os.Exit(1)
}
journalDir := getJournalDir()
tagsDir := filepath.Join(journalDir, tagsDirName)
createDirIfNotExist(journalDir)
createDirIfNotExist(tagsDir)
filename := title + ".txt"
filedir := filepath.Join(journalDir, filename)
file, err := os.Create(filedir)
if err != nil {
fmt.Printf("Error creating file: %s\n", err)
os.Exit(1)
}
defer file.Close()
w := bufio.NewWriter(file)
fmt.Fprintln(w, body)
w.Flush()
tagList := strings.Split(tags, ",")
for _, tag := range tagList {
tag = strings.TrimSpace(tag)
tagDir := filepath.Join(tagsDir, tag)
createDirIfNotExist(tagDir)
symlinkPath := filepath.Join(tagDir, filename)
if err := os.Symlink(filename, symlinkPath); err != nil {
fmt.Printf("Error creating symlink: %s\n", err)
}
}
openInEditor(filedir)
}
func listEntries() {
journalDir := getJournalDir()
entries, err := filepath.Glob(filepath.Join(journalDir, "*.txt"))
if err != nil {
fmt.Printf("Error listing entries: %s\n", err)
os.Exit(1)
}
fmt.Println("\n<#> <date>\t<size>\t<title>")
// Iterate over the journal entries
for i, entry := range entries {
// Get the modification time and title of the entry
info, err := os.Stat(entry)
if err != nil {
fmt.Printf("Error getting entry info: %s\n", err)
os.Exit(1)
}
// Prepare the timestamp
modTime := info.ModTime().Format("2006-01-02")
title := strings.TrimSuffix(filepath.Base(entry), filepath.Ext(entry))
// Get the size of the entry
size, err := getFileSize(entry)
if err != nil {
fmt.Printf("Error getting entry size: %s\n", err)
os.Exit(1)
}
// Display the entry
fmt.Printf("(%d) %s\t%s\t\"%s\"\n", i+1, modTime, size, title)
}
// Remove the redundant prompt and use promptForEntryNumber directly
entryIndex := promptForEntryNumber(len(entries))
// Open the selected journal entry in the default file editor
entry := entries[entryIndex-1]
openInEditor(entry)
}
func listAllTags() {
tagsDir := filepath.Join(getJournalDir(), tagsDirName)
entries, err := os.ReadDir(tagsDir)
if err != nil {
fmt.Printf("Error listing tags: %s\n", err)
os.Exit(1)
}
fmt.Println("All tags:")
for _, entry := range entries {
if !entry.IsDir() {
continue // Skip non-directory entries
}
name := entry.Name()
if !isHiddenOrSystemFile(name) {
fmt.Println(name)
}
}
}
func listEntriesByTag(tag string) {
tagDir := filepath.Join(getJournalDir(), tagsDirName, tag)
entries, err := filepath.Glob(filepath.Join(tagDir, "*.txt"))
if err != nil {
fmt.Printf("Error listing entries for tag '%s': %s\n", tag, err)
os.Exit(1)
}
fmt.Printf("Entries tagged with '%s':\n", tag)
displayEntries(entries)
}
func searchEntriesByTag(searchTag string) {
tagsDir := filepath.Join(getJournalDir(), tagsDirName)
entries, err := os.ReadDir(tagsDir)
if err != nil {
fmt.Printf("Error searching tags: %s\n", err)
os.Exit(1)
}
var matchingEntries []string
for _, entry := range entries {
if !entry.IsDir() || isHiddenOrSystemFile(entry.Name()) {
continue
}
if strings.Contains(entry.Name(), searchTag) {
tagDir := filepath.Join(tagsDir, entry.Name())
files, err := filepath.Glob(filepath.Join(tagDir, "*.txt"))
if err == nil {
matchingEntries = append(matchingEntries, files...)
}
}
}
fmt.Printf("Entries matching tag search '%s':\n", searchTag)
displayEntries(matchingEntries)
}
func displayEntries(entries []string) {
sort.Strings(entries)
for i, entry := range entries {
info, err := os.Stat(entry)
if err != nil {
continue
}
modTime := info.ModTime().Format("2006-01-02")
title := strings.TrimSuffix(filepath.Base(entry), filepath.Ext(entry))
size, _ := getFileSize(entry)
fmt.Printf("(%d) %s\t%s\t\"%s\"\n", i+1, modTime, size, title)
}
if len(entries) > 0 {
entryIndex := promptForEntryNumber(len(entries))
openInEditor(entries[entryIndex-1])
} else {
fmt.Println("No entries found.")
}
}
// Get the filesize in a human readable format
func getFileSize(filename string) (string, error) {
// Get the file information
info, err := os.Stat(filename)
if err != nil {
return "", err
}
// Get the size of the file in bytes
size := info.Size()
// If the size is less than 1024 bytes, return the size in bytes
if size < 1024 {
return fmt.Sprintf("%dB", size), nil
} else if size < 1024*1024 { // If the size is less than 1024 * 1024 bytes, return the size in kilobytes
return fmt.Sprintf("%.1fKB", float64(size)/1024), nil
} else if size < 1024*1024*1024 { // If the size is less than 1024 * 1024 * 1024 bytes, return the size in megabytes
return fmt.Sprintf("%.1fMB", float64(size)/1024/1024), nil
}
// If the size is more than or equal to 1024 * 1024 * 1024 bytes, return the size in gigabytes
return fmt.Sprintf("%.1fGB", float64(size)/1024/1024/1024), nil
}
func getJournalDir() string {
return filepath.Join(os.Getenv("HOME"), journalDirName, "journal")
}
func createDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
fmt.Printf("Error creating directory: %s\n", err)
os.Exit(1)
}
}
}
func openInEditor(filepath string) {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = defaultEditor
}
cmd := exec.Command(editor, filepath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Printf("Error opening editor: %s\n", err)
os.Exit(1)
}
}
func promptForEntryNumber(maxEntries int) int {
fmt.Print("\nEnter the number of the entry you want to view: ")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
entryIndex, err := strconv.Atoi(input)
if err != nil || entryIndex < 1 || entryIndex > maxEntries {
fmt.Printf("Invalid entry number: %s\n", input)
os.Exit(1)
}
return entryIndex
}
func isHiddenOrSystemFile(name string) bool {
// List of common hidden or system directories to ignore
ignoredPrefixes := []string{".", "_", "~$"}
ignoredNames := map[string]bool{
"System Volume Information": true,
"$RECYCLE.BIN": true,
"lost+found": true,
}
// Check if the name starts with any ignored prefix
for _, prefix := range ignoredPrefixes {
if strings.HasPrefix(name, prefix) {
return true
}
}
// Check if the name is in the list of ignored names
return ignoredNames[name]
}
func printUsage() {
fmt.Println("Usage:")
fmt.Println(" journal [command] [options]")
fmt.Println("\nCommands:")
fmt.Println(" create Create a new journal entry")
fmt.Println(" list List journal entries")
fmt.Println(" tags List or search tags")
fmt.Println("\nOptions:")
fmt.Println(" --help Show help information for a command")
fmt.Println("\nUse 'journal [command] --help' for more information about a command.")
}