-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
557 lines (472 loc) · 11.1 KB
/
types.go
File metadata and controls
557 lines (472 loc) · 11.1 KB
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/exp/slices"
"gopkg.in/yaml.v3"
)
type Note struct {
Id uuid.UUID `yaml:"id"`
Title string `yaml:"title"`
Alias string `yaml:"alias,omitempty"`
Attachments []Attachment `yaml:"attachments,omitempty"`
Versions []string `yaml:"versions"`
Tags []string `yaml:"tags,omitempty"`
VirtualTags []string `yaml:"-"`
DateCreated time.Time `yaml:"created"`
DateModified []time.Time `yaml:"modified,omitempty"`
DateDeleted time.Time `yaml:"deleted,omitempty"`
latestContent []byte
}
type NoteFilter struct {
TagsInclude []string
TagsExclude []string
CreatedAfter time.Time
CreatedBefore time.Time
ModifiedAfter time.Time
ModifiedBefore time.Time
IncludeDeleted bool
IsDeleted bool
HasFile bool
Notes []string
Aliases []string
}
type NoteAliases map[string]uuid.UUID
// I guess, not in use
type Metadata struct {
Id uuid.UUID `yaml:"id"`
Title string `yaml:"title"`
Tags []string `yaml:"tags,omitempty"`
Attachments []Attachment `yaml:"attachments,omitempty"`
Versions []string `yaml:"-"`
DateCreated time.Time `yaml:"created"`
DateModified []time.Time `yaml:"modified,omitempty"`
DateDeleted time.Time `yaml:"deleted,omitempty"`
}
type Config struct {
AliasesPath string
NotercPath string
DataDir string
Editor string
NoteDir string
TempDir string
TemplateDir string
TerminalReader string
FileManager string
VersionTimeFormat string
OutputTimeFormatShort string
OutputTimeFormatLong string
FilePermission os.FileMode
FilePermissionReadonly os.FileMode
DirPermission os.FileMode
}
type Attachment struct {
Filename string `yaml:"filename"`
Sha1 string `yaml:"sha1"`
DateCreated time.Time `yaml:"dateCreated"`
}
// checks if note exists
func (n Note) Exists() bool {
if _, err := os.Stat(filepath.Clean(notemanager.NoteDir + "/" + n.Id.String())); errors.Is(err, os.ErrNotExist) {
return false
} else {
return true
}
}
// write yaml encoded note struct to data file
func (n Note) WriteData() (err error) {
err = os.WriteFile(filepath.Clean(notemanager.NoteDir+"/"+n.Id.String()+"/data"), n.Yaml(), 0600)
if err != nil {
log.Fatal(err)
}
return
}
// encode note struct to yaml
func (n Note) Yaml() (encodedYaml []byte) {
encodedYaml, err := yaml.Marshal(n)
if err != nil {
log.Fatal(err)
}
return
}
func newNote(noteId string) (n Note, err error) {
id, err := uuid.Parse(noteId)
if err != nil {
// check if abbreviated uuid
if isUuidAbbr(noteId) == false {
err = errors.New("Invalid note syntax")
return
}
id, err = uuidByAbbr(noteId)
if err != nil {
err = errors.New("Note not found")
return
}
}
n.Id = id
/* err = n.Metadata()
if err != nil {
fmt.Println("err: ", err)
} */
//n.Title = n.Meta.Title
//fmt.Println(n)
return
}
func (n Note) Content(version ...string) (content []byte, err error) {
var v string
if len(version) > 1 {
log.Fatal("Method Note.Content: Too many arguments in call")
}
if len(version) == 0 {
v = n.LatestVersion()
}
if len(version) == 1 {
v = version[0]
}
//fmt.Println(notemanager.NoteDir + "/" + n.Id.String() + "/" + v)
content, err = os.ReadFile(filepath.Clean(notemanager.NoteDir + "/" + n.Id.String() + "/" + v))
if err != nil {
return
}
return
}
// returns a Note struct from a note YAML file
func loadNote(id string) (n Note, err error) {
yml, err := os.ReadFile(filepath.Clean(notemanager.NoteDir + "/" + id + "/data"))
if err != nil {
return
}
err = yaml.Unmarshal(yml, &n)
if err != nil {
log.Fatal(err)
}
n.latestContent, err = n.Content()
// build virtual tags
if n.DateCreated.Year() == time.Now().Year() {
_, nWeek := n.DateCreated.ISOWeek()
_, curWeek := time.Now().ISOWeek()
n.VirtualTags = append(n.VirtualTags, `YEAR`)
if n.DateCreated.Month() == time.Now().Month() {
n.VirtualTags = append(n.VirtualTags, `MONTH`)
}
if n.DateCreated.YearDay() == time.Now().YearDay() {
n.VirtualTags = append(n.VirtualTags, `TODAY`)
}
if n.DateCreated.YearDay()+1 == time.Now().YearDay() {
n.VirtualTags = append(n.VirtualTags, `YESTERDAY`)
}
if nWeek == curWeek {
n.VirtualTags = append(n.VirtualTags, `WEEK`)
}
}
if n.DateDeleted.IsZero() == false {
n.VirtualTags = append(n.VirtualTags, `DELETED`)
}
if len(n.DateModified) > 0 {
n.VirtualTags = append(n.VirtualTags, `MODIFIED`)
}
if len(n.Tags) > 0 {
n.VirtualTags = append(n.VirtualTags, `TAGGED`)
}
if len(n.Attachments) > 0 {
n.VirtualTags = append(n.VirtualTags, `FILE`)
}
return
}
// creates text output of note.
func (n Note) Output(version string) (b []byte) {
tpl := `+
+ Title: %s
+ Date: %s
+
+ Tags: %s
+ Attachments: %d
+ Version: %s
+
%s
`
content, err := n.Content(version)
if err != nil {
log.Fatal(err)
}
s := fmt.Sprintf(tpl,
n.Title,
n.DateCreated,
strings.Join(n.Tags, ", "),
len(n.Attachments),
//n.Versions[len(n.Versions)-1],
version,
content,
)
b = []byte(s)
return
}
// Mark a note as deleted by setting the DateDeleted value to current time stamp.
func (n Note) Delete() (err error) {
if n.DateDeleted != (time.Time{}) {
return
}
n.DateDeleted = time.Now().UTC()
err = n.WriteData()
return
}
// Delete the DateDeleted value and save to data file
func (n Note) Undelete() (err error) {
n.DateDeleted = time.Time{}
err = n.WriteData()
return
}
// UUIDs are long and clumsy
func (n Note) ShortId() (s string) {
return n.Id.String()[0:8]
}
// Checks if note matches the given filter.
func (n Note) MatchesFilter(filter NoteFilter) (ret bool, err error) {
if filter.IncludeDeleted == false {
if n.DateDeleted.IsZero() == false {
ret = false
return
}
}
// Must have tags
for _, x := range filter.TagsInclude {
exists := false
// explicit note tags
for _, t := range n.Tags {
if t == x {
exists = true
continue
}
}
// virtual note tags
for _, t := range n.VirtualTags {
if t == x {
exists = true
continue
}
}
if exists == false {
ret = false
return
}
}
// Must not have tags
for _, x := range filter.TagsExclude {
exists := false
// explicit note tags
for _, t := range n.Tags {
if t == x {
exists = true
continue
}
}
// virtual note tags
for _, t := range n.VirtualTags {
if t == x {
exists = true
continue
}
}
if exists == true {
ret = false
return
}
}
// check if in supplied notes
if len(filter.Notes) > 0 {
if slices.Contains(filter.Notes, n.Id.String()) == false {
ret = false
return
}
}
// check timestamps
// created.before
if filter.CreatedBefore.IsZero() == false {
if n.DateCreated.After(filter.CreatedBefore) {
ret = false
return
}
}
// created.after
if filter.CreatedAfter.IsZero() == false {
if n.DateCreated.Before(filter.CreatedAfter) {
ret = false
return
}
}
// modified.before
if filter.ModifiedBefore.IsZero() == false {
var modified time.Time
if len(n.DateModified) == 0 {
modified = n.DateCreated
} else {
modified = n.DateModified[len(n.DateModified)-1]
}
if modified.After(filter.ModifiedBefore) {
ret = false
return
}
}
// modified.after
if filter.ModifiedAfter.IsZero() == false {
var modified time.Time
if len(n.DateModified) == 0 {
modified = n.DateCreated
} else {
modified = n.DateModified[len(n.DateModified)-1]
}
if modified.Before(filter.ModifiedAfter) {
ret = false
return
}
}
ret = true
return
}
// add tags to note. if one of the notes already exist
// the single tag is skipped, but the other tags are added
func (n *Note) AddTags(t []string) error {
for _, v := range t {
if regexp.MustCompile(`^[\pL0-9]+$`).MatchString(v) == false {
return fmt.Errorf("Error: Tags must be alphanumeric")
}
if slices.Contains(n.Tags, v) {
continue
}
n.Tags = append(n.Tags, v)
}
return nil
}
// removes tags from note. if one of the notes does not exist
// the other notes are still removed
func (n *Note) RemoveTags(t []string) {
RESTART:
for k, v := range n.Tags {
if slices.Contains(t, v) {
n.Tags = slices.Delete(n.Tags, k, k+1)
// slice has changed, could be out of bounds.
// Therefore loop through it again.
goto RESTART
}
}
}
func (n *Note) AddTag(t string) error {
return n.AddTags([]string{t})
}
func (n *Note) RemoveTag(t string) {
n.RemoveTags([]string{t})
}
func (n *Note) RemoveAlias() {
n.Alias = ""
}
func (n *Note) SetAlias(str string) {
n.Alias = str
}
// returns path of note: $NoteDir/$UUID
func (n Note) Path() string {
return filepath.Clean(notemanager.NoteDir + `/` + n.Id.String())
}
// returns latest version of note
func (n Note) LatestVersion() string {
return n.Versions[len(n.Versions)-1]
}
// moves temporary note from tempDir to specific note directory inside noteDir
func (n Note) moveTmpFile() (err error) {
oldFile := filepath.Clean(notemanager.TempDir + `/` + n.Id.String())
newFile := filepath.Clean(n.Path() + `/` + n.LatestVersion())
os.MkdirAll(n.Path(), notemanager.DirPermission)
err = os.Rename(oldFile, newFile)
return
}
// Load aliases yaml file
func (a *NoteAliases) Load() (err error) {
yml, err := os.ReadFile(filepath.Clean(notemanager.DataDir + "/aliases"))
if err != nil {
Exit(err.Error())
return
}
err = yaml.Unmarshal(yml, &a)
if err != nil {
log.Fatal(err)
}
return
}
func (a *NoteAliases) Write() (err error) {
err = os.WriteFile(filepath.Clean(notemanager.DataDir+"/aliases"), a.Yaml(), 0600)
if err != nil {
log.Fatal(err)
}
return
}
// encode NoteAliases struct to yaml
func (a *NoteAliases) Yaml() (encodedYaml []byte) {
encodedYaml, err := yaml.Marshal(a)
if err != nil {
log.Fatal(err)
}
return
}
// Check if Alias exists
func (a NoteAliases) Get(needle string) (id uuid.UUID, exists bool) {
id, exists = a[needle]
return
}
// Delete alias from map
func (a *NoteAliases) Delete(needle string) {
delete(*a, needle)
}
// Add alias to map
func (a *NoteAliases) Set(alias string, noteId uuid.UUID) {
if regexp.MustCompile(`^[\pL0-9]+$`).MatchString(alias) == false {
Exit("Error: Alias must consist of letters or numbers")
}
blocklist := []string{
"",
"add",
"alias",
"delete",
"edit",
"list",
"modify",
"search",
"tags",
"version",
"versions",
}
if slices.Contains(blocklist, alias) {
Exit("Cannot set alias: " + alias)
}
if isUuidAbbr(alias) {
Exit("Alias must not be uuid")
}
if _, err := uuid.Parse(alias); err == nil {
Exit("Alias must not be uuid")
}
a.DeleteById(noteId)
(*a)[alias] = noteId
}
// Find alias by uuid and return slice of alias strings
func (a *NoteAliases) FindById(noteId uuid.UUID) (ret []string) {
for alias, id := range *a {
if noteId == id {
ret = append(ret, alias)
}
}
return
}
// Delete all aliases of note
func (a *NoteAliases) DeleteById(noteId uuid.UUID) {
for alias, id := range *a {
if noteId == id {
delete(*a, alias)
}
}
return
}