-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmodel.go
434 lines (390 loc) · 10.9 KB
/
model.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
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
package keg
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/rwxrob/choose"
"github.com/rwxrob/fs"
"github.com/rwxrob/fs/file"
"github.com/rwxrob/json"
"github.com/rwxrob/keg/kegml"
"github.com/rwxrob/term"
)
const IsoDateFmt = `2006-01-02 15:04:05Z`
const IsoDateExpStr = `\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\dZ`
// Local contains a name to full path mapping for kegs stored locally.
type Local struct {
Name string
Path string
}
// DexEntry represents a single line in an index (usually the changes.md
// or nodes.tsv file). All three fields are always required.
type DexEntry struct {
U time.Time // updated
T string // title
N int // node id (also see ID)
HBeg int // start of highlighted
HEnd int // end of highlighted
}
// Update gets the entry for the target keg at kegpath by looking up the
// latest change to any file within it and parsing the title.
func (e *DexEntry) Update(kegpath string) error {
var err error
dir := filepath.Join(kegpath, e.ID())
_, i := fs.LatestChange(dir)
if i != nil {
e.U = i.ModTime()
}
e.T, err = kegml.ReadTitle(filepath.Join(dir, `README.md`))
return err
}
// MarshalJSON produces JSON text that contains one DexEntry per line
// that has not been HTML escaped (unlike the default) and that uses
// a consistent DateTime format. Note that the (broken) encoding/json
// encoder is not used at all.
func (e *DexEntry) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 0, 0))
buf.WriteRune('{')
buf.WriteString(`"U":"` + e.U.Format(IsoDateFmt) + `",`)
buf.WriteString(`"N":` + strconv.Itoa(e.N) + `,`)
buf.WriteString(`"T":"` + json.Escape(e.T) + `"`)
buf.WriteRune('}')
return buf.Bytes(), nil
}
func (e *DexEntry) TSV() string {
return fmt.Sprintf("%v\t%v\t%v", e.N, e.U.Format(IsoDateFmt), e.T)
}
// ID returns the node identifier as a string instead of an integer.
// Returns an empty string if unable to parse the integer.
func (e *DexEntry) ID() string { return strconv.Itoa(e.N) }
// MD returns the entry as a single Markdown list item for inclusion in
// the dex/nodex.md file:
//
// 1. Second last changed in UTC in ISO8601 (RFC3339)
// 2. Current title (always first line of README.md)
// 2. Unique node integer identifier
//
// Note that the second of last change is based on *any* file within the
// node directory changing, not just the README.md or meta files.
func (e *DexEntry) MD() string {
return fmt.Sprintf(
"* %v [%v](../%v)",
e.U.Format(IsoDateFmt),
e.T, e.N,
)
}
// String implements fmt.Stringer interface as MD.
func (e DexEntry) String() string { return e.MD() }
// Asinclude returns a KEGML include link list item without the time
// suitable for creating include blocks in node files.
func (e *DexEntry) AsInclude() string {
return fmt.Sprintf("* [%v](../%v)", e.T, e.N)
}
// Pretty returns a string with pretty colors.
func (e *DexEntry) Pretty() string {
nwidth := len(e.ID())
text := e.T
if e.HBeg > 0 || e.HEnd > 0 {
before := e.T[0:e.HBeg]
hilight := e.T[e.HBeg:e.HEnd]
after := e.T[e.HEnd:]
text = before + term.Red + hilight + term.White + after
}
return fmt.Sprintf(
"%v%v %v%-"+strconv.Itoa(nwidth)+"v %v%v%v\n",
term.Black, e.U.Format(`2006-01-02 15:04Z`),
term.Green, e.N,
term.White, text,
term.Reset,
)
}
// -------------------------------- Dex -------------------------------
// Dex is a collection of DexEntry structs. This allows mapping methods
// for its serialization to different output formats.
type Dex []*DexEntry
// MarshalJSON produces JSON text that contains one DexEntry per line
// that has not been HTML escaped (unlike the default).
func (d *Dex) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 0, 0))
buf.WriteString("[")
for _, entry := range *d {
byt, _ := entry.MarshalJSON()
buf.Write(byt)
buf.WriteString(",\n")
}
byt := buf.Bytes()
byt[len(byt)-2] = ']'
return byt, nil
}
// Lookup does a linear search through the Dex for one with the passed
// id and if found returns, otherwise returns nil.
func (d Dex) Lookup(id int) *DexEntry {
for i, node := range d {
if node.N == id {
return d[i]
}
}
return nil
}
// String fulfills the fmt.Stringer interface as JSON. Any error returns
// a "null" string.
func (e Dex) String() string { return e.TSV() }
// MD renders the entire Dex as a Markdown list suitable for the
// standard dex/changes.md file.
func (e Dex) MD() string {
var str string
for _, entry := range e {
str += entry.MD() + "\n"
}
return str
}
// AsIncludes renders the entire Dex as a KEGML include list (markdown
// bulleted list) and cab be useful from within editing sessions to
// include from the current keg without leaving the terminal editor.
func (e Dex) AsIncludes() string {
var str string
for _, entry := range e {
str += entry.AsInclude() + "\n"
}
return str
}
// TSV renders the entire Dex as a loadable tab-separated values file.
func (e Dex) TSV() string {
var str string
for _, entry := range e {
str += entry.TSV() + "\n"
}
return str
}
// Last returns the DexEntry with the highest integer value identifier.
func (d Dex) Last() *DexEntry {
last := new(DexEntry)
for _, e := range d {
if e.N > last.N {
last = e
}
}
return last
}
// LastChanged returns the highest integer value identifier.
func (d Dex) LastChanged() *DexEntry {
last := new(DexEntry)
for _, e := range d {
if e.U.After(last.U) {
last = e
}
}
return last
}
// LastIdString returns Last as string.
func (d Dex) LastIdString() string { return strconv.Itoa(d.Last().N) }
// LastIdWidth returns width of Last integer identifier.
func (d Dex) LastIdWidth() int { return len(d.LastIdString()) }
// LastChangedIdString returns Last as string.
func (d Dex) LastChangedIdString() string { return strconv.Itoa(d.LastChanged().N) }
// LastChangedIdWidth returns width of Last integer identifier.
func (d Dex) LastChangedIdWidth() int { return len(d.LastChangedIdString()) }
// Pretty returns a string with pretty color string with no time stamps
// rendered in more readable way.
func (d Dex) Pretty() string {
var str string
nwidth := d.LastIdWidth()
for _, e := range d {
text := e.T
if e.HBeg > 0 || e.HEnd > 0 {
before := e.T[0:e.HBeg]
hilight := e.T[e.HBeg:e.HEnd]
after := e.T[e.HEnd:]
text = before + term.Red + hilight + term.White + after
}
str += fmt.Sprintf(
"%v%"+strconv.Itoa(nwidth)+"v %v%v%v\n",
term.Green, e.N,
term.White, text,
term.Reset,
)
}
return str
}
// PrettyLines returns Pretty but each line separate and without line
// return.
func (d Dex) PrettyLines() []string {
lines := make([]string, 0, len(d))
nwidth := d.LastIdWidth()
for _, e := range d {
text := e.T
if e.HBeg > 0 || e.HEnd > 0 {
before := e.T[0:e.HBeg]
hilight := e.T[e.HBeg:e.HEnd]
after := e.T[e.HEnd:]
text = before + term.Red + hilight + term.White + after
}
lines = append(lines, fmt.Sprintf(
"%v%-"+strconv.Itoa(nwidth)+"v %v%v%v",
term.Green, e.N,
term.White, text,
term.Reset,
))
}
return lines
}
// ByID sorts the Dex from lowest to highest node ID integer. A pointer
// to self is returned for convenience.
func (d Dex) ByID() Dex {
sort.Slice(d, func(i, j int) bool {
return d[i].N < d[j].N
})
return d
}
// ByChanges sorts the Dex from most recently changed to oldest. A pointer
// to self is returned for convenience.
func (d Dex) ByChanges() Dex {
sort.Slice(d, func(i, j int) bool {
return d[i].U.After(d[j].U)
})
return d
}
// Add appends the entry to the Dex.
func (d *Dex) Add(entry *DexEntry) {
(*d) = append((*d), entry)
}
// WithTitleText returns a new Dex from self with all nodes that do not
// contain the text substring in the title filtered out.
func (e *Dex) WithTitleText(keyword string) Dex {
dex := Dex{}
for _, d := range *e {
i := strings.Index(strings.ToLower(d.T), strings.ToLower(keyword))
if i >= 0 {
d.HBeg = i
d.HEnd = i + len(keyword)
dex = append(dex, d)
}
}
return dex
}
// WithTitleTextExp returns a new Dex from self with all nodes that do not
// contain the regular expression matches in the title filtered out.
func (e *Dex) WithTitleTextExp(re *regexp.Regexp) Dex {
dex := Dex{}
for _, d := range *e {
i := re.FindStringIndex(d.T)
if i != nil {
d.HBeg = i[0]
d.HEnd = i[1]
dex = append(dex, d)
}
}
return dex
}
// ChooseWithTitleText returns a single *DexEntry for the keyword
// passed. If there are more than one then user is prompted to choose
// from list sent to the terminal.
func (d *Dex) ChooseWithTitleText(key string) *DexEntry {
hits := d.WithTitleText(key)
switch len(hits) {
case 1:
return hits[0]
case 0:
return nil
default:
i, _, err := choose.From(hits.PrettyLines())
if err != nil {
return nil
}
if i < 0 {
return nil
}
return hits[i]
}
}
// ChooseWithTitleTextExp returns a single *DexEntry for the regular
// expression matches passed. If there are more than one then user is
// prompted to choose from list sent to the terminal.
func (d *Dex) ChooseWithTitleTextExp(re *regexp.Regexp) *DexEntry {
hits := d.WithTitleTextExp(re)
switch len(hits) {
case 1:
return hits[0]
case 0:
return nil
default:
i, _, err := choose.From(hits.PrettyLines())
if err != nil {
return nil
}
if i < 0 {
return nil
}
return hits[i]
}
}
// Random returns a random entry.
func (d Dex) Random() *DexEntry {
rand.Seed(time.Now().UnixNano())
i := rand.Intn(len(d))
return d[i]
}
// Delete removes the specified entry shrinking the slice without
// changing the underlying size of the supporting array while
// maintaining references to each DexEntry. Note that the persisted
// content node directory may still exist. This method only affects the
// Dex itself. Stops at first match.
func (d *Dex) Delete(entry *DexEntry) {
var index int
for i, it := range *d {
if it == entry || it.N == entry.N {
index = i
break
}
}
for i := index; i < len(*d)-1; i++ {
(*d)[i] = (*d)[i+1]
}
(*d) = (*d)[:len(*d)-1]
}
// ----------------------------- TagsList -----------------------------
type TagsMap map[string][]string
func (tl TagsMap) String() string {
var str string
for k, v := range tl {
str += k + " " + strings.Join(v, " ") + "\n"
}
return str
}
func (tl TagsMap) MarshalText() ([]byte, error) {
var str string
for k, v := range tl {
str += k + " " + strings.Join(v, " ") + "\n"
}
return []byte(str), nil
}
//Write writes the marshaled text of a TagsMap to the file at path.
func (tl TagsMap) Write(path string) error {
return file.Overwrite(path, tl.String())
}
// UnmarshalText parses the tag lines items from the bytes buffer and
// sets the key pair for that tag to the values overwriting any that
// were already set.
func (tl TagsMap) UnmarshalText(buf []byte) error {
s := bufio.NewScanner(strings.NewReader(string(buf)))
for s.Scan() {
line := s.Text()
f := strings.Split(line, " ")
switch len(f) {
case 0:
return fmt.Errorf(_InvalidTagLine, line)
case 1:
return nil
default:
tl[f[0]] = f[1:]
}
}
return nil
}