blob: e901f452da43b0639feffaf2bba6290dcdbe66d6 [file] [log] [blame]
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +02001package source
2
3import (
Sergiusz Bazanskif157b4d2020-04-10 17:39:43 +02004 "context"
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +02005 "fmt"
6 "io/ioutil"
7 "os"
8 "strings"
9)
10
11type LocalSource struct {
12 root string
13}
14
15func NewLocal(root string) Source {
16 return &LocalSource{
17 root: strings.TrimRight(root, "/"),
18 }
19}
20
21func (s *LocalSource) resolve(path string) (string, error) {
22 if !strings.HasPrefix(path, "//") {
23 return "", fmt.Errorf("invalid path %q, expected // prefix", path)
24 }
25 path = path[2:]
26 if strings.HasPrefix(path, "/") {
27 return "", fmt.Errorf("invalid path %q, expected // prefix", path)
28 }
29
30 return s.root + "/" + path, nil
31}
32
Sergiusz Bazanskif157b4d2020-04-10 17:39:43 +020033func (s *LocalSource) IsFile(ctx context.Context, path string) (bool, error) {
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +020034 path, err := s.resolve(path)
35 if err != nil {
36 return false, err
37 }
38 stat, err := os.Stat(path)
39 if err != nil {
40 if os.IsNotExist(err) {
41 return false, nil
42 }
43 return false, fmt.Errorf("os.Stat(%q): %w", path, err)
44 }
45 return !stat.IsDir(), nil
46}
47
Sergiusz Bazanskif157b4d2020-04-10 17:39:43 +020048func (s *LocalSource) ReadFile(ctx context.Context, path string) ([]byte, error) {
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +020049 path, err := s.resolve(path)
50 if err != nil {
51 return nil, err
52 }
53 // TODO(q3k): limit size
54 return ioutil.ReadFile(path)
55}
56
Sergiusz Bazanskif157b4d2020-04-10 17:39:43 +020057func (s *LocalSource) IsDirectory(ctx context.Context, path string) (bool, error) {
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +020058 path, err := s.resolve(path)
59 if err != nil {
60 return false, err
61 }
62 stat, err := os.Stat(path)
63 if err != nil {
64 if os.IsNotExist(err) {
65 return false, nil
66 }
67 return false, fmt.Errorf("os.Stat(%q): %w", path, err)
68 }
69 return stat.IsDir(), nil
70}
71
Sergiusz Bazanskif157b4d2020-04-10 17:39:43 +020072func (s *LocalSource) WebLinks(fpath string) []WebLink {
73 gitURL := fmt.Sprintf(FlagGitwebURLPattern, "master", fpath)
74 return []WebLink{
Serge Bazanskibc0d3cb2021-03-06 20:49:00 +000075 WebLink{Kind: "source", LinkLabel: "master", LinkURL: gitURL},
Sergiusz Bazanskif157b4d2020-04-10 17:39:43 +020076 }
Sergiusz Bazanskic881cf32020-04-08 20:03:12 +020077}