-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathhandler_file.go
70 lines (60 loc) · 1.39 KB
/
handler_file.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
/*
* Copyright 2018 Dgraph Labs, Inc. All rights reserved.
*
*/
package backup
import (
"os"
"path/filepath"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
)
// fileHandler is used for 'file:' URI scheme.
type fileHandler struct {
*session
fp *os.File
}
// Open authenticates or prepares a handler session.
// Returns error on failure, nil on success.
func (h *fileHandler) Open(s *session) error {
// check that this path exists and we can access it.
if !h.Exists(s.path) {
return x.Errorf("The path %q does not exist or it is inaccessible.", s.path)
}
path := filepath.Join(s.path, s.file)
fp, err := os.Create(path)
if err != nil {
return err
}
glog.V(3).Infof("using file path: %q", path)
h.fp = fp
h.session = s
return nil
}
func (h *fileHandler) Close() error {
defer func() {
if err := h.fp.Close(); err != nil {
glog.Errorf("Failed to close file %q: %s", h.file, err)
}
}()
if err := h.fp.Sync(); err != nil {
return err
}
return nil
}
func (h *fileHandler) Write(b []byte) (int, error) {
return h.fp.Write(b)
}
// Exists checks if a path (file or dir) is found at target.
// Returns true if found, false otherwise.
func (h *fileHandler) Exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
return !os.IsNotExist(err) && !os.IsPermission(err)
}
// Register this handler
func init() {
addHandler("file", &fileHandler{})
}