Sergiusz Bazanski | c881cf3 | 2020-04-08 20:03:12 +0200 | [diff] [blame] | 1 | package source |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/ioutil" |
| 6 | "os" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | type LocalSource struct { |
| 11 | root string |
| 12 | } |
| 13 | |
| 14 | func NewLocal(root string) Source { |
| 15 | return &LocalSource{ |
| 16 | root: strings.TrimRight(root, "/"), |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | func (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 | |
| 32 | func (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 | |
| 47 | func (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 | |
| 56 | func (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 | |
| 71 | func (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 | |
| 76 | func (s *LocalSource) CacheGet(key string) interface{} { |
| 77 | return nil |
| 78 | } |