This commit is contained in:
孟帅
2024-07-21 22:21:02 +08:00
parent 7d8330f72f
commit a37d088360
440 changed files with 6303 additions and 3339 deletions

View File

@@ -12,63 +12,111 @@ import (
)
// GenDefaultOption 生成默认表格回显样式
func GenDefaultOption(key interface{}, label string) *model.Option {
func GenDefaultOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: "default",
Extra: e,
}
}
func GenSuccessOption(key interface{}, label string) *model.Option {
func GenSuccessOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: "success",
Extra: e,
}
}
func GenWarningOption(key interface{}, label string) *model.Option {
func GenWarningOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: "warning",
Extra: e,
}
}
func GenErrorOption(key interface{}, label string) *model.Option {
func GenErrorOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: "error",
Extra: e,
}
}
func GenInfoOption(key interface{}, label string) *model.Option {
func GenInfoOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: "info",
Extra: e,
}
}
func GenPrimaryOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: "primary",
Extra: e,
}
}
// GenCustomOption 生成自定义表格回显样式
func GenCustomOption(key interface{}, label string, custom string) *model.Option {
func GenCustomOption(key interface{}, label string, custom string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
return &model.Option{
Key: key,
Label: label,
Value: key,
ListClass: custom,
Extra: e,
}
}
// GenHashOption 根据不同label以hash算法生成表格回显样式
func GenHashOption(key interface{}, label string) *model.Option {
func GenHashOption(key interface{}, label string, extra ...any) *model.Option {
e := interface{}(nil)
if len(extra) > 0 {
e = extra[0]
}
strings := []string{"default", "primary", "info", "success", "warning", "error"}
hash := fnv.New32()
@@ -84,6 +132,7 @@ func GenHashOption(key interface{}, label string) *model.Option {
Label: label,
Value: key,
ListClass: tag,
Extra: e,
}
}
@@ -94,7 +143,7 @@ func GetOptionLabel(ses []*model.Option, key interface{}) string {
return v.Label
}
}
return `Unknown`
return ``
}
// HasOptionKey 是否存在指定key

View File

@@ -0,0 +1,177 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package cmd
import (
"context"
"io"
"net/http"
"os"
"path"
"path/filepath"
"time"
"github.com/gogf/gf/v2/encoding/gcompress"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"hotgo/internal/library/hggen/internal/utility/mlog"
)
const (
// DocURL is the download address of the document
DocURL = "https://github.com/gogf/gf/archive/refs/heads/gh-pages.zip"
)
var (
Doc = cDoc{}
)
type cDoc struct {
g.Meta `name:"doc" brief:"download https://pages.goframe.org/ to run locally"`
}
type cDocInput struct {
g.Meta `name:"doc" config:"gfcli.doc"`
Path string `short:"p" name:"path" brief:"download docs directory path, default is \"%temp%/goframe\""`
Port int `short:"o" name:"port" brief:"http server port, default is 8080" d:"8080"`
Update bool `short:"u" name:"update" brief:"clean docs directory and update docs"`
Clean bool `short:"c" name:"clean" brief:"clean docs directory"`
Proxy string `short:"x" name:"proxy" brief:"proxy for download, such as https://hub.gitmirror.com/;https://ghproxy.com/;https://ghproxy.net/;https://ghps.cc/"`
}
type cDocOutput struct{}
func (c cDoc) Index(ctx context.Context, in cDocInput) (out *cDocOutput, err error) {
docs := NewDocSetting(ctx, in)
mlog.Print("Directory where the document is downloaded:", docs.TempDir)
if in.Clean {
mlog.Print("Cleaning document directory")
err = docs.Clean()
if err != nil {
mlog.Print("Failed to clean document directory:", err)
return
}
return
}
if in.Update {
mlog.Print("Cleaning old document directory")
err = docs.Clean()
if err != nil {
mlog.Print("Failed to clean old document directory:", err)
return
}
}
err = docs.DownloadDoc()
if err != nil {
mlog.Print("Failed to download document:", err)
return
}
s := g.Server()
s.SetServerRoot(docs.DocDir)
s.SetPort(in.Port)
s.SetDumpRouterMap(false)
mlog.Printf("Access address http://127.0.0.1:%d", in.Port)
s.Run()
return
}
// DocSetting doc setting
type DocSetting struct {
TempDir string
DocURL string
DocDir string
DocZipFile string
}
// NewDocSetting new DocSetting
func NewDocSetting(ctx context.Context, in cDocInput) *DocSetting {
fileName := "gf-doc-md.zip"
tempDir := in.Path
if tempDir == "" {
tempDir = gfile.Temp("goframe/docs")
} else {
tempDir = gfile.Abs(path.Join(tempDir, "docs"))
}
return &DocSetting{
TempDir: filepath.FromSlash(tempDir),
DocDir: filepath.FromSlash(path.Join(tempDir, "gf-gh-pages")),
DocURL: in.Proxy + DocURL,
DocZipFile: filepath.FromSlash(path.Join(tempDir, fileName)),
}
}
// Clean clean the temporary directory
func (d *DocSetting) Clean() error {
if _, err := os.Stat(d.TempDir); err == nil {
err = gfile.Remove(d.TempDir)
if err != nil {
mlog.Print("Failed to delete temporary directory:", err)
return err
}
}
return nil
}
// DownloadDoc download the document
func (d *DocSetting) DownloadDoc() error {
if _, err := os.Stat(d.TempDir); err != nil {
err = gfile.Mkdir(d.TempDir)
if err != nil {
mlog.Print("Failed to create temporary directory:", err)
return nil
}
}
// Check if the file exists
if _, err := os.Stat(d.DocDir); err == nil {
mlog.Print("Document already exists, no need to download and unzip")
return nil
}
if _, err := os.Stat(d.DocZipFile); err == nil {
mlog.Print("File already exists, no need to download")
} else {
mlog.Printf("File does not exist, start downloading: %s", d.DocURL)
startTime := time.Now()
// Download the file
resp, err := http.Get(d.DocURL)
if err != nil {
mlog.Print("Failed to download file:", err)
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(d.DocZipFile)
if err != nil {
mlog.Print("Failed to create file:", err)
return err
}
defer out.Close()
// Write the response body to the file
_, err = io.Copy(out, resp.Body)
if err != nil {
mlog.Print("Failed to write file:", err)
return err
}
mlog.Printf("Download successful, time-consuming: %v", time.Since(startTime))
}
mlog.Print("Start unzipping the file...")
// Unzip the file
err := gcompress.UnZipFile(d.DocZipFile, d.TempDir)
if err != nil {
mlog.Print("Failed to unzip the file, please run again:", err)
gfile.Remove(d.DocZipFile)
return err
}
mlog.Print("Download and unzip successful")
return nil
}

View File

@@ -8,6 +8,7 @@ package cmd
import (
//_ "github.com/gogf/gf/contrib/drivers/clickhouse/v2"
// _ "github.com/gogf/gf/contrib/drivers/dm/v2" // precompilation does not support certain target platforms.
//_ "github.com/gogf/gf/contrib/drivers/mssql/v2"
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
//_ "github.com/gogf/gf/contrib/drivers/oracle/v2"

View File

@@ -19,9 +19,9 @@ import (
"github.com/gogf/gf/v2/os/gres"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gtag"
"hotgo/internal/library/hggen/internal/utility/allyes"
"hotgo/internal/library/hggen/internal/utility/mlog"
"hotgo/internal/library/hggen/internal/utility/utils"
)
var (
@@ -34,13 +34,15 @@ type cInit struct {
}
const (
cInitRepoPrefix = `github.com/gogf/`
cInitMonoRepo = `template-mono`
cInitSingleRepo = `template-single`
cInitBrief = `create and initialize an empty GoFrame project`
cInitEg = `
cInitRepoPrefix = `github.com/gogf/`
cInitMonoRepo = `template-mono`
cInitMonoRepoApp = `template-mono-app`
cInitSingleRepo = `template-single`
cInitBrief = `create and initialize an empty GoFrame project`
cInitEg = `
gf init my-project
gf init my-mono-repo -m
gf init my-mono-repo -a
`
cInitNameBrief = `
name for the project. It will create a folder with NAME in current directory.
@@ -61,11 +63,12 @@ func init() {
}
type cInitInput struct {
g.Meta `name:"init"`
Name string `name:"NAME" arg:"true" v:"required" brief:"{cInitNameBrief}"`
Mono bool `name:"mono" short:"m" brief:"initialize a mono-repo instead a single-repo" orphan:"true"`
Update bool `name:"update" short:"u" brief:"update to the latest goframe version" orphan:"true"`
Module string `name:"module" short:"g" brief:"custom go module"`
g.Meta `name:"init"`
Name string `name:"NAME" arg:"true" v:"required" brief:"{cInitNameBrief}"`
Mono bool `name:"mono" short:"m" brief:"initialize a mono-repo instead a single-repo" orphan:"true"`
MonoApp bool `name:"monoApp" short:"a" brief:"initialize a mono-repo-app instead a single-repo" orphan:"true"`
Update bool `name:"update" short:"u" brief:"update to the latest goframe version" orphan:"true"`
Module string `name:"module" short:"g" brief:"custom go module"`
}
type cInitOutput struct{}
@@ -86,11 +89,15 @@ func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err
templateRepoName string
gitignoreFile = in.Name + "/" + cInitGitignore
)
if in.Mono {
templateRepoName = cInitMonoRepo
} else if in.MonoApp {
templateRepoName = cInitMonoRepoApp
} else {
templateRepoName = cInitSingleRepo
}
err = gres.Export(templateRepoName, in.Name, gres.ExportOption{
RemovePrefix: templateRepoName,
})
@@ -101,7 +108,8 @@ func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err
// build ignoreFiles from the .gitignore file
ignoreFiles := make([]string, 0, 10)
ignoreFiles = append(ignoreFiles, cInitGitDir)
if overwrote {
// in.MonoApp is a mono-repo-app, it should ignore the .gitignore file
if overwrote && !in.MonoApp {
err = gfile.ReadLines(gitignoreFile, func(line string) error {
// Add only hidden files or directories
// If other directories are added, it may cause the entire directory to be ignored
@@ -118,10 +126,14 @@ func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err
}
}
// Replace module name.
// Get template name and module name.
if in.Module == "" {
in.Module = gfile.Basename(gfile.RealPath(in.Name))
}
if in.MonoApp {
pwd := gfile.Pwd() + string(os.PathSeparator) + in.Name
in.Module = utils.GetImportPath(pwd)
}
// Replace template name to project name.
err = gfile.ReplaceDirFunc(func(path, content string) string {

View File

@@ -63,7 +63,7 @@ func init() {
}
type cPackInput struct {
g.Meta `name:"pack"`
g.Meta `name:"pack" config:"gfcli.pack"`
Src string `name:"SRC" arg:"true" v:"required" brief:"{cPackSrcBrief}"`
Dst string `name:"DST" arg:"true" v:"required" brief:"{cPackDstBrief}"`
Name string `name:"name" short:"n" brief:"{cPackNameBrief}"`

View File

@@ -9,6 +9,7 @@ package cmd
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
@@ -55,7 +56,7 @@ The "run" command is used for running go codes with hot-compiled-like feature,
which compiles and runs the go codes asynchronously when codes change.
`
cRunFileBrief = `building file path.`
cRunPathBrief = `output directory path for built binary file. it's "manifest/output" in default`
cRunPathBrief = `output directory path for built binary file. it's "./" in default`
cRunExtraBrief = `the same options as "go run"/"go build" except some options as follows defined`
cRunArgsBrief = `custom arguments for your process`
cRunWatchPathsBrief = `watch additional paths for live reload, separated by ",". i.e. "manifest/config/*.yaml"`
@@ -81,7 +82,7 @@ func init() {
type (
cRunInput struct {
g.Meta `name:"run"`
g.Meta `name:"run" config:"gfcli.run"`
File string `name:"FILE" arg:"true" brief:"{cRunFileBrief}" v:"required"`
Path string `name:"path" short:"p" brief:"{cRunPathBrief}" d:"./"`
Extra string `name:"extra" short:"e" brief:"{cRunExtraBrief}"`
@@ -104,13 +105,14 @@ func (c cRun) Index(ctx context.Context, in cRunInput) (out *cRunOutput, err err
app := &cRunApp{
File: in.File,
Path: in.Path,
Path: filepath.FromSlash(in.Path),
Options: in.Extra,
Args: in.Args,
WatchPaths: in.WatchPaths,
}
dirty := gtype.NewBool()
var outputPath = app.genOutputPath()
callbackFunc := func(event *gfsnotify.Event) {
if gfile.ExtName(event.Path) != "go" {
return
@@ -125,7 +127,7 @@ func (c cRun) Index(ctx context.Context, in cRunInput) (out *cRunOutput, err err
gtimer.SetTimeout(ctx, 1500*gtime.MS, func(ctx context.Context) {
defer dirty.Set(false)
mlog.Printf(`watched file changes: %s`, event.String())
app.Run(ctx)
app.Run(ctx, outputPath)
})
}
@@ -143,24 +145,21 @@ func (c cRun) Index(ctx context.Context, in cRunInput) (out *cRunOutput, err err
}
}
go app.Run(ctx)
go app.Run(ctx, outputPath)
gproc.AddSigHandlerShutdown(func(sig os.Signal) {
app.End(ctx, sig, outputPath)
os.Exit(0)
})
gproc.Listen()
select {}
}
func (app *cRunApp) Run(ctx context.Context) {
func (app *cRunApp) Run(ctx context.Context, outputPath string) {
// Rebuild and run the codes.
renamePath := ""
mlog.Printf("build: %s", app.File)
outputPath := gfile.Join(app.Path, gfile.Name(app.File))
if runtime.GOOS == "windows" {
outputPath += ".exe"
if gfile.Exists(outputPath) {
renamePath = outputPath + "~"
if err := gfile.Rename(outputPath, renamePath); err != nil {
mlog.Print(err)
}
}
}
// In case of `pipe: too many open files` error.
// Build the app.
buildCommand := fmt.Sprintf(
@@ -198,6 +197,36 @@ func (app *cRunApp) Run(ctx context.Context) {
}
}
func (app *cRunApp) End(ctx context.Context, sig os.Signal, outputPath string) {
// Delete the binary file.
// firstly, kill the process.
if process != nil {
if err := process.Kill(); err != nil {
mlog.Debugf("kill process error: %s", err.Error())
}
}
if err := gfile.Remove(outputPath); err != nil {
mlog.Printf("delete binary file error: %s", err.Error())
} else {
mlog.Printf("deleted binary file: %s", outputPath)
}
}
func (app *cRunApp) genOutputPath() (outputPath string) {
var renamePath string
outputPath = gfile.Join(app.Path, gfile.Name(app.File))
if runtime.GOOS == "windows" {
outputPath += ".exe"
if gfile.Exists(outputPath) {
renamePath = outputPath + "~"
if err := gfile.Rename(outputPath, renamePath); err != nil {
mlog.Print(err)
}
}
}
return filepath.FromSlash(outputPath)
}
func matchWatchPaths(watchPaths []string, eventPath string) bool {
for _, path := range watchPaths {
absPath, err := filepath.Abs(path)

View File

@@ -47,7 +47,7 @@ gf tpl parse -p ./template -v values.json -o ./template.parsed
type (
cTplParseInput struct {
g.Meta `name:"parse" brief:"{cTplParseBrief}" eg:"{cTplParseEg}"`
g.Meta `name:"parse" config:"gfcli.tpl.parse" brief:"{cTplParseBrief}" eg:"{cTplParseEg}"`
Path string `name:"path" short:"p" brief:"template file or folder path" v:"required"`
Pattern string `name:"pattern" short:"n" brief:"template file pattern when path is a folder, default is:*" d:"*"`
Recursive bool `name:"recursive" short:"c" brief:"recursively parsing files if path is folder, default is:true" d:"true"`

View File

@@ -48,7 +48,7 @@ func init() {
}
type cUpInput struct {
g.Meta `name:"up" config:"gfcli.up"`
g.Meta `name:"up" config:"gfcli.up"`
All bool `name:"all" short:"a" brief:"upgrade both version and cli, auto fix codes" orphan:"true"`
Cli bool `name:"cli" short:"c" brief:"also upgrade CLI tool" orphan:"true"`
Fix bool `name:"fix" short:"f" brief:"auto fix codes(it only make sense if cli is to be upgraded)" orphan:"true"`
@@ -142,8 +142,9 @@ func (c cUp) doUpgradeVersion(ctx context.Context, in cUpInput) (out *doUpgradeV
}
for _, pkg := range packages {
mlog.Printf(`upgrading "%s" from "%s" to "latest"`, pkg.Name, pkg.Version)
// go get -u
command := fmt.Sprintf(`cd %s && go get -u %s@latest`, dirPath, pkg.Name)
mlog.Printf(`running command: go get %s@latest`, pkg.Name)
// go get @latest
command := fmt.Sprintf(`cd %s && go get %s@latest`, dirPath, pkg.Name)
if err = gproc.ShellRun(ctx, command); err != nil {
return
}

View File

@@ -41,9 +41,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
defer gfile.Remove(path)
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
if err != nil {
panic(err)
}
t.AssertNil(err)
// apiInterface file
var (
@@ -84,3 +82,228 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
}
})
}
func expectFilesContent(t *gtest.T, paths []string, expectPaths []string) {
for i, expectFile := range expectPaths {
val := gfile.GetContents(paths[i])
expect := gfile.GetContents(expectFile)
t.Assert(val, expect)
}
}
// gf gen ctrl -m
// In the same module, different API files are added
func Test_Gen_Ctrl_UseMerge_AddNewFile(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
ctrlPath = gfile.Temp(guid.S())
//ctrlPath = gtest.DataPath("issue", "3460", "controller")
apiFolder = gtest.DataPath("genctrl-merge", "add_new_file", "api")
in = genctrl.CGenCtrlInput{
SrcFolder: apiFolder,
DstFolder: ctrlPath,
Merge: true,
}
)
const testNewApiFile = `
package v1
import "github.com/gogf/gf/v2/frame/g"
type DictTypeAddReq struct {
g.Meta
}
type DictTypeAddRes struct {
}
`
err := gfile.Mkdir(ctrlPath)
t.AssertNil(err)
defer gfile.Remove(ctrlPath)
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
t.AssertNil(err)
var (
genApi = filepath.Join(apiFolder, "/dict/dict.go")
genApiExpect = filepath.Join(apiFolder, "/dict/dict_expect.go")
)
defer gfile.Remove(genApi)
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
genCtrlFiles, err := gfile.ScanDir(ctrlPath, "*.go", true)
t.AssertNil(err)
t.Assert(genCtrlFiles, []string{
filepath.Join(ctrlPath, "/dict/dict.go"),
filepath.Join(ctrlPath, "/dict/dict_new.go"),
filepath.Join(ctrlPath, "/dict/dict_v1_dict_type.go"),
})
expectCtrlPath := gtest.DataPath("genctrl-merge", "add_new_file", "controller")
expectFiles := []string{
filepath.Join(expectCtrlPath, "/dict/dict.go"),
filepath.Join(expectCtrlPath, "/dict/dict_new.go"),
filepath.Join(expectCtrlPath, "/dict/dict_v1_dict_type.go"),
}
// Line Feed maybe \r\n or \n
expectFilesContent(t, genCtrlFiles, expectFiles)
// Add a new API file
newApiFilePath := filepath.Join(apiFolder, "/dict/v1/test_new.go")
err = gfile.PutContents(newApiFilePath, testNewApiFile)
t.AssertNil(err)
defer gfile.Remove(newApiFilePath)
// Then execute the command
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
t.AssertNil(err)
genApi = filepath.Join(apiFolder, "/dict.go")
genApiExpect = filepath.Join(apiFolder, "/dict_add_new_ctrl_expect.gotest")
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
genCtrlFiles = append(genCtrlFiles, filepath.Join(ctrlPath, "/dict/dict_v1_test_new.go"))
// Use the gotest suffix, otherwise the IDE will delete the import
expectFiles = append(expectFiles, filepath.Join(expectCtrlPath, "/dict/dict_v1_test_new.gotest"))
// Line Feed maybe \r\n or \n
expectFilesContent(t, genCtrlFiles, expectFiles)
})
}
// gf gen ctrl -m
// In the same module, Add the same file to the API
func Test_Gen_Ctrl_UseMerge_AddNewCtrl(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
ctrlPath = gfile.Temp(guid.S())
//ctrlPath = gtest.DataPath("issue", "3460", "controller")
apiFolder = gtest.DataPath("genctrl-merge", "add_new_ctrl", "api")
in = genctrl.CGenCtrlInput{
SrcFolder: apiFolder,
DstFolder: ctrlPath,
Merge: true,
}
)
err := gfile.Mkdir(ctrlPath)
t.AssertNil(err)
defer gfile.Remove(ctrlPath)
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
t.AssertNil(err)
var (
genApi = filepath.Join(apiFolder, "/dict/dict.go")
genApiExpect = filepath.Join(apiFolder, "/dict/dict_expect.go")
)
defer gfile.Remove(genApi)
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
genCtrlFiles, err := gfile.ScanDir(ctrlPath, "*.go", true)
t.AssertNil(err)
t.Assert(genCtrlFiles, []string{
filepath.Join(ctrlPath, "/dict/dict.go"),
filepath.Join(ctrlPath, "/dict/dict_new.go"),
filepath.Join(ctrlPath, "/dict/dict_v1_dict_type.go"),
})
expectCtrlPath := gtest.DataPath("genctrl-merge", "add_new_ctrl", "controller")
expectFiles := []string{
filepath.Join(expectCtrlPath, "/dict/dict.go"),
filepath.Join(expectCtrlPath, "/dict/dict_new.go"),
filepath.Join(expectCtrlPath, "/dict/dict_v1_dict_type.go"),
}
// Line Feed maybe \r\n or \n
expectFilesContent(t, genCtrlFiles, expectFiles)
const testNewApiFile = `
type DictTypeAddReq struct {
g.Meta
}
type DictTypeAddRes struct {
}
`
dictModuleFileName := filepath.Join(apiFolder, "/dict/v1/dict_type.go")
// Save the contents of the file before the changes
apiFileContents := gfile.GetContents(dictModuleFileName)
// Add a new API file
err = gfile.PutContentsAppend(dictModuleFileName, testNewApiFile)
t.AssertNil(err)
//==================================
// Then execute the command
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
t.AssertNil(err)
genApi = filepath.Join(apiFolder, "/dict.go")
genApiExpect = filepath.Join(apiFolder, "/dict_add_new_ctrl_expect.gotest")
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
// Use the gotest suffix, otherwise the IDE will delete the import
expectFiles[2] = filepath.Join(expectCtrlPath, "/dict/dict_v1_test_new.gotest")
// Line Feed maybe \r\n or \n
expectFilesContent(t, genCtrlFiles, expectFiles)
// Restore the contents of the original API file
err = gfile.PutContents(dictModuleFileName, apiFileContents)
t.AssertNil(err)
})
}
// https://github.com/gogf/gf/issues/3460
func Test_Gen_Ctrl_UseMerge_Issue3460(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
ctrlPath = gfile.Temp(guid.S())
//ctrlPath = gtest.DataPath("issue", "3460", "controller")
apiFolder = gtest.DataPath("issue", "3460", "api")
in = genctrl.CGenCtrlInput{
SrcFolder: apiFolder,
DstFolder: ctrlPath,
WatchFile: "",
SdkPath: "",
SdkStdVersion: false,
SdkNoV1: false,
Clear: false,
Merge: true,
}
)
err := gfile.Mkdir(ctrlPath)
t.AssertNil(err)
defer gfile.Remove(ctrlPath)
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
t.AssertNil(err)
files, err := gfile.ScanDir(ctrlPath, "*.go", true)
t.AssertNil(err)
t.Assert(files, []string{
filepath.Join(ctrlPath, "/hello/hello.go"),
filepath.Join(ctrlPath, "/hello/hello_new.go"),
filepath.Join(ctrlPath, "/hello/hello_v1_req.go"),
filepath.Join(ctrlPath, "/hello/hello_v2_req.go"),
})
expectCtrlPath := gtest.DataPath("issue", "3460", "controller")
expectFiles := []string{
filepath.Join(expectCtrlPath, "/hello/hello.go"),
filepath.Join(expectCtrlPath, "/hello/hello_new.go"),
filepath.Join(expectCtrlPath, "/hello/hello_v1_req.go"),
filepath.Join(expectCtrlPath, "/hello/hello_v2_req.go"),
}
// Line Feed maybe \r\n or \n
for i, expectFile := range expectFiles {
val := gfile.GetContents(files[i])
expect := gfile.GetContents(expectFile)
t.Assert(val, expect)
}
})
}

View File

@@ -12,6 +12,8 @@ import (
"testing"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcfg"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
@@ -69,6 +71,7 @@ func Test_Gen_Dao_Default(t *testing.T) {
NoModelComment: false,
Clear: false,
TypeMapping: nil,
FieldMapping: nil,
}
)
err = gutil.FillStructWithDefault(&in)
@@ -169,6 +172,7 @@ func Test_Gen_Dao_TypeMapping(t *testing.T) {
Import: "github.com/shopspring/decimal",
},
},
FieldMapping: nil,
}
)
err = gutil.FillStructWithDefault(&in)
@@ -211,6 +215,108 @@ func Test_Gen_Dao_TypeMapping(t *testing.T) {
})
}
func Test_Gen_Dao_FieldMapping(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`gendao`, `user.tpl.sql`),
table,
)
)
defer dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)
var (
path = gfile.Temp(guid.S())
group = "test"
in = gendao.CGenDaoInput{
Path: path,
Link: link,
Tables: "",
TablesEx: "",
Group: group,
Prefix: "",
RemovePrefix: "",
JsonCase: "",
ImportPrefix: "",
DaoPath: "",
DoPath: "",
EntityPath: "",
TplDaoIndexPath: "",
TplDaoInternalPath: "",
TplDaoDoPath: "",
TplDaoEntityPath: "",
StdTime: false,
WithTime: false,
GJsonSupport: false,
OverwriteDao: false,
DescriptionTag: false,
NoJsonTag: false,
NoModelComment: false,
Clear: false,
TypeMapping: map[gendao.DBFieldTypeName]gendao.CustomAttributeType{
"int": {
Type: "int64",
Import: "",
},
},
FieldMapping: map[gendao.DBTableFieldName]gendao.CustomAttributeType{
"table_user.score": {
Type: "decimal.Decimal",
Import: "github.com/shopspring/decimal",
},
},
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
// for go mod import path auto retrieve.
err = gfile.Copy(
gtest.DataPath("gendao", "go.mod.txt"),
gfile.Join(path, "go.mod"),
)
t.AssertNil(err)
_, err = gendao.CGenDao{}.Dao(ctx, in)
t.AssertNil(err)
defer gfile.Remove(path)
// files
files, err := gfile.ScanDir(path, "*.go", true)
t.AssertNil(err)
t.Assert(files, []string{
filepath.FromSlash(path + "/dao/internal/table_user.go"),
filepath.FromSlash(path + "/dao/table_user.go"),
filepath.FromSlash(path + "/model/do/table_user.go"),
filepath.FromSlash(path + "/model/entity/table_user.go"),
})
// content
testPath := gtest.DataPath("gendao", "generated_user_field_mapping")
expectFiles := []string{
filepath.FromSlash(testPath + "/dao/internal/table_user.go"),
filepath.FromSlash(testPath + "/dao/table_user.go"),
filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"),
}
for i, _ := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}
func execSqlFile(db gdb.DB, filePath string, args ...any) error {
sqlContent := fmt.Sprintf(
gfile.GetContents(filePath),
@@ -225,6 +331,7 @@ func execSqlFile(db gdb.DB, filePath string, args ...any) error {
return nil
}
// https://github.com/gogf/gf/issues/2572
func Test_Gen_Dao_Issue2572(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
@@ -244,7 +351,7 @@ func Test_Gen_Dao_Issue2572(t *testing.T) {
group = "test"
in = gendao.CGenDaoInput{
Path: path,
Link: link,
Link: "",
Tables: "",
TablesEx: "",
Group: group,
@@ -268,6 +375,7 @@ func Test_Gen_Dao_Issue2572(t *testing.T) {
NoModelComment: false,
Clear: false,
TypeMapping: nil,
FieldMapping: nil,
}
)
err = gutil.FillStructWithDefault(&in)
@@ -293,17 +401,26 @@ func Test_Gen_Dao_Issue2572(t *testing.T) {
for i, generatedFile := range generatedFiles {
generatedFiles[i] = gstr.TrimLeftStr(generatedFile, path)
}
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/dao/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/dao/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/internal/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/internal/user_2.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/user_2.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/do/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/do/user_2.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/entity/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/entity/user_2.go")), true)
})
}
// https://github.com/gogf/gf/issues/2616
func Test_Gen_Dao_Issue2616(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
@@ -323,7 +440,7 @@ func Test_Gen_Dao_Issue2616(t *testing.T) {
group = "test"
in = gendao.CGenDaoInput{
Path: path,
Link: link,
Link: "",
Tables: "",
TablesEx: "",
Group: group,
@@ -347,6 +464,7 @@ func Test_Gen_Dao_Issue2616(t *testing.T) {
NoModelComment: false,
Clear: false,
TypeMapping: nil,
FieldMapping: nil,
}
)
err = gutil.FillStructWithDefault(&in)
@@ -372,14 +490,22 @@ func Test_Gen_Dao_Issue2616(t *testing.T) {
for i, generatedFile := range generatedFiles {
generatedFiles[i] = gstr.TrimLeftStr(generatedFile, path)
}
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/dao/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/dao/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_1.go"), true)
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_2.go"), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/internal/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/internal/user_2.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/dao/user_2.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/do/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/do/user_2.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/entity/user_1.go")), true)
t.Assert(gstr.InArray(generatedFiles,
filepath.FromSlash("/model/entity/user_2.go")), true)
// Key string to check if overwrite the dao files.
// dao user1 is not be overwritten as configured in config.yaml.
@@ -449,6 +575,7 @@ func Test_Gen_Dao_Issue2746(t *testing.T) {
NoModelComment: false,
Clear: false,
TypeMapping: nil,
FieldMapping: nil,
}
)
err = gutil.FillStructWithDefault(&in)
@@ -468,3 +595,99 @@ func Test_Gen_Dao_Issue2746(t *testing.T) {
t.Assert(expectContent, gfile.GetContents(file))
})
}
// https://github.com/gogf/gf/issues/3459
func Test_Gen_Dao_Issue3459(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`gendao`, `user.tpl.sql`),
table,
)
)
dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)
var (
confDir = gtest.DataPath("issue", "3459")
path = gfile.Temp(guid.S())
group = "test"
in = gendao.CGenDaoInput{
Path: path,
Link: link,
Tables: "",
TablesEx: "",
Group: group,
Prefix: "",
RemovePrefix: "",
JsonCase: "SnakeScreaming",
ImportPrefix: "",
DaoPath: "",
DoPath: "",
EntityPath: "",
TplDaoIndexPath: "",
TplDaoInternalPath: "",
TplDaoDoPath: "",
TplDaoEntityPath: "",
StdTime: false,
WithTime: false,
GJsonSupport: false,
OverwriteDao: false,
DescriptionTag: false,
NoJsonTag: false,
NoModelComment: false,
Clear: false,
TypeMapping: nil,
}
)
err = g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetPath(confDir)
t.AssertNil(err)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
// for go mod import path auto retrieve.
err = gfile.Copy(
gtest.DataPath("gendao", "go.mod.txt"),
gfile.Join(path, "go.mod"),
)
t.AssertNil(err)
_, err = gendao.CGenDao{}.Dao(ctx, in)
t.AssertNil(err)
defer gfile.Remove(path)
// files
files, err := gfile.ScanDir(path, "*.go", true)
t.AssertNil(err)
t.Assert(files, []string{
filepath.FromSlash(path + "/dao/internal/table_user.go"),
filepath.FromSlash(path + "/dao/table_user.go"),
filepath.FromSlash(path + "/model/do/table_user.go"),
filepath.FromSlash(path + "/model/entity/table_user.go"),
})
// content
testPath := gtest.DataPath("gendao", "generated_user")
expectFiles := []string{
filepath.FromSlash(testPath + "/dao/internal/table_user.go"),
filepath.FromSlash(testPath + "/dao/table_user.go"),
filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"),
}
for i, _ := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}

View File

@@ -8,18 +8,18 @@ package cmd
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/guid"
"github.com/gogf/gf/v2/util/gutil"
"hotgo/internal/library/hggen/internal/cmd/genpbentity"
)
func Test_Gen_Pbentity_NameCase(t *testing.T) {
func Test_Gen_Pbentity_Default(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
@@ -38,31 +38,171 @@ func Test_Gen_Pbentity_NameCase(t *testing.T) {
}
}
defer dropTableWithDb(db, table)
var path = gfile.Temp(guid.S())
var (
path = gfile.Temp(guid.S())
in = genpbentity.CGenPbEntityInput{
Path: path,
Package: "unittest",
Link: link,
Tables: "",
Prefix: "",
RemovePrefix: "",
RemoveFieldPrefix: "",
NameCase: "",
JsonCase: "",
Option: "",
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)
root, err := gcmd.NewFromObject(GF)
t.AssertNil(err)
err = root.AddObject(
Gen,
)
t.AssertNil(err)
os.Args = []string{"gf", "gen", "pbentity", "-l", link, "-p", path, "-package=unittest", "-nameCase=SnakeScreaming"}
err = root.RunWithError(ctx)
_, err = genpbentity.CGenPbEntity{}.PbEntity(ctx, in)
t.AssertNil(err)
files := []string{
filepath.FromSlash(path + "/table_user.proto"),
}
// files
files, err := gfile.ScanDir(path, "*.proto", false)
t.AssertNil(err)
t.Assert(files, []string{
path + filepath.FromSlash("/table_user.proto"),
})
testPath := gtest.DataPath("genpbentity", "generated_user")
// contents
testPath := gtest.DataPath("genpbentity", "generated")
expectFiles := []string{
filepath.FromSlash(testPath + "/table_user.proto"),
testPath + filepath.FromSlash("/table_user.proto"),
}
for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}
func Test_Gen_Pbentity_NameCase_SnakeScreaming(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`genpbentity`, `user.tpl.sql`),
table,
)
)
dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)
var (
path = gfile.Temp(guid.S())
in = genpbentity.CGenPbEntityInput{
Path: path,
Package: "unittest",
Link: link,
Tables: "",
Prefix: "",
RemovePrefix: "",
RemoveFieldPrefix: "",
NameCase: "SnakeScreaming",
JsonCase: "",
Option: "",
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)
_, err = genpbentity.CGenPbEntity{}.PbEntity(ctx, in)
t.AssertNil(err)
// files
files, err := gfile.ScanDir(path, "*.proto", false)
t.AssertNil(err)
t.Assert(files, []string{
path + filepath.FromSlash("/table_user.proto"),
})
// contents
testPath := gtest.DataPath("genpbentity", "generated")
expectFiles := []string{
testPath + filepath.FromSlash("/table_user_snake_screaming.proto"),
}
for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}
// https://github.com/gogf/gf/issues/3545
func Test_Issue_3545(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`genpbentity`, `user.tpl.sql`),
table,
)
)
dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)
var (
path = gfile.Temp(guid.S())
in = genpbentity.CGenPbEntityInput{
Path: path,
Package: "",
Link: link,
Tables: "",
Prefix: "",
RemovePrefix: "",
RemoveFieldPrefix: "",
NameCase: "",
JsonCase: "",
Option: "",
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)
_, err = genpbentity.CGenPbEntity{}.PbEntity(ctx, in)
t.AssertNil(err)
// files
files, err := gfile.ScanDir(path, "*.proto", false)
t.AssertNil(err)
t.Assert(files, []string{
path + filepath.FromSlash("/table_user.proto"),
})
// contents
testPath := gtest.DataPath("issue", "3545")
expectFiles := []string{
testPath + filepath.FromSlash("/table_user.proto"),
}
// check files content
for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}

View File

@@ -42,9 +42,7 @@ func Test_Gen_Service_Default(t *testing.T) {
defer gfile.Remove(path)
_, err = genservice.CGenService{}.Service(ctx, in)
if err != nil {
panic(err)
}
t.AssertNil(err)
// logic file
var (
@@ -59,12 +57,16 @@ func Test_Gen_Service_Default(t *testing.T) {
t.AssertNil(err)
t.Assert(files, []string{
dstFolder + filepath.FromSlash("/article.go"),
dstFolder + filepath.FromSlash("/delivery.go"),
dstFolder + filepath.FromSlash("/user.go"),
})
// contents
testPath := gtest.DataPath("genservice", "service")
expectFiles := []string{
testPath + filepath.FromSlash("/article.go"),
testPath + filepath.FromSlash("/delivery.go"),
testPath + filepath.FromSlash("/user.go"),
}
for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))

View File

@@ -13,10 +13,8 @@ import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gtag"
"hotgo/internal/library/hggen/internal/utility/mlog"
)
@@ -38,7 +36,6 @@ gf gen ctrl
)
const (
PatternApiDefinition = `type[\s\(]+(\w+)Req\s+struct\s+{([\s\S]+?)}`
PatternCtrlDefinition = `func\s+\(.+?\)\s+\w+\(.+?\*(\w+)\.(\w+)Req\)\s+\(.+?\*(\w+)\.(\w+)Res,\s+\w+\s+error\)\s+{`
)
@@ -146,7 +143,11 @@ func (c CGenCtrl) generateByWatchFile(watchFile, sdkPath string, sdkStdVersion,
}
// watch file should have api definitions.
if gfile.Exists(watchFile) {
if !gregex.IsMatchString(PatternApiDefinition, gfile.GetContents(watchFile)) {
structsInfo, err := c.getStructsNameInSrc(watchFile)
if err != nil {
return err
}
if len(structsInfo) == 0 {
return nil
}
}

View File

@@ -0,0 +1,78 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package genctrl
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"
)
// getStructsNameInSrc retrieves all struct names
// that end in "Req" and have "g.Meta" in their body.
func (c CGenCtrl) getStructsNameInSrc(filePath string) (structsName []string, err error) {
var (
fileContent = gfile.GetContents(filePath)
fileSet = token.NewFileSet()
)
node, err := parser.ParseFile(fileSet, "", fileContent, parser.ParseComments)
if err != nil {
return
}
ast.Inspect(node, func(n ast.Node) bool {
if typeSpec, ok := n.(*ast.TypeSpec); ok {
methodName := typeSpec.Name.Name
if !gstr.HasSuffix(methodName, "Req") {
// ignore struct name that do not end in "Req"
return true
}
if structType, ok := typeSpec.Type.(*ast.StructType); ok {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fileSet, structType); err != nil {
return false
}
// ignore struct name that match a request, but has no g.Meta in its body.
if !gstr.Contains(buf.String(), `g.Meta`) {
return true
}
structsName = append(structsName, methodName)
}
}
return true
})
return
}
// getImportsInDst retrieves all import paths in the file.
func (c CGenCtrl) getImportsInDst(filePath string) (imports []string, err error) {
var (
fileContent = gfile.GetContents(filePath)
fileSet = token.NewFileSet()
)
node, err := parser.ParseFile(fileSet, "", fileContent, parser.ParseComments)
if err != nil {
return
}
ast.Inspect(node, func(n ast.Node) bool {
if imp, ok := n.(*ast.ImportSpec); ok {
imports = append(imports, imp.Path.Value)
}
return true
})
return
}

View File

@@ -0,0 +1,43 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package genctrl
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"github.com/gogf/gf/v2/os/gfile"
)
// getFuncInDst retrieves all function declarations and bodies in the file.
func (c *controllerClearer) getFuncInDst(filePath string) (funcs []string, err error) {
var (
fileContent = gfile.GetContents(filePath)
fileSet = token.NewFileSet()
)
node, err := parser.ParseFile(fileSet, "", fileContent, parser.ParseComments)
if err != nil {
return
}
ast.Inspect(node, func(n ast.Node) bool {
if fun, ok := n.(*ast.FuncDecl); ok {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fileSet, fun); err != nil {
return false
}
funcs = append(funcs, buf.String())
}
return true
})
return
}

View File

@@ -14,10 +14,7 @@ import (
)
func (c CGenCtrl) getApiItemsInSrc(apiModuleFolderPath string) (items []apiItem, err error) {
var (
fileContent string
importPath string
)
var importPath string
// The second level folders: versions.
apiVersionFolderPaths, err := gfile.ScanDir(apiModuleFolderPath, "*", false)
if err != nil {
@@ -37,20 +34,13 @@ func (c CGenCtrl) getApiItemsInSrc(apiModuleFolderPath string) (items []apiItem,
if gfile.IsDir(apiFileFolderPath) {
continue
}
fileContent = gfile.GetContents(apiFileFolderPath)
matches, err := gregex.MatchAllString(PatternApiDefinition, fileContent)
structsInfo, err := c.getStructsNameInSrc(apiFileFolderPath)
if err != nil {
return nil, err
}
for _, match := range matches {
var (
methodName = match[1]
structBody = match[2]
)
// ignore struct name that match a request, but has no g.Meta in its body.
if !gstr.Contains(structBody, `g.Meta`) {
continue
}
for _, methodName := range structsInfo {
// remove end "Req"
methodName = gstr.TrimRightStr(methodName, "Req", 1)
item := apiItem{
Import: gstr.Trim(importPath, `"`),
FileName: gfile.Name(apiFileFolderPath),
@@ -73,26 +63,22 @@ func (c CGenCtrl) getApiItemsInDst(dstFolder string) (items []apiItem, err error
Path string
Alias string
}
var fileContent string
filePaths, err := gfile.ScanDir(dstFolder, "*.go", true)
if err != nil {
return nil, err
}
for _, filePath := range filePaths {
fileContent = gfile.GetContents(filePath)
match, err := gregex.MatchString(`import\s+\(([\s\S]+?)\)`, fileContent)
if err != nil {
return nil, err
}
if len(match) < 2 {
continue
}
var (
array []string
importItems []importItem
importLines = gstr.SplitAndTrim(match[1], "\n")
importLines []string
module = gfile.Basename(gfile.Dir(filePath))
)
importLines, err = c.getImportsInDst(filePath)
if err != nil {
return nil, err
}
// retrieve all imports.
for _, importLine := range importLines {
array = gstr.SplitAndTrim(importLine, " ")
@@ -108,11 +94,15 @@ func (c CGenCtrl) getApiItemsInDst(dstFolder string) (items []apiItem, err error
}
}
// retrieve all api usages.
// retrieve it without using AST, but use regular expressions to retrieve.
// It's because the api definition is simple and regular.
// Use regular expressions to get better performance.
fileContent := gfile.GetContents(filePath)
matches, err := gregex.MatchAllString(PatternCtrlDefinition, fileContent)
if err != nil {
return nil, err
}
for _, match = range matches {
for _, match := range matches {
// try to find the import path of the api.
var (
importPath string

View File

@@ -9,6 +9,7 @@ package genctrl
import (
"fmt"
"path/filepath"
"strings"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
@@ -42,8 +43,16 @@ func (c *controllerGenerator) Generate(dstModuleFolderPath string, apiModuleApiI
); err != nil {
return
}
// use -merge
if merge {
err = c.doGenerateCtrlMergeItem(dstModuleFolderPath, subItems, doneApiItemSet)
continue
}
for _, subItem := range subItems {
if err = c.doGenerateCtrlItem(dstModuleFolderPath, subItem, merge); err != nil {
err = c.doGenerateCtrlItem(dstModuleFolderPath, subItem)
if err != nil {
return
}
doneApiItemSet.Add(subItem.String())
@@ -116,7 +125,7 @@ func (c *controllerGenerator) doGenerateCtrlNewByModuleAndVersion(
return
}
func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, item apiItem, merge bool) (err error) {
func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, item apiItem) (err error) {
var (
methodNameSnake = gstr.CaseSnake(item.MethodName)
ctrlName = fmt.Sprintf(`Controller%s`, gstr.UcFirst(item.Version))
@@ -126,13 +135,6 @@ func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, ite
)
var content string
if merge {
methodFilePath = gfile.Join(dstModuleFolderPath, fmt.Sprintf(
`%s_%s_%s.go`, item.Module, item.Version, item.FileName,
))
}
if gfile.Exists(methodFilePath) {
content = gstr.ReplaceByMap(consts.TemplateGenCtrlControllerMethodFuncMerge, g.MapStrStr{
"{Module}": item.Module,
@@ -141,7 +143,7 @@ func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, ite
"{MethodName}": item.MethodName,
})
if gstr.Contains(gfile.GetContents(methodFilePath), fmt.Sprintf(`func (c *%v) %v`, ctrlName, item.MethodName)) {
if gstr.Contains(gfile.GetContents(methodFilePath), fmt.Sprintf(`func (c *%v) %v(`, ctrlName, item.MethodName)) {
return
}
if err = gfile.PutContentsAppend(methodFilePath, gstr.TrimLeft(content)); err != nil {
@@ -162,3 +164,64 @@ func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, ite
mlog.Printf(`generated: %s`, methodFilePath)
return
}
// use -merge
func (c *controllerGenerator) doGenerateCtrlMergeItem(dstModuleFolderPath string, apiItems []apiItem, doneApiSet *gset.StrSet) (err error) {
type controllerFileItem struct {
module string
version string
importPath string
// Each ctrlFileItem has multiple CTRLs
controllers strings.Builder
}
// It is possible that there are multiple files under one module
ctrlFileItemMap := make(map[string]*controllerFileItem)
for _, api := range apiItems {
ctrlFileItem, found := ctrlFileItemMap[api.FileName]
if !found {
ctrlFileItem = &controllerFileItem{
module: api.Module,
version: api.Version,
controllers: strings.Builder{},
importPath: api.Import,
}
ctrlFileItemMap[api.FileName] = ctrlFileItem
}
ctrl := gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlControllerMethodFuncMerge, g.MapStrStr{
"{Module}": api.Module,
"{CtrlName}": fmt.Sprintf(`Controller%s`, gstr.UcFirst(api.Version)),
"{Version}": api.Version,
"{MethodName}": api.MethodName,
}))
ctrlFileItem.controllers.WriteString(ctrl)
doneApiSet.Add(api.String())
}
for ctrlFileName, ctrlFileItem := range ctrlFileItemMap {
ctrlFilePath := gfile.Join(dstModuleFolderPath, fmt.Sprintf(
`%s_%s_%s.go`, ctrlFileItem.module, ctrlFileItem.version, ctrlFileName,
))
// This logic is only followed when a new ctrlFileItem is generated
// Most of the rest of the time, the following logic is followed
if !gfile.Exists(ctrlFilePath) {
ctrlFileHeader := gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlControllerHeader, g.MapStrStr{
"{Module}": ctrlFileItem.module,
"{ImportPath}": ctrlFileItem.importPath,
}))
err = gfile.PutContents(ctrlFilePath, ctrlFileHeader)
if err != nil {
return err
}
}
if err = gfile.PutContentsAppend(ctrlFilePath, ctrlFileItem.controllers.String()); err != nil {
return err
}
mlog.Printf(`generated: %s`, ctrlFilePath)
}
return
}

View File

@@ -10,7 +10,6 @@ import (
"fmt"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/internal/library/hggen/internal/utility/mlog"
)
@@ -36,16 +35,16 @@ func (c *controllerClearer) doClear(dstModuleFolderPath string, item apiItem) (e
methodFilePath = gfile.Join(dstModuleFolderPath, fmt.Sprintf(
`%s_%s_%s.go`, item.Module, item.Version, methodNameSnake,
))
fileContent = gstr.Trim(gfile.GetContents(methodFilePath))
)
match, err := gregex.MatchString(`.+?Req.+?Res.+?{([\s\S]+?)}`, fileContent)
funcs, err := c.getFuncInDst(methodFilePath)
if err != nil {
return err
}
if len(match) > 1 {
implements := gstr.Trim(match[1])
if len(funcs) > 1 {
// One line.
if !gstr.Contains(implements, "\n") && gstr.Contains(implements, `CodeNotImplemented`) {
if !gstr.Contains(funcs[0], "\n") && gstr.Contains(funcs[0], `CodeNotImplemented`) {
mlog.Printf(
`remove unimplemented and of no api definitions controller file: %s`,
methodFilePath,

View File

@@ -103,6 +103,7 @@ func (c *apiSdkGenerator) doGenerateSdkIClient(
// append the import path to current import paths.
if !gstr.Contains(fileContent, moduleImportPath) {
isDirty = true
// It is without using AST, because it is from a template.
fileContent, err = gregex.ReplaceString(
`(import \([\s\S]*?)\)`,
fmt.Sprintf("$1\t%s\n)", moduleImportPath),
@@ -116,6 +117,7 @@ func (c *apiSdkGenerator) doGenerateSdkIClient(
// append the function definition to interface definition.
if !gstr.Contains(fileContent, interfaceFuncDefinition) {
isDirty = true
// It is without using AST, because it is from a template.
fileContent, err = gregex.ReplaceString(
`(type IClient interface {[\s\S]*?)}`,
fmt.Sprintf("$1\t%s\n}", interfaceFuncDefinition),

View File

@@ -58,6 +58,10 @@ CONFIGURATION SUPPORT
import: github.com/shopspring/decimal
numeric:
type: string
fieldMapping:
table_name.field_name:
type: decimal.Decimal
import: github.com/shopspring/decimal
`
CGenDaoBriefPath = `directory path for generated files`
CGenDaoBriefLink = `database configuration, the same as the ORM configuration of GoFrame`
@@ -81,6 +85,7 @@ CONFIGURATION SUPPORT
CGenDaoBriefNoModelComment = `no model comment will be added for each field`
CGenDaoBriefClear = `delete all generated go files that do not exist in database`
CGenDaoBriefTypeMapping = `custom local type mapping for generated struct attributes relevant to fields of table`
CGenDaoBriefFieldMapping = `custom local type mapping for generated struct attributes relevant to specific fields of table`
CGenDaoBriefGroup = `
specifying the configuration group name of database for generated ORM instance,
it's not necessary and the default value is "default"
@@ -113,6 +118,7 @@ generated json tag case for model struct, cases are as follows:
tplVarGroupName = `{TplGroupName}`
tplVarDatetimeStr = `{TplDatetimeStr}`
tplVarCreatedAtDatetimeStr = `{TplCreatedAtDatetimeStr}`
tplVarPackageName = `{TplPackageName}`
)
var (
@@ -162,6 +168,7 @@ func init() {
`CGenDaoBriefNoModelComment`: CGenDaoBriefNoModelComment,
`CGenDaoBriefClear`: CGenDaoBriefClear,
`CGenDaoBriefTypeMapping`: CGenDaoBriefTypeMapping,
`CGenDaoBriefFieldMapping`: CGenDaoBriefFieldMapping,
`CGenDaoBriefGroup`: CGenDaoBriefGroup,
`CGenDaoBriefJsonCase`: CGenDaoBriefJsonCase,
`CGenDaoBriefTplDaoIndexPath`: CGenDaoBriefTplDaoIndexPath,
@@ -201,8 +208,9 @@ type (
NoModelComment bool `name:"noModelComment" short:"m" brief:"{CGenDaoBriefNoModelComment}" orphan:"true"`
Clear bool `name:"clear" short:"a" brief:"{CGenDaoBriefClear}" orphan:"true"`
TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenDaoBriefTypeMapping}" orphan:"true"`
genItems *CGenDaoInternalGenItems
TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenDaoBriefTypeMapping}" orphan:"true"`
FieldMapping map[DBTableFieldName]CustomAttributeType `name:"fieldMapping" short:"fm" brief:"{CGenDaoBriefFieldMapping}" orphan:"true"`
genItems *CGenDaoInternalGenItems
}
CGenDaoOutput struct{}
@@ -212,7 +220,7 @@ type (
TableNames []string
NewTableNames []string
}
DBTableFieldName = string
DBFieldTypeName = string
CustomAttributeType struct {
Type string `brief:"custom attribute type name"`
@@ -222,7 +230,9 @@ type (
func (c CGenDao) Dao(ctx context.Context, in CGenDaoInput) (out *CGenDaoOutput, err error) {
in.genItems = newCGenDaoInternalGenItems()
if g.Cfg().Available(ctx) {
if in.Link != "" {
doGenDaoForArray(ctx, -1, in)
} else if g.Cfg().Available(ctx) {
v := g.Cfg().MustGet(ctx, CGenDaoConfig)
if v.IsSlice() {
for i := 0; i < len(v.Interfaces()); i++ {
@@ -244,6 +254,7 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
if in.genItems == nil {
in.genItems = newCGenDaoInternalGenItems()
}
var (
err error
db gdb.DB
@@ -364,7 +375,7 @@ func getImportPartContent(ctx context.Context, source string, isDo bool, appendI
}
// Check and update imports in go.mod
if appendImports != nil && len(appendImports) > 0 {
if len(appendImports) > 0 {
goModPath := utils.GetModPath()
if goModPath == "" {
mlog.Fatal("go.mod not found in current project")
@@ -382,8 +393,9 @@ func getImportPartContent(ctx context.Context, source string, isDo bool, appendI
}
}
if !found {
err = gproc.ShellRun(ctx, `go get `+appendImport)
mlog.Fatalf(`%+v`, err)
if err = gproc.ShellRun(ctx, `go get `+appendImport); err != nil {
mlog.Fatalf(`%+v`, err)
}
}
packageImportsArray.Append(fmt.Sprintf(`"%s"`, appendImport))
}

View File

@@ -58,8 +58,8 @@ func generateDaoSingle(ctx context.Context, in generateDaoSingleInput) {
mlog.Fatalf(`fetching tables fields failed for table "%s": %+v`, in.TableName, err)
}
var (
tableNameCamelCase = gstr.CaseCamel(in.NewTableName)
tableNameCamelLowerCase = gstr.CaseCamelLower(in.NewTableName)
tableNameCamelCase = gstr.CaseCamel(strings.ToLower(in.NewTableName))
tableNameCamelLowerCase = gstr.CaseCamelLower(strings.ToLower(in.NewTableName))
tableNameSnakeCase = gstr.CaseSnake(in.NewTableName)
importPrefix = in.ImportPrefix
)
@@ -116,6 +116,7 @@ func generateDaoIndex(in generateDaoIndexInput) {
tplVarTableName: in.TableName,
tplVarTableNameCamelCase: in.TableNameCamelCase,
tplVarTableNameCamelLowerCase: in.TableNameCamelLowerCase,
tplVarPackageName: filepath.Base(in.DaoPath),
})
indexContent = replaceDefaultVar(in.CGenDaoInternalInput, indexContent)
if err := gfile.PutContents(path, strings.TrimSpace(indexContent)); err != nil {
@@ -178,7 +179,7 @@ func generateColumnNamesForDao(fieldMap map[string]*gdb.TableField, removeFieldP
}
array[index] = []string{
" #" + gstr.CaseCamel(newFiledName) + ":",
" #" + gstr.CaseCamel(strings.ToLower(newFiledName)) + ":",
fmt.Sprintf(` #"%s",`, field.Name),
}
}
@@ -218,7 +219,7 @@ func generateColumnDefinitionForDao(fieldMap map[string]*gdb.TableField, removeF
newFiledName = gstr.TrimLeftStr(newFiledName, v, 1)
}
array[index] = []string{
" #" + gstr.CaseCamel(newFiledName),
" #" + gstr.CaseCamel(strings.ToLower(newFiledName)),
" # " + "string",
" #" + fmt.Sprintf(`// %s`, comment),
}

View File

@@ -40,7 +40,7 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
structDefinition, _ = generateStructDefinition(ctx, generateStructDefinitionInput{
CGenDaoInternalInput: in,
TableName: tableName,
StructName: gstr.CaseCamel(newTableName),
StructName: gstr.CaseCamel(strings.ToLower(newTableName)),
FieldMap: fieldMap,
IsDo: true,
})
@@ -61,7 +61,7 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
ctx,
in,
tableName,
gstr.CaseCamel(newTableName),
gstr.CaseCamel(strings.ToLower(newTableName)),
structDefinition,
)
in.genItems.AppendGeneratedFilePath(doFilePath)
@@ -85,6 +85,7 @@ func generateDoContent(
tplVarPackageImports: getImportPartContent(ctx, structDefine, true, nil),
tplVarTableNameCamelCase: tableNameCamelCase,
tplVarStructDefine: structDefine,
tplVarPackageName: filepath.Base(in.DoPath),
},
)
doContent = replaceDefaultVar(in, doContent)

View File

@@ -36,7 +36,7 @@ func generateEntity(ctx context.Context, in CGenDaoInternalInput) {
structDefinition, appendImports = generateStructDefinition(ctx, generateStructDefinitionInput{
CGenDaoInternalInput: in,
TableName: tableName,
StructName: gstr.CaseCamel(newTableName),
StructName: gstr.CaseCamel(strings.ToLower(newTableName)),
FieldMap: fieldMap,
IsDo: false,
})
@@ -44,7 +44,7 @@ func generateEntity(ctx context.Context, in CGenDaoInternalInput) {
ctx,
in,
newTableName,
gstr.CaseCamel(newTableName),
gstr.CaseCamel(strings.ToLower(newTableName)),
structDefinition,
appendImports,
)
@@ -70,6 +70,7 @@ func generateEntityContent(
tplVarPackageImports: getImportPartContent(ctx, structDefine, false, appendImports),
tplVarTableNameCamelCase: tableNameCamelCase,
tplVarStructDefine: structDefine,
tplVarPackageName: filepath.Base(in.EntityPath),
},
)
entityContent = replaceDefaultVar(in, entityContent)

View File

@@ -131,8 +131,16 @@ func generateStructFieldDefinition(
for _, v := range removeFieldPrefixArray {
newFiledName = gstr.TrimLeftStr(newFiledName, v, 1)
}
if in.FieldMapping != nil && len(in.FieldMapping) > 0 {
if typeMapping, ok := in.FieldMapping[fmt.Sprintf("%s.%s", in.TableName, newFiledName)]; ok {
localTypeNameStr = typeMapping.Type
appendImport = typeMapping.Import
}
}
attrLines = []string{
" #" + gstr.CaseCamel(newFiledName),
" #" + gstr.CaseCamel(strings.ToLower(newFiledName)),
" #" + localTypeNameStr,
}
attrLines = append(attrLines, fmt.Sprintf(` #%sjson:"%s"`, tagKey, jsonTag))

View File

@@ -14,6 +14,7 @@ import (
"strings"
"github.com/olekukonko/tablewriter"
"hotgo/internal/library/hggen/internal/utility/utils"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
@@ -176,20 +177,8 @@ func doGenPbEntityForArray(ctx context.Context, index int, in CGenPbEntityInput)
}
if in.Package == "" {
mlog.Debug(`package parameter is empty, trying calculating the package path using go.mod`)
if !gfile.Exists("go.mod") {
mlog.Fatal("go.mod does not exist in current working directory")
}
var (
modName string
goModContent = gfile.GetContents("go.mod")
match, _ = gregex.MatchString(`^module\s+(.+)\s*`, goModContent)
)
if len(match) > 1 {
modName = gstr.Trim(match[1])
in.Package = modName + "/" + defaultPackageSuffix
} else {
mlog.Fatal("module name does not found in go.mod")
}
modName := utils.GetImportPath(gfile.Pwd())
in.Package = modName + "/" + defaultPackageSuffix
}
removePrefixArray := gstr.SplitAndTrim(in.RemovePrefix, ",")
// It uses user passed database configuration.

View File

@@ -10,6 +10,8 @@ import (
"context"
"fmt"
"path/filepath"
"sync"
"sync/atomic"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap"
@@ -21,7 +23,6 @@ import (
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gtag"
"hotgo/internal/library/hggen/internal/utility/mlog"
"hotgo/internal/library/hggen/internal/utility/utils"
)
@@ -147,19 +148,22 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
}
var (
isDirty bool // Temp boolean.
isDirty atomic.Value // Temp boolean.
files []string // Temp file array.
fileContent string // Temp file content for handling go file.
initImportSrcPackages []string // Used for generating logic.go.
inputPackages = in.Packages // Custom packages.
dstPackageName = gstr.ToLower(gfile.Basename(in.DstFolder)) // Package name for generated go files.
generatedDstFilePathSet = gset.NewStrSet() // All generated file path set.
)
isDirty.Store(false)
// The first level folders.
srcFolderPaths, err := gfile.ScanDir(in.SrcFolder, "*", false)
if err != nil {
return nil, err
}
// it will use goroutine to generate service files for each package.
var wg = sync.WaitGroup{}
for _, srcFolderPath := range srcFolderPaths {
if !gfile.IsDir(srcFolderPath) {
continue
@@ -173,111 +177,30 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
}
// Parse single logic package folder.
var (
// StructName => FunctionDefinitions
srcPkgInterfaceMap = gmap.NewListMap()
srcImportedPackages = garray.NewSortedStrArray().SetUnique(true)
importAliasToPathMap = gmap.NewStrStrMap() // for conflict imports check. alias => import path(with `"`)
importPathToAliasMap = gmap.NewStrStrMap() // for conflict imports check. import path(with `"`) => alias
srcPackageName = gfile.Basename(srcFolderPath)
ok bool
dstFilePath = gfile.Join(in.DstFolder,
srcPackageName = gfile.Basename(srcFolderPath)
srcImportedPackages = garray.NewSortedStrArray().SetUnique(true)
srcStructFunctions = gmap.NewListMap()
dstFilePath = gfile.Join(in.DstFolder,
c.getDstFileNameCase(srcPackageName, in.DstFileNameCase)+".go",
)
srcCodeCommentedMap = make(map[string]string)
)
generatedDstFilePathSet.Add(dstFilePath)
// if it were to use goroutine,
// it would cause the order of the generated functions in the file to be disordered.
for _, file := range files {
var packageItems []packageItem
fileContent = gfile.GetContents(file)
// Calculate code comments in source Go files.
err = c.calculateCodeCommented(in, fileContent, srcCodeCommentedMap)
if err != nil {
return nil, err
}
// remove all comments.
fileContent, err = gregex.ReplaceString(`(//.*)|((?s)/\*.*?\*/)`, "", fileContent)
pkgItems, funcItems, err := c.parseItemsInSrc(file)
if err != nil {
return nil, err
}
// Calculate imported packages of source go files.
packageItems, err = c.calculateImportedPackages(fileContent)
// Calculate imported packages for service generating.
err = c.calculateImportedItems(in, pkgItems, funcItems, srcImportedPackages)
if err != nil {
return nil, err
}
// try finding the conflicts imports between files.
for _, item := range packageItems {
var alias = item.Alias
if alias == "" {
alias = gfile.Basename(gstr.Trim(item.Path, `"`))
}
// ignore unused import paths, which do not exist in function definitions.
if !gregex.IsMatchString(fmt.Sprintf(`func .+?([^\w])%s(\.\w+).+?{`, alias), fileContent) {
mlog.Debugf(`ignore unused package: %s`, item.RawImport)
continue
}
// find the exist alias with the same import path.
var existAlias = importPathToAliasMap.Get(item.Path)
if existAlias != "" {
fileContent, err = gregex.ReplaceStringFuncMatch(
fmt.Sprintf(`([^\w])%s(\.\w+)`, alias), fileContent,
func(match []string) string {
return match[1] + existAlias + match[2]
},
)
if err != nil {
return nil, err
}
continue
}
// resolve alias conflicts.
var importPath = importAliasToPathMap.Get(alias)
if importPath == "" {
importAliasToPathMap.Set(alias, item.Path)
importPathToAliasMap.Set(item.Path, alias)
srcImportedPackages.Add(item.RawImport)
continue
}
if importPath != item.Path {
// update the conflicted alias for import path with suffix.
// eg:
// v1 -> v10
// v11 -> v110
for aliasIndex := 0; ; aliasIndex++ {
item.Alias = fmt.Sprintf(`%s%d`, alias, aliasIndex)
var existPathForAlias = importAliasToPathMap.Get(item.Alias)
if existPathForAlias != "" {
if existPathForAlias == item.Path {
break
}
continue
}
break
}
importPathToAliasMap.Set(item.Path, item.Alias)
importAliasToPathMap.Set(item.Alias, item.Path)
// reformat the import path with alias.
item.RawImport = fmt.Sprintf(`%s %s`, item.Alias, item.Path)
// update the file content with new alias import.
fileContent, err = gregex.ReplaceStringFuncMatch(
fmt.Sprintf(`([^\w])%s(\.\w+)`, alias), fileContent,
func(match []string) string {
return match[1] + item.Alias + match[2]
},
)
if err != nil {
return nil, err
}
srcImportedPackages.Add(item.RawImport)
}
}
// Calculate functions and interfaces for service generating.
err = c.calculateInterfaceFunctions(in, fileContent, srcPkgInterfaceMap)
err = c.calculateFuncItems(in, funcItems, srcStructFunctions)
if err != nil {
return nil, err
}
@@ -295,22 +218,28 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
)
continue
}
// Generating service go file for single logic package.
if ok, err = c.generateServiceFile(generateServiceFilesInput{
wg.Add(1)
go func(generateServiceFilesInput generateServiceFilesInput) {
defer wg.Done()
ok, err := c.generateServiceFile(generateServiceFilesInput)
if err != nil {
mlog.Printf(`error generating service file "%s": %v`, generateServiceFilesInput.DstFilePath, err)
}
if !isDirty.Load().(bool) && ok {
isDirty.Store(true)
}
}(generateServiceFilesInput{
CGenServiceInput: in,
SrcStructFunctions: srcPkgInterfaceMap,
SrcImportedPackages: srcImportedPackages.Slice(),
SrcPackageName: srcPackageName,
SrcImportedPackages: srcImportedPackages.Slice(),
SrcStructFunctions: srcStructFunctions,
DstPackageName: dstPackageName,
DstFilePath: dstFilePath,
SrcCodeCommentedMap: srcCodeCommentedMap,
}); err != nil {
return
}
if ok {
isDirty = true
}
})
}
wg.Wait()
if in.Clear {
files, err = gfile.ScanDirFile(in.DstFolder, "*.go", false)
@@ -320,7 +249,9 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
var relativeFilePath string
for _, file := range files {
relativeFilePath = gstr.SubStrFromR(file, in.DstFolder)
if !generatedDstFilePathSet.Contains(relativeFilePath) && utils.IsFileDoNotEdit(relativeFilePath) {
if !generatedDstFilePathSet.Contains(relativeFilePath) &&
utils.IsFileDoNotEdit(relativeFilePath) {
mlog.Printf(`remove no longer used service file: %s`, relativeFilePath)
if err = gfile.Remove(file); err != nil {
return nil, err
@@ -329,7 +260,7 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
}
}
if isDirty {
if isDirty.Load().(bool) {
// Generate initialization go file.
if len(initImportSrcPackages) > 0 {
if err = c.generateInitializationFile(in, initImportSrcPackages); err != nil {

View File

@@ -0,0 +1,186 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package genservice
import (
"go/ast"
"go/parser"
"go/token"
"github.com/gogf/gf/v2/os/gfile"
)
type pkgItem struct {
Alias string `eg:"gdbas"`
Path string `eg:"github.com/gogf/gf/v2/database/gdb"`
RawImport string `eg:"gdbas github.com/gogf/gf/v2/database/gdb"`
}
type funcItem struct {
Receiver string `eg:"sUser"`
MethodName string `eg:"GetList"`
Params []map[string]string `eg:"ctx: context.Context, cond: *SearchInput"`
Results []map[string]string `eg:"list: []*User, err: error"`
Comment string `eg:"Get user list"`
}
// parseItemsInSrc parses the pkgItem and funcItem from the specified file.
// It can't skip the private methods.
// It can't skip the imported packages of import alias equal to `_`.
func (c CGenService) parseItemsInSrc(filePath string) (pkgItems []pkgItem, funcItems []funcItem, err error) {
var (
fileContent = gfile.GetContents(filePath)
fileSet = token.NewFileSet()
)
node, err := parser.ParseFile(fileSet, "", fileContent, parser.ParseComments)
if err != nil {
return
}
ast.Inspect(node, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.ImportSpec:
// parse the imported packages.
pkgItems = append(pkgItems, c.parseImportPackages(x))
case *ast.FuncDecl:
// parse the function items.
if x.Recv == nil {
return true
}
var funcName = x.Name.Name
funcItems = append(funcItems, funcItem{
Receiver: c.parseFuncReceiverTypeName(x),
MethodName: funcName,
Params: c.parseFuncParams(x),
Results: c.parseFuncResults(x),
Comment: c.parseFuncComment(x),
})
}
return true
})
return
}
// parseImportPackages retrieves the imported packages from the specified ast.ImportSpec.
func (c CGenService) parseImportPackages(node *ast.ImportSpec) (packages pkgItem) {
if node.Path == nil {
return
}
var (
alias string
path = node.Path.Value
rawImport string
)
if node.Name != nil {
alias = node.Name.Name
rawImport = alias + " " + path
} else {
rawImport = path
}
return pkgItem{
Alias: alias,
Path: path,
RawImport: rawImport,
}
}
// parseFuncReceiverTypeName retrieves the receiver type of the function.
// For example:
//
// func(s *sArticle) -> *sArticle
// func(s sArticle) -> sArticle
func (c CGenService) parseFuncReceiverTypeName(node *ast.FuncDecl) (receiverType string) {
if node.Recv == nil {
return ""
}
receiverType, err := c.astExprToString(node.Recv.List[0].Type)
if err != nil {
return ""
}
return
}
// parseFuncParams retrieves the input parameters of the function.
// It returns the name and type of the input parameters.
// For example:
//
// []map[string]string{paramName:ctx paramType:context.Context, paramName:info paramType:struct{}}
func (c CGenService) parseFuncParams(node *ast.FuncDecl) (params []map[string]string) {
if node.Type.Params == nil {
return
}
for _, param := range node.Type.Params.List {
if param.Names == nil {
// No name for the return value.
resultType, err := c.astExprToString(param.Type)
if err != nil {
continue
}
params = append(params, map[string]string{
"paramName": "",
"paramType": resultType,
})
continue
}
for _, name := range param.Names {
paramType, err := c.astExprToString(param.Type)
if err != nil {
continue
}
params = append(params, map[string]string{
"paramName": name.Name,
"paramType": paramType,
})
}
}
return
}
// parseFuncResults retrieves the output parameters of the function.
// It returns the name and type of the output parameters.
// For example:
//
// []map[string]string{resultName:list resultType:[]*User, resultName:err resultType:error}
// []map[string]string{resultName: "", resultType: error}
func (c CGenService) parseFuncResults(node *ast.FuncDecl) (results []map[string]string) {
if node.Type.Results == nil {
return
}
for _, result := range node.Type.Results.List {
if result.Names == nil {
// No name for the return value.
resultType, err := c.astExprToString(result.Type)
if err != nil {
continue
}
results = append(results, map[string]string{
"resultName": "",
"resultType": resultType,
})
continue
}
for _, name := range result.Names {
resultType, err := c.astExprToString(result.Type)
if err != nil {
continue
}
results = append(results, map[string]string{
"resultName": name.Name,
"resultType": resultType,
})
}
}
return
}
// parseFuncComment retrieves the comment of the function.
func (c CGenService) parseFuncComment(node *ast.FuncDecl) string {
return c.astCommentToString(node.Doc)
}

View File

@@ -0,0 +1,48 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package genservice
import (
"bytes"
"go/ast"
"go/format"
"go/token"
"strings"
)
// exprToString converts ast.Expr to string.
// For example:
//
// ast.Expr -> "context.Context"
// ast.Expr -> "*v1.XxxReq"
// ast.Expr -> "error"
// ast.Expr -> "int"
func (c CGenService) astExprToString(expr ast.Expr) (string, error) {
var (
buf bytes.Buffer
err error
)
err = format.Node(&buf, token.NewFileSet(), expr)
if err != nil {
return "", err
}
return buf.String(), nil
}
// astCommentToString returns the raw (original) text of the comment.
// It includes the comment markers (//, /*, and */).
// It adds a newline at the end of the comment.
func (c CGenService) astCommentToString(node *ast.CommentGroup) string {
if node == nil {
return ""
}
var b strings.Builder
for _, c := range node.List {
b.WriteString(c.Text + "\n")
}
return b.String()
}

View File

@@ -8,168 +8,145 @@ package genservice
import (
"fmt"
"go/parser"
"go/token"
"strings"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/internal/library/hggen/internal/utility/mlog"
)
type packageItem struct {
Alias string
Path string
RawImport string
}
func (c CGenService) calculateImportedPackages(fileContent string) (packages []packageItem, err error) {
f, err := parser.ParseFile(token.NewFileSet(), "", fileContent, parser.ImportsOnly)
if err != nil {
return nil, err
}
packages = make([]packageItem, 0)
for _, s := range f.Imports {
if s.Path != nil {
if s.Name != nil {
// If it has alias, and it is not `_`.
if pkgAlias := s.Name.String(); pkgAlias != "_" {
packages = append(packages, packageItem{
Alias: pkgAlias,
Path: s.Path.Value,
RawImport: pkgAlias + " " + s.Path.Value,
})
}
} else {
// no alias
packages = append(packages, packageItem{
Alias: "",
Path: s.Path.Value,
RawImport: s.Path.Value,
})
}
}
}
return packages, nil
}
func (c CGenService) calculateCodeCommented(in CGenServiceInput, fileContent string, srcCodeCommentedMap map[string]string) error {
matches, err := gregex.MatchAllString(`((((//.*)|(/\*[\s\S]*?\*/))\s)+)func \((.+?)\) ([\s\S]+?) {`, fileContent)
if err != nil {
return err
}
for _, match := range matches {
var (
structName string
structMatch []string
funcReceiver = gstr.Trim(match[1+5])
receiverArray = gstr.SplitAndTrim(funcReceiver, " ")
functionHead = gstr.Trim(gstr.Replace(match[2+5], "\n", ""))
commentedInfo = ""
)
if len(receiverArray) > 1 {
structName = receiverArray[1]
} else if len(receiverArray) == 1 {
structName = receiverArray[0]
}
structName = gstr.Trim(structName, "*")
// Case of:
// Xxx(\n ctx context.Context, req *v1.XxxReq,\n) -> Xxx(ctx context.Context, req *v1.XxxReq)
functionHead = gstr.Replace(functionHead, `,)`, `)`)
functionHead, _ = gregex.ReplaceString(`\(\s+`, `(`, functionHead)
functionHead, _ = gregex.ReplaceString(`\s{2,}`, ` `, functionHead)
if !gstr.IsLetterUpper(functionHead[0]) {
continue
}
// Match and pick the struct name from receiver.
if structMatch, err = gregex.MatchString(in.StPattern, structName); err != nil {
return err
}
if len(structMatch) < 1 {
continue
}
structName = gstr.CaseCamel(structMatch[1])
commentedInfo = match[1]
if len(commentedInfo) > 0 {
srcCodeCommentedMap[fmt.Sprintf("%s-%s", structName, functionHead)] = commentedInfo
}
}
return nil
}
func (c CGenService) calculateInterfaceFunctions(
in CGenServiceInput, fileContent string, srcPkgInterfaceMap *gmap.ListMap,
func (c CGenService) calculateImportedItems(
in CGenServiceInput,
pkgItems []pkgItem, funcItems []funcItem,
srcImportedPackages *garray.SortedStrArray,
) (err error) {
var (
matches [][]string
srcPkgInterfaceFuncArray *garray.StrArray
)
// calculate struct name and its functions according function definitions.
matches, err = gregex.MatchAllString(`func \((.+?)\) ([\s\S]+?) {`, fileContent)
if err != nil {
return err
}
for _, match := range matches {
var (
structName string
structMatch []string
funcReceiver = gstr.Trim(match[1])
receiverArray = gstr.SplitAndTrim(funcReceiver, " ")
functionHead = gstr.Trim(gstr.Replace(match[2], "\n", ""))
)
if len(receiverArray) > 1 {
structName = receiverArray[1]
} else if len(receiverArray) == 1 {
structName = receiverArray[0]
}
structName = gstr.Trim(structName, "*")
// allFuncParamType saves all the param and result types of the functions.
var allFuncParamType strings.Builder
// Case of:
// Xxx(\n ctx context.Context, req *v1.XxxReq,\n) -> Xxx(ctx context.Context, req *v1.XxxReq)
functionHead = gstr.Replace(functionHead, `,)`, `)`)
functionHead, _ = gregex.ReplaceString(`\(\s+`, `(`, functionHead)
functionHead, _ = gregex.ReplaceString(`\s{2,}`, ` `, functionHead)
if !gstr.IsLetterUpper(functionHead[0]) {
continue
for _, item := range funcItems {
for _, param := range item.Params {
allFuncParamType.WriteString(param["paramType"] + ",")
}
// Match and pick the struct name from receiver.
if structMatch, err = gregex.MatchString(in.StPattern, structName); err != nil {
return err
for _, result := range item.Results {
allFuncParamType.WriteString(result["resultType"] + ",")
}
if len(structMatch) < 1 {
continue
}
structName = gstr.CaseCamel(structMatch[1])
if !srcPkgInterfaceMap.Contains(structName) {
srcPkgInterfaceFuncArray = garray.NewStrArray()
srcPkgInterfaceMap.Set(structName, srcPkgInterfaceFuncArray)
} else {
srcPkgInterfaceFuncArray = srcPkgInterfaceMap.Get(structName).(*garray.StrArray)
}
srcPkgInterfaceFuncArray.Append(functionHead)
}
// calculate struct name according type definitions.
matches, err = gregex.MatchAllString(`type (.+) struct\s*{`, fileContent)
if err != nil {
return err
}
for _, match := range matches {
var (
structName string
structMatch []string
)
if structMatch, err = gregex.MatchString(in.StPattern, match[1]); err != nil {
return err
}
if len(structMatch) < 1 {
for _, item := range pkgItems {
alias := item.Alias
// If the alias is _, it means that the package is not generated.
if alias == "_" {
mlog.Debugf(`ignore anonymous package: %s`, item.RawImport)
continue
}
structName = gstr.CaseCamel(structMatch[1])
if !srcPkgInterfaceMap.Contains(structName) {
srcPkgInterfaceMap.Set(structName, garray.NewStrArray())
// If the alias is empty, it will use the package name as the alias.
if alias == "" {
alias = gfile.Basename(gstr.Trim(item.Path, `"`))
}
if !gstr.Contains(allFuncParamType.String(), alias) {
mlog.Debugf(`ignore unused package: %s`, item.RawImport)
continue
}
srcImportedPackages.Add(item.RawImport)
}
return nil
}
func (c CGenService) calculateFuncItems(
in CGenServiceInput,
funcItems []funcItem,
srcPkgInterfaceMap *gmap.ListMap,
) (err error) {
var srcPkgInterfaceFunc []map[string]string
for _, item := range funcItems {
var (
// eg: "sArticle"
receiverName string
receiverMatch []string
// eg: "GetList(ctx context.Context, req *v1.ArticleListReq) (list []*v1.Article, err error)"
funcHead string
)
// handle the receiver name.
if item.Receiver == "" {
continue
}
receiverName = item.Receiver
receiverName = gstr.Trim(receiverName, "*")
// Match and pick the struct name from receiver.
if receiverMatch, err = gregex.MatchString(in.StPattern, receiverName); err != nil {
return err
}
if len(receiverMatch) < 1 {
continue
}
receiverName = gstr.CaseCamel(receiverMatch[1])
// check if the func name is public.
if !gstr.IsLetterUpper(item.MethodName[0]) {
continue
}
if !srcPkgInterfaceMap.Contains(receiverName) {
srcPkgInterfaceFunc = make([]map[string]string, 0)
srcPkgInterfaceMap.Set(receiverName, srcPkgInterfaceFunc)
} else {
srcPkgInterfaceFunc = srcPkgInterfaceMap.Get(receiverName).([]map[string]string)
}
// make the func head.
paramsStr := c.tidyParam(item.Params)
resultsStr := c.tidyResult(item.Results)
funcHead = fmt.Sprintf("%s(%s) (%s)", item.MethodName, paramsStr, resultsStr)
srcPkgInterfaceFunc = append(srcPkgInterfaceFunc, map[string]string{
"funcHead": funcHead,
"funcComment": item.Comment,
})
srcPkgInterfaceMap.Set(receiverName, srcPkgInterfaceFunc)
}
return nil
}
// tidyParam tidies the input parameters.
// For example:
//
// []map[string]string{paramName:ctx paramType:context.Context, paramName:info paramType:struct{}}
// -> ctx context.Context, info struct{}
func (c CGenService) tidyParam(paramSlice []map[string]string) (paramStr string) {
for i, param := range paramSlice {
if i > 0 {
paramStr += ", "
}
paramStr += fmt.Sprintf("%s %s", param["paramName"], param["paramType"])
}
return
}
// tidyResult tidies the output parameters.
// For example:
//
// []map[string]string{resultName:list resultType:[]*User, resultName:err resultType:error}
// -> list []*User, err error
//
// []map[string]string{resultName: "", resultType: error}
// -> error
func (c CGenService) tidyResult(resultSlice []map[string]string) (resultStr string) {
for i, result := range resultSlice {
if i > 0 {
resultStr += ", "
}
if result["resultName"] != "" {
resultStr += fmt.Sprintf("%s %s", result["resultName"], result["resultType"])
} else {
resultStr += result["resultType"]
}
}
return
}

View File

@@ -7,15 +7,13 @@
package genservice
import (
"bytes"
"fmt"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/internal/library/hggen/internal/consts"
"hotgo/internal/library/hggen/internal/utility/mlog"
"hotgo/internal/library/hggen/internal/utility/utils"
@@ -23,96 +21,20 @@ import (
type generateServiceFilesInput struct {
CGenServiceInput
DstFilePath string // Absolute file path for generated service go file.
SrcStructFunctions *gmap.ListMap
SrcImportedPackages []string
SrcPackageName string
SrcImportedPackages []string
SrcStructFunctions *gmap.ListMap
DstPackageName string
SrcCodeCommentedMap map[string]string
DstFilePath string // Absolute file path for generated service go file.
}
func (c CGenService) generateServiceFile(in generateServiceFilesInput) (ok bool, err error) {
var (
generatedContent string
allFuncArray = garray.NewStrArray() // Used for check whether interface dirty, going to change file content.
importedPackagesContent = fmt.Sprintf(
"import (\n%s\n)", gstr.Join(in.SrcImportedPackages, "\n"),
)
)
generatedContent += gstr.ReplaceByMap(consts.TemplateGenServiceContentHead, g.MapStrStr{
"{Imports}": importedPackagesContent,
"{PackageName}": in.DstPackageName,
})
var generatedContent bytes.Buffer
// Type definitions.
generatedContent += "type("
generatedContent += "\n"
in.SrcStructFunctions.Iterator(func(key, value interface{}) bool {
structName, funcArray := key.(string), value.(*garray.StrArray)
allFuncArray.Append(funcArray.Slice()...)
// Add comments to a method.
for index, funcName := range funcArray.Slice() {
if commentedInfo, exist := in.SrcCodeCommentedMap[fmt.Sprintf("%s-%s", structName, funcName)]; exist {
funcName = commentedInfo + funcName
_ = funcArray.Set(index, funcName)
}
}
generatedContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentInterface, g.MapStrStr{
"{InterfaceName}": "I" + structName,
"{FuncDefinition}": funcArray.Join("\n\t"),
}))
generatedContent += "\n"
return true
})
generatedContent += ")"
generatedContent += "\n"
// Generating variable and register definitions.
var (
variableContent string
generatingInterfaceCheck string
)
// Variable definitions.
in.SrcStructFunctions.Iterator(func(key, value interface{}) bool {
structName := key.(string)
generatingInterfaceCheck = fmt.Sprintf(`[^\w\d]+%s.I%s[^\w\d]`, in.DstPackageName, structName)
if gregex.IsMatchString(generatingInterfaceCheck, generatedContent) {
return true
}
variableContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentVariable, g.MapStrStr{
"{StructName}": structName,
"{InterfaceName}": "I" + structName,
}))
variableContent += "\n"
return true
})
if variableContent != "" {
generatedContent += "var("
generatedContent += "\n"
generatedContent += variableContent
generatedContent += ")"
generatedContent += "\n"
}
// Variable register function definitions.
in.SrcStructFunctions.Iterator(func(key, value interface{}) bool {
structName := key.(string)
generatingInterfaceCheck = fmt.Sprintf(`[^\w\d]+%s.I%s[^\w\d]`, in.DstPackageName, structName)
if gregex.IsMatchString(generatingInterfaceCheck, generatedContent) {
return true
}
generatedContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentRegister, g.MapStrStr{
"{StructName}": structName,
"{InterfaceName}": "I" + structName,
}))
generatedContent += "\n\n"
return true
})
// Replace empty braces that have new line.
generatedContent, _ = gregex.ReplaceString(`{[\s\t]+}`, `{}`, generatedContent)
// Remove package name calls of `dstPackageName` in produced codes.
generatedContent, _ = gregex.ReplaceString(fmt.Sprintf(`\*{0,1}%s\.`, in.DstPackageName), ``, generatedContent)
c.generatePackageImports(&generatedContent, in.DstPackageName, in.SrcImportedPackages)
c.generateType(&generatedContent, in.SrcStructFunctions, in.DstPackageName)
c.generateVar(&generatedContent, in.SrcStructFunctions)
c.generateFunc(&generatedContent, in.SrcStructFunctions)
// Write file content to disk.
if gfile.Exists(in.DstFilePath) {
@@ -120,59 +42,14 @@ func (c CGenService) generateServiceFile(in generateServiceFilesInput) (ok bool,
mlog.Printf(`ignore file as it is manually maintained: %s`, in.DstFilePath)
return false, nil
}
if !c.isToGenerateServiceGoFile(in.DstPackageName, in.DstFilePath, allFuncArray) {
mlog.Printf(`not dirty, ignore generating service go file: %s`, in.DstFilePath)
return false, nil
}
}
mlog.Printf(`generating service go file: %s`, in.DstFilePath)
if err = gfile.PutContents(in.DstFilePath, generatedContent); err != nil {
if err = gfile.PutBytes(in.DstFilePath, generatedContent.Bytes()); err != nil {
return true, err
}
return true, nil
}
// isToGenerateServiceGoFile checks and returns whether the service content dirty.
func (c CGenService) isToGenerateServiceGoFile(dstPackageName, filePath string, funcArray *garray.StrArray) bool {
var (
err error
fileContent = gfile.GetContents(filePath)
generatedFuncArray = garray.NewSortedStrArrayFrom(funcArray.Slice())
contentFuncArray = garray.NewSortedStrArray()
)
if fileContent == "" {
return true
}
// remove all comments.
fileContent, err = gregex.ReplaceString(`(//.*)|((?s)/\*.*?\*/)`, "", fileContent)
if err != nil {
panic(err)
return false
}
matches, _ := gregex.MatchAllString(`\s+interface\s+{([\s\S]+?)}`, fileContent)
for _, match := range matches {
contentFuncArray.Append(gstr.SplitAndTrim(match[1], "\n")...)
}
if generatedFuncArray.Len() != contentFuncArray.Len() {
mlog.Debugf(
`dirty, generatedFuncArray.Len()[%d] != contentFuncArray.Len()[%d]`,
generatedFuncArray.Len(), contentFuncArray.Len(),
)
return true
}
var funcDefinition string
for i := 0; i < generatedFuncArray.Len(); i++ {
funcDefinition, _ = gregex.ReplaceString(
fmt.Sprintf(`\*{0,1}%s\.`, dstPackageName), ``, generatedFuncArray.At(i),
)
if funcDefinition != contentFuncArray.At(i) {
mlog.Debugf(`dirty, %s != %s`, funcDefinition, contentFuncArray.At(i))
return true
}
}
return false
}
// generateInitializationFile generates `logic.go`.
func (c CGenService) generateInitializationFile(in CGenServiceInput, importSrcPackages []string) (err error) {
var (

View File

@@ -0,0 +1,104 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package genservice
import (
"bytes"
"fmt"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"hotgo/internal/library/hggen/internal/consts"
)
func (c CGenService) generatePackageImports(generatedContent *bytes.Buffer, packageName string, imports []string) {
generatedContent.WriteString(gstr.ReplaceByMap(consts.TemplateGenServiceContentHead, g.MapStrStr{
"{PackageName}": packageName,
"{Imports}": fmt.Sprintf(
"import (\n%s\n)", gstr.Join(imports, "\n"),
),
}))
}
// generateType type definitions.
// See: const.TemplateGenServiceContentInterface
func (c CGenService) generateType(generatedContent *bytes.Buffer, srcStructFunctions *gmap.ListMap, dstPackageName string) {
generatedContent.WriteString("type(")
generatedContent.WriteString("\n")
srcStructFunctions.Iterator(func(key, value interface{}) bool {
var (
funcContents = make([]string, 0)
funcContent string
)
structName, funcSlice := key.(string), value.([]map[string]string)
// Generating interface content.
for _, funcInfo := range funcSlice {
// Remove package name calls of `dstPackageName` in produced codes.
funcHead, _ := gregex.ReplaceString(
fmt.Sprintf(`\*{0,1}%s\.`, dstPackageName),
``, funcInfo["funcHead"],
)
funcContent = funcInfo["funcComment"] + funcHead
funcContents = append(funcContents, funcContent)
}
// funcContents to string.
generatedContent.WriteString(
gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentInterface, g.MapStrStr{
"{InterfaceName}": "I" + structName,
"{FuncDefinition}": gstr.Join(funcContents, "\n\t"),
})),
)
generatedContent.WriteString("\n")
return true
})
generatedContent.WriteString(")")
generatedContent.WriteString("\n")
}
// generateVar variable definitions.
// See: const.TemplateGenServiceContentVariable
func (c CGenService) generateVar(generatedContent *bytes.Buffer, srcStructFunctions *gmap.ListMap) {
// Generating variable and register definitions.
var variableContent string
srcStructFunctions.Iterator(func(key, value interface{}) bool {
structName := key.(string)
variableContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentVariable, g.MapStrStr{
"{StructName}": structName,
"{InterfaceName}": "I" + structName,
}))
variableContent += "\n"
return true
})
if variableContent != "" {
generatedContent.WriteString("var(")
generatedContent.WriteString("\n")
generatedContent.WriteString(variableContent)
generatedContent.WriteString(")")
generatedContent.WriteString("\n")
}
}
// generateFunc function definitions.
// See: const.TemplateGenServiceContentRegister
func (c CGenService) generateFunc(generatedContent *bytes.Buffer, srcStructFunctions *gmap.ListMap) {
// Variable register function definitions.
srcStructFunctions.Iterator(func(key, value interface{}) bool {
structName := key.(string)
generatedContent.WriteString(gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentRegister, g.MapStrStr{
"{StructName}": structName,
"{InterfaceName}": "I" + structName,
})))
generatedContent.WriteString("\n\n")
return true
})
}

View File

@@ -0,0 +1,5 @@
package main
func main() {
}

View File

@@ -0,0 +1,5 @@
package main
func main() {
}

View File

@@ -0,0 +1,12 @@
module github.com/gogf/gf/cmd/gf/cmd/gf/testdata/vardump/v2
go 1.18
require github.com/gogf/gf/v2 v2.6.1
require (
go.opentelemetry.io/otel v1.14.0 // indirect
go.opentelemetry.io/otel/trace v1.14.0 // indirect
)
replace github.com/gogf/gf/v2 => ../../../../../../../

View File

@@ -0,0 +1,27 @@
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/grokify/html-strip-tags-go v0.1.0 h1:03UrQLjAny8xci+R+qjCce/MYnpNXCtgzltlQbOBae4=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM=
go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU=
go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY=
go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M=
go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@@ -0,0 +1,13 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/os/gbuild"
)
func main() {
for k, v := range gbuild.Data() {
fmt.Printf("%s: %v\n", k, v)
}
}

View File

@@ -0,0 +1,30 @@
package testdata
import (
"fmt"
"testing"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/util/guid"
)
func Test_Router_Hook_Multi(t *testing.T) {
s := g.Server(guid.S())
s.BindHandler("/multi-hook", func(r *ghttp.Request) {
r.Response.Write("show")
})
s.BindHookHandlerByMap("/multi-hook", map[string]ghttp.HandlerFunc{
ghttp.HookBeforeServe: func(r *ghttp.Request) {
r.Response.Write("1")
},
})
s.BindHookHandlerByMap("/multi-hook/{id}", map[string]ghttp.HandlerFunc{
ghttp.HookBeforeServe: func(r *ghttp.Request) {
r.Response.Write("2")
},
})
}

View File

@@ -0,0 +1,17 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package dict
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
)
type IDictV1 interface {
DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error)
DictTypeAdd(ctx context.Context, req *v1.DictTypeAddReq) (res *v1.DictTypeAddRes, err error)
}

View File

@@ -0,0 +1,15 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package dict
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
)
type IDictV1 interface {
DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error)
}

View File

@@ -0,0 +1,17 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package v1
import "github.com/gogf/gf/v2/frame/g"
type DictTypeAddPageReq struct {
g.Meta `path:"/dict/type/add" tags:"字典管理" method:"get" summary:"字典类型添加页面"`
}
type DictTypeAddPageRes struct {
g.Meta `mime:"text/html" type:"string" example:"<html/>"`
}

View File

@@ -0,0 +1,5 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dict

View File

@@ -0,0 +1,15 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dict
import (
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict"
)
type ControllerV1 struct{}
func NewV1() dict.IDictV1 {
return &ControllerV1{}
}

View File

@@ -0,0 +1,14 @@
package dict
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
)
func (c *ControllerV1) DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,17 @@
package dict
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
)
func (c *ControllerV1) DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}
func (c *ControllerV1) DictTypeAdd(ctx context.Context, req *v1.DictTypeAddReq) (res *v1.DictTypeAddRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,17 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package dict
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
)
type IDictV1 interface {
DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error)
DictTypeAdd(ctx context.Context, req *v1.DictTypeAddReq) (res *v1.DictTypeAddRes, err error)
}

View File

@@ -0,0 +1,15 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package dict
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict/v1"
)
type IDictV1 interface {
DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error)
}

View File

@@ -0,0 +1,17 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package v1
import "github.com/gogf/gf/v2/frame/g"
type DictTypeAddPageReq struct {
g.Meta `path:"/dict/type/add" tags:"字典管理" method:"get" summary:"字典类型添加页面"`
}
type DictTypeAddPageRes struct {
g.Meta `mime:"text/html" type:"string" example:"<html/>"`
}

View File

@@ -0,0 +1,5 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dict

View File

@@ -0,0 +1,15 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dict
import (
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict"
)
type ControllerV1 struct{}
func NewV1() dict.IDictV1 {
return &ControllerV1{}
}

View File

@@ -0,0 +1,14 @@
package dict
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict/v1"
)
func (c *ControllerV1) DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,14 @@
package dict
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict/v1"
)
func (c *ControllerV1) DictTypeAdd(ctx context.Context, req *v1.DictTypeAddReq) (res *v1.DictTypeAddRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,24 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package article
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v1"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v2"
)
type IArticleV1 interface {
Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error)
Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error)
GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error)
GetOne(ctx context.Context, req *v1.GetOneReq) (res *v1.GetOneRes, err error)
}
type IArticleV2 interface {
Create(ctx context.Context, req *v2.CreateReq) (res *v2.CreateRes, err error)
Update(ctx context.Context, req *v2.UpdateReq) (res *v2.UpdateRes, err error)
}

View File

@@ -0,0 +1,27 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package v1
import "github.com/gogf/gf/v2/frame/g"
type (
CreateReq struct {
g.Meta `path:"/article/create" method:"post" tags:"ArticleService"`
Title string `v:"required"`
}
CreateRes struct{}
)
type (
UpdateReq struct {
g.Meta `path:"/article/update" method:"post" tags:"ArticleService"`
Title string `v:"required"`
}
UpdateRes struct{}
)

View File

@@ -0,0 +1,25 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package v1
import "github.com/gogf/gf/v2/frame/g"
type GetListReq struct {
g.Meta `path:"/article/list" method:"get" tags:"ArticleService"`
}
type GetListRes struct {
list []struct{}
}
type GetOneReq struct {
g.Meta `path:"/article/one" method:"get" tags:"ArticleService"`
}
type GetOneRes struct {
one struct{}
}

View File

@@ -0,0 +1,31 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package v2
import "github.com/gogf/gf/v2/frame/g"
type CreateReq struct {
g.Meta `path:"/article/create" method:"post" tags:"ArticleService"`
Title string `v:"required"`
}
type CreateRes struct{}
type UpdateReq struct {
g.Meta `path:"/article/update" method:"post" tags:"ArticleService"`
Title string `v:"required"`
}
type UpdateRes struct{}
//type GetListReq struct {
// g.Meta `path:"/article/list" method:"get" tags:"ArticleService"`
//}
//
//type GetListRes struct {
// list []struct{}
//}

View File

@@ -0,0 +1,5 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package article

View File

@@ -0,0 +1,21 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package article
import (
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article"
)
type ControllerV1 struct{}
func NewV1() article.IArticleV1 {
return &ControllerV1{}
}
type ControllerV2 struct{}
func NewV2() article.IArticleV2 {
return &ControllerV2{}
}

View File

@@ -0,0 +1,14 @@
package article
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v1"
)
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,14 @@
package article
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v1"
)
func (c *ControllerV1) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,14 @@
package article
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v1"
)
func (c *ControllerV1) GetOne(ctx context.Context, req *v1.GetOneReq) (res *v1.GetOneRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,14 @@
package article
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v1"
)
func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,14 @@
package article
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v2"
)
func (c *ControllerV2) Create(ctx context.Context, req *v2.CreateReq) (res *v2.CreateRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,14 @@
package article
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"hotgo/internal/library/hggen/internal/cmd/testdata/genctrl/api/article/v2"
)
func (c *ControllerV2) Update(ctx context.Context, req *v2.UpdateReq) (res *v2.UpdateRes, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}

View File

@@ -0,0 +1,85 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// TableUserDao is the data access object for table table_user.
type TableUserDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns TableUserColumns // columns contains all the column names of Table for convenient usage.
}
// TableUserColumns defines and stores column names for table table_user.
type TableUserColumns struct {
Id string // User ID
Passport string // User Passport
Password string // User Password
Nickname string // User Nickname
Score string // Total score amount.
CreateAt string // Created Time
UpdateAt string // Updated Time
}
// tableUserColumns holds the columns for table table_user.
var tableUserColumns = TableUserColumns{
Id: "id",
Passport: "passport",
Password: "password",
Nickname: "nickname",
Score: "score",
CreateAt: "create_at",
UpdateAt: "update_at",
}
// NewTableUserDao creates and returns a new DAO object for table data access.
func NewTableUserDao() *TableUserDao {
return &TableUserDao{
group: "test",
table: "table_user",
columns: tableUserColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *TableUserDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *TableUserDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *TableUserDao) Columns() TableUserColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *TableUserDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *TableUserDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *TableUserDao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"for-gendao-test/pkg/dao/internal"
)
// internalTableUserDao is internal type for wrapping internal DAO implements.
type internalTableUserDao = *internal.TableUserDao
// tableUserDao is the data access object for table table_user.
// You can define custom methods on it to extend its functionality as you wish.
type tableUserDao struct {
internalTableUserDao
}
var (
// TableUser is globally public accessible object for table table_user operations.
TableUser = tableUserDao{
internal.NewTableUserDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,22 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package do
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
)
// TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct {
g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID
Passport interface{} // User Passport
Password interface{} // User Password
Nickname interface{} // User Nickname
Score interface{} // Total score amount.
CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time
}

View File

@@ -0,0 +1,20 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package entity
import (
"github.com/gogf/gf/v2/os/gtime"
)
// TableUser is the golang structure for table table_user.
type TableUser struct {
Id uint `json:"ID" orm:"id" ` // User ID
Passport string `json:"PASSPORT" orm:"passport" ` // User Passport
Password string `json:"PASSWORD" orm:"password" ` // User Password
Nickname string `json:"NICKNAME" orm:"nickname" ` // User Nickname
Score float64 `json:"SCORE" orm:"score" ` // Total score amount.
CreateAt *gtime.Time `json:"CREATE_AT" orm:"create_at" ` // Created Time
UpdateAt *gtime.Time `json:"UPDATE_AT" orm:"update_at" ` // Updated Time
}

View File

@@ -0,0 +1,85 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// TableUserDao is the data access object for table table_user.
type TableUserDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns TableUserColumns // columns contains all the column names of Table for convenient usage.
}
// TableUserColumns defines and stores column names for table table_user.
type TableUserColumns struct {
Id string // User ID
Passport string // User Passport
Password string // User Password
Nickname string // User Nickname
Score string // Total score amount.
CreateAt string // Created Time
UpdateAt string // Updated Time
}
// tableUserColumns holds the columns for table table_user.
var tableUserColumns = TableUserColumns{
Id: "id",
Passport: "passport",
Password: "password",
Nickname: "nickname",
Score: "score",
CreateAt: "create_at",
UpdateAt: "update_at",
}
// NewTableUserDao creates and returns a new DAO object for table data access.
func NewTableUserDao() *TableUserDao {
return &TableUserDao{
group: "test",
table: "table_user",
columns: tableUserColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *TableUserDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *TableUserDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *TableUserDao) Columns() TableUserColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *TableUserDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *TableUserDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *TableUserDao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"for-gendao-test/pkg/dao/internal"
)
// internalTableUserDao is internal type for wrapping internal DAO implements.
type internalTableUserDao = *internal.TableUserDao
// tableUserDao is the data access object for table table_user.
// You can define custom methods on it to extend its functionality as you wish.
type tableUserDao struct {
internalTableUserDao
}
var (
// TableUser is globally public accessible object for table table_user operations.
TableUser = tableUserDao{
internal.NewTableUserDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,22 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package do
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
)
// TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct {
g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID
Passport interface{} // User Passport
Password interface{} // User Password
Nickname interface{} // User Nickname
Score interface{} // Total score amount.
CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time
}

View File

@@ -0,0 +1,21 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package entity
import (
"github.com/gogf/gf/v2/os/gtime"
"github.com/shopspring/decimal"
)
// TableUser is the golang structure for table table_user.
type TableUser struct {
Id int64 `json:"id" orm:"id" ` // User ID
Passport string `json:"passport" orm:"passport" ` // User Passport
Password string `json:"password" orm:"password" ` // User Password
Nickname string `json:"nickname" orm:"nickname" ` // User Nickname
Score decimal.Decimal `json:"score" orm:"score" ` // Total score amount.
CreateAt *gtime.Time `json:"createAt" orm:"create_at" ` // Created Time
UpdateAt *gtime.Time `json:"updateAt" orm:"update_at" ` // Updated Time
}

View File

@@ -0,0 +1,85 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// TableUserDao is the data access object for table table_user.
type TableUserDao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns TableUserColumns // columns contains all the column names of Table for convenient usage.
}
// TableUserColumns defines and stores column names for table table_user.
type TableUserColumns struct {
Id string // User ID
Passport string // User Passport
Password string // User Password
Nickname string // User Nickname
Score string // Total score amount.
CreateAt string // Created Time
UpdateAt string // Updated Time
}
// tableUserColumns holds the columns for table table_user.
var tableUserColumns = TableUserColumns{
Id: "id",
Passport: "passport",
Password: "password",
Nickname: "nickname",
Score: "score",
CreateAt: "create_at",
UpdateAt: "update_at",
}
// NewTableUserDao creates and returns a new DAO object for table data access.
func NewTableUserDao() *TableUserDao {
return &TableUserDao{
group: "test",
table: "table_user",
columns: tableUserColumns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *TableUserDao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *TableUserDao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *TableUserDao) Columns() TableUserColumns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *TableUserDao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *TableUserDao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *TableUserDao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"for-gendao-test/pkg/dao/internal"
)
// internalTableUserDao is internal type for wrapping internal DAO implements.
type internalTableUserDao = *internal.TableUserDao
// tableUserDao is the data access object for table table_user.
// You can define custom methods on it to extend its functionality as you wish.
type tableUserDao struct {
internalTableUserDao
}
var (
// TableUser is globally public accessible object for table table_user operations.
TableUser = tableUserDao{
internal.NewTableUserDao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,22 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package do
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
)
// TableUser is the golang structure of table table_user for DAO operations like Where/Data.
type TableUser struct {
g.Meta `orm:"table:table_user, do:true"`
Id interface{} // User ID
Passport interface{} // User Passport
Password interface{} // User Password
Nickname interface{} // User Nickname
Score interface{} // Total score amount.
CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time
}

View File

@@ -0,0 +1,21 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package entity
import (
"github.com/gogf/gf/v2/os/gtime"
"github.com/shopspring/decimal"
)
// TableUser is the golang structure for table table_user.
type TableUser struct {
Id int64 `json:"id" orm:"id" ` // User ID
Passport string `json:"passport" orm:"passport" ` // User Passport
Password string `json:"password" orm:"password" ` // User Password
Nickname string `json:"nickname" orm:"nickname" ` // User Nickname
Score decimal.Decimal `json:"score" orm:"score" ` // Total score amount.
CreateAt *gtime.Time `json:"createAt" orm:"create_at" ` // Created Time
UpdateAt *gtime.Time `json:"updateAt" orm:"update_at" ` // Updated Time
}

View File

@@ -0,0 +1,32 @@
module for-gendao-test/pkg
go 1.18
require (
github.com/gogf/gf/v2 v2.5.3
github.com/shopspring/decimal v1.3.1
)
require (
github.com/BurntSushi/toml v1.2.0 // indirect
github.com/clbanning/mxj/v2 v2.7.0 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/grokify/html-strip-tags-go v0.0.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
go.opentelemetry.io/otel v1.14.0 // indirect
go.opentelemetry.io/otel/sdk v1.14.0 // indirect
go.opentelemetry.io/otel/trace v1.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -0,0 +1,10 @@
CREATE TABLE `%s` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
`password` varchar(45) NOT NULL COMMENT 'User Password',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@@ -0,0 +1,21 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
syntax = "proto3";
package unittest;
option go_package = "unittest";
import "google/protobuf/timestamp.proto";
message TableUser {
uint32 Id = 1; // User ID
string Passport = 2; // User Passport
string Password = 3; // User Password
string Nickname = 4; // User Nickname
string Score = 5; // Total score amount.
google.protobuf.Timestamp CreateAt = 6; // Created Time
google.protobuf.Timestamp UpdateAt = 7; // Updated Time
}

View File

@@ -0,0 +1,21 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
syntax = "proto3";
package unittest;
option go_package = "unittest";
import "google/protobuf/timestamp.proto";
message TableUser {
uint32 ID = 1; // User ID
string PASSPORT = 2; // User Passport
string PASSWORD = 3; // User Password
string NICKNAME = 4; // User Nickname
string SCORE = 5; // Total score amount.
google.protobuf.Timestamp CREATE_AT = 6; // Created Time
google.protobuf.Timestamp UPDATE_AT = 7; // Updated Time
}

View File

@@ -0,0 +1,10 @@
CREATE TABLE `%s` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
`password` varchar(45) NOT NULL COMMENT 'User Password',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@@ -0,0 +1,47 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package article
import (
"context"
"go/ast"
t "time"
gdbalias "github.com/gogf/gf/v2/database/gdb"
"hotgo/internal/library/hggen/internal/cmd/testdata/genservice/service"
)
type sArticle struct {
}
func init() {
service.RegisterArticle(&sArticle{})
}
// Get article details
func (s *sArticle) Get(ctx context.Context, id uint) (info struct{}, err error) {
return struct{}{}, err
}
// Create
/**
* create an article.
* @author oldme
*/
func (s *sArticle) Create(ctx context.Context, info struct{}) (id uint, err error) {
// Use time package to test alias import.
t.Now()
return id, err
}
func (s *sArticle) A1o2(ctx context.Context, str string, a, b *ast.GoStmt) error {
return nil
}
func (s *sArticle) B_2(ctx context.Context, db gdbalias.Raw) (err error) {
return nil
}

View File

@@ -0,0 +1,75 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package article
// import (
// "context"
//
// "hotgo/internal/library/hggen/internal/cmd/testdata/genservice/service"
// )
import (
"context"
// This is a random comment
gdbas "github.com/gogf/gf/v2/database/gdb"
/**
*
*/
_ "github.com/gogf/gf/v2/os/gfile"
)
// T1 random comment
func (s sArticle) T1(ctx context.Context, id, id2 uint) (gdb gdbas.Model, err error) {
g := gdbas.Model{}
return g, err
}
// I'm a random comment
// t2 random comment
func (s *sArticle) t2(ctx context.Context) (err error) {
/**
* random comment
* i (1). func (s *sArticle) t2(ctx context.Context) (err error) { /** 1883
*
*/
_ = func(ctx2 context.Context) {}
return nil
}
// T3
/**
* random comment @*4213hHY1&%##%><<Y
* @param b
* @return c, d
* @return err
* @author oldme
*/
func (s *sArticle) T3(ctx context.Context, b *gdbas.Model) (c, d *gdbas.Model, err error) {
/* import (
* "context"
*
* "hotgo/internal/library/hggen/internal/cmd/testdata/genservice/service"
*/
return nil, nil, nil
}
/**
* random comment
*/
// func (s *sArticle) T4(i interface{}) interface{}
// # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . /
func (s *sArticle) T4(i interface{}) interface{} {
return nil
}
/**
* func (s *sArticle) T4(i interface{}) interface{} {
* return nil
* }
*/

View File

@@ -0,0 +1,38 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package delivery
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genservice/service"
)
type sDeliveryApp struct{}
func NewDeliveryApp() *sDeliveryApp {
return &sDeliveryApp{}
}
func (s *sDeliveryApp) Create(ctx context.Context) (i service.IDeliveryCluster, err error) {
return
}
func (s *sDeliveryApp) GetList(ctx context.Context, i service.IDeliveryCluster) (err error) {
service.Article().Get(ctx, 1)
return
}
func (s *sDeliveryApp) GetOne(ctx context.Context) (err error) {
return
}
func (s *sDeliveryApp) Delete(ctx context.Context) (err error) {
return
}
func (s *sDeliveryApp) AA(ctx context.Context) (err error) { return }

View File

@@ -0,0 +1,32 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package delivery
import (
"context"
gdbas "github.com/gogf/gf/v2/database/gdb"
)
type sDeliveryCluster struct{}
func NewDeliveryCluster() *sDeliveryCluster {
return &sDeliveryCluster{}
}
// Create 自动创建Cluster及Project.
func (s *sDeliveryCluster) Create(ctx context.Context) (err error, gdb gdbas.Model) {
return
}
func (s *sDeliveryCluster) Delete(ctx context.Context) (err error) {
return
}
func (s *sDeliveryCluster) GetList(ctx context.Context) (err error) {
return
}

View File

@@ -0,0 +1,11 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package logic
import (
_ "hotgo/internal/library/hggen/internal/cmd/testdata/genservice/logic/article"
_ "hotgo/internal/library/hggen/internal/cmd/testdata/genservice/logic/delivery"
_ "hotgo/internal/library/hggen/internal/cmd/testdata/genservice/logic/user"
)

View File

@@ -0,0 +1,49 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package user
import (
"context"
"hotgo/internal/library/hggen/internal/cmd/testdata/genservice/service"
)
func init() {
service.RegisterUser(New())
}
type sUser struct {
}
func New() *sUser {
return &sUser{}
}
// Create creates a new user.
func (s *sUser) Create(ctx context.Context, name string) (id int, err error) {
return 0, nil
}
// GetOne retrieves user by id.
func (s *sUser) GetOne(ctx context.Context, id int) (name string, err error) {
return "", nil
}
// GetList retrieves user list.
func (s *sUser) GetList(ctx context.Context) (names []string, err error) {
return nil, nil
}
// Update updates user by id.
func (s *sUser) Update(ctx context.Context, id int) (name string, err error) {
return "", nil
}
// Delete deletes user by id.
func (s *sUser) Delete(ctx context.Context, id int) (err error) {
return nil
}

View File

@@ -0,0 +1,58 @@
// ================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// You can delete these comments if you wish manually maintain this interface file.
// ================================================================================
package service
import (
"context"
"go/ast"
gdbalias "github.com/gogf/gf/v2/database/gdb"
gdbas "github.com/gogf/gf/v2/database/gdb"
)
type (
IArticle interface {
// Get article details
Get(ctx context.Context, id uint) (info struct{}, err error)
// Create
/**
* create an article.
* @author oldme
*/
Create(ctx context.Context, info struct{}) (id uint, err error)
A1o2(ctx context.Context, str string, a *ast.GoStmt, b *ast.GoStmt) error
B_2(ctx context.Context, db gdbalias.Raw) (err error)
// T1 random comment
T1(ctx context.Context, id uint, id2 uint) (gdb gdbas.Model, err error)
// T3
/**
* random comment @*4213hHY1&%##%><<Y
* @param b
* @return c, d
* @return err
* @author oldme
*/
T3(ctx context.Context, b *gdbas.Model) (c *gdbas.Model, d *gdbas.Model, err error)
// func (s *sArticle) T4(i interface{}) interface{}
// # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . /
T4(i interface{}) interface{}
}
)
var (
localArticle IArticle
)
func Article() IArticle {
if localArticle == nil {
panic("implement not found for interface IArticle, forgot register?")
}
return localArticle
}
func RegisterArticle(i IArticle) {
localArticle = i
}

View File

@@ -0,0 +1,55 @@
// ================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// You can delete these comments if you wish manually maintain this interface file.
// ================================================================================
package service
import (
"context"
gdbas "github.com/gogf/gf/v2/database/gdb"
)
type (
IDeliveryApp interface {
Create(ctx context.Context) (i IDeliveryCluster, err error)
GetList(ctx context.Context, i IDeliveryCluster) (err error)
GetOne(ctx context.Context) (err error)
Delete(ctx context.Context) (err error)
AA(ctx context.Context) (err error)
}
IDeliveryCluster interface {
// Create 自动创建Cluster及Project.
Create(ctx context.Context) (err error, gdb gdbas.Model)
Delete(ctx context.Context) (err error)
GetList(ctx context.Context) (err error)
}
)
var (
localDeliveryApp IDeliveryApp
localDeliveryCluster IDeliveryCluster
)
func DeliveryApp() IDeliveryApp {
if localDeliveryApp == nil {
panic("implement not found for interface IDeliveryApp, forgot register?")
}
return localDeliveryApp
}
func RegisterDeliveryApp(i IDeliveryApp) {
localDeliveryApp = i
}
func DeliveryCluster() IDeliveryCluster {
if localDeliveryCluster == nil {
panic("implement not found for interface IDeliveryCluster, forgot register?")
}
return localDeliveryCluster
}
func RegisterDeliveryCluster(i IDeliveryCluster) {
localDeliveryCluster = i
}

View File

@@ -0,0 +1,40 @@
// ================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// You can delete these comments if you wish manually maintain this interface file.
// ================================================================================
package service
import (
"context"
)
type (
IUser interface {
// Create creates a new user.
Create(ctx context.Context, name string) (id int, err error)
// GetOne retrieves user by id.
GetOne(ctx context.Context, id int) (name string, err error)
// GetList retrieves user list.
GetList(ctx context.Context) (names []string, err error)
// Update updates user by id.
Update(ctx context.Context, id int) (name string, err error)
// Delete deletes user by id.
Delete(ctx context.Context, id int) (err error)
}
)
var (
localUser IUser
)
func User() IUser {
if localUser == nil {
panic("implement not found for interface IUser, forgot register?")
}
return localUser
}
func RegisterUser(i IUser) {
localUser = i
}

View File

@@ -0,0 +1,20 @@
gfcli:
gen:
dao:
- link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
tables: "user1"
descriptionTag: true
noModelComment: true
group: "sys"
clear: true
overwriteDao: true
- link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
tables: "user2"
descriptionTag: true
noModelComment: true
group: "book"
clear: true
overwriteDao: true

View File

@@ -0,0 +1,85 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// User3Dao is the data access object for table user3.
type User3Dao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns User3Columns // columns contains all the column names of Table for convenient usage.
}
// User3Columns defines and stores column names for table user3.
type User3Columns struct {
Id string // User ID
Passport string // User Passport
Password string // User Password
Nickname string // User Nickname
Score string // Total score amount.
CreateAt string // Created Time
UpdateAt string // Updated Time
}
// user3Columns holds the columns for table user3.
var user3Columns = User3Columns{
Id: "id",
Passport: "passport",
Password: "password",
Nickname: "nickname",
Score: "score",
CreateAt: "create_at",
UpdateAt: "update_at",
}
// NewUser3Dao creates and returns a new DAO object for table data access.
func NewUser3Dao() *User3Dao {
return &User3Dao{
group: "sys",
table: "user3",
columns: user3Columns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *User3Dao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *User3Dao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *User3Dao) Columns() User3Columns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *User3Dao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *User3Dao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *User3Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,85 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================
package internal
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// User4Dao is the data access object for table user4.
type User4Dao struct {
table string // table is the underlying table name of the DAO.
group string // group is the database configuration group name of current DAO.
columns User4Columns // columns contains all the column names of Table for convenient usage.
}
// User4Columns defines and stores column names for table user4.
type User4Columns struct {
Id string // User ID
Passport string // User Passport
Password string // User Password
Nickname string // User Nickname
Score string // Total score amount.
CreateAt string // Created Time
UpdateAt string // Updated Time
}
// user4Columns holds the columns for table user4.
var user4Columns = User4Columns{
Id: "id",
Passport: "passport",
Password: "password",
Nickname: "nickname",
Score: "score",
CreateAt: "create_at",
UpdateAt: "update_at",
}
// NewUser4Dao creates and returns a new DAO object for table data access.
func NewUser4Dao() *User4Dao {
return &User4Dao{
group: "book",
table: "user4",
columns: user4Columns,
}
}
// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *User4Dao) DB() gdb.DB {
return g.DB(dao.group)
}
// Table returns the table name of current dao.
func (dao *User4Dao) Table() string {
return dao.table
}
// Columns returns all column names of current dao.
func (dao *User4Dao) Columns() User4Columns {
return dao.columns
}
// Group returns the configuration group name of database of current dao.
func (dao *User4Dao) Group() string {
return dao.group
}
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
func (dao *User4Dao) Ctx(ctx context.Context) *gdb.Model {
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
}
// Transaction wraps the transaction logic using function f.
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
// It commits the transaction and returns nil if function f returns nil.
//
// Note that, you should not Commit or Rollback the transaction in function f
// as it is automatically handled by this function.
func (dao *User4Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
return dao.Ctx(ctx).Transaction(ctx, f)
}

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"/internal"
)
// internalUser3Dao is internal type for wrapping internal DAO implements.
type internalUser3Dao = *internal.User3Dao
// user3Dao is the data access object for table user3.
// You can define custom methods on it to extend its functionality as you wish.
type user3Dao struct {
internalUser3Dao
}
var (
// User3 is globally public accessible object for table user3 operations.
User3 = user3Dao{
internal.NewUser3Dao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package dao
import (
"/internal"
)
// internalUser4Dao is internal type for wrapping internal DAO implements.
type internalUser4Dao = *internal.User4Dao
// user4Dao is the data access object for table user4.
// You can define custom methods on it to extend its functionality as you wish.
type user4Dao struct {
internalUser4Dao
}
var (
// User4 is globally public accessible object for table user4 operations.
User4 = user4Dao{
internal.NewUser4Dao(),
}
)
// Fill with you ideas below.

View File

@@ -0,0 +1,22 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package do
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
)
// User1 is the golang structure of table user1 for DAO operations like Where/Data.
type User1 struct {
g.Meta `orm:"table:user1, do:true"`
Id interface{} // User ID
Passport interface{} // User Passport
Password interface{} // User Password
Nickname interface{} // User Nickname
Score interface{} // Total score amount.
CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time
}

View File

@@ -0,0 +1,22 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package do
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
)
// User2 is the golang structure of table user2 for DAO operations like Where/Data.
type User2 struct {
g.Meta `orm:"table:user2, do:true"`
Id interface{} // User ID
Passport interface{} // User Passport
Password interface{} // User Password
Nickname interface{} // User Nickname
Score interface{} // Total score amount.
CreateAt *gtime.Time // Created Time
UpdateAt *gtime.Time // Updated Time
}

View File

@@ -0,0 +1,20 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package entity
import (
"github.com/gogf/gf/v2/os/gtime"
)
// User1 is the golang structure for table user1.
type User1 struct {
Id uint `json:"ID" description:"User ID"`
Passport string `json:"PASSPORT" description:"User Passport"`
Password string `json:"PASSWORD" description:"User Password"`
Nickname string `json:"NICKNAME" description:"User Nickname"`
Score float64 `json:"SCORE" description:"Total score amount."`
CreateAt *gtime.Time `json:"CREATE_AT" description:"Created Time"`
UpdateAt *gtime.Time `json:"UPDATE_AT" description:"Updated Time"`
}

View File

@@ -0,0 +1,20 @@
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package entity
import (
"github.com/gogf/gf/v2/os/gtime"
)
// User2 is the golang structure for table user2.
type User2 struct {
Id uint `json:"ID" description:"User ID"`
Passport string `json:"PASSPORT" description:"User Passport"`
Password string `json:"PASSWORD" description:"User Password"`
Nickname string `json:"NICKNAME" description:"User Nickname"`
Score float64 `json:"SCORE" description:"Total score amount."`
CreateAt *gtime.Time `json:"CREATE_AT" description:"Created Time"`
UpdateAt *gtime.Time `json:"UPDATE_AT" description:"Updated Time"`
}

View File

@@ -0,0 +1,10 @@
CREATE TABLE `user1` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
`password` varchar(45) NOT NULL COMMENT 'User Password',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@@ -0,0 +1,10 @@
CREATE TABLE `user2` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
`password` varchar(45) NOT NULL COMMENT 'User Password',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Some files were not shown because too many files have changed in this diff Show More