-
Notifications
You must be signed in to change notification settings - Fork 18
/
local.go
90 lines (73 loc) · 1.88 KB
/
local.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
package local
import (
"context"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs"
securejoin "github.com/cyphar/filepath-securejoin"
"io/ioutil"
"os"
"path/filepath"
)
type Local struct {
root string
cwd string
}
func New(root string) *Local {
return &Local{
root: root,
cwd: "/",
}
}
func (lfs *Local) Chdir(path string) {
lfs.cwd = path
}
func (lfs *Local) Stat(ctx context.Context, path string) (*fs.FileInfo, error) {
pivotedPath, err := lfs.Pivot(path)
if err != nil {
return nil, err
}
fileInfo, err := os.Stat(pivotedPath)
if err != nil {
return nil, err
}
return &fs.FileInfo{IsDir: fileInfo.IsDir()}, nil
}
func (lfs *Local) Get(ctx context.Context, path string) ([]byte, error) {
pivotedPath, err := lfs.Pivot(path)
if err != nil {
return nil, err
}
return ioutil.ReadFile(pivotedPath)
}
func (lfs *Local) ReadDir(ctx context.Context, path string) ([]string, error) {
pivotedPath, err := lfs.Pivot(path)
if err != nil {
return nil, err
}
fileInfos, err := ioutil.ReadDir(pivotedPath)
if err != nil {
return nil, err
}
var result []string
for _, fileInfo := range fileInfos {
result = append(result, fileInfo.Name())
}
return result, nil
}
func (lfs *Local) Join(elem ...string) string {
return filepath.Join(elem...)
}
func (lfs *Local) Pivot(path string) (string, error) {
// To make Starlark scripts cross-platform, load statements are expected to always use slashes,
// but to actually make this work on non-Unix platforms we need to adapt the path
// to the current platform
adaptedPath := filepath.FromSlash(path)
// Pivot around current directory
//
// This doesn't need to be secure since as security
// is already guaranteed by the SecureJoin below.
cwdPath := filepath.Join(lfs.cwd, adaptedPath)
// Pivot around root
//
// This needs to be secure to avoid lfs.root breakout.
return securejoin.SecureJoin(lfs.root, cwdPath)
}