-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfile.go
More file actions
127 lines (104 loc) · 2.42 KB
/
file.go
File metadata and controls
127 lines (104 loc) · 2.42 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package codegen
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/go-courier/codegen/formatx"
"golang.org/x/tools/go/packages"
)
func NewFile(pkgName string, filename string) *File {
return &File{
PkgName: LowerSnakeCase(pkgName),
filename: filename,
}
}
type File struct {
PkgName string
filename string
imports map[string]string
bytes.Buffer
}
func (file *File) WriteBlock(ss ...Snippet) {
for _, s := range ss {
file.Write(s.Bytes())
file.WriteString("\n\n")
}
}
func (file *File) Bytes() []byte {
buf := &bytes.Buffer{}
buf.WriteString(`package ` + LowerSnakeCase(file.PkgName) + `
`)
if file.imports != nil {
buf.WriteString(`import (
`)
for importPath, alias := range file.imports {
buf.WriteString(alias)
buf.WriteString(" ")
buf.WriteString(strconv.Quote(importPath))
buf.WriteString("\n")
}
buf.WriteString(`)
`)
}
io.Copy(buf, &file.Buffer)
return formatx.MustFormat(file.filename, buf.Bytes(), formatx.SortImportsProcess)
}
func (file *File) Expr(f string, args ...interface{}) SnippetExpr {
return createExpr(file.importAliaser)(f, args...)
}
func (file *File) TypeOf(tpe reflect.Type) SnippetType {
return createTypeOf(file.importAliaser)(tpe)
}
func (file *File) Val(v interface{}) Snippet {
return createVal(file.importAliaser)(v)
}
func (file *File) importAliaser(importPath string) string {
if file.imports == nil {
file.imports = map[string]string{}
}
if file.imports[importPath] == "" {
pkgs, err := packages.Load(nil, importPath)
if err != nil {
panic(err)
}
if len(pkgs) == 0 {
panic(fmt.Errorf("`%s` not found", importPath))
}
importPath = pkgs[0].PkgPath
file.imports[importPath] = LowerSnakeCase(importPath)
}
return file.imports[importPath]
}
func (file *File) Use(importPath string, exposedName string) string {
return file.importAliaser(importPath) + "." + exposedName
}
func deVendor(importPath string) string {
parts := strings.Split(importPath, "/vendor/")
return parts[len(parts)-1]
}
func (file *File) WriteFile() (int, error) {
dir := filepath.Dir(file.filename)
if dir != "" {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return -1, err
}
}
f, err := os.Create(file.filename)
defer f.Close()
if err != nil {
return -1, err
}
n3, err := f.Write(file.Bytes())
if err != nil {
return -1, err
}
if err := f.Sync(); err != nil {
return -1, err
}
return n3, nil
}