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
|
package system
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"syscall"
)
// CopyFile appends [TmpfileOp] to [I].
func (sys *I) CopyFile(payload *[]byte, src string, cap int, n int64) *I {
buf := new(bytes.Buffer)
buf.Grow(cap)
sys.ops = append(sys.ops, &TmpfileOp{payload, src, n, buf})
return sys
}
// TmpfileOp reads up to n bytes from src and writes the resulting byte slice to payload.
type TmpfileOp struct {
payload *[]byte
src string
n int64
buf *bytes.Buffer
}
func (t *TmpfileOp) Type() Enablement { return Process }
func (t *TmpfileOp) apply(*I) error {
msg.Verbose("copying", t)
if t.payload == nil {
// this is a misuse of the API; do not return an error message
return errors.New("invalid payload")
}
if b, err := os.Stat(t.src); err != nil {
return newOpError("tmpfile", err, false)
} else {
if b.IsDir() {
return newOpError("tmpfile", &os.PathError{Op: "stat", Path: t.src, Err: syscall.EISDIR}, false)
}
if s := b.Size(); s > t.n {
return newOpError("tmpfile", &os.PathError{Op: "stat", Path: t.src, Err: syscall.ENOMEM}, false)
}
}
if f, err := os.Open(t.src); err != nil {
return newOpError("tmpfile", err, false)
} else if _, err = io.CopyN(t.buf, f, t.n); err != nil {
return newOpError("tmpfile", err, false)
}
*t.payload = t.buf.Bytes()
return nil
}
func (t *TmpfileOp) revert(*I, *Criteria) error { t.buf.Reset(); return nil }
func (t *TmpfileOp) Is(o Op) bool {
target, ok := o.(*TmpfileOp)
return ok && t != nil && target != nil &&
t.src == target.src && t.n == target.n
}
func (t *TmpfileOp) Path() string { return t.src }
func (t *TmpfileOp) String() string { return fmt.Sprintf("up to %d bytes from %q", t.n, t.src) }
|