forked from wrouesnel/p2cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_filters.go
78 lines (67 loc) · 2.22 KB
/
custom_filters.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
package main
import (
"fmt"
"github.com/flosch/pongo2"
"os"
)
// This noop filter is registered in place of custom filters which otherwise
// passthru their input (our file filters). This allows debugging and testing
// without running file operations.
func filterNoopPassthru(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return in, nil
}
// This noop filter is registered in place of custom filters which otherwise
// produce no output.
func filterNoop(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return nil, nil
}
// This filter writes the content of its input to the filename specified as its
// argument. The templated content is returned verbatim.
func filterWriteFile(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
if !in.IsString() {
return nil, &pongo2.Error{
Sender: "filter:write_file",
ErrorMsg: "Filter input must be of type 'string'.",
}
}
if !param.IsString() {
return nil, &pongo2.Error{
Sender: "filter:write_file",
ErrorMsg: "Filter parameter must be of type 'string'.",
}
}
f, err := os.OpenFile(param.String(), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.FileMode(0777))
if err != nil {
return nil, &pongo2.Error{
Sender: "filter:write_file",
ErrorMsg: fmt.Sprintf("Could not open file for output: %s", err.Error()),
}
}
defer f.Close()
_, werr := f.WriteString(in.String())
if werr != nil {
return nil, &pongo2.Error{
Sender: "filter:write_file",
ErrorMsg: fmt.Sprintf("Could not write file for output: %s", werr.Error()),
}
}
return in, nil
}
// This filter makes a directory based on the value of its argument. It passes
// through any content without alteration. This allows chaining with write-file.
func filterMakeDirs(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
if !param.IsString() {
return nil, &pongo2.Error{
Sender: "filter:make_dirs",
ErrorMsg: "Filter parameter must be of type 'string'.",
}
}
err := os.MkdirAll(param.String(), os.FileMode(0777))
if err != nil {
return nil, &pongo2.Error{
Sender: "filter:make_dirs",
ErrorMsg: fmt.Sprintf("Could not create directories: %s %s", in.String(), err.Error()),
}
}
return in, nil
}