Code refactoring for bpa operator
[icn.git] / cmd / bpa-operator / vendor / sigs.k8s.io / controller-tools / pkg / util / util.go
1 /*
2 Copyright 2018 The Kubernetes Authors.
3
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
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
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.
15 */
16
17 package util
18
19 import (
20         "fmt"
21         "io"
22         "log"
23         "os"
24         "path/filepath"
25
26         "github.com/spf13/afero"
27 )
28
29 // FileWriter is a io wrapper to write files
30 type FileWriter struct {
31         Fs afero.Fs
32 }
33
34 // WriteCloser returns a WriteCloser to write to given path
35 func (fw *FileWriter) WriteCloser(path string) (io.Writer, error) {
36         if fw.Fs == nil {
37                 fw.Fs = afero.NewOsFs()
38         }
39         dir := filepath.Dir(path)
40         err := fw.Fs.MkdirAll(dir, 0700)
41         if err != nil {
42                 return nil, err
43         }
44
45         fi, err := fw.Fs.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
46         if err != nil {
47                 return nil, err
48         }
49
50         return fi, nil
51 }
52
53 // WriteFile write given content to the file path
54 func (fw *FileWriter) WriteFile(filePath string, content []byte) error {
55         if fw.Fs == nil {
56                 fw.Fs = afero.NewOsFs()
57         }
58         f, err := fw.WriteCloser(filePath)
59         if err != nil {
60                 return fmt.Errorf("failed to create %s: %v", filePath, err)
61         }
62
63         if c, ok := f.(io.Closer); ok {
64                 defer func() {
65                         if err := c.Close(); err != nil {
66                                 log.Fatal(err)
67                         }
68                 }()
69         }
70
71         _, err = f.Write(content)
72         if err != nil {
73                 return fmt.Errorf("failed to write %s: %v", filePath, err)
74         }
75
76         return nil
77 }