-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser_hook.go
More file actions
61 lines (55 loc) · 1.36 KB
/
Copy pathparser_hook.go
File metadata and controls
61 lines (55 loc) · 1.36 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
package libparser
import (
"strings"
liberrors "github.com/tomefile/lib-errors"
)
// A function to be called on every Node before the parser attempts to append it to the tree.
//
// Return `nil` to discard the Node.
type Hook func(original Node) (modified Node, derr *liberrors.DetailedError)
// Discards Nodes of type T
func ExcludeHook[T Node](node Node) (Node, *liberrors.DetailedError) {
switch node.(type) {
case T:
return nil, nil
}
return node, nil
}
// Removes the UNIX shebang
func NoShebangHook(node Node) (Node, *liberrors.DetailedError) {
switch node := node.(type) {
case *NodeComment:
if strings.HasPrefix(node.Contents, "!") {
return nil, nil
}
}
return node, nil
}
// Puts the node to chan before it gets appended to the tree.
// Useful for tracking the progress of parsing in very large files.
//
// # Example usage:
//
// channel := make(chan libparser.Node)
//
// parser := libparser.New(file)
// parser.Hooks = []libparser.Hook{
// libparser.StreamHook(channel),
// }
//
// go func() {
// defer close(channel) // IMPORTANT! Without this you'll hang the process FOREVER.
// if derr := parser.Run(); derr != nil {
// ...
// }
// }()
//
// for node := range channel {
// ...
// }
func StreamHook(channel chan Node) Hook {
return func(node Node) (Node, *liberrors.DetailedError) {
channel <- node
return node, nil
}
}