Compare commits

..

13 Commits

Author SHA1 Message Date
Kevin Wan
acd48f0abb optimize dockerfile generation (#284) 2020-12-12 16:53:06 +08:00
kingxt
f919bc6713 refactor (#283) 2020-12-12 11:18:22 +08:00
Kevin Wan
a0030b8f45 format dockerfile on non-chinese mode (#282) 2020-12-12 10:13:33 +08:00
Kevin Wan
a5f0cce1b1 Update readme-en.md 2020-12-12 09:06:09 +08:00
Kevin Wan
4d13dda605 add EXPOSE in dockerfile generation (#281) 2020-12-12 08:18:01 +08:00
songmeizi
b56cc8e459 optimize test case of TestRpcGenerate (#279)
Co-authored-by: anqiansong <anqiansong@xiaoheiban.cn>
2020-12-11 21:57:04 +08:00
Kevin Wan
c435811479 fix gocyclo warnings (#278) 2020-12-11 20:57:48 +08:00
Kevin Wan
c686c93fb5 fix dockerfile generation bug (#277) 2020-12-11 20:31:31 +08:00
Kevin Wan
da8f76e6bd add category docker & kube (#276) 2020-12-11 18:53:40 +08:00
Kevin Wan
99596a4149 fix issue #266 (#275)
* optimize dockerfile

* fix issue #266
2020-12-11 16:12:33 +08:00
wayne
ec2a9f2c57 fix tracelogger_test TestTraceLog (#271) 2020-12-10 17:04:57 +08:00
Kevin Wan
fd73ced6dc optimize dockerfile (#272) 2020-12-10 16:21:06 +08:00
Kevin Wan
5071736ab4 fmt code (#270) 2020-12-10 15:16:13 +08:00
20 changed files with 260 additions and 194 deletions

View File

@@ -21,6 +21,7 @@ var mock tracespec.Trace = new(mockTrace)
func TestTraceLog(t *testing.T) { func TestTraceLog(t *testing.T) {
var buf mockWriter var buf mockWriter
atomic.StoreUint32(&initialized, 1)
ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock) ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock)
WithContext(ctx).(*traceLogger).write(&buf, levelInfo, testlog) WithContext(ctx).(*traceLogger).write(&buf, levelInfo, testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceId))

View File

@@ -153,58 +153,57 @@ func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fie
key := strings.TrimSpace(segments[0]) key := strings.TrimSpace(segments[0])
options := segments[1:] options := segments[1:]
if len(options) > 0 { if len(options) == 0 {
var fieldOpts fieldOptions return key, nil, nil
for _, segment := range options {
option := strings.TrimSpace(segment)
switch {
case option == stringOption:
fieldOpts.FromString = true
case strings.HasPrefix(option, optionalOption):
segs := strings.Split(option, equalToken)
switch len(segs) {
case 1:
fieldOpts.Optional = true
case 2:
fieldOpts.Optional = true
fieldOpts.OptionalDep = segs[1]
default:
return "", nil, fmt.Errorf("field %s has wrong optional", field.Name)
}
case option == optionalOption:
fieldOpts.Optional = true
case strings.HasPrefix(option, optionsOption):
segs := strings.Split(option, equalToken)
if len(segs) != 2 {
return "", nil, fmt.Errorf("field %s has wrong options", field.Name)
} else {
fieldOpts.Options = strings.Split(segs[1], optionSeparator)
}
case strings.HasPrefix(option, defaultOption):
segs := strings.Split(option, equalToken)
if len(segs) != 2 {
return "", nil, fmt.Errorf("field %s has wrong default option", field.Name)
} else {
fieldOpts.Default = strings.TrimSpace(segs[1])
}
case strings.HasPrefix(option, rangeOption):
segs := strings.Split(option, equalToken)
if len(segs) != 2 {
return "", nil, fmt.Errorf("field %s has wrong range", field.Name)
}
if nr, err := parseNumberRange(segs[1]); err != nil {
return "", nil, err
} else {
fieldOpts.Range = nr
}
}
}
return key, &fieldOpts, nil
} }
return key, nil, nil var fieldOpts fieldOptions
for _, segment := range options {
option := strings.TrimSpace(segment)
switch {
case option == stringOption:
fieldOpts.FromString = true
case strings.HasPrefix(option, optionalOption):
segs := strings.Split(option, equalToken)
switch len(segs) {
case 1:
fieldOpts.Optional = true
case 2:
fieldOpts.Optional = true
fieldOpts.OptionalDep = segs[1]
default:
return "", nil, fmt.Errorf("field %s has wrong optional", field.Name)
}
case option == optionalOption:
fieldOpts.Optional = true
case strings.HasPrefix(option, optionsOption):
segs := strings.Split(option, equalToken)
if len(segs) != 2 {
return "", nil, fmt.Errorf("field %s has wrong options", field.Name)
} else {
fieldOpts.Options = strings.Split(segs[1], optionSeparator)
}
case strings.HasPrefix(option, defaultOption):
segs := strings.Split(option, equalToken)
if len(segs) != 2 {
return "", nil, fmt.Errorf("field %s has wrong default option", field.Name)
} else {
fieldOpts.Default = strings.TrimSpace(segs[1])
}
case strings.HasPrefix(option, rangeOption):
segs := strings.Split(option, equalToken)
if len(segs) != 2 {
return "", nil, fmt.Errorf("field %s has wrong range", field.Name)
}
if nr, err := parseNumberRange(segs[1]); err != nil {
return "", nil, err
} else {
fieldOpts.Range = nr
}
}
}
return key, &fieldOpts, nil
} }
func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) { func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {

View File

@@ -129,7 +129,7 @@ go get -u github.com/tal-tech/go-zero
the .api files also can be generate by goctl, like below: the .api files also can be generate by goctl, like below:
```shell ```shell
goctl api -o greet.api goctl api -o greet.api
``` ```
3. generate the go server side code 3. generate the go server side code

View File

@@ -64,7 +64,7 @@ func (pr *patRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
} }
allow, ok := pr.methodNotAllowed(r.Method, reqPath) allows, ok := pr.methodsAllowed(r.Method, reqPath)
if !ok { if !ok {
pr.handleNotFound(w, r) pr.handleNotFound(w, r)
return return
@@ -73,7 +73,7 @@ func (pr *patRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if pr.notAllowed != nil { if pr.notAllowed != nil {
pr.notAllowed.ServeHTTP(w, r) pr.notAllowed.ServeHTTP(w, r)
} else { } else {
w.Header().Set(allowHeader, allow) w.Header().Set(allowHeader, allows)
w.WriteHeader(http.StatusMethodNotAllowed) w.WriteHeader(http.StatusMethodNotAllowed)
} }
} }
@@ -94,7 +94,7 @@ func (pr *patRouter) handleNotFound(w http.ResponseWriter, r *http.Request) {
} }
} }
func (pr *patRouter) methodNotAllowed(method, path string) (string, bool) { func (pr *patRouter) methodsAllowed(method, path string) (string, bool) {
var allows []string var allows []string
for treeMethod, tree := range pr.trees { for treeMethod, tree := range pr.trees {

View File

@@ -38,11 +38,12 @@ func RevertTemplate(name string) error {
return util.CreateTemplate(category, name, content) return util.CreateTemplate(category, name, content)
} }
func Update(category string) error { func Update() error {
err := Clean() err := Clean()
if err != nil { if err != nil {
return err return err
} }
return util.InitTemplates(category, templates) return util.InitTemplates(category, templates)
} }
@@ -50,6 +51,6 @@ func Clean() error {
return util.Clean(category) return util.Clean(category)
} }
func GetCategory() string { func Category() string {
return category return category
} }

View File

@@ -84,7 +84,7 @@ func TestUpdate(t *testing.T) {
assert.Equal(t, string(data), modifyData) assert.Equal(t, string(data), modifyData)
assert.Nil(t, Update(category)) assert.Nil(t, Update())
data, err = ioutil.ReadFile(file) data, err = ioutil.ReadFile(file)
assert.Nil(t, err) assert.Nil(t, err)

View File

@@ -9,15 +9,17 @@ import (
"text/template" "text/template"
"time" "time"
"github.com/logrusorgru/aurora"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/urfave/cli" "github.com/urfave/cli"
) )
const ( const (
etcDir = "etc" dockerfileName = "Dockerfile"
yamlEtx = ".yaml" etcDir = "etc"
cstOffset = 60 * 60 * 8 // 8 hours offset for Chinese Standard Time yamlEtx = ".yaml"
cstOffset = 60 * 60 * 8 // 8 hours offset for Chinese Standard Time
) )
type Docker struct { type Docker struct {
@@ -25,10 +27,18 @@ type Docker struct {
GoRelPath string GoRelPath string
GoFile string GoFile string
ExeFile string ExeFile string
HasPort bool
Port int
Argument string Argument string
} }
func DockerCommand(c *cli.Context) error { func DockerCommand(c *cli.Context) (err error) {
defer func() {
if err == nil {
fmt.Println(aurora.Green("Done."))
}
}()
goFile := c.String("go") goFile := c.String("go")
if len(goFile) == 0 { if len(goFile) == 0 {
return errors.New("-go can't be empty") return errors.New("-go can't be empty")
@@ -38,8 +48,9 @@ func DockerCommand(c *cli.Context) error {
return fmt.Errorf("file %q not found", goFile) return fmt.Errorf("file %q not found", goFile)
} }
port := c.Int("port")
if _, err := os.Stat(etcDir); os.IsNotExist(err) { if _, err := os.Stat(etcDir); os.IsNotExist(err) {
return generateDockerfile(goFile) return generateDockerfile(goFile, port)
} }
cfg, err := findConfig(goFile, etcDir) cfg, err := findConfig(goFile, etcDir)
@@ -47,13 +58,13 @@ func DockerCommand(c *cli.Context) error {
return err return err
} }
if err := generateDockerfile(goFile, "-f", "etc/"+cfg); err != nil { if err := generateDockerfile(goFile, port, "-f", "etc/"+cfg); err != nil {
return err return err
} }
projDir, ok := util.FindProjectPath(goFile) projDir, ok := util.FindProjectPath(goFile)
if ok { if ok {
fmt.Printf("Run \"docker build ...\" command in dir %q\n", projDir) fmt.Printf("Hint: run \"docker build ...\" command in dir %q\n", projDir)
} }
return nil return nil
@@ -88,18 +99,22 @@ func findConfig(file, dir string) (string, error) {
return files[0], nil return files[0], nil
} }
func generateDockerfile(goFile string, args ...string) error { func generateDockerfile(goFile string, port int, args ...string) error {
projPath, err := getFilePath(filepath.Dir(goFile)) projPath, err := getFilePath(filepath.Dir(goFile))
if err != nil { if err != nil {
return err return err
} }
pos := strings.IndexByte(projPath, '/') if len(projPath) == 0 {
if pos >= 0 { projPath = "."
projPath = projPath[pos+1:] } else {
pos := strings.IndexByte(projPath, os.PathSeparator)
if pos >= 0 {
projPath = projPath[pos+1:]
}
} }
out, err := util.CreateIfNotExist("Dockerfile") out, err := util.CreateIfNotExist(dockerfileName)
if err != nil { if err != nil {
return err return err
} }
@@ -122,6 +137,8 @@ func generateDockerfile(goFile string, args ...string) error {
GoRelPath: projPath, GoRelPath: projPath,
GoFile: goFile, GoFile: goFile,
ExeFile: util.FileNameWithoutExt(filepath.Base(goFile)), ExeFile: util.FileNameWithoutExt(filepath.Base(goFile)),
HasPort: port > 0,
Port: port,
Argument: builder.String(), Argument: builder.String(),
}) })
} }

View File

@@ -14,34 +14,59 @@ LABEL stage=gobuilder
ENV CGO_ENABLED 0 ENV CGO_ENABLED 0
ENV GOOS linux ENV GOOS linux
{{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct{{end}} {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct
{{end}}
WORKDIR /build/zero WORKDIR /build/zero
ADD go.mod . ADD go.mod .
ADD go.sum . ADD go.sum .
RUN go mod download RUN go mod download
COPY . . COPY . .
COPY {{.GoRelPath}}/etc /app/etc {{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc
RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}} {{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}}
FROM alpine FROM alpine
RUN apk update --no-cache RUN apk update --no-cache && apk add --no-cache ca-certificates tzdata
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai ENV TZ Asia/Shanghai
WORKDIR /app WORKDIR /app
COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}} COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}}
COPY --from=builder /app/etc /app/etc COPY --from=builder /app/etc /app/etc{{end}}
{{if .HasPort}}
EXPOSE {{.Port}}
{{end}}
CMD ["./{{.ExeFile}}"{{.Argument}}] CMD ["./{{.ExeFile}}"{{.Argument}}]
` `
) )
func Clean() error {
return util.Clean(category)
}
func GenTemplates(_ *cli.Context) error { func GenTemplates(_ *cli.Context) error {
return initTemplate()
}
func Category() string {
return category
}
func RevertTemplate(name string) error {
return util.CreateTemplate(category, name, dockerTemplate)
}
func Update() error {
err := Clean()
if err != nil {
return err
}
return initTemplate()
}
func initTemplate() error {
return util.InitTemplates(category, map[string]string{ return util.InitTemplates(category, map[string]string{
dockerTemplateFile: dockerTemplate, dockerTemplateFile: dockerTemplate,
}) })

View File

@@ -27,7 +27,7 @@ import (
) )
var ( var (
BuildVersion = "20201125" BuildVersion = "1.1.1"
commands = []cli.Command{ commands = []cli.Command{
{ {
Name: "api", Name: "api",
@@ -54,14 +54,12 @@ var (
Usage: "the format target dir", Usage: "the format target dir",
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "iu", Name: "iu",
Usage: "ignore update", Usage: "ignore update",
Required: false,
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "stdin", Name: "stdin",
Usage: "use stdin to input api doc content, press \"ctrl + d\" to send EOF", Usage: "use stdin to input api doc content, press \"ctrl + d\" to send EOF",
Required: false,
}, },
}, },
Action: format.GoFormatApi, Action: format.GoFormatApi,
@@ -101,9 +99,8 @@ var (
Usage: "the api file", Usage: "the api file",
}, },
cli.StringFlag{ cli.StringFlag{
Name: "style", Name: "style",
Required: false, Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
}, },
}, },
Action: gogen.GoCommand, Action: gogen.GoCommand,
@@ -136,19 +133,16 @@ var (
Usage: "the api file", Usage: "the api file",
}, },
cli.StringFlag{ cli.StringFlag{
Name: "webapi", Name: "webapi",
Usage: "the web api file path", Usage: "the web api file path",
Required: false,
}, },
cli.StringFlag{ cli.StringFlag{
Name: "caller", Name: "caller",
Usage: "the web api caller", Usage: "the web api caller",
Required: false,
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "unwrap", Name: "unwrap",
Usage: "unwrap the webapi caller for import", Usage: "unwrap the webapi caller for import",
Required: false,
}, },
}, },
Action: tsgen.TsCommand, Action: tsgen.TsCommand,
@@ -204,9 +198,8 @@ var (
Usage: "the api file", Usage: "the api file",
}, },
cli.StringFlag{ cli.StringFlag{
Name: "style", Name: "style",
Required: false, Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
}, },
}, },
Action: plugin.PluginCommand, Action: plugin.PluginCommand,
@@ -221,6 +214,11 @@ var (
Name: "go", Name: "go",
Usage: "the file that contains main function", Usage: "the file that contains main function",
}, },
cli.IntFlag{
Name: "port",
Usage: "the port to expose, default none",
Value: 0,
},
}, },
Action: docker.DockerCommand, Action: docker.DockerCommand,
}, },
@@ -248,9 +246,8 @@ var (
Required: true, Required: true,
}, },
cli.StringFlag{ cli.StringFlag{
Name: "secret", Name: "secret",
Usage: "the image pull secret", Usage: "the secret to image pull from registry",
Required: true,
}, },
cli.IntFlag{ cli.IntFlag{
Name: "requestCpu", Name: "requestCpu",
@@ -321,9 +318,8 @@ var (
Usage: `generate rpc demo service`, Usage: `generate rpc demo service`,
Flags: []cli.Flag{ Flags: []cli.Flag{
cli.StringFlag{ cli.StringFlag{
Name: "style", Name: "style",
Required: false, Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "idea", Name: "idea",
@@ -360,9 +356,8 @@ var (
Usage: `the target path of the code`, Usage: `the target path of the code`,
}, },
cli.StringFlag{ cli.StringFlag{
Name: "style", Name: "style",
Required: false, Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "idea", Name: "idea",
@@ -394,9 +389,8 @@ var (
Usage: "the target dir", Usage: "the target dir",
}, },
cli.StringFlag{ cli.StringFlag{
Name: "style", Name: "style",
Required: false, Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "cache, c", Name: "cache, c",
@@ -430,9 +424,8 @@ var (
Usage: "the target dir", Usage: "the target dir",
}, },
cli.StringFlag{ cli.StringFlag{
Name: "style", Name: "style",
Required: false, Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
Usage: "the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]",
}, },
cli.BoolFlag{ cli.BoolFlag{
Name: "idea", Name: "idea",
@@ -476,7 +469,7 @@ var (
Flags: []cli.Flag{ Flags: []cli.Flag{
cli.StringFlag{ cli.StringFlag{
Name: "category,c", Name: "category,c",
Usage: "the category of template, enum [api,rpc,model]", Usage: "the category of template, enum [api,rpc,model,docker,kube]",
}, },
}, },
Action: tpl.UpdateTemplates, Action: tpl.UpdateTemplates,
@@ -487,7 +480,7 @@ var (
Flags: []cli.Flag{ Flags: []cli.Flag{
cli.StringFlag{ cli.StringFlag{
Name: "category,c", Name: "category,c",
Usage: "the category of template, enum [api,rpc,model]", Usage: "the category of template, enum [api,rpc,model,docker,kube]",
}, },
cli.StringFlag{ cli.StringFlag{
Name: "name,n", Name: "name,n",

View File

@@ -47,9 +47,9 @@ spec:
volumeMounts: volumeMounts:
- name: timezone - name: timezone
mountPath: /etc/localtime mountPath: /etc/localtime
imagePullSecrets: {{if .Secret}}imagePullSecrets:
- name: {{.Secret}} - name: {{.Secret}}
volumes: {{end}}volumes:
- name: timezone - name: timezone
hostPath: hostPath:
path: /usr/share/zoneinfo/Asia/Shanghai path: /usr/share/zoneinfo/Asia/Shanghai

View File

@@ -2,8 +2,10 @@ package kube
import ( import (
"errors" "errors"
"fmt"
"text/template" "text/template"
"github.com/logrusorgru/aurora"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/urfave/cli" "github.com/urfave/cli"
) )
@@ -16,47 +18,23 @@ const (
portLimit = 32767 portLimit = 32767
) )
var errUnknownServiceType = errors.New("unknown service type") type Deployment struct {
Name string
type ( Namespace string
ServiceType string Image string
Secret string
KubeRequest struct { Replicas int
Env string Revisions int
ServiceName string Port int
ServiceType ServiceType NodePort int
Namespace string UseNodePort bool
Schedule string RequestCpu int
Replicas int RequestMem int
RevisionHistoryLimit int LimitCpu int
Port int LimitMem int
LimitCpu int MinReplicas int
LimitMem int MaxReplicas int
RequestCpu int }
RequestMem int
SuccessfulJobsHistoryLimit int
HpaMinReplicas int
HpaMaxReplicas int
}
Deployment struct {
Name string
Namespace string
Image string
Secret string
Replicas int
Revisions int
Port int
NodePort int
UseNodePort bool
RequestCpu int
RequestMem int
LimitCpu int
LimitMem int
MinReplicas int
MaxReplicas int
}
)
func DeploymentCommand(c *cli.Context) error { func DeploymentCommand(c *cli.Context) error {
nodePort := c.Int("nodePort") nodePort := c.Int("nodePort")
@@ -77,7 +55,7 @@ func DeploymentCommand(c *cli.Context) error {
defer out.Close() defer out.Close()
t := template.Must(template.New("deploymentTemplate").Parse(text)) t := template.Must(template.New("deploymentTemplate").Parse(text))
return t.Execute(out, Deployment{ err = t.Execute(out, Deployment{
Name: c.String("name"), Name: c.String("name"),
Namespace: c.String("namespace"), Namespace: c.String("namespace"),
Image: c.String("image"), Image: c.String("image"),
@@ -94,6 +72,20 @@ func DeploymentCommand(c *cli.Context) error {
MinReplicas: c.Int("minReplicas"), MinReplicas: c.Int("minReplicas"),
MaxReplicas: c.Int("maxReplicas"), MaxReplicas: c.Int("maxReplicas"),
}) })
if err != nil {
return err
}
fmt.Println(aurora.Green("Done."))
return nil
}
func Category() string {
return category
}
func Clean() error {
return util.Clean(category)
} }
func GenTemplates(_ *cli.Context) error { func GenTemplates(_ *cli.Context) error {
@@ -102,3 +94,19 @@ func GenTemplates(_ *cli.Context) error {
jobTemplateFile: jobTmeplate, jobTemplateFile: jobTmeplate,
}) })
} }
func RevertTemplate(name string) error {
return util.CreateTemplate(category, name, deploymentTemplate)
}
func Update() error {
err := Clean()
if err != nil {
return err
}
return util.InitTemplates(category, map[string]string{
deployTemplateFile: deploymentTemplate,
jobTemplateFile: jobTmeplate,
})
}

View File

@@ -54,6 +54,14 @@ var templates = map[string]string{
errTemplateFile: template.Error, errTemplateFile: template.Error,
} }
func Category() string {
return category
}
func Clean() error {
return util.Clean(category)
}
func GenTemplates(_ *cli.Context) error { func GenTemplates(_ *cli.Context) error {
return util.InitTemplates(category, templates) return util.InitTemplates(category, templates)
} }
@@ -66,18 +74,10 @@ func RevertTemplate(name string) error {
return util.CreateTemplate(category, name, content) return util.CreateTemplate(category, name, content)
} }
func Clean() error { func Update() error {
return util.Clean(category)
}
func Update(category string) error {
err := Clean() err := Clean()
if err != nil { if err != nil {
return err return err
} }
return util.InitTemplates(category, templates) return util.InitTemplates(category, templates)
} }
func GetCategory() string {
return category
}

View File

@@ -85,7 +85,7 @@ func TestUpdate(t *testing.T) {
assert.Equal(t, string(data), modifyData) assert.Equal(t, string(data), modifyData)
assert.Nil(t, Update(category)) assert.Nil(t, Update())
data, err = ioutil.ReadFile(file) data, err = ioutil.ReadFile(file)
assert.Nil(t, err) assert.Nil(t, err)

View File

@@ -25,9 +25,10 @@ const (
) )
type Plugin struct { type Plugin struct {
Api *spec.ApiSpec Api *spec.ApiSpec
Style string ApiFilePath string
Dir string Style string
Dir string
} }
func PluginCommand(c *cli.Context) error { func PluginCommand(c *cli.Context) error {
@@ -86,6 +87,12 @@ func prepareArgs(c *cli.Context) ([]byte, error) {
transferData.Api = api transferData.Api = api
} }
absApiFilePath, err := filepath.Abs(apiPath)
if err != nil {
return nil, err
}
transferData.ApiFilePath = absApiFilePath
dirAbs, err := filepath.Abs(c.String("dir")) dirAbs, err := filepath.Abs(c.String("dir"))
if err != nil { if err != nil {
return nil, err return nil, err

View File

@@ -4,6 +4,7 @@ import (
"go/build" "go/build"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -44,7 +45,9 @@ func TestRpcGenerate(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
_, err = execx.Run("go test "+projectName, projectDir) _, err = execx.Run("go test "+projectName, projectDir)
if err != nil { if err != nil {
assert.Contains(t, err.Error(), "not in GOROOT") assert.True(t, func() bool {
return strings.Contains(err.Error(), "not in GOROOT") || strings.Contains(err.Error(), "cannot find package")
}())
} }
// case go mod // case go mod
@@ -61,7 +64,9 @@ func TestRpcGenerate(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
_, err = execx.Run("go test "+projectName, projectDir) _, err = execx.Run("go test "+projectName, projectDir)
if err != nil { if err != nil {
assert.Contains(t, err.Error(), "not in GOROOT") assert.True(t, func() bool {
return strings.Contains(err.Error(), "not in GOROOT") || strings.Contains(err.Error(), "cannot find package")
}())
} }
// case not in go mod and go path // case not in go mod and go path
@@ -69,7 +74,9 @@ func TestRpcGenerate(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
_, err = execx.Run("go test "+projectName, projectDir) _, err = execx.Run("go test "+projectName, projectDir)
if err != nil { if err != nil {
assert.Contains(t, err.Error(), "not in GOROOT") assert.True(t, func() bool {
return strings.Contains(err.Error(), "not in GOROOT") || strings.Contains(err.Error(), "cannot find package")
}())
} }
// invalid directory // invalid directory

View File

@@ -54,14 +54,15 @@ func Clean() error {
return util.Clean(category) return util.Clean(category)
} }
func Update(category string) error { func Update() error {
err := Clean() err := Clean()
if err != nil { if err != nil {
return err return err
} }
return util.InitTemplates(category, templates) return util.InitTemplates(category, templates)
} }
func GetCategory() string { func Category() string {
return category return category
} }

View File

@@ -97,8 +97,7 @@ func TestUpdate(t *testing.T) {
} }
assert.Equal(t, "modify", string(data)) assert.Equal(t, "modify", string(data))
err = Update(category) assert.Nil(t, Update())
assert.Nil(t, err)
data, err = ioutil.ReadFile(mainTpl) data, err = ioutil.ReadFile(mainTpl)
if err != nil { if err != nil {
@@ -109,6 +108,6 @@ func TestUpdate(t *testing.T) {
func TestGetCategory(t *testing.T) { func TestGetCategory(t *testing.T) {
_ = Clean() _ = Clean()
result := GetCategory() result := Category()
assert.Equal(t, category, result) assert.Equal(t, category, result)
} }

View File

@@ -76,12 +76,16 @@ func UpdateTemplates(ctx *cli.Context) (err error) {
} }
}() }()
switch category { switch category {
case gogen.GetCategory(): case docker.Category():
return gogen.Update(category) return docker.Update()
case rpcgen.GetCategory(): case gogen.Category():
return rpcgen.Update(category) return gogen.Update()
case modelgen.GetCategory(): case kube.Category():
return modelgen.Update(category) return kube.Update()
case rpcgen.Category():
return rpcgen.Update()
case modelgen.Category():
return modelgen.Update()
default: default:
err = fmt.Errorf("unexpected category: %s", category) err = fmt.Errorf("unexpected category: %s", category)
return return
@@ -97,11 +101,15 @@ func RevertTemplates(ctx *cli.Context) (err error) {
} }
}() }()
switch category { switch category {
case gogen.GetCategory(): case docker.Category():
return docker.RevertTemplate(filename)
case kube.Category():
return kube.RevertTemplate(filename)
case gogen.Category():
return gogen.RevertTemplate(filename) return gogen.RevertTemplate(filename)
case rpcgen.GetCategory(): case rpcgen.Category():
return rpcgen.RevertTemplate(filename) return rpcgen.RevertTemplate(filename)
case modelgen.GetCategory(): case modelgen.Category():
return modelgen.RevertTemplate(filename) return modelgen.RevertTemplate(filename)
default: default:
err = fmt.Errorf("unexpected category: %s", category) err = fmt.Errorf("unexpected category: %s", category)

View File

@@ -60,7 +60,6 @@ func FindGoModPath(dir string) (string, bool) {
var hasGoMod = false var hasGoMod = false
for { for {
if FileExists(filepath.Join(tempPath, goModeIdentifier)) { if FileExists(filepath.Join(tempPath, goModeIdentifier)) {
tempPath = filepath.Dir(tempPath)
rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/") rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/")
hasGoMod = true hasGoMod = true
break break

View File

@@ -19,10 +19,11 @@ func Untitle(s string) string {
} }
func Index(slice []string, item string) int { func Index(slice []string, item string) int {
for i, _ := range slice { for i := range slice {
if slice[i] == item { if slice[i] == item {
return i return i
} }
} }
return -1 return -1
} }