Debian Codegraph @

utils/write.go

raw symbols SCIP
1 package utils
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "strings"
11 "time"
12
13 "github.com/pkg/errors"
14 "github.com/smallstep/cli/command"
15 "github.com/smallstep/cli/errs"
16 "github.com/smallstep/cli/ui"
17 )
18
19 var (
20 // ErrFileExists is the error returned if a file exists.
21 ErrFileExists = errors.New("file exists")
22
23 // ErrIsDir is the error returned if the file is a directory.
24 ErrIsDir = errors.New("file is a directory")
25
26 // SnippetHeader is the header of a step generated snippet in a
27 // configuration file.
28 SnippetHeader = "# autogenerated by step"
29
30 // SnippetFooter is the header of a step generated snippet in a
31 // configuration file.
32 SnippetFooter = "# end"
33 )
34
35 // WriteFile wraps ioutil.WriteFile with a prompt to overwrite a file if
36 // the file exists. It returns ErrFileExists if the user picks to not overwrite
37 // the file. If force is set to true, the prompt will not be presented and the
38 // file if exists will be overwritten.
39 func WriteFile(filename string, data []byte, perm os.FileMode) error {
40 if command.IsForce() {
41 return ioutil.WriteFile(filename, data, perm)
42 }
43
44 st, err := os.Stat(filename)
45 if err != nil {
46 if os.IsNotExist(err) {
47 return ioutil.WriteFile(filename, data, perm)
48 }
49 return errors.Wrapf(err, "error reading information for %s", filename)
50 }
51
52 if st.IsDir() {
53 return ErrIsDir
54 }
55
56 str, err := ui.Prompt(fmt.Sprintf("Would you like to overwrite %s [y/n]", filename), ui.WithValidateYesNo())
57 if err != nil {
58 return err
59 }
60 switch strings.ToLower(strings.TrimSpace(str)) {
61 case "y", "yes":
62 case "n", "no":
63 return ErrFileExists
64 }
65
66 return ioutil.WriteFile(filename, data, perm)
67 }
68
69 // AppendNewLine appends the given data at the end of the file. If the last
70 // character of the file does not contain an LF it prepends it to the data.
71 func AppendNewLine(filename string, data []byte, perm os.FileMode) error {
72 f, err := OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, perm)
73 if err != nil {
74 return err
75 }
76 // Read last character
77 if st, err := f.File.Stat(); err == nil && st.Size() != 0 {
78 last := make([]byte, 1)
79 f.Seek(-1, 2)
80 f.Read(last)
81 if last[0] != '\n' {
82 f.WriteString("\n")
83 }
84 }
85 f.Write(data)
86 return f.Close()
87 }
88
89 // WriteSnippet writes the given data on the given filename. It surrounds the
90 // data with a header and footer, and it will replace the previous one.
91 func WriteSnippet(filename string, data []byte, perm os.FileMode) error {
92 // Get file permissions
93 if st, err := os.Stat(filename); err == nil {
94 perm = st.Mode()
95 } else if !os.IsNotExist(err) {
96 return errs.FileError(err, filename)
97 }
98
99 // Read file contents
100 b, err := ioutil.ReadFile(filename)
101 if err != nil && !os.IsNotExist(err) {
102 return errs.FileError(err, filename)
103 }
104
105 // Detect previous configuration
106 _, start, end := findConfiguration(bytes.NewReader(b))
107
108 // Replace previous configuration
109 f, err := OpenFile(filename, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, perm)
110 if err != nil {
111 return errs.FileError(err, filename)
112 }
113 if len(b) > 0 {
114 f.Write(b[:start])
115 if start == end {
116 f.WriteString("\n")
117 }
118 }
119 f.WriteString(fmt.Sprintf("%s @ %s\n", SnippetHeader, time.Now().UTC().Format(time.RFC3339)))
120 f.Write(data)
121 if !bytes.HasSuffix(data, []byte("\n")) {
122 f.WriteString("\n")
123 }
124 f.WriteString(SnippetFooter + "\n")
125 if len(b) > 0 {
126 f.Write(b[end:])
127 }
128 return f.Close()
129 }
130
131 type offsetCounter struct {
132 offset int64
133 }
134
135 func (o *offsetCounter) ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
136 advance, token, err = bufio.ScanLines(data, atEOF)
137 o.offset += int64(advance)
138 return
139 }
140
141 func findConfiguration(r io.Reader) (lines []string, start int64, end int64) {
142 var inConfig bool
143 counter := new(offsetCounter)
144 scanner := bufio.NewScanner(r)
145 scanner.Split(counter.ScanLines)
146 for scanner.Scan() {
147 line := scanner.Text()
148 switch {
149 case !inConfig && strings.HasPrefix(line, SnippetHeader):
150 inConfig = true
151 start = counter.offset - int64(len(line)+1)
152 case inConfig && strings.HasPrefix(line, SnippetFooter):
153 return lines, start, counter.offset
154 case inConfig:
155 lines = append(lines, line)
156 }
157 }
158
159 return lines, counter.offset, counter.offset
160 }