forked from smallstep/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
54 lines (45 loc) · 1.32 KB
/
write.go
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
package utils
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/RTradeLtd/ca-cli/command"
"github.com/RTradeLtd/ca-cli/ui"
"github.com/pkg/errors"
)
var (
// ErrFileExists is the error returned if a file exists.
ErrFileExists = errors.New("file exists")
// ErrIsDir is the error returned if the file is a directory.
ErrIsDir = errors.New("file is a directory")
)
// WriteFile wraps ioutil.WriteFile with a prompt to overwrite a file if
// the file exists. It returns ErrFileExists if the user picks to not overwrite
// the file. If force is set to true, the prompt will not be presented and the
// file if exists will be overwritten.
func WriteFile(filename string, data []byte, perm os.FileMode) error {
if command.IsForce() {
return ioutil.WriteFile(filename, data, perm)
}
st, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
return ioutil.WriteFile(filename, data, perm)
}
return errors.Wrapf(err, "error reading information for %s", filename)
}
if st.IsDir() {
return ErrIsDir
}
str, err := ui.Prompt(fmt.Sprintf("Would you like to overwrite %s [y/n]", filename), ui.WithValidateYesNo())
if err != nil {
return err
}
switch strings.ToLower(strings.TrimSpace(str)) {
case "y", "yes":
case "n", "no":
return ErrFileExists
}
return ioutil.WriteFile(filename, data, perm)
}