-
Notifications
You must be signed in to change notification settings - Fork 351
/
injectsnippetsfs.go
104 lines (90 loc) · 2.17 KB
/
injectsnippetsfs.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
package api
import (
"bytes"
"fmt"
"html"
"io"
"io/fs"
"time"
"github.com/treeverse/lakefs/pkg/api/params"
)
type InjectSnippetsFS struct {
fs.FS
name string
content string
}
func NewInjectIndexFS(fsys fs.FS, name string, marker string, snippets []params.CodeSnippet) (fs.FS, error) {
if len(snippets) == 0 {
// no snippets, return the original marker
return fsys, nil
}
// read the content and inject snippets
f, err := fsys.Open(name)
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
all, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", name, err)
}
// inject snippets code into content
codeSnippets := renderCodeSnippets(snippets)
contentBytes := bytes.ReplaceAll(all, []byte(marker), codeSnippets)
return &InjectSnippetsFS{
FS: fsys,
name: name,
content: string(contentBytes),
}, nil
}
func renderCodeSnippets(snippets []params.CodeSnippet) []byte {
var b bytes.Buffer
for _, item := range snippets {
_, _ = b.WriteString("<!-- snippet: " + html.EscapeString(item.ID) + " -->")
_, _ = b.WriteString(item.Code)
}
return b.Bytes()
}
func (i *InjectSnippetsFS) Open(name string) (fs.File, error) {
if name != i.name {
return i.FS.Open(name)
}
return &memFile{
at: 0,
Name: name,
data: []byte(i.content),
}, nil
}
type memFile struct {
at int64
Name string
data []byte
}
func (f *memFile) Close() error {
return nil
}
func (f *memFile) Stat() (fs.FileInfo, error) {
return &memFileFileInfo{file: f}, nil
}
func (f *memFile) Read(b []byte) (int, error) {
i := 0
dataLen := int64(len(f.data))
for f.at < dataLen && i < len(b) {
b[i] = f.data[f.at]
i++
f.at++
}
if f.at >= dataLen {
return i, io.EOF
}
return i, nil
}
type memFileFileInfo struct {
file *memFile
}
func (s *memFileFileInfo) Name() string { return s.file.Name }
func (s *memFileFileInfo) Size() int64 { return int64(len(s.file.data)) }
func (s *memFileFileInfo) Mode() fs.FileMode { return fs.ModeTemporary }
func (s *memFileFileInfo) ModTime() time.Time { return time.Time{} }
func (s *memFileFileInfo) IsDir() bool { return false }
func (s *memFileFileInfo) Sys() interface{} { return nil }