-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsource.go
More file actions
92 lines (76 loc) · 1.92 KB
/
source.go
File metadata and controls
92 lines (76 loc) · 1.92 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
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
package gozero
import (
"bytes"
"errors"
"io"
"os"
"strings"
"github.com/projectdiscovery/gozero/types"
fileutil "github.com/projectdiscovery/utils/file"
)
// Source is a source file for gozero and is meant to
// contain i/o for code execution
type Source struct {
Variables []types.Variable
Temporary bool
CloseAfterWrite bool
Filename string
File *os.File
}
func NewSource() (*Source, error) {
return NewSourceWithString("", "", "")
}
func NewSourceWithFile(src string) (*Source, error) {
if fileutil.FileExists(src) {
file, err := os.Open(src)
if err != nil {
return nil, err
}
return &Source{Filename: src, File: file}, nil
}
return nil, errors.New("file does not exist")
}
func NewSourceWithBytes(src []byte, wantedPattern, dir string) (*Source, error) {
return NewSourceWithReader(bytes.NewReader(src), wantedPattern, dir)
}
func NewSourceWithString(src, wantedPattern, dir string) (*Source, error) {
return NewSourceWithReader(strings.NewReader(src), wantedPattern, dir)
}
func NewSourceWithReader(src io.Reader, wantedPattern, dir string) (*Source, error) {
srcFile, err := os.CreateTemp(dir, wantedPattern)
if err != nil {
return nil, err
}
gfileName := srcFile.Name()
if _, err := io.Copy(srcFile, src); err != nil {
return nil, err
}
if err := srcFile.Sync(); err != nil {
return nil, err
}
if _, err := srcFile.Seek(0, 0); err != nil {
return nil, err
}
return &Source{Filename: gfileName, Temporary: true, File: srcFile}, nil
}
func (s *Source) Close() error {
if s.File != nil {
return s.File.Close()
}
return nil
}
func (s *Source) Cleanup() error {
if err := s.Close(); err != nil {
return err
}
if s.Temporary {
return os.RemoveAll(s.Filename)
}
return nil
}
func (s *Source) ReadAll() ([]byte, error) {
return os.ReadFile(s.Filename)
}
func (s *Source) AddVariable(vars ...types.Variable) {
s.Variables = append(s.Variables, vars...)
}