Skip to content

Commit

Permalink
✨ feat:add command
Browse files Browse the repository at this point in the history
  • Loading branch information
linyyyang committed Sep 3, 2021
1 parent 1278e76 commit 911fde7
Show file tree
Hide file tree
Showing 15 changed files with 579 additions and 34 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.ginny
.ginny.yml
34 changes: 34 additions & 0 deletions ginny/command/handle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package command

import (
"github.com/gorillazer/ginny-cli/ginny/handle"
"github.com/gorillazer/ginny-cli/ginny/util"
"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(handleCmd)
}

var handleCmd = &cobra.Command{
Use: "handle",
Short: "Create handle file",
Long: "Create handle file from template",
PreRunE: func(cmd *cobra.Command, args []string) (err error) {
return nil
},
RunE: func(cmd *cobra.Command, args []string) (err error) {
if err := CheckArgs(args); err != nil {
return err
}
// 获取参数
handleName := args[0]

if err := handle.CreateHandle(handleName); err != nil {
return err
}

util.Info("Create new handle file success!")
return nil
},
}
40 changes: 40 additions & 0 deletions ginny/command/proto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package command

import (
"github.com/gorillazer/ginny-cli/ginny/handle"
"github.com/gorillazer/ginny-cli/ginny/util"
"github.com/spf13/cobra"
)

func init() {
protoCmd.Flags().BoolP("validate", "v", false, "Added support for parameter verification")
rootCmd.AddCommand(protoCmd)
}

var protoCmd = &cobra.Command{
Use: "proto",
Short: "Create proto file",
Long: "Create proto file from template",
PreRunE: func(cmd *cobra.Command, args []string) (err error) {
return nil
},
RunE: func(cmd *cobra.Command, args []string) (err error) {
if err := CheckArgs(args); err != nil {
return err
}
// 获取参数
serviceName := args[0]
flags := cmd.Flags()
validate, err := flags.GetBool("validate")
if err != nil {
return err
}
if err := handle.CreateProto(serviceName, validate); err != nil {
return err
}

util.Info("Create new proto file success!")
util.Info("You can modify the proto file, and then execute `make proto` to generate pb code.")
return nil
},
}
39 changes: 39 additions & 0 deletions ginny/command/repo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package command

import (
"github.com/gorillazer/ginny-cli/ginny/handle"
"github.com/gorillazer/ginny-cli/ginny/util"
"github.com/spf13/cobra"
)

func init() {
repoCmd.Flags().StringArrayP("database", "d", []string{}, "Define the database used by the project, support mysql、mongo、redis")
rootCmd.AddCommand(repoCmd)
}

var repoCmd = &cobra.Command{
Use: "repo",
Short: "Create repository file",
Long: "Create repository file from template",
PreRunE: func(cmd *cobra.Command, args []string) (err error) {
return nil
},
RunE: func(cmd *cobra.Command, args []string) (err error) {
if err := CheckArgs(args); err != nil {
return err
}
// 获取参数
repoName := args[0]
flags := cmd.Flags()
database, err := flags.GetStringArray("database")
if err != nil {
return err
}
if err := handle.CreateRepo(repoName, database); err != nil {
return err
}

util.Info("Create new repository file success!")
return nil
},
}
34 changes: 34 additions & 0 deletions ginny/command/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package command

import (
"github.com/gorillazer/ginny-cli/ginny/handle"
"github.com/gorillazer/ginny-cli/ginny/util"
"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(serviceCmd)
}

var serviceCmd = &cobra.Command{
Use: "service",
Short: "Create service file",
Long: "Create service file from template",
PreRunE: func(cmd *cobra.Command, args []string) (err error) {
return nil
},
RunE: func(cmd *cobra.Command, args []string) (err error) {
if err := CheckArgs(args); err != nil {
return err
}
// 获取参数
serviceName := args[0]

if err := handle.CreateService(serviceName); err != nil {
return err
}

util.Info("Create new service file success!")
return nil
},
}
1 change: 1 addition & 0 deletions ginny/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.16
require (
github.com/fatih/structs v1.1.0
github.com/go-git/go-git/v5 v5.4.2
github.com/iancoleman/strcase v0.2.0
github.com/spf13/cobra v1.2.1
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
)
2 changes: 2 additions & 0 deletions ginny/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/iancoleman/strcase v0.2.0 h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0=
github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
Expand Down
102 changes: 84 additions & 18 deletions ginny/handle/common.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package handle

import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"

"github.com/fatih/structs"
"github.com/go-git/go-git/v5"
"github.com/gorillazer/ginny-cli/ginny/options"
"github.com/gorillazer/ginny-cli/ginny/util"
"gopkg.in/yaml.v3"
)

// GetCurrentDir 获取当前目录
Expand All @@ -23,35 +25,99 @@ func GetCurrentDir() (string, error) {
}

// PullTemplate 拉取模板
func PullTemplate(dir string) error {
// Clone the given repository to the given directory
util.Info("git clone " + options.TemplateRepo)
func PullTemplate(dir, repo string) error {
if !util.Exists(dir) {
_ = util.MkDir(dir)
// Clone the given repository to the given directory
util.Info("git clone " + repo)
_, err := git.PlainClone(dir, false, &git.CloneOptions{
URL: repo,
Progress: os.Stdout,
})
if err != nil {
util.Error("Clone the given repository error:", err.Error())
return err
}
} else {
if !util.Exists(dir + "/.git") {
return errors.New("The directory is not empty and is not a valid git directory")
}

_, err := git.PlainClone(dir, false, &git.CloneOptions{
URL: options.TemplateRepo,
Progress: os.Stdout,
})
if err != nil {
util.Error("Clone the given repository error:", err.Error())
return err
// We instantiate a new repository targeting the given path (the .git folder)
r, err := git.PlainOpen(dir)
if err != nil {
return err
}
// Get the working directory for the repository
w, err := r.Worktree()
if err != nil {
return err
}
util.Info("git pull origin master ")
err = w.Pull(&git.PullOptions{RemoteName: "origin", Force: true})
if err != nil {
util.Error(err.Error())
return nil
}
// Print the latest commit that was just pulled
ref, err := r.Head()
if err != nil {
util.Error(err.Error())
return nil
}
commit, err := r.CommitObject(ref.Hash())
if err != nil {
util.Error(err.Error())
return nil
}
util.Info("git pull success", commit)
}

return nil
}

// GenerateProjectInfo 构造项目标识
func GenerateProjectInfo() {

func GenerateProjectInfo(projectDir string, p *options.ProjectInfo) error {
bt, err := yaml.Marshal(p)
if err != nil {
return err
}
return util.WriteToFile(projectDir+"/"+options.ProjectFlag, bt)
}

// GetProjectInfo 检查当前目录是否ginny项目,并返回项目信息
func GetProjectInfo() (conf *options.ProjectInfo, err error) {
return nil, nil
func GetProjectInfo() (*options.ProjectInfo, error) {
dir, err := GetCurrentDir()
if err != nil {
return nil, errors.New("Failed to get project directory.")
}

flagFile := dir + "/" + options.ProjectFlag
if !util.Exists(flagFile) {
return nil, errors.New("Current project is not a Ginny project.\n" +
"Please execute command after enter Ginny project root directory.")
}

bin, err := ioutil.ReadFile(flagFile)
if err != nil {
return nil, errors.New("Failed to read project flag file.")
}
conf := &options.ProjectInfo{}
err = yaml.Unmarshal(bin, conf)
if err != nil {
return nil, errors.New("Failed Unmarshal projectinfo.")
}
if conf.ProjectName == "" {
return nil, errors.New("The project flags file is corrupted .")
}
conf.ProjectPath = dir

return conf, nil
}

// ReplaceFileKeyword
func ReplaceFileKeyword(file []string, r *options.ReplaceKeywords) error {
m := structs.Map(r)
for _, f := range file {
func ReplaceFileKeyword(files []string, m map[string]interface{}) error {
for _, f := range files {
if !util.IsFile(f) {
continue
}
Expand Down
61 changes: 61 additions & 0 deletions ginny/handle/handle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package handle

import (
"errors"
"fmt"

"github.com/fatih/structs"
"github.com/gorillazer/ginny-cli/ginny/options"
"github.com/gorillazer/ginny-cli/ginny/util"
"github.com/iancoleman/strcase"
)

func CreateHandle(handleName string) error {
conf, err := GetProjectInfo()
if err != nil {
util.Error("Failed to get project info, ", err.Error())
return err
}

tmpPath := fmt.Sprintf("%s/%s", conf.ProjectPath, options.TempPath)
if err := PullTemplate(tmpPath, options.ComponentTemplateRepo); err != nil {
return err
}

srcFile := fmt.Sprintf("%s/handlers/test.go", tmpPath)
dstFile := fmt.Sprintf("%s/internal/handlers/%s.go", conf.ProjectPath, handleName)
if util.Exists(dstFile) {
return errors.New("File already exists and overwriting is not allowed")
}
if err := util.CopyFile(srcFile, dstFile); err != nil {
return err
}
// replace handle
caseName := strcase.ToCamel(handleName)
r := &options.ReplaceKeywords{
APP_NAME: conf.ProjectName,
MODULE_NAME: conf.ProjectModule,
HANDLE_NAME: caseName,
}

// replace provider
providerFile := fmt.Sprintf("%s/internal/handlers/provider.go", conf.ProjectPath)
if !util.Exists(providerFile) {
if err := util.CopyFile(fmt.Sprintf("%s/handlers/provider.go", tmpPath), providerFile); err != nil {
return err
}
}
m := structs.Map(r)
m[options.HandleReplaceAnchor[1]] = options.HandleReplaceAnchorValue[1]([]string{handleName, caseName})
m[options.HandleReplaceAnchor[2]] = options.HandleReplaceAnchorValue[2]([]string{caseName})

if err := ReplaceFileKeyword([]string{dstFile, providerFile}, m); err != nil {
return err
}

if err := ExecCommand(conf.ProjectPath, "go", "mod", "tidy"); err != nil {
return err
}

return nil
}
Loading

0 comments on commit 911fde7

Please sign in to comment.