add type.proto and mysql init code commands

This commit is contained in:
zhuyasen 2023-08-17 00:01:59 +08:00
parent 61166eecb5
commit 6075364a04
6 changed files with 317 additions and 0 deletions

View File

@ -169,6 +169,12 @@ deploy-binary: binary-package
@expect scripts/deploy-binary.sh $(USER) $(PWD) $(IP)
.PHONY: patch
# patch some dependent code, such as types.proto, mysql initialization code. e.g. make patch TYPE=types-pb , make patch TYPE=mysql-redis-init
patch:
@bash scripts/patch.sh $(TYPE)
.PHONY: clean
# clean binary file, cover.out, template file
clean:

View File

@ -0,0 +1,23 @@
package commands
import (
"github.com/zhufuyi/sponge/cmd/sponge/commands/generate"
"github.com/spf13/cobra"
)
// GenCommand generate dependency code
func GenCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "gen",
Short: "Generate dependency code, e.g. mysql and redis initialization code, types.proto",
Long: `generate dependency code.`,
SilenceErrors: true,
SilenceUsage: true,
}
cmd.AddCommand(
generate.MysqlAndRedisCommand(),
generate.TypesPbCommand(),
)
return cmd
}

View File

@ -0,0 +1,129 @@
package generate
import (
"errors"
"fmt"
"strings"
"github.com/zhufuyi/sponge/pkg/gofile"
"github.com/zhufuyi/sponge/pkg/replacer"
"github.com/spf13/cobra"
)
// MysqlAndRedisCommand generate mysql and redis initialization code
func MysqlAndRedisCommand() *cobra.Command {
var (
moduleName string // go.mod module name
outPath string // output directory
targetFile = "internal/model/init.go"
)
cmd := &cobra.Command{
Use: "mysql-redis-init",
Short: "Generate mysql and redis initialization code",
Long: `generate mysql and redis initialization code
Examples:
# generate mysql and redis initialization code.
sponge gen mysql-redis-init --module-name=yourModuleName
# generate mysql and redis initialization code, and specify the server directory, Note: code generation will be canceled when the latest generated file already exists.
sponge gen mysql-redis-init --out=./yourServerDir
`,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
mdName, _ := getNamesFromOutDir(outPath)
if mdName != "" {
moduleName = mdName
} else if moduleName == "" {
return fmt.Errorf(`required flag(s) "module-name" not set, use "sponge gen mysql-redis-init -h" for help`)
}
var isEmpty bool
if outPath == "" {
isEmpty = true
} else {
isEmpty = false
if gofile.IsExists(targetFile) {
fmt.Printf("'%s' already exists, no need to generate it.\n", targetFile)
return nil
}
}
var err error
outPath, err = runMysqlCliCommand(moduleName, outPath)
if err != nil {
return err
}
if isEmpty {
fmt.Printf(`
using help:
move the folder "internal" to your project code folder.
`)
}
if gofile.IsWindows() {
targetFile = "\\" + strings.ReplaceAll(targetFile, "/", "\\")
} else {
targetFile = "/" + targetFile
}
fmt.Printf("generate 'mysql-redis-init' codes successfully, out = %s\n", outPath+targetFile)
return nil
},
}
cmd.Flags().StringVarP(&moduleName, "module-name", "m", "", "module-name is the name of the module in the 'go.mod' file")
cmd.Flags().StringVarP(&outPath, "out", "o", "", "output directory, default is ./mysql-redis-init_<time>, "+
"if you specify the directory where the web or microservice generated by sponge, the module-name flag can be ignored")
return cmd
}
func runMysqlCliCommand(moduleName string, outPath string) (string, error) {
subTplName := "mysql-redis-init"
r := Replacers[TplNameSponge]
if r == nil {
return "", errors.New("replacer is nil")
}
// setting up template information
subDirs := []string{"internal/model"} // only the specified subdirectory is processed, if empty or no subdirectory is specified, it means all files
ignoreDirs := []string{} // specify the directory in the subdirectory where processing is ignored
ignoreFiles := []string{ // specify the files in the subdirectory to be ignored for processing
"userExample.go",
}
r.SetSubDirsAndFiles(subDirs)
r.SetIgnoreSubDirs(ignoreDirs...)
r.SetIgnoreSubFiles(ignoreFiles...)
fields := addMysqlAndRedisInitFields(moduleName)
r.SetReplacementFields(fields)
_ = r.SetOutputDir(outPath, subTplName)
if err := r.SaveFiles(); err != nil {
return "", err
}
return r.GetOutputDir(), nil
}
func addMysqlAndRedisInitFields(moduleName string) []replacer.Field {
var fields []replacer.Field
fields = append(fields, []replacer.Field{
{
Old: "github.com/zhufuyi/sponge/internal",
New: moduleName + "/internal",
IsCaseSensitive: false,
},
{
Old: "github.com/zhufuyi/sponge/configs",
New: moduleName + "/configs",
IsCaseSensitive: false,
},
}...)
return fields
}

View File

@ -0,0 +1,124 @@
package generate
import (
"errors"
"fmt"
"strings"
"github.com/zhufuyi/sponge/pkg/gofile"
"github.com/zhufuyi/sponge/pkg/replacer"
"github.com/spf13/cobra"
)
// TypesPbCommand generate types.proto file
func TypesPbCommand() *cobra.Command {
var (
moduleName string // go.mod module name
outPath string // output directory
targetFile = "api/types/types.proto"
)
cmd := &cobra.Command{
Use: "types-pb",
Short: "Generate types.proto file",
Long: `generate types.proto file
Examples:
# generate types.proto file.
sponge gen types-pb --module-name=yourModuleName
# generate types.proto file and specify the server directory, Note: code generation will be canceled when the latest generated file already exists.
sponge gen types-pb --out=./yourServerDir
`,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
mdName, _ := getNamesFromOutDir(outPath)
if mdName != "" {
moduleName = mdName
} else if moduleName == "" {
return fmt.Errorf(`required flag(s) "module-name" not set, use "sponge gen types-pb -h" for help`)
}
var isEmpty bool
if outPath == "" {
isEmpty = true
} else {
isEmpty = false
if gofile.IsExists(targetFile) {
fmt.Printf("'%s' already exists, no need to generate it.\n", targetFile)
return nil
}
}
var err error
outPath, err = runTypesPbCommand(moduleName, outPath)
if err != nil {
return err
}
if isEmpty {
fmt.Printf(`
using help:
move the folder "api" to your project code folder.
`)
}
if gofile.IsWindows() {
targetFile = "\\" + strings.ReplaceAll(targetFile, "/", "\\")
} else {
targetFile = "/" + targetFile
}
fmt.Printf("generate 'types-pb' codes successfully, out = %s\n", outPath+targetFile)
return nil
},
}
cmd.Flags().StringVarP(&moduleName, "module-name", "m", "", "module-name is the name of the module in the 'go.mod' file")
cmd.Flags().StringVarP(&outPath, "out", "o", "", "output directory, default is ./types-pb_<time>, "+
"if you specify the directory where the web or microservice generated by sponge, the module-name flag can be ignored")
return cmd
}
func runTypesPbCommand(moduleName string, outPath string) (string, error) {
subTplName := "types-pb"
r := Replacers[TplNameSponge]
if r == nil {
return "", errors.New("replacer is nil")
}
// setting up template information
subDirs := []string{"api/types"} // only the specified subdirectory is processed, if empty or no subdirectory is specified, it means all files
ignoreDirs := []string{} // specify the directory in the subdirectory where processing is ignored
ignoreFiles := []string{ // specify the files in the subdirectory to be ignored for processing
"types.pb.go", "types.pb.validate.go",
}
r.SetSubDirsAndFiles(subDirs)
r.SetIgnoreSubDirs(ignoreDirs...)
r.SetIgnoreSubFiles(ignoreFiles...)
fields := addTypePbFields(moduleName)
r.SetReplacementFields(fields)
_ = r.SetOutputDir(outPath, subTplName)
if err := r.SaveFiles(); err != nil {
return "", err
}
return r.GetOutputDir(), nil
}
func addTypePbFields(moduleName string) []replacer.Field {
var fields []replacer.Field
fields = append(fields, []replacer.Field{
{
Old: "github.com/zhufuyi/sponge",
New: moduleName,
IsCaseSensitive: false,
},
}...)
return fields
}

View File

@ -24,6 +24,7 @@ func NewWebCommand() *cobra.Command {
generate.HTTPCommand(),
generate.HTTPPbCommand(),
generate.ConvertSwagJSONCommand("web"),
generate.HandlerPbCommand(),
)
return cmd

34
scripts/patch.sh Normal file
View File

@ -0,0 +1,34 @@
#!/bin/bash
patchType=$1
typesPb="types-pb"
mysqlInit="mysql-redis-init"
function checkResult() {
result=$1
if [ ${result} -ne 0 ]; then
exit ${result}
fi
}
function patchTypesPb() {
sponge gen types-pb --out=./
checkResult $?
}
function patchMysqlAndRedisInit() {
sponge gen mysql-redis-init --out=./
checkResult $?
}
if [ "X$patchType" = "X" ];then
patchTypesPb
patchMysqlAndRedisInit
elif [ "$patchType" = "$typesPb" ]; then
patchTypesPb
elif [ "$patchType" = "$mysqlInit" ]; then
patchMysqlAndRedisInit
else
echo "TYPE should be "", $typesPb or $mysqlInit."
exit 1
fi