2 Copyright 2018 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
26 "github.com/spf13/afero"
29 // FileWriter is a io wrapper to write files
30 type FileWriter struct {
34 // WriteCloser returns a WriteCloser to write to given path
35 func (fw *FileWriter) WriteCloser(path string) (io.Writer, error) {
37 fw.Fs = afero.NewOsFs()
39 dir := filepath.Dir(path)
40 err := fw.Fs.MkdirAll(dir, 0700)
45 fi, err := fw.Fs.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
53 // WriteFile write given content to the file path
54 func (fw *FileWriter) WriteFile(filePath string, content []byte) error {
56 fw.Fs = afero.NewOsFs()
58 f, err := fw.WriteCloser(filePath)
60 return fmt.Errorf("failed to create %s: %v", filePath, err)
63 if c, ok := f.(io.Closer); ok {
65 if err := c.Close(); err != nil {
71 _, err = f.Write(content)
73 return fmt.Errorf("failed to write %s: %v", filePath, err)