summaryrefslogtreecommitdiff
path: root/data/datasource_file.go
blob: 175f92f0f97da86a4c71fde1622b6d6a9ec24721 (plain)
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
package data

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/url"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/afero"

	"github.com/pkg/errors"
)

func readFile(source *Source, args ...string) ([]byte, error) {
	if source.fs == nil {
		source.fs = afero.NewOsFs()
	}

	p := filepath.FromSlash(source.URL.Path)

	if len(args) == 1 {
		parsed, err := url.Parse(args[0])
		if err != nil {
			return nil, err
		}

		if parsed.Path != "" {
			p = filepath.Join(p, parsed.Path)
		}
	}

	// make sure we can access the file
	i, err := source.fs.Stat(p)
	if err != nil {
		return nil, errors.Wrapf(err, "Can't stat %s", p)
	}

	if strings.HasSuffix(p, string(filepath.Separator)) {
		source.mediaType = jsonArrayMimetype
		if i.IsDir() {
			return readFileDir(source, p)
		}
		return nil, errors.Errorf("%s is not a directory", p)
	}

	f, err := source.fs.OpenFile(p, os.O_RDONLY, 0)
	if err != nil {
		return nil, errors.Wrapf(err, "Can't open %s", p)
	}

	defer f.Close()

	b, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, errors.Wrapf(err, "Can't read %s", p)
	}
	return b, nil
}

func readFileDir(source *Source, p string) ([]byte, error) {
	names, err := afero.ReadDir(source.fs, p)
	if err != nil {
		return nil, err
	}
	files := make([]string, len(names))
	for i, v := range names {
		files[i] = v.Name()
	}

	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	if err := enc.Encode(files); err != nil {
		return nil, err
	}
	b := buf.Bytes()
	// chop off the newline added by the json encoder
	return b[:len(b)-1], nil
}