blob: 35ad1722c3bf92b52a4d31a95add9ed34bf16232 [file] [log] [blame]
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +02001package source
2
3import (
4 "fmt"
5 "io/ioutil"
6 "os"
7 "strings"
8)
9
10type LocalSource struct {
11 root string
12}
13
14func NewLocal(root string) Source {
15 return &LocalSource{
16 root: strings.TrimRight(root, "/"),
17 }
18}
19
20func (s *LocalSource) resolve(path string) (string, error) {
21 if !strings.HasPrefix(path, "//") {
22 return "", fmt.Errorf("invalid path %q, expected // prefix", path)
23 }
24 path = path[2:]
25 if strings.HasPrefix(path, "/") {
26 return "", fmt.Errorf("invalid path %q, expected // prefix", path)
27 }
28
29 return s.root + "/" + path, nil
30}
31
32func (s *LocalSource) IsFile(path string) (bool, error) {
33 path, err := s.resolve(path)
34 if err != nil {
35 return false, err
36 }
37 stat, err := os.Stat(path)
38 if err != nil {
39 if os.IsNotExist(err) {
40 return false, nil
41 }
42 return false, fmt.Errorf("os.Stat(%q): %w", path, err)
43 }
44 return !stat.IsDir(), nil
45}
46
47func (s *LocalSource) ReadFile(path string) ([]byte, error) {
48 path, err := s.resolve(path)
49 if err != nil {
50 return nil, err
51 }
52 // TODO(q3k): limit size
53 return ioutil.ReadFile(path)
54}
55
56func (s *LocalSource) IsDirectory(path string) (bool, error) {
57 path, err := s.resolve(path)
58 if err != nil {
59 return false, err
60 }
61 stat, err := os.Stat(path)
62 if err != nil {
63 if os.IsNotExist(err) {
64 return false, nil
65 }
66 return false, fmt.Errorf("os.Stat(%q): %w", path, err)
67 }
68 return stat.IsDir(), nil
69}
70
71func (s *LocalSource) CacheSet(dependencies []string, key string, value interface{}) {
72 // Swallow writes. The local filesystem can always change underneath us and
73 // we're not tracking anything, so we cannot ever keep caches.
74}
75
76func (s *LocalSource) CacheGet(key string) interface{} {
77 return nil
78}