summaryrefslogtreecommitdiff
path: root/file/file.go
blob: 00b3acbaad64d8ad25ac3eb6e01dcbea18c6df81 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Package file contains functions for working with files and directories on the local filesystem
package file

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"github.com/hairyhenderson/gomplate/v3/internal/iohelpers"
	"github.com/pkg/errors"

	"github.com/spf13/afero"
)

// for overriding in tests
var fs = afero.NewOsFs()

// Read the contents of the referenced file, as a string.
func Read(filename string) (string, error) {
	inFile, err := fs.OpenFile(filename, os.O_RDONLY, 0)
	if err != nil {
		return "", errors.Wrapf(err, "failed to open %s", filename)
	}
	// nolint: errcheck
	defer inFile.Close()
	bytes, err := ioutil.ReadAll(inFile)
	if err != nil {
		err = errors.Wrapf(err, "read failed for %s", filename)
		return "", err
	}
	return string(bytes), nil
}

// ReadDir gets a directory listing.
func ReadDir(path string) ([]string, error) {
	f, err := fs.Open(path)
	if err != nil {
		return nil, err
	}
	i, err := f.Stat()
	if err != nil {
		return nil, err
	}
	if i.IsDir() {
		return f.Readdirnames(0)
	}
	return nil, errors.New("file is not a directory")
}

// Write the given content to the file, truncating any existing file, and
// creating the directory structure leading up to it if necessary.
func Write(filename string, content []byte) error {
	err := assertPathInWD(filename)
	if err != nil {
		return errors.Wrapf(err, "failed to open %s", filename)
	}

	fi, err := os.Stat(filename)
	if err != nil && !os.IsNotExist(err) {
		return errors.Wrapf(err, "failed to stat %s", filename)
	}
	mode := iohelpers.NormalizeFileMode(0o644)
	if fi != nil {
		mode = fi.Mode()
	}
	err = fs.MkdirAll(filepath.Dir(filename), 0o755)
	if err != nil {
		return errors.Wrapf(err, "failed to make dirs for %s", filename)
	}
	inFile, err := fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
	if err != nil {
		return errors.Wrapf(err, "failed to open %s", filename)
	}

	defer inFile.Close()

	n, err := inFile.Write(content)
	if err != nil {
		return errors.Wrapf(err, "failed to write %s", filename)
	}
	if n != len(content) {
		return errors.Wrapf(err, "short write on %s (%d bytes)", filename, n)
	}
	return nil
}

func assertPathInWD(filename string) error {
	wd, err := os.Getwd()
	if err != nil {
		return err
	}
	f, err := filepath.Abs(filename)
	if err != nil {
		return err
	}
	r, err := filepath.Rel(wd, f)
	if err != nil {
		return err
	}
	if strings.HasPrefix(r, "..") {
		return errors.Errorf("path %s not contained by working directory %s (rel: %s)", filename, wd, r)
	}
	return nil
}