-
Notifications
You must be signed in to change notification settings - Fork 8
/
node.go
479 lines (414 loc) · 11.9 KB
/
node.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
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
// Copyright 2017 Atelier Disko. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto/sha1"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/fatih/color"
"github.com/mozillazg/go-unidecode"
"golang.org/x/text/unicode/norm"
)
var (
// Basenames matching this pattern are considered configuration files.
NodeMetaRegexp = regexp.MustCompile(`(?i)^(index|meta)\.(json|ya?ml)$`)
// Basenames matching this pattern are considered documents.
NodeDocsRegexp = regexp.MustCompile(`(?i)^.*\.(md|markdown|html?|txt)$`)
// Files that are not considered to be assets in addition to node
// meta and doc files.
NodeAssetsIgnoreRegexp = regexp.MustCompile(`(?i)^(dsk.*|AUTHORS\.txt|empty)$`)
// Characters that are ignored when looking up an URL,
// i.e. "foo/bar baz" and "foo/barbaz" are than equal.
NodeLookupURLIgnoreChars = regexp.MustCompile(`[\s\-_]+`)
// Patterns for extracting order number and title from a node's
// path/URL segment in the form of 06_Foo. As well as for
// "slugging" the URL/path segment.
NodePathTitleRegexp = regexp.MustCompile(`^0?(\d+)[_,-]+(.*)$`)
NodePathInvalidCharsRegexp = regexp.MustCompile(`[^A-Za-z0-9-_]`)
NodePathMultipleDashRegexp = regexp.MustCompile(`-+`)
)
// NewNode constructs a new Node using its path in the filesystem and
// initalizing fields. The initialization must finalized by using Load().
func NewNode(path string, root string) *Node {
return &Node{
root: root,
path: path,
Children: make([]*Node, 0),
meta: &NodeMeta{},
}
}
// Node represents a directory inside the design definitions tree.
type Node struct {
// Ensure node is locked for writes, when updating the node's hash
// value cache.
sync.RWMutex
// Absolute path to the design defintions tree root.
root string
// Absolute path to the node's directory.
path string
// The parent node. If this is the root node, left unset.
Parent *Node
// A list of children nodes.
Children []*Node
// Meta data as parsed from the node configuration file.
meta *NodeMeta
// Cached hash of the node.
hash []byte
}
func (n *Node) Create() error {
return os.Mkdir(n.path, 0777)
}
// CreateMeta creates a meta file in the node's directory using the
// given name as the file name. The provided NodeMeta struct, does not
// need to have its path initialized, this is done by this function.
func (n *Node) CreateMeta(name string, meta *NodeMeta) error {
n.meta = meta
n.meta.path = filepath.Join(n.path, name)
return n.meta.Create()
}
// CreateDoc creates a document in the node's directory.
func (n *Node) CreateDoc(name string, contents []byte) error {
return ioutil.WriteFile(filepath.Join(n.path, name), contents, 0666)
}
// Load node meta data from the first config file found and further
// initialize Node.
func (n *Node) Load() error {
files, err := ioutil.ReadDir(n.path)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() {
continue
}
if !NodeMetaRegexp.MatchString(f.Name()) {
continue
}
n.meta.path = filepath.Join(n.path, f.Name())
if err := n.meta.Load(); err != nil {
return err
}
return nil
}
// No node configuration found, but is optional.
return nil
}
// Hash calculates a good enough hash over all aspects of the node,
// including its children. Excludes parent in calculation, as it would
// cause an infinite loop.
func (n *Node) Hash() ([]byte, error) {
n.RLock()
if n.hash != nil {
defer n.RUnlock()
return n.hash, nil
}
n.RUnlock()
h := sha1.New()
hcom := sha1.New()
// Covers parent name changes, too.
h.Write([]byte(n.path))
// To avoid expensive calculation of asset (may be large videos)
// and doc hashes over the whole underlying files, we instead use
// the last modified file time. This also includes any meta data
// files.
m, err := n.Modified()
if err != nil {
return nil, err
}
h.Write([]byte(strconv.FormatInt(m.Unix(), 10)))
hcom.Write(h.Sum(nil))
for _, v := range n.Children {
hv, err := v.Hash()
if err != nil {
return nil, err
}
hcom.Write(hv)
}
n.Lock()
defer n.Unlock()
n.hash = hcom.Sum(nil)
return n.hash, nil
}
// Returns the normalized URL path fragment, that can be used to
// address this node i.e Input/Password.
func (n *Node) URL() string {
if n.root == n.path {
return ""
}
return normalizeNodeURL(strings.TrimPrefix(n.path, n.root+"/"))
}
// Returns the unnormalized URL path fragment.
func (n *Node) UnnormalizedURL() string {
if n.root == n.path {
return ""
}
return strings.TrimPrefix(n.path, n.root+"/")
}
// Returns the normalized and lower cased lookup URL for this node.
func (n *Node) LookupURL() string {
return NodeLookupURLIgnoreChars.ReplaceAllString(
strings.ToLower(n.URL()),
"",
)
}
// An order number, as a hint for outside sorting mechanisms.
func (n *Node) Order() uint64 {
return orderNumber(filepath.Base(n.path))
}
// Name is the basename of the file without its order number.
func (n *Node) Name() string {
return removeOrderNumber(norm.NFC.String(filepath.Base(n.path)))
}
// The node's computed title with any ordering numbers stripped off, usually for display purposes.
// We normalize the title string to make sure all special characters are represented in their composed form.
// Some filesystems store filenames in decomposed form. Using these directly in the frontend led to visual
// inconsistencies. See: https://blog.golang.org/normalization
func (n *Node) Title() string {
if n.root == n.path {
return norm.NFC.String(filepath.Base(n.root))
}
return removeOrderNumber(norm.NFC.String(filepath.Base(n.path)))
}
// Returns the full description of the node.
func (n *Node) Description() string {
return n.meta.Description
}
func (n *Node) Custom() interface{} {
return n.meta.Custom
}
// Returns a list of related nodes.
func (n *Node) Related(get NodeGetter) []*Node {
nodes := make([]*Node, 0, len(n.meta.Related))
yellow := color.New(color.FgYellow).SprintfFunc()
for _, r := range n.meta.Related {
ok, node, err := get(r)
if err != nil {
log.Printf(yellow("Skipping related in %s: %s", n.URL(), err))
continue
}
if !ok {
log.Printf(yellow("Skipping related in %s: '%s' not found in tree", n.URL(), r))
continue
}
nodes = append(nodes, node)
}
return nodes
}
// Returns an alphabetically sorted list of tags.
func (n *Node) Tags() []string {
if n.meta.Tags == nil {
return make([]string, 0)
}
tags := n.meta.Tags
sort.Strings(tags)
return tags
}
// Returns a list of keywords terms. Deprecated, will be removed once
// APIv1 search support is removed.
func (n *Node) Keywords() []string {
if n.meta.Keywords == nil {
return make([]string, 0)
}
return n.meta.Keywords
}
// Returns a list of node authors; wil use the given authors
// database to lookup information.
func (n *Node) Authors(as *Authors) []*Author {
r := make([]*Author, 0)
if n.meta.Authors == nil {
return r
}
for _, email := range n.meta.Authors {
ok, author, _ := as.Get(email)
if !ok {
author = &Author{email, ""}
}
r = append(r, author)
}
return r
}
// Modified finds the most recent modified time of the node.
//
// Modified will look at the directory's and all files modification
// times, and recursively into each contained directory's (node) and
// return the most recent time.
//
// This method has different semantics than the file system's mtime:
// Most file systems change the mtime of the directory when a new file
// or directory is created inside it, the mtime will not change when a
// file has been modified.
func (n *Node) Modified() (time.Time, error) {
var modified time.Time
d, err := os.Stat(n.path)
if err != nil {
return modified, err
}
modified = d.ModTime()
files, err := ioutil.ReadDir(n.path)
if err != nil {
return modified, err
}
for _, f := range files {
if f.IsDir() {
continue
}
if f.ModTime().After(modified) {
modified = f.ModTime()
}
}
for _, c := range n.Children {
cmodified, err := c.Modified()
if err != nil {
return modified, err
}
if cmodified.After(modified) {
modified = cmodified
}
}
return modified, nil
}
// ModifiedFromRepository uses a Repository for calculating the
// modified time. This is trying to provide a better solution for
// situations where the modified date on disk may not reflect the
// actual modification date. This is the case when the DDT was checked
// out from Git during a build process step.
func (n *Node) ModifiedFromRepository(repo *Repository) (time.Time, error) {
return repo.Modified(n.path)
}
func (n *Node) Version() string {
return n.meta.Version
}
// Asset given its basename.
func (n *Node) Asset(name string) (*NodeAsset, error) {
path := filepath.Join(n.path, name)
f, err := os.Stat(path)
if os.IsNotExist(err) || err != nil {
return nil, err
}
if f.IsDir() {
return nil, fmt.Errorf("Accessing directory as asset: %s", path)
}
return &NodeAsset{
path: filepath.Join(n.path, f.Name()),
URL: filepath.Join(n.URL(), f.Name()),
}, nil
}
// Assets aare all files inside the node directory excluding system
// files, node documents and meta files.
func (n *Node) Assets() ([]*NodeAsset, error) {
as := make([]*NodeAsset, 0)
files, err := ioutil.ReadDir(n.path)
if err != nil {
return as, err
}
for _, f := range files {
if f.IsDir() {
continue
}
if strings.HasPrefix(f.Name(), ".") {
continue
}
if NodeMetaRegexp.MatchString(f.Name()) {
continue
}
if NodeDocsRegexp.MatchString(f.Name()) {
continue
}
if NodeAssetsIgnoreRegexp.MatchString(f.Name()) {
continue
}
as = append(as, &NodeAsset{
path: filepath.Join(n.path, f.Name()),
URL: filepath.Join(n.URL(), f.Name()),
})
}
return as, nil
}
// Returns a slice of documents for this node.
//
// The provided tree URL prefix will be used to resolve and make
// relative links inside the document absolute. This is usually
// something like: /api/v1/tree
func (n *Node) Docs() ([]*NodeDoc, error) {
docs := make([]*NodeDoc, 0)
files, err := ioutil.ReadDir(n.path)
if err != nil {
return docs, err
}
for _, f := range files {
if f.IsDir() {
continue
}
if !NodeDocsRegexp.MatchString(f.Name()) {
continue
}
docs = append(docs, &NodeDoc{
path: filepath.Join(n.path, f.Name()),
})
}
return docs, nil
}
// Returns a list of crumbs. The last element is the current active
// one. Does not include a root node.
func (n *Node) Crumbs(get NodeGetter) []*Node {
nodes := make([]*Node, 0)
parts := strings.Split(strings.TrimSuffix(n.URL(), "/"), "/")
yellow := color.New(color.FgYellow).SprintfFunc()
for index, _ := range parts {
url := strings.Join(parts[:index+1], "/")
ok, node, err := get(url)
if err != nil {
log.Printf(yellow("Skipping crumb in %s: %s", n.URL(), err))
continue
}
if !ok {
log.Printf(yellow("Skipping crumb in %s: '%s' not found in tree", n.URL(), url))
continue
}
nodes = append(nodes, node)
}
return nodes
}
// "Prettifies" (and normalizes) given relative node URL. Idempotent
// function. Removes any order numbers, as well as leading and
// trailing slashes.
//
// /foo/bar/ -> foo/bar
// foo/02_bar -> foo/bar
//
// Some filesystems store paths in decomposed form. Using these in the URL
// led to URL inconsistencies between different OS. We therefore make sure
// characters are composed. See: https://blog.golang.org/normalization
func normalizeNodeURL(url string) string {
var normalized []string
for _, p := range strings.Split(url, "/") {
if p == "/" {
continue
}
p = norm.NFC.String(p)
p = removeOrderNumber(p)
p = unidecode.Unidecode(p)
p = NodePathInvalidCharsRegexp.ReplaceAllString(p, "-")
p = NodePathMultipleDashRegexp.ReplaceAllString(p, "-")
p = strings.Trim(p, "-")
normalized = append(normalized, p)
}
return strings.Join(normalized, "/")
}
func lookupNodeURL(url string) string {
return NodeLookupURLIgnoreChars.ReplaceAllString(
strings.ToLower(normalizeNodeURL(url)),
"",
)
}