-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
executable file
·106 lines (90 loc) · 2.18 KB
/
util.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package gogen
import (
"fmt"
"go/types"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
func MustLoadTemplate(pathToTemplate string) string {
contents, err := LoadTemplate(pathToTemplate)
if err != nil {
panic(err)
}
return contents
}
func LoadTemplate(pathToTemplate string) (string, error) {
b, err := ioutil.ReadFile(pathToTemplate)
if err != nil {
return "", err
}
return string(b), nil
}
func findGoNamedType(def types.Type) (*types.Named, error) {
if def == nil {
return nil, nil
}
namedType, ok := def.(*types.Named)
if !ok {
return nil, errors.Errorf("expected %s to be a named type, instead found %T\n", def.String(), def)
}
return namedType, nil
}
func findGoInterface(def types.Type) (*types.Interface, error) {
if def == nil {
return nil, nil
}
namedType, err := findGoNamedType(def)
if err != nil {
return nil, err
}
if namedType == nil {
return nil, nil
}
underlying, ok := namedType.Underlying().(*types.Interface)
if !ok {
return nil, errors.Errorf("expected %s to be a named interface, instead found %s", def.String(), namedType.String())
}
return underlying, nil
}
func equalFieldName(source, target string) bool {
source = strings.Replace(source, "_", "", -1)
target = strings.Replace(target, "_", "", -1)
return strings.EqualFold(source, target)
}
// getWorkingPath gets the current working directory
func getWorkingPath() (string, error) {
wd, err := os.Getwd()
if err != nil {
return "", err
}
return wd, nil
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func makeDirForFile(fileName string) error {
dir := filepath.Dir(fileName)
if err := makeDir(dir); err != nil {
return fmt.Errorf("unable to create dir for file: %s %w", fileName, err)
}
return nil
}
func makeDir(dir string) error {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("unable to create dir: %s %w", dir, err)
}
return nil
}
func createFile(fileName string, data []byte) error {
if err := ioutil.WriteFile(fileName, data, 0644); err != nil {
return fmt.Errorf("unable to create file: %s %w", fileName, err)
}
return nil
}