Skip to content

Commit

Permalink
feat(command): add nirvana command to generate go client (caicloud#212)
Browse files Browse the repository at this point in the history
* refactor(utils): adjust util directories

* refactor(router): export Split()

* feat(errors): support external errors

* feat(rest): implement basic rest client

* feat(api): enhance api tools

* feat(cmd): update to satisfy new api package

* feat(client): implement golang client generator

* feat(golang): generate function name from definition.Summary

* fix(project): fix wrong arg in entrypoint

* fix(*): fix two minor bugs

* fix(comments): fix comments of golang generator
  • Loading branch information
kdada authored and caicloud-bot committed Jun 20, 2018
1 parent d221eab commit 6b8ee51
Show file tree
Hide file tree
Showing 27 changed files with 2,432 additions and 263 deletions.
70 changes: 10 additions & 60 deletions cmd/nirvana/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ import (
"fmt"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"

"github.com/caicloud/nirvana"
"github.com/caicloud/nirvana/cmd/nirvana/utils"
"github.com/caicloud/nirvana/definition"
"github.com/caicloud/nirvana/log"
"github.com/caicloud/nirvana/service"
"github.com/caicloud/nirvana/utils/builder"
"github.com/caicloud/nirvana/utils/generators/swagger"
"github.com/caicloud/nirvana/utils/project"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
Expand Down Expand Up @@ -77,30 +77,27 @@ func (o *apiOptions) Install(flags *pflag.FlagSet) {
}

func (o *apiOptions) Validate(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("must specify a project path")
}
return nil
}

func (o *apiOptions) Run(cmd *cobra.Command, args []string) error {
builder := utils.NewAPIBuilder(o.findAllChildernPaths(args...)...)
builder := builder.NewAPIBuilder(project.Subdirectories(false, args...)...)
definitions, err := builder.Build()
if err != nil {
return err
}
file := ""
config := &project.Config{}
for _, path := range args {
file, err = o.findProjectFile(path)
config, err = project.LoadDefaultProjectFile(path)
if err == nil {
break
}
}
config := &swagger.Config{}
if file == "" {
log.Warning("can't find nirvana.yaml, use empty config as instead")
} else {
config, err = swagger.LoadConfig(file)
if err != nil {
return err
}
if err != nil {
log.Warning("can't find project file, use empty config as instead")
}
generator := swagger.NewDefaultGenerator(config, definitions)
swaggers, err := generator.Generate()
Expand All @@ -127,53 +124,6 @@ func (o *apiOptions) Run(cmd *cobra.Command, args []string) error {
return err
}

// findAllChildernPaths walkthroughs all child directories but ignore vendors.
func (o *apiOptions) findAllChildernPaths(paths ...string) []string {
walked := map[string]bool{}
goDir := map[string]bool{}
for _, path := range paths {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
if info.Name() == "vendor" || walked[path] {
return filepath.SkipDir
}
walked[path] = true
return nil
}
if strings.HasSuffix(path, ".go") {
dir := filepath.Dir(path)
goDir[dir] = true
}
return nil
})
_ = err
}
results := []string{}
for path := range goDir {
results = append(results, path)
}
return results
}

// findProjectFile find the path of nirvana.yaml.
// It will find the path itself and its parents recursively.
func (o *apiOptions) findProjectFile(path string) (string, error) {
goPath, absPath, err := utils.GoPath(path)
if err != nil {
return "", err
}
fileName := "nirvana.yaml"
for len(absPath) > len(goPath) {
path = filepath.Join(absPath, fileName)
info, err := os.Stat(path)
if err == nil && !info.IsDir() {
return path, nil
}
absPath = filepath.Dir(absPath)
}
return "", fmt.Errorf("can't find nirvana.yaml")
}

func (o *apiOptions) write(apis map[string][]byte) error {
dir := o.Output
for version, data := range apis {
Expand Down
116 changes: 116 additions & 0 deletions cmd/nirvana/client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Copyright 2018 Caicloud Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package client

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"

"github.com/caicloud/nirvana/log"
"github.com/caicloud/nirvana/utils/builder"
"github.com/caicloud/nirvana/utils/generators/golang"
"github.com/caicloud/nirvana/utils/project"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)

func newClientCommand() *cobra.Command {
options := &clientOptions{}
cmd := &cobra.Command{
Use: "client /path/to/project",
Short: "Create client for project",
Long: options.Manuals(),
Run: func(cmd *cobra.Command, args []string) {
if err := options.Validate(cmd, args); err != nil {
log.Fatalln(err)
}
if err := options.Run(cmd, args); err != nil {
log.Fatalln(err)
}
},
}
options.Install(cmd.PersistentFlags())
return cmd
}

type clientOptions struct {
Output string
Rest string
}

func (o *clientOptions) Install(flags *pflag.FlagSet) {
flags.StringVar(&o.Output, "output", "", "Output directory for generated client")
flags.StringVar(&o.Rest, "rest", "github.com/caicloud/nirvana/rest", "Package of rest client")
}

func (o *clientOptions) Validate(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("must specify an api directory")
}
if o.Output == "" {
return fmt.Errorf("must specify generated client path")
}
return nil
}

func (o *clientOptions) Run(cmd *cobra.Command, args []string) error {
builder := builder.NewAPIBuilder(project.Subdirectories(false, args...)...)
definitions, err := builder.Build()
if err != nil {
return err
}
config := &project.Config{}
for _, path := range args {
config, err = project.LoadDefaultProjectFile(path)
if err == nil {
break
}
}
if err != nil {
log.Warning("can't find project file, use empty config as instead")
}
pkg, err := project.PackageForPath(o.Output)
if err != nil {
return err
}
generator := golang.NewGenerator(config, definitions, o.Rest, pkg)
files, err := generator.Generate()
if err != nil {
return err
}

for path, data := range files {
path = filepath.Join(o.Output, path+".go")
dir := filepath.Dir(path)
_, err := os.Stat(dir)
if os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0775); err != nil {
return fmt.Errorf("can't create directory %s: %v", dir, err)
}
}
if err := ioutil.WriteFile(path, data, 0664); err != nil {
return err
}
}
return nil
}

func (o *clientOptions) Manuals() string {
return ""
}
24 changes: 24 additions & 0 deletions cmd/nirvana/client/register.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Copyright 2018 Caicloud Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package client

import "github.com/spf13/cobra"

// Register registers all commands.
func Register(root *cobra.Command) {
root.AddCommand(newClientCommand())
}
2 changes: 2 additions & 0 deletions cmd/nirvana/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package main

import (
"github.com/caicloud/nirvana/cmd/nirvana/api"
"github.com/caicloud/nirvana/cmd/nirvana/client"
"github.com/caicloud/nirvana/cmd/nirvana/project"
"github.com/caicloud/nirvana/log"
"github.com/spf13/cobra"
Expand All @@ -31,6 +32,7 @@ var root = &cobra.Command{
func main() {
project.Register(root)
api.Register(root)
client.Register(root)
if err := root.Execute(); err != nil {
log.Fatalln(err)
}
Expand Down
44 changes: 23 additions & 21 deletions cmd/nirvana/project/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import (
"text/template"
"time"

"github.com/caicloud/nirvana/cmd/nirvana/utils"
"github.com/caicloud/nirvana/log"
"github.com/caicloud/nirvana/utils/project"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
Expand Down Expand Up @@ -130,7 +130,7 @@ func (o *initOptions) Run(cmd *cobra.Command, args []string) error {
BuildImage: o.BuildImage,
RuntimeImage: o.RuntimeImage,
}
td.ProjectPackage, err = utils.PackageForPath(pathToProject)
td.ProjectPackage, err = project.PackageForPath(pathToProject)
if err != nil {
return err
}
Expand Down Expand Up @@ -212,23 +212,23 @@ func (o *initOptions) directories(project string) []string {
}
}

func (o *initOptions) templates(project string) map[string]string {
func (o *initOptions) templates(proj string) map[string]string {
return map[string]string{
fmt.Sprintf("cmd/%s/main.go", project): o.templateMain(),
fmt.Sprintf("build/%s/Dockerfile", project): o.templateDockerfile(),
"pkg/api/filters/filters.go": o.templateFilters(),
"pkg/api/middlewares/middlewares.go": o.templateMiddlewares(),
"pkg/api/modifiers/modifiers.go": o.templateModifiers(),
"pkg/api/v1/descriptors/descriptors.go": o.templateDescriptors(),
"pkg/api/v1/descriptors/message.go": o.templateMessageAPI(),
"pkg/api/v1/middlewares/middlewares.go": o.templateMiddlewares(),
"pkg/api/api.go": o.templateAPI(),
"pkg/message/message.go": o.templateMessage(),
"pkg/version/version.go": o.templateVersion(),
"Gopkg.toml": o.templateGopkg(),
"Makefile": o.templateMakefile(),
"nirvana.yaml": o.templateProject(),
"README.md": o.templateReadme(),
fmt.Sprintf("cmd/%s/main.go", proj): o.templateMain(),
fmt.Sprintf("build/%s/Dockerfile", proj): o.templateDockerfile(),
"pkg/api/filters/filters.go": o.templateFilters(),
"pkg/api/middlewares/middlewares.go": o.templateMiddlewares(),
"pkg/api/modifiers/modifiers.go": o.templateModifiers(),
"pkg/api/v1/descriptors/descriptors.go": o.templateDescriptors(),
"pkg/api/v1/descriptors/message.go": o.templateMessageAPI(),
"pkg/api/v1/middlewares/middlewares.go": o.templateMiddlewares(),
"pkg/api/api.go": o.templateAPI(),
"pkg/message/message.go": o.templateMessage(),
"pkg/version/version.go": o.templateVersion(),
"Gopkg.toml": o.templateGopkg(),
"Makefile": o.templateMakefile(),
project.DefaultProjectFileName: o.templateProject(),
"README.md": o.templateReadme(),
}
}

Expand Down Expand Up @@ -456,7 +456,7 @@ func init() {
}
var listMessages = def.Definition{
Method: def.Get,
Method: def.List,
Summary: "List Messages",
Description: "Query a specified number of messages and returns an array",
Function: message.ListMessages,
Expand Down Expand Up @@ -576,7 +576,9 @@ ARG TARGET={{ .ProjectName }}
COPY --from=0 /tmp/${TARGET} /${TARGET}
ENTRYPOINT [/${TARGET}]
RUN ln -s /${TARGET} /entrypoint
ENTRYPOINT ["/entrypoint"]
`
}

Expand Down Expand Up @@ -744,7 +746,7 @@ versions:
- name: v1
description: The v1 version is the first version of this project
rules:
- "^/api/v1.*"
- prefix: /api/v1
`
}

Expand Down
Loading

0 comments on commit 6b8ee51

Please sign in to comment.