forked from gopasspw/gopass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tempdir.go
79 lines (69 loc) · 1.35 KB
/
tempdir.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
package fsutil
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
type tempfile struct {
dir string
dev string
fh *os.File
dbg bool
}
// TempFiler is a tempfile interface
type TempFiler interface {
io.WriteCloser
Name() string
Remove() error
}
// TempFile returns a new tempfile wrapper
func TempFile(prefix string) (TempFiler, error) {
td, err := ioutil.TempDir(tempdirBase(), prefix)
if err != nil {
return nil, err
}
tf := &tempfile{
dir: td,
}
if gdb := os.Getenv("GOPASS_DEBUG"); gdb == "true" {
tf.dbg = true
}
if err := tf.mount(); err != nil {
_ = os.RemoveAll(tf.dir)
return nil, err
}
fn := filepath.Join(tf.dir, "tempfile")
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return nil, fmt.Errorf("Failed to open file %s: %s", fn, err)
}
tf.fh = fh
return tf, nil
}
func (t *tempfile) Name() string {
if t.fh == nil {
return ""
}
return t.fh.Name()
}
func (t *tempfile) Write(p []byte) (int, error) {
if t.fh == nil {
return 0, fmt.Errorf("not initialized")
}
return t.fh.Write(p)
}
func (t *tempfile) Close() error {
if t.fh == nil {
return nil
}
return t.fh.Close()
}
func (t *tempfile) Remove() error {
_ = t.Close()
if err := t.unmount(); err != nil {
return fmt.Errorf("Failed to unmount %s from %s: %s", t.dev, t.dir, err)
}
return os.RemoveAll(t.dir)
}