OSDN Git Service

versoin1.1.9 (#594)
[bytom/vapor.git] / vendor / github.com / spf13 / cobra / cobra / cmd / helpers.go
1 // Copyright © 2015 Steve Francia <spf@spf13.com>.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package cmd
15
16 import (
17         "bytes"
18         "fmt"
19         "io"
20         "os"
21         "os/exec"
22         "path/filepath"
23         "strings"
24         "text/template"
25 )
26
27 var cmdDirs = [...]string{"cmd", "cmds", "command", "commands"}
28 var srcPaths []string
29
30 func init() {
31         // Initialize srcPaths.
32         envGoPath := os.Getenv("GOPATH")
33         goPaths := filepath.SplitList(envGoPath)
34         if len(goPaths) == 0 {
35                 // Adapted from https://github.com/Masterminds/glide/pull/798/files.
36                 // As of Go 1.8 the GOPATH is no longer required to be set. Instead there
37                 // is a default value. If there is no GOPATH check for the default value.
38                 // Note, checking the GOPATH first to avoid invoking the go toolchain if
39                 // possible.
40
41                 goExecutable := os.Getenv("COBRA_GO_EXECUTABLE")
42                 if len(goExecutable) <= 0 {
43                         goExecutable = "go"
44                 }
45
46                 out, err := exec.Command(goExecutable, "env", "GOPATH").Output()
47                 if err != nil {
48                         er(err)
49                 }
50
51                 toolchainGoPath := strings.TrimSpace(string(out))
52                 goPaths = filepath.SplitList(toolchainGoPath)
53                 if len(goPaths) == 0 {
54                         er("$GOPATH is not set")
55                 }
56         }
57         srcPaths = make([]string, 0, len(goPaths))
58         for _, goPath := range goPaths {
59                 srcPaths = append(srcPaths, filepath.Join(goPath, "src"))
60         }
61 }
62
63 func er(msg interface{}) {
64         fmt.Println("Error:", msg)
65         os.Exit(1)
66 }
67
68 // isEmpty checks if a given path is empty.
69 // Hidden files in path are ignored.
70 func isEmpty(path string) bool {
71         fi, err := os.Stat(path)
72         if err != nil {
73                 er(err)
74         }
75
76         if !fi.IsDir() {
77                 return fi.Size() == 0
78         }
79
80         f, err := os.Open(path)
81         if err != nil {
82                 er(err)
83         }
84         defer f.Close()
85
86         names, err := f.Readdirnames(-1)
87         if err != nil && err != io.EOF {
88                 er(err)
89         }
90
91         for _, name := range names {
92                 if len(name) > 0 && name[0] != '.' {
93                         return false
94                 }
95         }
96         return true
97 }
98
99 // exists checks if a file or directory exists.
100 func exists(path string) bool {
101         if path == "" {
102                 return false
103         }
104         _, err := os.Stat(path)
105         if err == nil {
106                 return true
107         }
108         if !os.IsNotExist(err) {
109                 er(err)
110         }
111         return false
112 }
113
114 func executeTemplate(tmplStr string, data interface{}) (string, error) {
115         tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr)
116         if err != nil {
117                 return "", err
118         }
119
120         buf := new(bytes.Buffer)
121         err = tmpl.Execute(buf, data)
122         return buf.String(), err
123 }
124
125 func writeStringToFile(path string, s string) error {
126         return writeToFile(path, strings.NewReader(s))
127 }
128
129 // writeToFile writes r to file with path only
130 // if file/directory on given path doesn't exist.
131 // If file/directory exists on given path, then
132 // it terminates app and prints an appropriate error.
133 func writeToFile(path string, r io.Reader) error {
134         if exists(path) {
135                 return fmt.Errorf("%v already exists", path)
136         }
137
138         dir := filepath.Dir(path)
139         if dir != "" {
140                 if err := os.MkdirAll(dir, 0777); err != nil {
141                         return err
142                 }
143         }
144
145         file, err := os.Create(path)
146         if err != nil {
147                 return err
148         }
149         defer file.Close()
150
151         _, err = io.Copy(file, r)
152         return err
153 }
154
155 // commentfyString comments every line of in.
156 func commentifyString(in string) string {
157         var newlines []string
158         lines := strings.Split(in, "\n")
159         for _, line := range lines {
160                 if strings.HasPrefix(line, "//") {
161                         newlines = append(newlines, line)
162                 } else {
163                         if line == "" {
164                                 newlines = append(newlines, "//")
165                         } else {
166                                 newlines = append(newlines, "// "+line)
167                         }
168                 }
169         }
170         return strings.Join(newlines, "\n")
171 }