mirror of
https://gitee.com/johng/gf
synced 2026-06-08 10:37:44 +08:00
Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c8c7c8c71 | |||
| 73211707fb | |||
| 609f44c5fe | |||
| 0a82036da5 | |||
| b4053ed32e | |||
| 110e3fbf16 | |||
| 095c69c424 | |||
| cee6f499fc | |||
| 73560cfe31 | |||
| 9a7df9944c | |||
| dd02af1b2f | |||
| 626fc629ef | |||
| 2d05fb426f | |||
| bf2997e9cc | |||
| 82d4d77e56 | |||
| 4f43b40a18 | |||
| f3f2cb3c57 | |||
| 102c3b6cb0 | |||
| 5e677a1e05 | |||
| 75f89f19ba | |||
| afe6bebde7 | |||
| 2af2342d67 |
3
.gitignore
vendored
3
.gitignore
vendored
@ -24,4 +24,5 @@ node_modules
|
||||
.docusaurus
|
||||
output
|
||||
.example/
|
||||
.golangci.bck.yml
|
||||
.golangci.bck.yml
|
||||
*.exe
|
||||
@ -1,7 +1,6 @@
|
||||
version: "2"
|
||||
run:
|
||||
concurrency: 4
|
||||
go: "1.25"
|
||||
modules-download-mode: readonly
|
||||
issues-exit-code: 2
|
||||
tests: false
|
||||
|
||||
@ -1,19 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Function to detect OS and set sed parameters
|
||||
setup_sed() {
|
||||
# Function to run sed in-place with OS-specific options
|
||||
sed_inplace() {
|
||||
if [[ "$OSTYPE" == "darwin"* ]]; then
|
||||
# macOS
|
||||
SED_INPLACE="sed -i ''"
|
||||
# macOS - requires empty string after -i
|
||||
sed -i '' "$@"
|
||||
else
|
||||
# Linux/Windows Git Bash
|
||||
SED_INPLACE="sed -i"
|
||||
sed -i "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize sed command
|
||||
setup_sed
|
||||
|
||||
if [ $# -ne 2 ]; then
|
||||
echo "Parameter exception, please execute in the format of $0 [directory] [version number]"
|
||||
echo "PS:$0 ./ v2.4.0"
|
||||
@ -43,10 +40,11 @@ fi
|
||||
|
||||
if [[ true ]]; then
|
||||
# Use sed to replace the version number in version.go
|
||||
$SED_INPLACE 's/VERSION = ".*"/VERSION = "'${newVersion}'"/' version.go
|
||||
sed_inplace 's/VERSION = ".*"/VERSION = "'${newVersion}'"/' version.go
|
||||
|
||||
# Use sed to replace the version number in README.MD
|
||||
$SED_INPLACE 's/version=[^"]*/version='${newVersion}'/' README.MD
|
||||
sed_inplace 's/version=[^"]*/version='${newVersion}'/' README.MD
|
||||
sed_inplace 's/version=[^"]*/version='${newVersion}'/' README.zh_CN.MD
|
||||
fi
|
||||
|
||||
if [ -f "go.work" ]; then
|
||||
@ -70,6 +68,8 @@ for file in `find ${workdir} -name go.mod`; do
|
||||
fi
|
||||
|
||||
cd $goModPath
|
||||
|
||||
# Add replace directive for local development.
|
||||
if [ $goModPath = "./cmd/gf" ]; then
|
||||
mv go.work go.work.version.bak
|
||||
go mod edit -replace github.com/gogf/gf/v2=../../
|
||||
@ -81,20 +81,20 @@ for file in `find ${workdir} -name go.mod`; do
|
||||
go mod edit -replace github.com/gogf/gf/contrib/drivers/sqlite/v2=../../contrib/drivers/sqlite
|
||||
fi
|
||||
# Remove indirect dependencies
|
||||
sed -i '/\/\/ indirect/d' go.mod
|
||||
sed_inplace '/\/\/ indirect/d' go.mod
|
||||
go mod tidy
|
||||
# Remove toolchain line if exists
|
||||
$SED_INPLACE '/^toolchain/d' go.mod
|
||||
sed_inplace '/^toolchain/d' go.mod
|
||||
|
||||
# Upgrading only GoFrame related libraries, sometimes even if a version number is specified,
|
||||
# Upgrading only GoFrame related libraries, sometimes even if a version number is specified,
|
||||
# it may not be possible to successfully upgrade. Please confirm before submitting the code
|
||||
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf"
|
||||
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf" | xargs -L1 go get -v
|
||||
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf" | xargs -L1 go get -v
|
||||
# Remove indirect dependencies
|
||||
sed -i '/\/\/ indirect/d' go.mod
|
||||
sed_inplace '/\/\/ indirect/d' go.mod
|
||||
go mod tidy
|
||||
# Remove toolchain line if exists
|
||||
$SED_INPLACE '/^toolchain/d' go.mod
|
||||
sed_inplace '/^toolchain/d' go.mod
|
||||
if [ $goModPath = "./cmd/gf" ]; then
|
||||
go mod edit -dropreplace github.com/gogf/gf/v2
|
||||
go mod edit -dropreplace github.com/gogf/gf/contrib/drivers/clickhouse/v2
|
||||
|
||||
@ -45,7 +45,7 @@ go get -u github.com/gogf/gf/v2
|
||||
💖 [Thanks to all the contributors who made GoFrame possible](https://github.com/gogf/gf/graphs/contributors) 💖
|
||||
|
||||
<a href="https://github.com/gogf/gf/graphs/contributors">
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.9.8" alt="goframe contributors"/>
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.10.0" alt="goframe contributors"/>
|
||||
</a>
|
||||
|
||||
## License
|
||||
|
||||
@ -45,7 +45,7 @@ go get -u github.com/gogf/gf/v2
|
||||
💖 [感谢所有使 GoFrame 成为可能的贡献者](https://github.com/gogf/gf/graphs/contributors) 💖
|
||||
|
||||
<a href="https://github.com/gogf/gf/graphs/contributors">
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.9.5" alt="goframe contributors"/>
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.10.0" alt="goframe contributors"/>
|
||||
</a>
|
||||
|
||||
## 许可证
|
||||
|
||||
@ -3,13 +3,13 @@ module github.com/gogf/gf/cmd/gf/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.10.0
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.10.0
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.10.0
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.10.0
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.10.0
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.10.0
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f
|
||||
github.com/olekukonko/tablewriter v1.1.0
|
||||
github.com/schollz/progressbar/v3 v3.15.0
|
||||
|
||||
@ -37,11 +37,13 @@ type cEnvInput struct {
|
||||
type cEnvOutput struct{}
|
||||
|
||||
func (c cEnv) Index(ctx context.Context, in cEnvInput) (out *cEnvOutput, err error) {
|
||||
result, err := gproc.ShellExec(ctx, "go env")
|
||||
if err != nil {
|
||||
mlog.Fatal(err)
|
||||
}
|
||||
result, execErr := gproc.ShellExec(ctx, "go env")
|
||||
// Note: go env may return non-zero exit code when there are warnings (e.g., invalid characters in env vars),
|
||||
// but it still outputs valid environment variables. So we only fail if result is empty.
|
||||
if result == "" {
|
||||
if execErr != nil {
|
||||
mlog.Fatal(execErr)
|
||||
}
|
||||
mlog.Fatal(`retrieving Golang environment variables failed, did you install Golang?`)
|
||||
}
|
||||
var (
|
||||
@ -59,7 +61,9 @@ func (c cEnv) Index(ctx context.Context, in cEnvInput) (out *cEnvOutput, err err
|
||||
}
|
||||
match, _ := gregex.MatchString(`(.+?)=(.*)`, line)
|
||||
if len(match) < 3 {
|
||||
mlog.Fatalf(`invalid Golang environment variable: "%s"`, line)
|
||||
// Skip lines that don't match key=value format (e.g., warning messages from go env)
|
||||
mlog.Debugf(`invalid Golang environment variable: "%s"`, line)
|
||||
continue
|
||||
}
|
||||
array = append(array, []string{gstr.Trim(match[1]), gstr.Trim(match[2])})
|
||||
}
|
||||
|
||||
@ -15,9 +15,11 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ctx = context.Background()
|
||||
testDB gdb.DB
|
||||
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true"
|
||||
ctx = context.Background()
|
||||
testDB gdb.DB
|
||||
testPgDB gdb.DB
|
||||
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true"
|
||||
linkPg = "pgsql:postgres:12345678@tcp(127.0.0.1:5432)/test"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@ -28,6 +30,10 @@ func init() {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// PostgreSQL connection (optional, may not be available in all environments)
|
||||
testPgDB, _ = gdb.New(gdb.ConfigNode{
|
||||
Link: linkPg,
|
||||
})
|
||||
}
|
||||
|
||||
func dropTableWithDb(db gdb.DB, table string) {
|
||||
@ -36,3 +42,11 @@ func dropTableWithDb(db gdb.DB, table string) {
|
||||
gtest.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
// dropTableStd uses standard SQL syntax compatible with MySQL and PostgreSQL.
|
||||
func dropTableStd(db gdb.DB, table string) {
|
||||
dropTableStmt := fmt.Sprintf("DROP TABLE IF EXISTS %s", table)
|
||||
if _, err := db.Exec(ctx, dropTableStmt); err != nil {
|
||||
gtest.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
84
cmd/gf/internal/cmd/cmd_z_unit_env_test.go
Normal file
84
cmd/gf/internal/cmd/cmd_z_unit_env_test.go
Normal file
@ -0,0 +1,84 @@
|
||||
// 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 (
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
func Test_Env_Index(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test that env command runs without error
|
||||
_, err := Env.Index(ctx, cEnvInput{})
|
||||
t.AssertNil(err)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Env_ParseGoEnvOutput(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test parsing normal go env output
|
||||
lines := []string{
|
||||
"set GOPATH=C:\\Users\\test\\go",
|
||||
"set GOROOT=C:\\Go",
|
||||
"set GOOS=windows",
|
||||
"GOARCH=amd64", // Unix format without "set " prefix
|
||||
"CGO_ENABLED=0",
|
||||
}
|
||||
|
||||
for _, line := range lines {
|
||||
line = gstr.Trim(line)
|
||||
if gstr.Pos(line, "set ") == 0 {
|
||||
line = line[4:]
|
||||
}
|
||||
match, _ := gregex.MatchString(`(.+?)=(.*)`, line)
|
||||
t.Assert(len(match) >= 3, true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Env_ParseGoEnvOutput_WithWarnings(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test parsing go env output that contains warning messages
|
||||
// These lines should be skipped without causing errors
|
||||
lines := []string{
|
||||
"go: stripping unprintable or unescapable characters from %\"GOPROXY\"%",
|
||||
"go: warning: some warning message",
|
||||
"# this is a comment",
|
||||
"",
|
||||
"set GOPATH=C:\\Users\\test\\go",
|
||||
"set GOOS=windows",
|
||||
}
|
||||
|
||||
array := make([][]string, 0)
|
||||
for _, line := range lines {
|
||||
line = gstr.Trim(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if gstr.Pos(line, "set ") == 0 {
|
||||
line = line[4:]
|
||||
}
|
||||
match, _ := gregex.MatchString(`(.+?)=(.*)`, line)
|
||||
if len(match) < 3 {
|
||||
// Skip lines that don't match key=value format (e.g., warning messages)
|
||||
continue
|
||||
}
|
||||
array = append(array, []string{gstr.Trim(match[1]), gstr.Trim(match[2])})
|
||||
}
|
||||
|
||||
// Should have parsed 2 valid environment variables
|
||||
t.Assert(len(array), 2)
|
||||
t.Assert(array[0][0], "GOPATH")
|
||||
t.Assert(array[0][1], "C:\\Users\\test\\go")
|
||||
t.Assert(array[1][0], "GOOS")
|
||||
t.Assert(array[1][1], "windows")
|
||||
})
|
||||
}
|
||||
@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
func Test_Fix_doFixV25Content(t *testing.T) {
|
||||
@ -22,3 +23,82 @@ func Test_Fix_doFixV25Content(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Fix_doFixV25Content_WithReplacement(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
f = cFix{}
|
||||
content = `s.BindHookHandlerByMap("/path", map[string]ghttp.HandlerFunc{
|
||||
ghttp.HookBeforeServe: func(r *ghttp.Request) {},
|
||||
})`
|
||||
)
|
||||
newContent, err := f.doFixV25Content(content)
|
||||
t.AssertNil(err)
|
||||
// Verify the replacement was made
|
||||
t.Assert(gstr.Contains(newContent, "map[ghttp.HookName]ghttp.HandlerFunc"), true)
|
||||
t.Assert(gstr.Contains(newContent, "map[string]ghttp.HandlerFunc"), false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Fix_doFixV25Content_NoMatch(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
f = cFix{}
|
||||
content = `package main
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello World")
|
||||
}
|
||||
`
|
||||
)
|
||||
newContent, err := f.doFixV25Content(content)
|
||||
t.AssertNil(err)
|
||||
// Content should remain unchanged
|
||||
t.Assert(newContent, content)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Fix_doFixV25Content_MultipleMatches(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
f = cFix{}
|
||||
content = `
|
||||
s.BindHookHandlerByMap("/path1", map[string]ghttp.HandlerFunc{})
|
||||
s.BindHookHandlerByMap("/path2", map[string]ghttp.HandlerFunc{})
|
||||
`
|
||||
)
|
||||
newContent, err := f.doFixV25Content(content)
|
||||
t.AssertNil(err)
|
||||
// Both should be replaced
|
||||
count := gstr.Count(newContent, "map[ghttp.HookName]ghttp.HandlerFunc")
|
||||
t.Assert(count, 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Fix_doFixV25Content_EmptyContent(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
f = cFix{}
|
||||
content = ""
|
||||
)
|
||||
newContent, err := f.doFixV25Content(content)
|
||||
t.AssertNil(err)
|
||||
t.Assert(newContent, "")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Fix_doFixV25Content_ComplexPath(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
f = cFix{}
|
||||
content = `s.BindHookHandlerByMap("/api/v1/user/{id}/profile", map[string]ghttp.HandlerFunc{
|
||||
ghttp.HookBeforeServe: func(r *ghttp.Request) {
|
||||
r.Response.Write("before")
|
||||
},
|
||||
})`
|
||||
)
|
||||
newContent, err := f.doFixV25Content(content)
|
||||
t.AssertNil(err)
|
||||
t.Assert(gstr.Contains(newContent, "map[ghttp.HookName]ghttp.HandlerFunc"), true)
|
||||
})
|
||||
}
|
||||
|
||||
@ -460,3 +460,398 @@ func Test_Gen_Dao_Issue3749(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
// Test tables pattern matching with * wildcard.
|
||||
func Test_Gen_Dao_Issue4629_TablesPattern_Star(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "trade_order"
|
||||
table2 = "trade_item"
|
||||
table3 = "user_info"
|
||||
table4 = "user_log"
|
||||
table5 = "config"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `tables_pattern.sql`)
|
||||
)
|
||||
dropTableStd(db, table1)
|
||||
dropTableStd(db, table2)
|
||||
dropTableStd(db, table3)
|
||||
dropTableStd(db, table4)
|
||||
dropTableStd(db, table5)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableStd(db, table1)
|
||||
defer dropTableStd(db, table2)
|
||||
defer dropTableStd(db, table3)
|
||||
defer dropTableStd(db, table4)
|
||||
defer dropTableStd(db, table5)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Group: group,
|
||||
Tables: "trade_*", // Should match trade_order, trade_item
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 2 dao files: trade_order.go, trade_item.go
|
||||
generatedFiles, err := gfile.ScanDir(gfile.Join(path, "dao"), "*.go", false)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 2)
|
||||
|
||||
// Verify the correct files are generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_order.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_item.go")), true)
|
||||
// user_* and config should NOT be generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_info.go")), false)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_log.go")), false)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "config.go")), false)
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
// Test tables pattern matching with multiple patterns.
|
||||
func Test_Gen_Dao_Issue4629_TablesPattern_Multiple(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "trade_order"
|
||||
table2 = "trade_item"
|
||||
table3 = "user_info"
|
||||
table4 = "user_log"
|
||||
table5 = "config"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `tables_pattern.sql`)
|
||||
)
|
||||
dropTableStd(db, table1)
|
||||
dropTableStd(db, table2)
|
||||
dropTableStd(db, table3)
|
||||
dropTableStd(db, table4)
|
||||
dropTableStd(db, table5)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableStd(db, table1)
|
||||
defer dropTableStd(db, table2)
|
||||
defer dropTableStd(db, table3)
|
||||
defer dropTableStd(db, table4)
|
||||
defer dropTableStd(db, table5)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Group: group,
|
||||
Tables: "trade_*,user_*", // Should match trade_order, trade_item, user_info, user_log
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 4 dao files
|
||||
generatedFiles, err := gfile.ScanDir(gfile.Join(path, "dao"), "*.go", false)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 4)
|
||||
|
||||
// Verify the correct files are generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_order.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_item.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_info.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_log.go")), true)
|
||||
// config should NOT be generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "config.go")), false)
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
// Test tables pattern mixed with exact table name.
|
||||
func Test_Gen_Dao_Issue4629_TablesPattern_Mixed(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "trade_order"
|
||||
table2 = "trade_item"
|
||||
table3 = "user_info"
|
||||
table4 = "user_log"
|
||||
table5 = "config"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `tables_pattern.sql`)
|
||||
)
|
||||
dropTableStd(db, table1)
|
||||
dropTableStd(db, table2)
|
||||
dropTableStd(db, table3)
|
||||
dropTableStd(db, table4)
|
||||
dropTableStd(db, table5)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableStd(db, table1)
|
||||
defer dropTableStd(db, table2)
|
||||
defer dropTableStd(db, table3)
|
||||
defer dropTableStd(db, table4)
|
||||
defer dropTableStd(db, table5)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Group: group,
|
||||
Tables: "trade_*,config", // Pattern + exact name
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 3 dao files: trade_order.go, trade_item.go, config.go
|
||||
generatedFiles, err := gfile.ScanDir(gfile.Join(path, "dao"), "*.go", false)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 3)
|
||||
|
||||
// Verify the correct files are generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_order.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_item.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "config.go")), true)
|
||||
// user_* should NOT be generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_info.go")), false)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_log.go")), false)
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
// Test tables pattern with ? wildcard (single character match).
|
||||
func Test_Gen_Dao_Issue4629_TablesPattern_Question(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "trade_order"
|
||||
table2 = "trade_item"
|
||||
table3 = "user_info"
|
||||
table4 = "user_log"
|
||||
table5 = "config"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `tables_pattern.sql`)
|
||||
)
|
||||
dropTableStd(db, table1)
|
||||
dropTableStd(db, table2)
|
||||
dropTableStd(db, table3)
|
||||
dropTableStd(db, table4)
|
||||
dropTableStd(db, table5)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableStd(db, table1)
|
||||
defer dropTableStd(db, table2)
|
||||
defer dropTableStd(db, table3)
|
||||
defer dropTableStd(db, table4)
|
||||
defer dropTableStd(db, table5)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Group: group,
|
||||
Tables: "user_???", // ? matches single char: user_log (3 chars) but not user_info (4 chars)
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 1 dao file: user_log.go (3 chars after user_)
|
||||
generatedFiles, err := gfile.ScanDir(gfile.Join(path, "dao"), "*.go", false)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 1)
|
||||
|
||||
// Verify only user_log is generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_log.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_info.go")), false) // 4 chars, doesn't match
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
// Test that exact table names still work (backward compatibility).
|
||||
func Test_Gen_Dao_Issue4629_TablesPattern_ExactNames(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "trade_order"
|
||||
table2 = "trade_item"
|
||||
table3 = "user_info"
|
||||
table4 = "user_log"
|
||||
table5 = "config"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `tables_pattern.sql`)
|
||||
)
|
||||
dropTableStd(db, table1)
|
||||
dropTableStd(db, table2)
|
||||
dropTableStd(db, table3)
|
||||
dropTableStd(db, table4)
|
||||
dropTableStd(db, table5)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableStd(db, table1)
|
||||
defer dropTableStd(db, table2)
|
||||
defer dropTableStd(db, table3)
|
||||
defer dropTableStd(db, table4)
|
||||
defer dropTableStd(db, table5)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Group: group,
|
||||
Tables: "trade_order,config", // Exact names, no patterns
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 2 dao files
|
||||
generatedFiles, err := gfile.ScanDir(gfile.Join(path, "dao"), "*.go", false)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 2)
|
||||
|
||||
// Verify exactly the specified tables are generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_order.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "config.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_item.go")), false)
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
// Test tables pattern matching with PostgreSQL.
|
||||
func Test_Gen_Dao_Issue4629_TablesPattern_PgSql(t *testing.T) {
|
||||
if testPgDB == nil {
|
||||
t.Skip("PostgreSQL database not available, skipping test")
|
||||
return
|
||||
}
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testPgDB
|
||||
table1 = "trade_order"
|
||||
table2 = "trade_item"
|
||||
table3 = "user_info"
|
||||
table4 = "user_log"
|
||||
table5 = "config"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `tables_pattern.sql`)
|
||||
)
|
||||
dropTableStd(db, table1)
|
||||
dropTableStd(db, table2)
|
||||
dropTableStd(db, table3)
|
||||
dropTableStd(db, table4)
|
||||
dropTableStd(db, table5)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableStd(db, table1)
|
||||
defer dropTableStd(db, table2)
|
||||
defer dropTableStd(db, table3)
|
||||
defer dropTableStd(db, table4)
|
||||
defer dropTableStd(db, table5)
|
||||
|
||||
// Test tables pattern with tablesEx pattern
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: linkPg,
|
||||
Group: group,
|
||||
Tables: "trade_*,user_*,config", // Match only our test tables
|
||||
TablesEx: "user_*", // Exclude user_* tables
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 3 dao files: trade_order, trade_item, config (user_* excluded by tablesEx)
|
||||
generatedFiles, err := gfile.ScanDir(gfile.Join(path, "dao"), "*.go", false)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 3)
|
||||
|
||||
// Verify the correct files are generated
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_order.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "trade_item.go")), true)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "config.go")), true)
|
||||
// user_* should NOT be generated (excluded by tablesEx)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_info.go")), false)
|
||||
t.Assert(gfile.Exists(gfile.Join(path, "dao", "user_log.go")), false)
|
||||
})
|
||||
}
|
||||
|
||||
@ -18,6 +18,92 @@ import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/gendao"
|
||||
)
|
||||
|
||||
// Test_Gen_Dao_Sharding_Overlapping tests the fix for issue #4603.
|
||||
// When sharding patterns have overlapping prefixes (like "a_?", "a_b_?", "a_c_?"),
|
||||
// longer (more specific) patterns should be matched first.
|
||||
// https://github.com/gogf/gf/issues/4603
|
||||
func Test_Gen_Dao_Sharding_Overlapping(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
tableA1 = "a_1"
|
||||
tableA2 = "a_2"
|
||||
tableAB1 = "a_b_1"
|
||||
tableAB2 = "a_b_2"
|
||||
tableAC1 = "a_c_1"
|
||||
tableAC2 = "a_c_2"
|
||||
sqlFilePath = gtest.DataPath(`gendao`, `sharding`, `sharding_overlapping.sql`)
|
||||
)
|
||||
dropTableWithDb(db, tableA1)
|
||||
dropTableWithDb(db, tableA2)
|
||||
dropTableWithDb(db, tableAB1)
|
||||
dropTableWithDb(db, tableAB2)
|
||||
dropTableWithDb(db, tableAC1)
|
||||
dropTableWithDb(db, tableAC2)
|
||||
t.AssertNil(execSqlFile(db, sqlFilePath))
|
||||
defer dropTableWithDb(db, tableA1)
|
||||
defer dropTableWithDb(db, tableA2)
|
||||
defer dropTableWithDb(db, tableAB1)
|
||||
defer dropTableWithDb(db, tableAB2)
|
||||
defer dropTableWithDb(db, tableAC1)
|
||||
defer dropTableWithDb(db, tableAC2)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Group: group,
|
||||
Prefix: "",
|
||||
// Patterns with overlapping prefixes - order should not matter due to sorting fix
|
||||
ShardingPattern: []string{
|
||||
`a_?`, // shortest, matches a_1, a_2 but also a_b_1, a_c_1 without fix
|
||||
`a_b_?`, // longer, should match a_b_1, a_b_2
|
||||
`a_c_?`, // longer, should match a_c_1, a_c_2
|
||||
},
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(pwd)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should generate 3 dao files: a.go, a_b.go, a_c.go (plus internal versions)
|
||||
generatedFiles, err := gfile.ScanDir(path, "*.go", true)
|
||||
t.AssertNil(err)
|
||||
// 3 sharding groups * 4 files each (dao, internal, do, entity) = 12 files
|
||||
t.Assert(len(generatedFiles), 12)
|
||||
|
||||
var (
|
||||
daoAContent = gfile.GetContents(gfile.Join(path, "dao", "a.go"))
|
||||
daoABContent = gfile.GetContents(gfile.Join(path, "dao", "a_b.go"))
|
||||
daoACContent = gfile.GetContents(gfile.Join(path, "dao", "a_c.go"))
|
||||
)
|
||||
|
||||
// Verify each sharding group has correct dao file generated
|
||||
t.Assert(gstr.Contains(daoAContent, "aShardingHandler"), true)
|
||||
t.Assert(gstr.Contains(daoAContent, "m.Sharding(gdb.ShardingConfig{"), true)
|
||||
|
||||
t.Assert(gstr.Contains(daoABContent, "aBShardingHandler"), true)
|
||||
t.Assert(gstr.Contains(daoABContent, "m.Sharding(gdb.ShardingConfig{"), true)
|
||||
|
||||
t.Assert(gstr.Contains(daoACContent, "aCShardingHandler"), true)
|
||||
t.Assert(gstr.Contains(daoACContent, "m.Sharding(gdb.ShardingConfig{"), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Gen_Dao_Sharding(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
|
||||
158
cmd/gf/internal/cmd/cmd_z_unit_gen_enums_test.go
Normal file
158
cmd/gf/internal/cmd/cmd_z_unit_gen_enums_test.go
Normal file
@ -0,0 +1,158 @@
|
||||
// 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 (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/util/guid"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/genenums"
|
||||
)
|
||||
|
||||
// https://github.com/gogf/gf/issues/4387
|
||||
// Test that the output path is relative to the original working directory,
|
||||
// not the source directory after Chdir.
|
||||
func Test_Gen_Enums_Issue4387_RelativePath(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
// Create temp directory to simulate user's project
|
||||
tempPath = gfile.Temp(guid.S())
|
||||
// Copy testdata to temp directory
|
||||
srcTestData = gtest.DataPath("issue", "4387")
|
||||
)
|
||||
|
||||
// Setup: create temp project structure
|
||||
err := gfile.CopyDir(srcTestData, tempPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempPath)
|
||||
|
||||
// Save original working directory
|
||||
originalWd := gfile.Pwd()
|
||||
|
||||
// Change to temp directory (simulate user being in project root)
|
||||
err = gfile.Chdir(tempPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(originalWd) // Restore original working directory
|
||||
|
||||
// Run gen enums with relative paths
|
||||
var (
|
||||
srcFolder = "api"
|
||||
outputPath = filepath.FromSlash("internal/packed/packed_enums.go")
|
||||
in = genenums.CGenEnumsInput{
|
||||
Src: srcFolder,
|
||||
Path: outputPath,
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
_, err = genenums.CGenEnums{}.Enums(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Expected: file should be created at tempPath/internal/packed/packed_enums.go
|
||||
expectedPath := filepath.Join(tempPath, "internal", "packed", "packed_enums.go")
|
||||
// Bug: file is created at tempPath/api/internal/packed/packed_enums.go
|
||||
wrongPath := filepath.Join(tempPath, "api", "internal", "packed", "packed_enums.go")
|
||||
|
||||
// Assert the file is at the expected location
|
||||
t.Assert(gfile.Exists(expectedPath), true)
|
||||
// Assert the file is NOT at the wrong location
|
||||
t.Assert(gfile.Exists(wrongPath), false)
|
||||
})
|
||||
}
|
||||
|
||||
// Test gen enums with absolute output path (should work correctly)
|
||||
func Test_Gen_Enums_AbsolutePath(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
tempPath = gfile.Temp(guid.S())
|
||||
srcTestData = gtest.DataPath("issue", "4387")
|
||||
)
|
||||
|
||||
err := gfile.CopyDir(srcTestData, tempPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempPath)
|
||||
|
||||
originalWd := gfile.Pwd()
|
||||
err = gfile.Chdir(tempPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(originalWd)
|
||||
|
||||
// Use absolute path for output
|
||||
var (
|
||||
srcFolder = "api"
|
||||
outputPath = filepath.Join(tempPath, "internal", "packed", "packed_enums.go")
|
||||
in = genenums.CGenEnumsInput{
|
||||
Src: srcFolder,
|
||||
Path: outputPath,
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
_, err = genenums.CGenEnums{}.Enums(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Assert the file exists at absolute path
|
||||
t.Assert(gfile.Exists(outputPath), true)
|
||||
})
|
||||
}
|
||||
|
||||
// Test gen enums in monorepo mode (cd app/xxx/ then run command)
|
||||
func Test_Gen_Enums_Issue4387_Monorepo(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
// Simulate monorepo structure
|
||||
tempPath = gfile.Temp(guid.S())
|
||||
srcTestData = gtest.DataPath("issue", "4387")
|
||||
// app/myapp is the subdirectory in monorepo
|
||||
appPath = filepath.Join(tempPath, "app", "myapp")
|
||||
)
|
||||
|
||||
// Create monorepo structure: tempPath/app/myapp/api/...
|
||||
err := gfile.Mkdir(appPath)
|
||||
t.AssertNil(err)
|
||||
// Copy testdata into app/myapp
|
||||
err = gfile.CopyDir(srcTestData, appPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempPath)
|
||||
|
||||
originalWd := gfile.Pwd()
|
||||
|
||||
// cd app/myapp (simulate user in monorepo subdirectory)
|
||||
err = gfile.Chdir(appPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Chdir(originalWd)
|
||||
|
||||
var (
|
||||
srcFolder = "api"
|
||||
outputPath = filepath.FromSlash("internal/packed/packed_enums.go")
|
||||
in = genenums.CGenEnumsInput{
|
||||
Src: srcFolder,
|
||||
Path: outputPath,
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
_, err = genenums.CGenEnums{}.Enums(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Expected: file at app/myapp/internal/packed/packed_enums.go
|
||||
expectedPath := filepath.Join(appPath, "internal", "packed", "packed_enums.go")
|
||||
// Bug: file at app/myapp/api/internal/packed/packed_enums.go
|
||||
wrongPath := filepath.Join(appPath, "api", "internal", "packed", "packed_enums.go")
|
||||
|
||||
t.Assert(gfile.Exists(expectedPath), true)
|
||||
t.Assert(gfile.Exists(wrongPath), false)
|
||||
})
|
||||
}
|
||||
@ -88,3 +88,76 @@ func TestGenPbIssue3953(t *testing.T) {
|
||||
t.Assert(gstr.Contains(genContent, notExceptText), false)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGenPb_MultipleTags(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
outputPath = gfile.Temp(guid.S())
|
||||
outputApiPath = filepath.Join(outputPath, "api")
|
||||
outputCtrlPath = filepath.Join(outputPath, "controller")
|
||||
|
||||
protobufFolder = gtest.DataPath("genpb")
|
||||
in = genpb.CGenPbInput{
|
||||
Path: protobufFolder,
|
||||
OutputApi: outputApiPath,
|
||||
OutputCtrl: outputCtrlPath,
|
||||
}
|
||||
err error
|
||||
)
|
||||
err = gfile.Mkdir(outputApiPath)
|
||||
t.AssertNil(err)
|
||||
err = gfile.Mkdir(outputCtrlPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(outputPath)
|
||||
|
||||
_, err = genpb.CGenPb{}.Pb(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Test multiple_tags.proto output
|
||||
genContent := gfile.GetContents(filepath.Join(outputApiPath, "multiple_tags.pb.go"))
|
||||
// Id field should have combined validation tags: v:"required#Id > 0"
|
||||
t.Assert(gstr.Contains(genContent, `v:"required#Id > 0"`), true)
|
||||
// Name field should have dc tag from plain comment
|
||||
t.Assert(gstr.Contains(genContent, `dc:"User name for login"`), true)
|
||||
// Email field should have combined validation and dc tag
|
||||
t.Assert(gstr.Contains(genContent, `v:"requiredemail"`), true)
|
||||
t.Assert(gstr.Contains(genContent, `dc:"User email address"`), true)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGenPb_NestedMessage(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
outputPath = gfile.Temp(guid.S())
|
||||
outputApiPath = filepath.Join(outputPath, "api")
|
||||
outputCtrlPath = filepath.Join(outputPath, "controller")
|
||||
|
||||
protobufFolder = gtest.DataPath("genpb")
|
||||
in = genpb.CGenPbInput{
|
||||
Path: protobufFolder,
|
||||
OutputApi: outputApiPath,
|
||||
OutputCtrl: outputCtrlPath,
|
||||
}
|
||||
err error
|
||||
)
|
||||
err = gfile.Mkdir(outputApiPath)
|
||||
t.AssertNil(err)
|
||||
err = gfile.Mkdir(outputCtrlPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(outputPath)
|
||||
|
||||
_, err = genpb.CGenPb{}.Pb(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Test nested_message.proto output
|
||||
genContent := gfile.GetContents(filepath.Join(outputApiPath, "nested_message.pb.go"))
|
||||
// Order.OrderId should have v:"required"
|
||||
t.Assert(gstr.Contains(genContent, `v:"required"`), true)
|
||||
// Order.Detail should have dc:"Order details"
|
||||
t.Assert(gstr.Contains(genContent, `dc:"Order details"`), true)
|
||||
// OrderDetail.Quantity should have v:"min:1"
|
||||
t.Assert(gstr.Contains(genContent, `v:"min:1"`), true)
|
||||
// OrderDetail.Price should have v:"min:0.01"
|
||||
t.Assert(gstr.Contains(genContent, `v:"min:0.01"`), true)
|
||||
})
|
||||
}
|
||||
|
||||
@ -156,3 +156,130 @@ func Test_Issue3835(t *testing.T) {
|
||||
t.Assert(gfile.GetContents(genFile), gfile.GetContents(expectFile))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Gen_Service_CamelCase(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
dstFolder = path + filepath.FromSlash("/service")
|
||||
srvFolder = gtest.DataPath("genservice", "logic")
|
||||
in = genservice.CGenServiceInput{
|
||||
SrcFolder: srvFolder,
|
||||
DstFolder: dstFolder,
|
||||
DstFileNameCase: "Camel",
|
||||
WatchFile: "",
|
||||
StPattern: "",
|
||||
Packages: nil,
|
||||
ImportPrefix: "",
|
||||
Clear: false,
|
||||
}
|
||||
)
|
||||
err := gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
// Clean up generated logic.go
|
||||
genSrv := srvFolder + filepath.FromSlash("/logic.go")
|
||||
defer gfile.Remove(genSrv)
|
||||
|
||||
_, err = genservice.CGenService{}.Service(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Files should be in CamelCase
|
||||
files, err := gfile.ScanDir(dstFolder, "*.go", true)
|
||||
t.AssertNil(err)
|
||||
t.Assert(files, []string{
|
||||
dstFolder + filepath.FromSlash("/Article.go"),
|
||||
dstFolder + filepath.FromSlash("/Base.go"),
|
||||
dstFolder + filepath.FromSlash("/Delivery.go"),
|
||||
dstFolder + filepath.FromSlash("/User.go"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Gen_Service_PackagesFilter(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
dstFolder = path + filepath.FromSlash("/service")
|
||||
srvFolder = gtest.DataPath("genservice", "logic")
|
||||
in = genservice.CGenServiceInput{
|
||||
SrcFolder: srvFolder,
|
||||
DstFolder: dstFolder,
|
||||
DstFileNameCase: "Snake",
|
||||
WatchFile: "",
|
||||
StPattern: "",
|
||||
Packages: []string{"user"},
|
||||
ImportPrefix: "",
|
||||
Clear: false,
|
||||
}
|
||||
)
|
||||
err := gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
// Clean up generated logic.go
|
||||
genSrv := srvFolder + filepath.FromSlash("/logic.go")
|
||||
defer gfile.Remove(genSrv)
|
||||
|
||||
_, err = genservice.CGenService{}.Service(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Only user.go should be generated
|
||||
files, err := gfile.ScanDir(dstFolder, "*.go", true)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(files), 1)
|
||||
t.Assert(files[0], dstFolder+filepath.FromSlash("/user.go"))
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/4242
|
||||
// Test that versioned imports and aliased imports are correctly preserved.
|
||||
// The issue is that imports like "github.com/minio/minio-go/v7" were being
|
||||
// incorrectly handled because the package name (minio) differs from
|
||||
// the directory name (minio-go).
|
||||
func Test_Issue4242(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
dstFolder = path + filepath.FromSlash("/service")
|
||||
srvFolder = gtest.DataPath("issue", "4242", "logic")
|
||||
in = genservice.CGenServiceInput{
|
||||
SrcFolder: srvFolder,
|
||||
DstFolder: dstFolder,
|
||||
DstFileNameCase: "Snake",
|
||||
WatchFile: "",
|
||||
StPattern: "",
|
||||
Packages: nil,
|
||||
ImportPrefix: "",
|
||||
Clear: false,
|
||||
}
|
||||
)
|
||||
err := gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
_, err = genservice.CGenService{}.Service(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Test versioned imports
|
||||
t.Assert(
|
||||
gfile.GetContents(dstFolder+filepath.FromSlash("/issue_4242.go")),
|
||||
gfile.GetContents(gtest.DataPath("issue", "4242", "service", "issue_4242.go")),
|
||||
)
|
||||
// Test aliased imports
|
||||
t.Assert(
|
||||
gfile.GetContents(dstFolder+filepath.FromSlash("/issue_4242_alias.go")),
|
||||
gfile.GetContents(gtest.DataPath("issue", "4242", "service", "issue_4242_alias.go")),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
346
cmd/gf/internal/cmd/cmd_z_unit_pack_test.go
Normal file
346
cmd/gf/internal/cmd/cmd_z_unit_pack_test.go
Normal file
@ -0,0 +1,346 @@
|
||||
// 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"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
func Test_Pack_ToGoFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "packed", "data.go")
|
||||
)
|
||||
// Create source directory with test files
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create test files
|
||||
err = gfile.PutContents(filepath.Join(srcPath, "test.txt"), "hello world")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(srcPath, "test.json"), `{"key":"value"}`)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create packed directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "packed"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack to go file
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
Name: "packed",
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
|
||||
// Verify it's a valid Go file
|
||||
content := gfile.GetContents(dstFile)
|
||||
t.Assert(gstr.Contains(content, "package packed"), true)
|
||||
t.Assert(gstr.Contains(content, "func init()"), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_ToBinaryFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "data.bin")
|
||||
)
|
||||
// Create source directory with test files
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create test file
|
||||
err = gfile.PutContents(filepath.Join(srcPath, "test.txt"), "binary content")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack to binary file (no Name specified)
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
|
||||
// Verify it's a binary file (not a Go file)
|
||||
content := gfile.GetContents(dstFile)
|
||||
t.Assert(gstr.Contains(content, "package"), false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_MultipleSources(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath1 = gfile.Temp(guid.S())
|
||||
srcPath2 = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "packed", "multi.go")
|
||||
)
|
||||
// Create source directories
|
||||
err := gfile.Mkdir(srcPath1)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath1)
|
||||
|
||||
err = gfile.Mkdir(srcPath2)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath2)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create test files in each source
|
||||
err = gfile.PutContents(filepath.Join(srcPath1, "file1.txt"), "content1")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(srcPath2, "file2.txt"), "content2")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create packed directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "packed"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack multiple sources (comma-separated)
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath1 + "," + srcPath2,
|
||||
Dst: dstFile,
|
||||
Name: "packed",
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_WithPrefix(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "packed", "prefix.go")
|
||||
)
|
||||
// Create source directory
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create test file
|
||||
err = gfile.PutContents(filepath.Join(srcPath, "test.txt"), "with prefix")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create packed directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "packed"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack with prefix
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
Name: "packed",
|
||||
Prefix: "/static",
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_WithKeepPath(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "packed", "keeppath.go")
|
||||
)
|
||||
// Create source directory with subdirectory
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create subdirectory and file
|
||||
subDir := filepath.Join(srcPath, "subdir")
|
||||
err = gfile.Mkdir(subDir)
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(subDir, "test.txt"), "keeppath content")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create packed directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "packed"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack with keepPath
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
Name: "packed",
|
||||
KeepPath: true,
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_AutoPackageName(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "mypackage", "data.go")
|
||||
)
|
||||
// Create source directory
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create test file
|
||||
err = gfile.PutContents(filepath.Join(srcPath, "test.txt"), "auto package name")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create mypackage directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "mypackage"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack without Name - should use directory name "mypackage"
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
// Name not specified, should be auto-detected as "mypackage"
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists and has correct package name
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
content := gfile.GetContents(dstFile)
|
||||
t.Assert(gstr.Contains(content, "package mypackage"), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_EmptySource(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "packed", "empty.go")
|
||||
)
|
||||
// Create empty source directory
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create packed directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "packed"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack empty directory
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
Name: "packed",
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists (even if source is empty)
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Pack_NestedDirectories(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gfile.Temp(guid.S())
|
||||
dstPath = gfile.Temp(guid.S())
|
||||
dstFile = filepath.Join(dstPath, "packed", "nested.go")
|
||||
)
|
||||
// Create source directory with nested structure
|
||||
err := gfile.Mkdir(srcPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(srcPath)
|
||||
|
||||
err = gfile.Mkdir(dstPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// Create nested directories and files
|
||||
level1 := filepath.Join(srcPath, "level1")
|
||||
level2 := filepath.Join(level1, "level2")
|
||||
level3 := filepath.Join(level2, "level3")
|
||||
err = gfile.Mkdir(level3)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.PutContents(filepath.Join(srcPath, "root.txt"), "root")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(level1, "l1.txt"), "level1")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(level2, "l2.txt"), "level2")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(level3, "l3.txt"), "level3")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create packed directory
|
||||
err = gfile.Mkdir(filepath.Join(dstPath, "packed"))
|
||||
t.AssertNil(err)
|
||||
|
||||
// Pack nested directories
|
||||
_, err = Pack.Index(context.Background(), cPackInput{
|
||||
Src: srcPath,
|
||||
Dst: dstFile,
|
||||
Name: "packed",
|
||||
})
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify output file exists
|
||||
t.Assert(gfile.Exists(dstFile), true)
|
||||
|
||||
// Verify content includes all files
|
||||
content := gfile.GetContents(dstFile)
|
||||
t.Assert(gstr.Contains(content, "package packed"), true)
|
||||
})
|
||||
}
|
||||
@ -9,6 +9,7 @@ package gendao
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/olekukonko/tablewriter"
|
||||
@ -187,7 +188,27 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
|
||||
var tableNames []string
|
||||
if in.Tables != "" {
|
||||
tableNames = gstr.SplitAndTrim(in.Tables, ",")
|
||||
inputTables := gstr.SplitAndTrim(in.Tables, ",")
|
||||
// Check if any table pattern contains wildcard characters.
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
var hasPattern bool
|
||||
for _, t := range inputTables {
|
||||
if containsWildcard(t) {
|
||||
hasPattern = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasPattern {
|
||||
// Fetch all tables first, then filter by patterns.
|
||||
allTables, err := db.Tables(context.TODO())
|
||||
if err != nil {
|
||||
mlog.Fatalf("fetching tables failed: %+v", err)
|
||||
}
|
||||
tableNames = filterTablesByPatterns(allTables, inputTables)
|
||||
} else {
|
||||
// Use exact table names as before.
|
||||
tableNames = inputTables
|
||||
}
|
||||
} else {
|
||||
tableNames, err = db.Tables(context.TODO())
|
||||
if err != nil {
|
||||
@ -198,22 +219,11 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
if in.TablesEx != "" {
|
||||
array := garray.NewStrArrayFrom(tableNames)
|
||||
for _, p := range gstr.SplitAndTrim(in.TablesEx, ",") {
|
||||
if gstr.Contains(p, "*") || gstr.Contains(p, "?") {
|
||||
p = gstr.ReplaceByMap(p, map[string]string{
|
||||
"\r": "",
|
||||
"\n": "",
|
||||
})
|
||||
p = gstr.ReplaceByMap(p, map[string]string{
|
||||
"*": "\r",
|
||||
"?": "\n",
|
||||
})
|
||||
p = gregex.Quote(p)
|
||||
p = gstr.ReplaceByMap(p, map[string]string{
|
||||
"\r": ".*",
|
||||
"\n": ".",
|
||||
})
|
||||
if containsWildcard(p) {
|
||||
// Use exact match with ^ and $ anchors for consistency with tables pattern.
|
||||
regPattern := "^" + patternToRegex(p) + "$"
|
||||
for _, v := range array.Clone().Slice() {
|
||||
if gregex.IsMatchString(p, v) {
|
||||
if gregex.IsMatchString(regPattern, v) {
|
||||
array.RemoveValue(v)
|
||||
}
|
||||
}
|
||||
@ -240,13 +250,22 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
newTableNames = make([]string, len(tableNames))
|
||||
shardingNewTableSet = gset.NewStrSet()
|
||||
)
|
||||
// Sort sharding patterns by length descending, so that longer (more specific) patterns
|
||||
// are matched first. This prevents shorter patterns like "a_?" from incorrectly matching
|
||||
// tables that should match longer patterns like "a_b_?" or "a_c_?".
|
||||
// https://github.com/gogf/gf/issues/4603
|
||||
sortedShardingPatterns := make([]string, len(in.ShardingPattern))
|
||||
copy(sortedShardingPatterns, in.ShardingPattern)
|
||||
sort.Slice(sortedShardingPatterns, func(i, j int) bool {
|
||||
return len(sortedShardingPatterns[i]) > len(sortedShardingPatterns[j])
|
||||
})
|
||||
for i, tableName := range tableNames {
|
||||
newTableName := tableName
|
||||
for _, v := range removePrefixArray {
|
||||
newTableName = gstr.TrimLeftStr(newTableName, v, 1)
|
||||
}
|
||||
if len(in.ShardingPattern) > 0 {
|
||||
for _, pattern := range in.ShardingPattern {
|
||||
if len(sortedShardingPatterns) > 0 {
|
||||
for _, pattern := range sortedShardingPatterns {
|
||||
var (
|
||||
match []string
|
||||
regPattern = gstr.Replace(pattern, "?", `(.+)`)
|
||||
@ -262,10 +281,11 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
newTableName = gstr.Trim(newTableName, `_.-`)
|
||||
if shardingNewTableSet.Contains(newTableName) {
|
||||
tableNames[i] = ""
|
||||
continue
|
||||
break
|
||||
}
|
||||
// Add prefix to sharding table name, if not, the isSharding check would not match.
|
||||
shardingNewTableSet.Add(in.Prefix + newTableName)
|
||||
break
|
||||
}
|
||||
}
|
||||
newTableName = in.Prefix + newTableName
|
||||
@ -411,3 +431,61 @@ func getTemplateFromPathOrDefault(filePath string, def string) string {
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// containsWildcard checks if the pattern contains wildcard characters (* or ?).
|
||||
func containsWildcard(pattern string) bool {
|
||||
return gstr.Contains(pattern, "*") || gstr.Contains(pattern, "?")
|
||||
}
|
||||
|
||||
// patternToRegex converts a wildcard pattern to a regex pattern.
|
||||
// Wildcard characters: * matches any characters, ? matches single character.
|
||||
func patternToRegex(pattern string) string {
|
||||
pattern = gstr.ReplaceByMap(pattern, map[string]string{
|
||||
"\r": "",
|
||||
"\n": "",
|
||||
})
|
||||
pattern = gstr.ReplaceByMap(pattern, map[string]string{
|
||||
"*": "\r",
|
||||
"?": "\n",
|
||||
})
|
||||
pattern = gregex.Quote(pattern)
|
||||
pattern = gstr.ReplaceByMap(pattern, map[string]string{
|
||||
"\r": ".*",
|
||||
"\n": ".",
|
||||
})
|
||||
return pattern
|
||||
}
|
||||
|
||||
// filterTablesByPatterns filters tables by given patterns.
|
||||
// Patterns support wildcard characters: * matches any characters, ? matches single character.
|
||||
// https://github.com/gogf/gf/issues/4629
|
||||
func filterTablesByPatterns(allTables []string, patterns []string) []string {
|
||||
var result []string
|
||||
matched := make(map[string]bool)
|
||||
allTablesSet := make(map[string]bool)
|
||||
for _, t := range allTables {
|
||||
allTablesSet[t] = true
|
||||
}
|
||||
for _, p := range patterns {
|
||||
if containsWildcard(p) {
|
||||
regPattern := "^" + patternToRegex(p) + "$"
|
||||
for _, table := range allTables {
|
||||
if !matched[table] && gregex.IsMatchString(regPattern, table) {
|
||||
result = append(result, table)
|
||||
matched[table] = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Exact table name, use direct string comparison.
|
||||
if !allTablesSet[p] {
|
||||
mlog.Printf(`table "%s" does not exist, skipped`, p)
|
||||
continue
|
||||
}
|
||||
if !matched[p] {
|
||||
result = append(result, p)
|
||||
matched[p] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
182
cmd/gf/internal/cmd/gendao/gendao_test.go
Normal file
182
cmd/gf/internal/cmd/gendao/gendao_test.go
Normal file
@ -0,0 +1,182 @@
|
||||
// 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 gendao
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
)
|
||||
|
||||
// Test containsWildcard function.
|
||||
func Test_containsWildcard(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
t.Assert(containsWildcard("trade_*"), true)
|
||||
t.Assert(containsWildcard("user_?"), true)
|
||||
t.Assert(containsWildcard("*"), true)
|
||||
t.Assert(containsWildcard("?"), true)
|
||||
t.Assert(containsWildcard("trade_order"), false)
|
||||
t.Assert(containsWildcard(""), false)
|
||||
})
|
||||
}
|
||||
|
||||
// Test patternToRegex function.
|
||||
func Test_patternToRegex(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// * should become .*
|
||||
t.Assert(patternToRegex("trade_*"), "trade_.*")
|
||||
// ? should become .
|
||||
t.Assert(patternToRegex("user_???"), "user_...")
|
||||
// Mixed
|
||||
t.Assert(patternToRegex("*_order_?"), ".*_order_.")
|
||||
// No wildcards - should escape special regex chars
|
||||
t.Assert(patternToRegex("trade_order"), "trade_order")
|
||||
// Just *
|
||||
t.Assert(patternToRegex("*"), ".*")
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns with * wildcard.
|
||||
func Test_filterTablesByPatterns_Star(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info", "user_log", "config"}
|
||||
|
||||
// Single pattern with *
|
||||
result := filterTablesByPatterns(allTables, []string{"trade_*"})
|
||||
t.Assert(len(result), 2)
|
||||
t.AssertIN("trade_order", result)
|
||||
t.AssertIN("trade_item", result)
|
||||
|
||||
// Multiple patterns with *
|
||||
result = filterTablesByPatterns(allTables, []string{"trade_*", "user_*"})
|
||||
t.Assert(len(result), 4)
|
||||
t.AssertIN("trade_order", result)
|
||||
t.AssertIN("trade_item", result)
|
||||
t.AssertIN("user_info", result)
|
||||
t.AssertIN("user_log", result)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns with ? wildcard.
|
||||
func Test_filterTablesByPatterns_Question(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info", "user_log", "config"}
|
||||
|
||||
// ? matches single character: user_log (3 chars) but not user_info (4 chars)
|
||||
result := filterTablesByPatterns(allTables, []string{"user_???"})
|
||||
t.Assert(len(result), 1)
|
||||
t.AssertIN("user_log", result)
|
||||
t.AssertNI("user_info", result)
|
||||
|
||||
// user_???? should match user_info (4 chars)
|
||||
result = filterTablesByPatterns(allTables, []string{"user_????"})
|
||||
t.Assert(len(result), 1)
|
||||
t.AssertIN("user_info", result)
|
||||
t.AssertNI("user_log", result)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns with mixed patterns and exact names.
|
||||
func Test_filterTablesByPatterns_Mixed(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info", "user_log", "config"}
|
||||
|
||||
// Pattern + exact name
|
||||
result := filterTablesByPatterns(allTables, []string{"trade_*", "config"})
|
||||
t.Assert(len(result), 3)
|
||||
t.AssertIN("trade_order", result)
|
||||
t.AssertIN("trade_item", result)
|
||||
t.AssertIN("config", result)
|
||||
t.AssertNI("user_info", result)
|
||||
t.AssertNI("user_log", result)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns with exact names only (backward compatibility).
|
||||
func Test_filterTablesByPatterns_ExactNames(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info", "user_log", "config"}
|
||||
|
||||
// Exact names only
|
||||
result := filterTablesByPatterns(allTables, []string{"trade_order", "config"})
|
||||
t.Assert(len(result), 2)
|
||||
t.AssertIN("trade_order", result)
|
||||
t.AssertIN("config", result)
|
||||
t.AssertNI("trade_item", result)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns - no duplicates when table matches multiple patterns.
|
||||
func Test_filterTablesByPatterns_NoDuplicates(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info"}
|
||||
|
||||
// trade_order matches both patterns, should only appear once
|
||||
result := filterTablesByPatterns(allTables, []string{"trade_*", "trade_order"})
|
||||
t.Assert(len(result), 2) // trade_order, trade_item
|
||||
|
||||
// Count occurrences of trade_order
|
||||
count := 0
|
||||
for _, v := range result {
|
||||
if v == "trade_order" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
t.Assert(count, 1) // No duplicates
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns - pattern matches nothing.
|
||||
func Test_filterTablesByPatterns_NoMatch(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info"}
|
||||
|
||||
// Pattern that matches nothing
|
||||
result := filterTablesByPatterns(allTables, []string{"nonexistent_*"})
|
||||
t.Assert(len(result), 0)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns - empty input.
|
||||
func Test_filterTablesByPatterns_Empty(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item"}
|
||||
|
||||
// Empty patterns
|
||||
result := filterTablesByPatterns(allTables, []string{})
|
||||
t.Assert(len(result), 0)
|
||||
|
||||
// Empty tables
|
||||
result = filterTablesByPatterns([]string{}, []string{"trade_*"})
|
||||
t.Assert(len(result), 0)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns - "*" matches all tables.
|
||||
func Test_filterTablesByPatterns_MatchAll(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info", "user_log", "config"}
|
||||
|
||||
// "*" should match all tables
|
||||
result := filterTablesByPatterns(allTables, []string{"*"})
|
||||
t.Assert(len(result), 5)
|
||||
})
|
||||
}
|
||||
|
||||
// Test filterTablesByPatterns - non-existent exact table name should be skipped.
|
||||
func Test_filterTablesByPatterns_NonExistent(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
allTables := []string{"trade_order", "trade_item", "user_info"}
|
||||
|
||||
// Mix of existing and non-existing tables
|
||||
result := filterTablesByPatterns(allTables, []string{"trade_order", "nonexistent", "user_info"})
|
||||
t.Assert(len(result), 2)
|
||||
t.AssertIN("trade_order", result)
|
||||
t.AssertIN("user_info", result)
|
||||
t.AssertNI("nonexistent", result)
|
||||
})
|
||||
}
|
||||
@ -55,6 +55,13 @@ func (c CGenEnums) Enums(ctx context.Context, in CGenEnumsInput) (out *CGenEnums
|
||||
if realPath == "" {
|
||||
mlog.Fatalf(`source folder path "%s" does not exist`, in.Src)
|
||||
}
|
||||
// Convert output path to absolute before Chdir, so it remains correct after directory change.
|
||||
// See: https://github.com/gogf/gf/issues/4387
|
||||
outputPath := gfile.Abs(in.Path)
|
||||
|
||||
originPwd := gfile.Pwd()
|
||||
defer gfile.Chdir(originPwd)
|
||||
|
||||
err = gfile.Chdir(realPath)
|
||||
if err != nil {
|
||||
mlog.Fatal(err)
|
||||
@ -72,14 +79,14 @@ func (c CGenEnums) Enums(ctx context.Context, in CGenEnumsInput) (out *CGenEnums
|
||||
p := NewEnumsParser(in.Prefixes)
|
||||
p.ParsePackages(pkgs)
|
||||
var enumsContent = gstr.ReplaceByMap(consts.TemplateGenEnums, g.MapStrStr{
|
||||
"{PackageName}": gfile.Basename(gfile.Dir(in.Path)),
|
||||
"{PackageName}": gfile.Basename(gfile.Dir(outputPath)),
|
||||
"{EnumsJson}": "`" + p.Export() + "`",
|
||||
})
|
||||
enumsContent = gstr.Trim(enumsContent)
|
||||
if err = gfile.PutContents(in.Path, enumsContent); err != nil {
|
||||
if err = gfile.PutContents(outputPath, enumsContent); err != nil {
|
||||
return
|
||||
}
|
||||
mlog.Printf(`generated enums go file: %s`, in.Path)
|
||||
mlog.Printf(`generated enums go file: %s`, outputPath)
|
||||
mlog.Print("done!")
|
||||
return
|
||||
}
|
||||
|
||||
368
cmd/gf/internal/cmd/genenums/genenums_z_unit_test.go
Normal file
368
cmd/gf/internal/cmd/genenums/genenums_z_unit_test.go
Normal file
@ -0,0 +1,368 @@
|
||||
// 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 genenums
|
||||
|
||||
import (
|
||||
"go/constant"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/tools/go/packages"
|
||||
|
||||
"github.com/gogf/gf/v2/encoding/gjson"
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/util/guid"
|
||||
)
|
||||
|
||||
func Test_NewEnumsParser(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test creating parser without prefixes
|
||||
p := NewEnumsParser(nil)
|
||||
t.AssertNE(p, nil)
|
||||
t.Assert(len(p.enums), 0)
|
||||
t.Assert(len(p.prefixes), 0)
|
||||
t.AssertNE(p.parsedPkg, nil)
|
||||
t.AssertNE(p.standardPackages, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_NewEnumsParser_WithPrefixes(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test creating parser with prefixes
|
||||
prefixes := []string{"github.com/gogf", "github.com/test"}
|
||||
p := NewEnumsParser(prefixes)
|
||||
t.AssertNE(p, nil)
|
||||
t.Assert(len(p.prefixes), 2)
|
||||
t.Assert(p.prefixes[0], "github.com/gogf")
|
||||
t.Assert(p.prefixes[1], "github.com/test")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_Empty(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test exporting empty enums
|
||||
p := NewEnumsParser(nil)
|
||||
result := p.Export()
|
||||
t.Assert(result, "{}")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_WithEnums(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test exporting with manually added enums
|
||||
p := NewEnumsParser(nil)
|
||||
|
||||
// Add some test enums
|
||||
p.enums = []EnumItem{
|
||||
{
|
||||
Name: "StatusActive",
|
||||
Value: "1",
|
||||
Type: "pkg.Status",
|
||||
Kind: constant.Int,
|
||||
},
|
||||
{
|
||||
Name: "StatusInactive",
|
||||
Value: "0",
|
||||
Type: "pkg.Status",
|
||||
Kind: constant.Int,
|
||||
},
|
||||
{
|
||||
Name: "TypeA",
|
||||
Value: "type_a",
|
||||
Type: "pkg.Type",
|
||||
Kind: constant.String,
|
||||
},
|
||||
}
|
||||
|
||||
result := p.Export()
|
||||
t.AssertNE(result, "")
|
||||
|
||||
// Parse the result to verify - use raw map to avoid gjson path issues with "."
|
||||
var resultMap map[string][]interface{}
|
||||
err := gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify Status type has 2 values
|
||||
statusValues := resultMap["pkg.Status"]
|
||||
t.Assert(len(statusValues), 2)
|
||||
|
||||
// Verify Type type has 1 value
|
||||
typeValues := resultMap["pkg.Type"]
|
||||
t.Assert(len(typeValues), 1)
|
||||
t.Assert(typeValues[0], "type_a")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_IntValues(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := NewEnumsParser(nil)
|
||||
p.enums = []EnumItem{
|
||||
{Name: "One", Value: "1", Type: "pkg.Int", Kind: constant.Int},
|
||||
{Name: "Two", Value: "2", Type: "pkg.Int", Kind: constant.Int},
|
||||
{Name: "Negative", Value: "-5", Type: "pkg.Int", Kind: constant.Int},
|
||||
}
|
||||
|
||||
result := p.Export()
|
||||
var resultMap map[string][]interface{}
|
||||
err := gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
values := resultMap["pkg.Int"]
|
||||
t.Assert(len(values), 3)
|
||||
// Int values should be exported as integers (stored as float64 in JSON)
|
||||
t.Assert(values[0], float64(1))
|
||||
t.Assert(values[1], float64(2))
|
||||
t.Assert(values[2], float64(-5))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_FloatValues(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := NewEnumsParser(nil)
|
||||
p.enums = []EnumItem{
|
||||
{Name: "Pi", Value: "3.14159", Type: "pkg.Float", Kind: constant.Float},
|
||||
{Name: "E", Value: "2.71828", Type: "pkg.Float", Kind: constant.Float},
|
||||
}
|
||||
|
||||
result := p.Export()
|
||||
var resultMap map[string][]interface{}
|
||||
err := gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
values := resultMap["pkg.Float"]
|
||||
t.Assert(len(values), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_BoolValues(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := NewEnumsParser(nil)
|
||||
p.enums = []EnumItem{
|
||||
{Name: "True", Value: "true", Type: "pkg.Bool", Kind: constant.Bool},
|
||||
{Name: "False", Value: "false", Type: "pkg.Bool", Kind: constant.Bool},
|
||||
}
|
||||
|
||||
result := p.Export()
|
||||
var resultMap map[string][]interface{}
|
||||
err := gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
values := resultMap["pkg.Bool"]
|
||||
t.Assert(len(values), 2)
|
||||
t.Assert(values[0], true)
|
||||
t.Assert(values[1], false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_StringValues(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := NewEnumsParser(nil)
|
||||
p.enums = []EnumItem{
|
||||
{Name: "Hello", Value: "hello", Type: "pkg.Str", Kind: constant.String},
|
||||
{Name: "World", Value: "world", Type: "pkg.Str", Kind: constant.String},
|
||||
}
|
||||
|
||||
result := p.Export()
|
||||
var resultMap map[string][]interface{}
|
||||
err := gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
values := resultMap["pkg.Str"]
|
||||
t.Assert(len(values), 2)
|
||||
t.Assert(values[0], "hello")
|
||||
t.Assert(values[1], "world")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_Export_MixedTypes(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := NewEnumsParser(nil)
|
||||
p.enums = []EnumItem{
|
||||
{Name: "IntVal", Value: "42", Type: "pkg.IntType", Kind: constant.Int},
|
||||
{Name: "StrVal", Value: "test", Type: "pkg.StrType", Kind: constant.String},
|
||||
{Name: "BoolVal", Value: "true", Type: "pkg.BoolType", Kind: constant.Bool},
|
||||
}
|
||||
|
||||
result := p.Export()
|
||||
var resultMap map[string][]interface{}
|
||||
err := gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Each type should have its own array
|
||||
t.Assert(len(resultMap["pkg.IntType"]), 1)
|
||||
t.Assert(len(resultMap["pkg.StrType"]), 1)
|
||||
t.Assert(len(resultMap["pkg.BoolType"]), 1)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumItem_Structure(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test EnumItem structure
|
||||
item := EnumItem{
|
||||
Name: "TestEnum",
|
||||
Value: "test_value",
|
||||
Type: "github.com/test/pkg.EnumType",
|
||||
Kind: constant.String,
|
||||
}
|
||||
|
||||
t.Assert(item.Name, "TestEnum")
|
||||
t.Assert(item.Value, "test_value")
|
||||
t.Assert(item.Type, "github.com/test/pkg.EnumType")
|
||||
t.Assert(item.Kind, constant.String)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_ParsePackages_Integration(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a temporary directory with a Go package containing enums
|
||||
// Note: The module path must contain "/" for enums to be parsed
|
||||
// (the parser skips std types without "/" in the type name)
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create go.mod with a path containing "/"
|
||||
goModContent := `module github.com/test/enumtest
|
||||
|
||||
go 1.21
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "go.mod"), goModContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create a Go file with enum definitions
|
||||
enumsContent := `package enumtest
|
||||
|
||||
type Status int
|
||||
|
||||
const (
|
||||
StatusActive Status = 1
|
||||
StatusInactive Status = 0
|
||||
)
|
||||
|
||||
type Color string
|
||||
|
||||
const (
|
||||
ColorRed Color = "red"
|
||||
ColorGreen Color = "green"
|
||||
ColorBlue Color = "blue"
|
||||
)
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "enums.go"), enumsContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Load the package
|
||||
cfg := &packages.Config{
|
||||
Dir: tempDir,
|
||||
Mode: pkgLoadMode,
|
||||
Tests: false,
|
||||
}
|
||||
pkgs, err := packages.Load(cfg)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(pkgs) > 0, true)
|
||||
|
||||
// Parse the packages
|
||||
p := NewEnumsParser(nil)
|
||||
p.ParsePackages(pkgs)
|
||||
|
||||
// Export and verify - result should contain parsed enums
|
||||
result := p.Export()
|
||||
// Verify the export contains some data
|
||||
t.Assert(len(result) > 2, true) // More than just "{}"
|
||||
|
||||
// Parse result as raw map to handle keys with "/"
|
||||
var resultMap map[string][]interface{}
|
||||
err = gjson.DecodeTo(result, &resultMap)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify Status enum was parsed (type will be "github.com/test/enumtest.Status")
|
||||
statusKey := "github.com/test/enumtest.Status"
|
||||
statusValues, hasStatus := resultMap[statusKey]
|
||||
t.Assert(hasStatus, true)
|
||||
t.Assert(len(statusValues), 2)
|
||||
|
||||
// Verify Color enum was parsed
|
||||
colorKey := "github.com/test/enumtest.Color"
|
||||
colorValues, hasColor := resultMap[colorKey]
|
||||
t.Assert(hasColor, true)
|
||||
t.Assert(len(colorValues), 3)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_EnumsParser_ParsePackages_WithPrefixes(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a temporary directory with a Go package
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create go.mod with a specific module name
|
||||
goModContent := `module github.com/allowed/pkg
|
||||
|
||||
go 1.21
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "go.mod"), goModContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create a Go file with enum definitions
|
||||
enumsContent := `package pkg
|
||||
|
||||
type Status int
|
||||
|
||||
const (
|
||||
StatusOK Status = 1
|
||||
)
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "enums.go"), enumsContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Load the package
|
||||
cfg := &packages.Config{
|
||||
Dir: tempDir,
|
||||
Mode: pkgLoadMode,
|
||||
Tests: false,
|
||||
}
|
||||
pkgs, err := packages.Load(cfg)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Parse with prefix filter that matches
|
||||
p := NewEnumsParser([]string{"github.com/allowed"})
|
||||
p.ParsePackages(pkgs)
|
||||
|
||||
result := p.Export()
|
||||
// Should have enums because prefix matches
|
||||
t.AssertNE(result, "{}")
|
||||
|
||||
// Parse with prefix filter that doesn't match
|
||||
p2 := NewEnumsParser([]string{"github.com/other"})
|
||||
p2.ParsePackages(pkgs)
|
||||
|
||||
result2 := p2.Export()
|
||||
// Should be empty because prefix doesn't match
|
||||
t.Assert(result2, "{}")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_getStandardPackages(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
stdPkgs := getStandardPackages()
|
||||
t.AssertNE(stdPkgs, nil)
|
||||
t.Assert(len(stdPkgs) > 0, true)
|
||||
|
||||
// Verify some common standard packages are included
|
||||
_, hasFmt := stdPkgs["fmt"]
|
||||
t.Assert(hasFmt, true)
|
||||
|
||||
_, hasOs := stdPkgs["os"]
|
||||
t.Assert(hasOs, true)
|
||||
|
||||
_, hasContext := stdPkgs["context"]
|
||||
t.Assert(hasContext, true)
|
||||
})
|
||||
}
|
||||
359
cmd/gf/internal/cmd/geninit/geninit_z_unit_test.go
Normal file
359
cmd/gf/internal/cmd/geninit/geninit_z_unit_test.go
Normal file
@ -0,0 +1,359 @@
|
||||
// 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 geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/util/guid"
|
||||
)
|
||||
|
||||
func Test_ParseGitURL_Basic(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test basic github URL
|
||||
info, err := ParseGitURL("github.com/gogf/gf")
|
||||
t.AssertNil(err)
|
||||
t.Assert(info.Host, "github.com")
|
||||
t.Assert(info.Owner, "gogf")
|
||||
t.Assert(info.Repo, "gf")
|
||||
t.Assert(info.SubPath, "")
|
||||
t.Assert(info.Branch, "main")
|
||||
t.Assert(info.CloneURL, "https://github.com/gogf/gf.git")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ParseGitURL_WithHTTPS(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test URL with https prefix
|
||||
info, err := ParseGitURL("https://github.com/gogf/gf")
|
||||
t.AssertNil(err)
|
||||
t.Assert(info.Host, "github.com")
|
||||
t.Assert(info.Owner, "gogf")
|
||||
t.Assert(info.Repo, "gf")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ParseGitURL_WithGitSuffix(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test URL with .git suffix
|
||||
info, err := ParseGitURL("github.com/gogf/gf.git")
|
||||
t.AssertNil(err)
|
||||
t.Assert(info.Host, "github.com")
|
||||
t.Assert(info.Owner, "gogf")
|
||||
t.Assert(info.Repo, "gf")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ParseGitURL_WithSubPath(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test URL with subdirectory
|
||||
info, err := ParseGitURL("github.com/gogf/examples/httpserver/jwt")
|
||||
t.AssertNil(err)
|
||||
t.Assert(info.Host, "github.com")
|
||||
t.Assert(info.Owner, "gogf")
|
||||
t.Assert(info.Repo, "examples")
|
||||
t.Assert(info.SubPath, "httpserver/jwt")
|
||||
t.Assert(info.CloneURL, "https://github.com/gogf/examples.git")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ParseGitURL_WithTreeBranch(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test GitHub web URL with /tree/branch/
|
||||
info, err := ParseGitURL("github.com/gogf/examples/tree/develop/httpserver/jwt")
|
||||
t.AssertNil(err)
|
||||
t.Assert(info.Host, "github.com")
|
||||
t.Assert(info.Owner, "gogf")
|
||||
t.Assert(info.Repo, "examples")
|
||||
t.Assert(info.Branch, "develop")
|
||||
t.Assert(info.SubPath, "httpserver/jwt")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ParseGitURL_WithVersion(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test URL with version suffix
|
||||
info, err := ParseGitURL("github.com/gogf/gf/cmd/gf/v2@v2.9.7")
|
||||
t.AssertNil(err)
|
||||
t.Assert(info.Host, "github.com")
|
||||
t.Assert(info.Owner, "gogf")
|
||||
t.Assert(info.Repo, "gf")
|
||||
t.Assert(info.SubPath, "cmd/gf/v2")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ParseGitURL_Invalid(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test invalid URL (too short)
|
||||
_, err := ParseGitURL("github.com/gogf")
|
||||
t.AssertNE(err, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_IsSubdirRepo_NotSubdir(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Standard Go module paths should not be detected as subdirectory
|
||||
t.Assert(IsSubdirRepo("github.com/gogf/gf"), false)
|
||||
t.Assert(IsSubdirRepo("github.com/gogf/gf/v2"), false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_IsSubdirRepo_GoModuleWithCmd(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Go module paths with common patterns should not be detected as subdirectory
|
||||
t.Assert(IsSubdirRepo("github.com/gogf/gf/cmd/gf/v2"), false)
|
||||
t.Assert(IsSubdirRepo("github.com/gogf/gf/contrib/drivers/mysql/v2"), false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_IsSubdirRepo_ActualSubdir(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Actual subdirectories should be detected
|
||||
t.Assert(IsSubdirRepo("github.com/gogf/examples/httpserver/jwt"), true)
|
||||
t.Assert(IsSubdirRepo("github.com/gogf/examples/grpc/basic"), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetModuleNameFromGoMod_Valid(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create temp directory with go.mod
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Write go.mod file
|
||||
goModContent := `module github.com/test/myproject
|
||||
|
||||
go 1.21
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.0
|
||||
)
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "go.mod"), goModContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Test extraction
|
||||
moduleName := GetModuleNameFromGoMod(tempDir)
|
||||
t.Assert(moduleName, "github.com/test/myproject")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetModuleNameFromGoMod_NoFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create temp directory without go.mod
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Test extraction - should return empty
|
||||
moduleName := GetModuleNameFromGoMod(tempDir)
|
||||
t.Assert(moduleName, "")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetModuleNameFromGoMod_SimpleModule(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create temp directory with simple go.mod
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Write simple go.mod file
|
||||
goModContent := `module main
|
||||
|
||||
go 1.21
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "go.mod"), goModContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Test extraction
|
||||
moduleName := GetModuleNameFromGoMod(tempDir)
|
||||
t.Assert(moduleName, "main")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ASTReplacer_ReplaceInFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create temp directory
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create a Go file with imports
|
||||
goFileContent := `package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/old/module/internal/service"
|
||||
"github.com/old/module/pkg/utils"
|
||||
"github.com/other/package"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello")
|
||||
}
|
||||
`
|
||||
goFilePath := filepath.Join(tempDir, "main.go")
|
||||
err = gfile.PutContents(goFilePath, goFileContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Replace imports
|
||||
replacer := NewASTReplacer("github.com/old/module", "github.com/new/project")
|
||||
err = replacer.ReplaceInFile(context.Background(), goFilePath)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify replacement
|
||||
content := gfile.GetContents(goFilePath)
|
||||
t.Assert(gfile.Exists(goFilePath), true)
|
||||
|
||||
// Check that old imports are replaced
|
||||
t.AssertNE(content, "")
|
||||
t.Assert(contains(content, `"github.com/new/project/internal/service"`), true)
|
||||
t.Assert(contains(content, `"github.com/new/project/pkg/utils"`), true)
|
||||
|
||||
// Check that other imports are not affected
|
||||
t.Assert(contains(content, `"github.com/other/package"`), true)
|
||||
t.Assert(contains(content, `"fmt"`), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ASTReplacer_ReplaceInDir(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create temp directory structure
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create subdirectory
|
||||
subDir := filepath.Join(tempDir, "sub")
|
||||
err = gfile.Mkdir(subDir)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create main.go
|
||||
mainContent := `package main
|
||||
|
||||
import "github.com/old/module/sub"
|
||||
|
||||
func main() {
|
||||
sub.Hello()
|
||||
}
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "main.go"), mainContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create sub/sub.go
|
||||
subContent := `package sub
|
||||
|
||||
import "github.com/old/module/pkg"
|
||||
|
||||
func Hello() {
|
||||
pkg.Do()
|
||||
}
|
||||
`
|
||||
err = gfile.PutContents(filepath.Join(subDir, "sub.go"), subContent)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Replace imports in directory
|
||||
replacer := NewASTReplacer("github.com/old/module", "github.com/new/project")
|
||||
err = replacer.ReplaceInDir(context.Background(), tempDir)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Verify main.go replacement
|
||||
mainResult := gfile.GetContents(filepath.Join(tempDir, "main.go"))
|
||||
t.Assert(contains(mainResult, `"github.com/new/project/sub"`), true)
|
||||
|
||||
// Verify sub/sub.go replacement
|
||||
subResult := gfile.GetContents(filepath.Join(subDir, "sub.go"))
|
||||
t.Assert(contains(subResult, `"github.com/new/project/pkg"`), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_findGoFiles(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create temp directory structure
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create subdirectories
|
||||
subDir := filepath.Join(tempDir, "sub")
|
||||
err = gfile.Mkdir(subDir)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Create various files
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "main.go"), "package main")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(tempDir, "readme.md"), "# README")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(subDir, "sub.go"), "package sub")
|
||||
t.AssertNil(err)
|
||||
err = gfile.PutContents(filepath.Join(subDir, "data.json"), "{}")
|
||||
t.AssertNil(err)
|
||||
|
||||
// Find Go files
|
||||
files, err := findGoFiles(tempDir)
|
||||
t.AssertNil(err)
|
||||
|
||||
// Should find exactly 2 Go files
|
||||
t.Assert(len(files), 2)
|
||||
|
||||
// Verify file names
|
||||
hasMain := false
|
||||
hasSub := false
|
||||
for _, f := range files {
|
||||
if filepath.Base(f) == "main.go" {
|
||||
hasMain = true
|
||||
}
|
||||
if filepath.Base(f) == "sub.go" {
|
||||
hasSub = true
|
||||
}
|
||||
}
|
||||
t.Assert(hasMain, true)
|
||||
t.Assert(hasSub, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_findGoFiles_EmptyDir(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create empty temp directory
|
||||
tempDir := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tempDir)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Find Go files
|
||||
files, err := findGoFiles(tempDir)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(files), 0)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function to check if string contains substring
|
||||
func contains(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsAt(s, substr))
|
||||
}
|
||||
|
||||
func containsAt(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@ -12,7 +12,6 @@ import (
|
||||
|
||||
"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"
|
||||
|
||||
@ -37,21 +36,14 @@ func (c CGenService) calculateImportedItems(
|
||||
}
|
||||
|
||||
for _, item := range pkgItems {
|
||||
alias := item.Alias
|
||||
|
||||
// If the alias is _, it means that the package is not generated.
|
||||
if alias == "_" {
|
||||
// Skip anonymous imports
|
||||
if item.Alias == "_" {
|
||||
mlog.Debugf(`ignore anonymous package: %s`, item.RawImport)
|
||||
continue
|
||||
}
|
||||
// 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
|
||||
}
|
||||
// Keep all imports, let gofmt clean up unused ones.
|
||||
// We cannot accurately infer package name from import path
|
||||
// (e.g., path "minio-go" but package name is "minio").
|
||||
srcImportedPackages.Add(item.RawImport)
|
||||
}
|
||||
return nil
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
toolchain go1.24.6
|
||||
|
||||
require github.com/gogf/gf/v2 v2.9.7
|
||||
require github.com/gogf/gf/v2 v2.9.8
|
||||
|
||||
require (
|
||||
go.opentelemetry.io/otel v1.38.0 // indirect
|
||||
|
||||
47
cmd/gf/internal/cmd/testdata/gendao/sharding/sharding_overlapping.sql
vendored
Normal file
47
cmd/gf/internal/cmd/testdata/gendao/sharding/sharding_overlapping.sql
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
-- Test case for issue #4603: overlapping sharding patterns
|
||||
-- https://github.com/gogf/gf/issues/4603
|
||||
--
|
||||
-- Patterns: "a_?", "a_b_?", "a_c_?"
|
||||
-- Expected: a_1/a_2 -> "a", a_b_1/a_b_2 -> "a_b", a_c_1/a_c_2 -> "a_c"
|
||||
|
||||
CREATE TABLE `a_1`
|
||||
(
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(45) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
CREATE TABLE `a_2`
|
||||
(
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(45) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
CREATE TABLE `a_b_1`
|
||||
(
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(45) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
CREATE TABLE `a_b_2`
|
||||
(
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(45) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
CREATE TABLE `a_c_1`
|
||||
(
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(45) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
CREATE TABLE `a_c_2`
|
||||
(
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(45) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
30
cmd/gf/internal/cmd/testdata/gendao/tables_pattern.sql
vendored
Normal file
30
cmd/gf/internal/cmd/testdata/gendao/tables_pattern.sql
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
-- Test case for issue #4629: tables pattern matching
|
||||
-- https://github.com/gogf/gf/issues/4629
|
||||
-- Standard SQL syntax compatible with MySQL and PostgreSQL
|
||||
--
|
||||
-- Tables: trade_order, trade_item, user_info, user_log, config
|
||||
|
||||
CREATE TABLE trade_order (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(45) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE trade_item (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(45) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE user_info (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(45) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE user_log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(45) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE config (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(45) NOT NULL
|
||||
);
|
||||
22
cmd/gf/internal/cmd/testdata/genpb/multiple_tags.proto
vendored
Normal file
22
cmd/gf/internal/cmd/testdata/genpb/multiple_tags.proto
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package genpb;
|
||||
|
||||
option go_package = "genpb/v1";
|
||||
|
||||
message UserReq {
|
||||
// v:required
|
||||
// v:#Id > 0
|
||||
int64 Id = 1;
|
||||
// User name for login
|
||||
string Name = 2;
|
||||
// v:required
|
||||
// v:email
|
||||
string Email = 3; // User email address
|
||||
}
|
||||
|
||||
message UserResp {
|
||||
int64 Id = 1;
|
||||
string Name = 2;
|
||||
string Email = 3;
|
||||
}
|
||||
21
cmd/gf/internal/cmd/testdata/genpb/nested_message.proto
vendored
Normal file
21
cmd/gf/internal/cmd/testdata/genpb/nested_message.proto
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package genpb;
|
||||
|
||||
option go_package = "genpb/v1";
|
||||
|
||||
message Order {
|
||||
// v:required
|
||||
int64 OrderId = 1;
|
||||
// Order details
|
||||
OrderDetail Detail = 2;
|
||||
}
|
||||
|
||||
message OrderDetail {
|
||||
// v:required
|
||||
string ProductName = 1;
|
||||
// v:min:1
|
||||
int32 Quantity = 2;
|
||||
// v:min:0.01
|
||||
double Price = 3;
|
||||
}
|
||||
34
cmd/gf/internal/cmd/testdata/issue/4242/logic/issue4242/issue4242.go
vendored
Normal file
34
cmd/gf/internal/cmd/testdata/issue/4242/logic/issue4242/issue4242.go
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
package issue4242
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/issue/4242/service"
|
||||
|
||||
"github.com/gogf/gf/contrib/drivers/mysql/v2"
|
||||
)
|
||||
|
||||
func init() {
|
||||
service.RegisterIssue4242(New())
|
||||
}
|
||||
|
||||
type sIssue4242 struct {
|
||||
}
|
||||
|
||||
func New() *sIssue4242 {
|
||||
return &sIssue4242{}
|
||||
}
|
||||
|
||||
// GetDriver tests versioned import path is preserved.
|
||||
func (s *sIssue4242) GetDriver(ctx context.Context) (d mysql.Driver, err error) {
|
||||
return mysql.Driver{}, nil
|
||||
}
|
||||
|
||||
// GetRequest tests another versioned import.
|
||||
func (s *sIssue4242) GetRequest(ctx context.Context) (*ghttp.Request, error) {
|
||||
g.Log().Info(ctx, "getting request")
|
||||
return nil, nil
|
||||
}
|
||||
37
cmd/gf/internal/cmd/testdata/issue/4242/logic/issue4242alias/issue4242alias.go
vendored
Normal file
37
cmd/gf/internal/cmd/testdata/issue/4242/logic/issue4242alias/issue4242alias.go
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
package issue4242alias
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
// Anonymous import (should be skipped)
|
||||
_ "github.com/gogf/gf/v2/os/gres"
|
||||
|
||||
// Versioned import without alias
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/issue/4242/service"
|
||||
|
||||
// Explicit alias import
|
||||
mysqlDriver "github.com/gogf/gf/contrib/drivers/mysql/v2"
|
||||
)
|
||||
|
||||
func init() {
|
||||
service.RegisterIssue4242Alias(New())
|
||||
}
|
||||
|
||||
type sIssue4242Alias struct {
|
||||
}
|
||||
|
||||
func New() *sIssue4242Alias {
|
||||
return &sIssue4242Alias{}
|
||||
}
|
||||
|
||||
// GetDriver tests explicit alias import.
|
||||
func (s *sIssue4242Alias) GetDriver(ctx context.Context) (d mysqlDriver.Driver, err error) {
|
||||
return mysqlDriver.Driver{}, nil
|
||||
}
|
||||
|
||||
// GetRequest tests versioned import.
|
||||
func (s *sIssue4242Alias) GetRequest(ctx context.Context) (*ghttp.Request, error) {
|
||||
return nil, nil
|
||||
}
|
||||
10
cmd/gf/internal/cmd/testdata/issue/4242/logic/logic.go
vendored
Normal file
10
cmd/gf/internal/cmd/testdata/issue/4242/logic/logic.go
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package logic
|
||||
|
||||
import (
|
||||
_ "github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/issue/4242/logic/issue4242"
|
||||
_ "github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/issue/4242/logic/issue4242alias"
|
||||
)
|
||||
37
cmd/gf/internal/cmd/testdata/issue/4242/service/issue_4242.go
vendored
Normal file
37
cmd/gf/internal/cmd/testdata/issue/4242/service/issue_4242.go
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
// ================================================================================
|
||||
// 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"
|
||||
|
||||
"github.com/gogf/gf/contrib/drivers/mysql/v2"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
type (
|
||||
IIssue4242 interface {
|
||||
// GetDriver tests versioned import path is preserved.
|
||||
GetDriver(ctx context.Context) (d mysql.Driver, err error)
|
||||
// GetRequest tests another versioned import.
|
||||
GetRequest(ctx context.Context) (*ghttp.Request, error)
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
localIssue4242 IIssue4242
|
||||
)
|
||||
|
||||
func Issue4242() IIssue4242 {
|
||||
if localIssue4242 == nil {
|
||||
panic("implement not found for interface IIssue4242, forgot register?")
|
||||
}
|
||||
return localIssue4242
|
||||
}
|
||||
|
||||
func RegisterIssue4242(i IIssue4242) {
|
||||
localIssue4242 = i
|
||||
}
|
||||
37
cmd/gf/internal/cmd/testdata/issue/4242/service/issue_4242_alias.go
vendored
Normal file
37
cmd/gf/internal/cmd/testdata/issue/4242/service/issue_4242_alias.go
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
// ================================================================================
|
||||
// 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"
|
||||
|
||||
mysqlDriver "github.com/gogf/gf/contrib/drivers/mysql/v2"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
type (
|
||||
IIssue4242Alias interface {
|
||||
// GetDriver tests explicit alias import.
|
||||
GetDriver(ctx context.Context) (d mysqlDriver.Driver, err error)
|
||||
// GetRequest tests versioned import.
|
||||
GetRequest(ctx context.Context) (*ghttp.Request, error)
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
localIssue4242Alias IIssue4242Alias
|
||||
)
|
||||
|
||||
func Issue4242Alias() IIssue4242Alias {
|
||||
if localIssue4242Alias == nil {
|
||||
panic("implement not found for interface IIssue4242Alias, forgot register?")
|
||||
}
|
||||
return localIssue4242Alias
|
||||
}
|
||||
|
||||
func RegisterIssue4242Alias(i IIssue4242Alias) {
|
||||
localIssue4242Alias = i
|
||||
}
|
||||
16
cmd/gf/internal/cmd/testdata/issue/4387/api/types.go
vendored
Normal file
16
cmd/gf/internal/cmd/testdata/issue/4387/api/types.go
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
// 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 api
|
||||
|
||||
// Status is a sample enum type for testing.
|
||||
type Status int
|
||||
|
||||
const (
|
||||
StatusPending Status = iota
|
||||
StatusActive
|
||||
StatusDone
|
||||
)
|
||||
3
cmd/gf/internal/cmd/testdata/issue/4387/go.mod
vendored
Normal file
3
cmd/gf/internal/cmd/testdata/issue/4387/go.mod
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
module github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/issue/4387
|
||||
|
||||
go 1.20
|
||||
@ -749,7 +749,9 @@ func (a *TArray[T]) String() string {
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
// DO NOT change this receiver to pointer type, as the TArray can be used as a var defined variable, like:
|
||||
// var a TArray[int]
|
||||
// Please refer to corresponding tests for more details.
|
||||
func (a TArray[T]) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
|
||||
@ -46,7 +46,7 @@ func NewSortedTArray[T comparable](comparator func(a, b T) int, safe ...bool) *S
|
||||
return NewSortedTArraySize(0, comparator, safe...)
|
||||
}
|
||||
|
||||
// NewSortedTArraySize create and returns an sorted array with given size and cap.
|
||||
// NewSortedTArraySize create and returns a sorted array with given size and cap.
|
||||
// The parameter `safe` is used to specify whether using array in concurrent-safety,
|
||||
// which is false in default.
|
||||
func NewSortedTArraySize[T comparable](cap int, comparator func(a, b T) int, safe ...bool) *SortedTArray[T] {
|
||||
@ -718,7 +718,9 @@ func (a *SortedTArray[T]) String() string {
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
// DO NOT change this receiver to pointer type, as the TArray can be used as a var defined variable, like:
|
||||
// var a SortedTArray[int]
|
||||
// Please refer to corresponding tests for more details.
|
||||
func (a SortedTArray[T]) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
|
||||
@ -22,8 +22,11 @@ type NilChecker[V any] func(V) bool
|
||||
|
||||
// KVMap wraps map type `map[K]V` and provides more map features.
|
||||
type KVMap[K comparable, V any] struct {
|
||||
mu rwmutex.RWMutex
|
||||
data map[K]V
|
||||
mu rwmutex.RWMutex
|
||||
data map[K]V
|
||||
|
||||
// nilChecker is the custom nil checker function.
|
||||
// It uses empty.IsNil if it's nil.
|
||||
nilChecker NilChecker[V]
|
||||
}
|
||||
|
||||
@ -58,15 +61,15 @@ func NewKVMapFrom[K comparable, V any](data map[K]V, safe ...bool) *KVMap[K, V]
|
||||
// The parameter `safe` is used to specify whether to use the map in concurrent-safety mode, which is false by default.
|
||||
func NewKVMapWithCheckerFrom[K comparable, V any](data map[K]V, checker NilChecker[V], safe ...bool) *KVMap[K, V] {
|
||||
m := NewKVMapFrom[K, V](data, safe...)
|
||||
m.RegisterNilChecker(checker)
|
||||
m.SetNilChecker(checker)
|
||||
return m
|
||||
}
|
||||
|
||||
// RegisterNilChecker registers a custom nil checker function for the map values.
|
||||
// SetNilChecker registers a custom nil checker function for the map values.
|
||||
// This function is used to determine if a value should be considered as nil.
|
||||
// The nil checker function takes a value of type V and returns a boolean indicating
|
||||
// whether the value should be treated as nil.
|
||||
func (m *KVMap[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
func (m *KVMap[K, V]) SetNilChecker(nilChecker NilChecker[V]) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.nilChecker = nilChecker
|
||||
@ -74,12 +77,12 @@ func (m *KVMap[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
|
||||
// isNil checks whether the given value is nil.
|
||||
// It first checks if a custom nil checker function is registered and uses it if available,
|
||||
// otherwise it performs a standard nil check using any(v) == nil.
|
||||
// otherwise it falls back to the default empty.IsNil function.
|
||||
func (m *KVMap[K, V]) isNil(v V) bool {
|
||||
if m.nilChecker != nil {
|
||||
return m.nilChecker(v)
|
||||
}
|
||||
return any(v) == nil
|
||||
return empty.IsNil(v)
|
||||
}
|
||||
|
||||
// Iterator iterates the hash map readonly with custom callback function `f`.
|
||||
@ -242,11 +245,12 @@ func (m *KVMap[K, V]) Pops(size int) map[K]V {
|
||||
return newMap
|
||||
}
|
||||
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given `key`,
|
||||
// or else just return the existing value.
|
||||
// doSetWithLockCheck sets value with given `value` if it does not exist,
|
||||
// and then returns this value and whether it exists.
|
||||
//
|
||||
// It returns value with given `key`.
|
||||
// It is a helper function for GetOrSet* functions.
|
||||
//
|
||||
// Note that, it does not add the value to the map if the given `value` is nil.
|
||||
func (m *KVMap[K, V]) doSetWithLockCheck(key K, value V) (val V, ok bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -274,6 +278,8 @@ func (m *KVMap[K, V]) GetOrSet(key K, value V) V {
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with returned value of callback function `f` if it does not exist
|
||||
// and then returns this value.
|
||||
//
|
||||
// Note that, it does not add the value to the map if the returned value of `f` is nil.
|
||||
func (m *KVMap[K, V]) GetOrSetFunc(key K, f func() V) V {
|
||||
v, _ := m.doSetWithLockCheck(key, f())
|
||||
return v
|
||||
@ -285,6 +291,8 @@ func (m *KVMap[K, V]) GetOrSetFunc(key K, f func() V) V {
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
|
||||
// with mutex.Lock of the hash map.
|
||||
//
|
||||
// Note that, it does not add the value to the map if the returned value of `f` is nil.
|
||||
func (m *KVMap[K, V]) GetOrSetFuncLock(key K, f func() V) V {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -524,6 +532,9 @@ func (m *KVMap[K, V]) String() string {
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// DO NOT change this receiver to pointer type, as the KVMap can be used as a var defined variable, like:
|
||||
// var m gmap.KVMap[int, string]
|
||||
// Please refer to corresponding tests for more details.
|
||||
func (m KVMap[K, V]) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(gconv.Map(m.Map()))
|
||||
}
|
||||
|
||||
@ -56,7 +56,7 @@ func NewListKVMap[K comparable, V any](safe ...bool) *ListKVMap[K, V] {
|
||||
// which is false by default.
|
||||
func NewListKVMapWithChecker[K comparable, V any](checker NilChecker[V], safe ...bool) *ListKVMap[K, V] {
|
||||
m := NewListKVMap[K, V](safe...)
|
||||
m.RegisterNilChecker(checker)
|
||||
m.SetNilChecker(checker)
|
||||
return m
|
||||
}
|
||||
|
||||
@ -81,11 +81,11 @@ func NewListKVMapWithCheckerFrom[K comparable, V any](data map[K]V, nilChecker N
|
||||
return m
|
||||
}
|
||||
|
||||
// RegisterNilChecker registers a custom nil checker function for the map values.
|
||||
// SetNilChecker registers a custom nil checker function for the map values.
|
||||
// This function is used to determine if a value should be considered as nil.
|
||||
// The nil checker function takes a value of type V and returns a boolean indicating
|
||||
// whether the value should be treated as nil.
|
||||
func (m *ListKVMap[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
func (m *ListKVMap[K, V]) SetNilChecker(nilChecker NilChecker[V]) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.nilChecker = nilChecker
|
||||
@ -93,12 +93,12 @@ func (m *ListKVMap[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
|
||||
// isNil checks whether the given value is nil.
|
||||
// It first checks if a custom nil checker function is registered and uses it if available,
|
||||
// otherwise it performs a standard nil check using any(v) == nil.
|
||||
// otherwise it falls back to the default empty.IsNil function.
|
||||
func (m *ListKVMap[K, V]) isNil(v V) bool {
|
||||
if m.nilChecker != nil {
|
||||
return m.nilChecker(v)
|
||||
}
|
||||
return any(v) == nil
|
||||
return empty.IsNil(v)
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
@ -402,6 +402,8 @@ func (m *ListKVMap[K, V]) GetVarOrSetFuncLock(key K, f func() V) *gvar.Var {
|
||||
|
||||
// SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true.
|
||||
// It returns false if `key` exists, and `value` would be ignored.
|
||||
//
|
||||
// Note that it does not add the value to the map if `value` is nil.
|
||||
func (m *ListKVMap[K, V]) SetIfNotExist(key K, value V) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -421,6 +423,8 @@ func (m *ListKVMap[K, V]) SetIfNotExist(key K, value V) bool {
|
||||
|
||||
// SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true.
|
||||
// It returns false if `key` exists, and `value` would be ignored.
|
||||
//
|
||||
// Note that, it does not add the value to the map if the returned value of `f` is nil.
|
||||
func (m *ListKVMap[K, V]) SetIfNotExistFunc(key K, f func() V) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -444,6 +448,8 @@ func (m *ListKVMap[K, V]) SetIfNotExistFunc(key K, f func() V) bool {
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function `f` with mutex.Lock of the map.
|
||||
//
|
||||
// Note that, it does not add the value to the map if the returned value of `f` is nil.
|
||||
func (m *ListKVMap[K, V]) SetIfNotExistFuncLock(key K, f func() V) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -609,6 +615,9 @@ func (m *ListKVMap[K, V]) String() string {
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// DO NOT change this receiver to pointer type, as the ListKVMap can be used as a var defined variable, like:
|
||||
// var m gmap.ListKVMap[string]string
|
||||
// Please refer to corresponding tests for more details.
|
||||
func (m ListKVMap[K, V]) MarshalJSON() (jsonBytes []byte, err error) {
|
||||
if m.data == nil {
|
||||
return []byte("{}"), nil
|
||||
|
||||
@ -774,6 +774,13 @@ func Test_KVMap_MarshalJSON(t *testing.T) {
|
||||
t.Assert(data["a"], 1)
|
||||
t.Assert(data["b"], 2)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var m gmap.KVMap[int, int]
|
||||
m.Set(1, 10)
|
||||
b, err := json.Marshal(m)
|
||||
t.AssertNil(err)
|
||||
t.Assert(string(b), `{"1":10}`)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_KVMap_UnmarshalJSON(t *testing.T) {
|
||||
@ -1647,9 +1654,10 @@ func Test_KVMap_TypedNil(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
t.Assert(m1.Size(), 10)
|
||||
t.Assert(m1.Size(), 5)
|
||||
|
||||
m2 := gmap.NewKVMap[int, *Student](true)
|
||||
m2.RegisterNilChecker(func(student *Student) bool {
|
||||
m2.SetNilChecker(func(student *Student) bool {
|
||||
return student == nil
|
||||
})
|
||||
for i := 0; i < 10; i++ {
|
||||
@ -1679,7 +1687,8 @@ func Test_NewKVMapWithChecker_TypedNil(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
t.Assert(m1.Size(), 10)
|
||||
t.Assert(m1.Size(), 5)
|
||||
|
||||
m2 := gmap.NewKVMapWithChecker[int, *Student](func(student *Student) bool {
|
||||
return student == nil
|
||||
}, true)
|
||||
|
||||
@ -183,77 +183,6 @@ func Test_ListKVMap_SetIfNotExistFuncLock_MultipleKeys(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// Test_ListKVMap_GetOrSetFuncLock_NilValue tests that nil values are handled correctly.
|
||||
func Test_ListKVMap_GetOrSetFuncLock_NilValue(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
m := gmap.NewListKVMap[string, *int](true)
|
||||
key := "nilKey"
|
||||
callCount := int32(0)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
goroutines := 50
|
||||
wg.Add(goroutines)
|
||||
|
||||
for i := 0; i < goroutines; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
m.GetOrSetFuncLock(key, func() *int {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Callback should be called once
|
||||
t.Assert(atomic.LoadInt32(&callCount), 1)
|
||||
// Typed nil pointer (*int)(nil) is stored because any(value) != nil for typed nil
|
||||
// This is a Go language feature: typed nil is not the same as interface nil
|
||||
t.Assert(m.Contains(key), true)
|
||||
t.Assert(m.Get(key), (*int)(nil))
|
||||
t.Assert(m.Size(), 1)
|
||||
})
|
||||
}
|
||||
|
||||
// Test_ListKVMap_SetIfNotExistFuncLock_NilValue tests that nil values are handled correctly.
|
||||
func Test_ListKVMap_SetIfNotExistFuncLock_NilValue(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
m := gmap.NewListKVMap[string, *string](true)
|
||||
key := "nilKey"
|
||||
callCount := int32(0)
|
||||
successCount := int32(0)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
goroutines := 50
|
||||
wg.Add(goroutines)
|
||||
|
||||
for i := 0; i < goroutines; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
success := m.SetIfNotExistFuncLock(key, func() *string {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
return nil
|
||||
})
|
||||
if success {
|
||||
atomic.AddInt32(&successCount, 1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Callback should be called once
|
||||
t.Assert(atomic.LoadInt32(&callCount), 1)
|
||||
// Should report success once
|
||||
t.Assert(atomic.LoadInt32(&successCount), 1)
|
||||
// Typed nil pointer (*string)(nil) is stored because any(value) != nil for typed nil
|
||||
t.Assert(m.Contains(key), true)
|
||||
t.Assert(m.Get(key), (*string)(nil))
|
||||
t.Assert(m.Size(), 1)
|
||||
})
|
||||
}
|
||||
|
||||
// Test_ListKVMap_GetOrSetFuncLock_ExistingKey tests behavior when key already exists.
|
||||
func Test_ListKVMap_GetOrSetFuncLock_ExistingKey(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
|
||||
@ -1159,6 +1159,13 @@ func Test_ListKVMap_MarshalJSON_Error(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
t.Assert(string(b), `{"a":"1"}`)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var m gmap.ListKVMap[int, int]
|
||||
m.Set(1, 10)
|
||||
b, err := json.Marshal(m)
|
||||
t.AssertNil(err)
|
||||
t.Assert(string(b), `{"1":10}`)
|
||||
})
|
||||
}
|
||||
|
||||
// Test empty map operations
|
||||
@ -1358,9 +1365,10 @@ func Test_ListKVMap_TypedNil(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
t.Assert(m1.Size(), 10)
|
||||
t.Assert(m1.Size(), 5)
|
||||
|
||||
m2 := gmap.NewListKVMap[int, *Student](true)
|
||||
m2.RegisterNilChecker(func(student *Student) bool {
|
||||
m2.SetNilChecker(func(student *Student) bool {
|
||||
return student == nil
|
||||
})
|
||||
for i := 0; i < 10; i++ {
|
||||
@ -1390,7 +1398,8 @@ func Test_NewListKVMapWithChecker_TypedNil(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
t.Assert(m1.Size(), 10)
|
||||
t.Assert(m1.Size(), 5)
|
||||
|
||||
m2 := gmap.NewListKVMapWithChecker[int, *Student](func(student *Student) bool {
|
||||
return student == nil
|
||||
}, true)
|
||||
|
||||
@ -9,6 +9,7 @@ package gset
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
@ -39,7 +40,7 @@ func NewTSet[T comparable](safe ...bool) *TSet[T] {
|
||||
// The parameter `safe` is used to specify whether using set in concurrent-safety mode.
|
||||
func NewTSetWithChecker[T comparable](checker NilChecker[T], safe ...bool) *TSet[T] {
|
||||
s := NewTSet[T](safe...)
|
||||
s.RegisterNilChecker(checker)
|
||||
s.SetNilChecker(checker)
|
||||
return s
|
||||
}
|
||||
|
||||
@ -66,11 +67,11 @@ func NewTSetWithCheckerFrom[T comparable](items []T, checker NilChecker[T], safe
|
||||
return set
|
||||
}
|
||||
|
||||
// RegisterNilChecker registers a custom nil checker function for the set elements.
|
||||
// SetNilChecker registers a custom nil checker function for the set elements.
|
||||
// This function is used to determine if an element should be considered as nil.
|
||||
// The nil checker function takes an element of type T and returns a boolean indicating
|
||||
// whether the element should be treated as nil.
|
||||
func (set *TSet[T]) RegisterNilChecker(nilChecker NilChecker[T]) {
|
||||
func (set *TSet[T]) SetNilChecker(nilChecker NilChecker[T]) {
|
||||
set.mu.Lock()
|
||||
defer set.mu.Unlock()
|
||||
set.nilChecker = nilChecker
|
||||
@ -78,12 +79,12 @@ func (set *TSet[T]) RegisterNilChecker(nilChecker NilChecker[T]) {
|
||||
|
||||
// isNil checks whether the given value is nil.
|
||||
// It first checks if a custom nil checker function is registered and uses it if available,
|
||||
// otherwise it performs a standard nil check using any(v) == nil.
|
||||
// otherwise it falls back to the default empty.IsNil function.
|
||||
func (set *TSet[T]) isNil(v T) bool {
|
||||
if set.nilChecker != nil {
|
||||
return set.nilChecker(v)
|
||||
}
|
||||
return any(v) == nil
|
||||
return empty.IsNil(v)
|
||||
}
|
||||
|
||||
// Iterator iterates the set readonly with given callback function `f`,
|
||||
@ -109,7 +110,7 @@ func (set *TSet[T]) Add(items ...T) {
|
||||
}
|
||||
|
||||
// AddIfNotExist checks whether item exists in the set,
|
||||
// it adds the item to set and returns true if it does not exists in the set,
|
||||
// it adds the item to set and returns true if it does not exist in the set,
|
||||
// or else it does nothing and returns false.
|
||||
//
|
||||
// Note that, if `item` is nil, it does nothing and returns false.
|
||||
|
||||
@ -601,10 +601,10 @@ func Test_TSet_TypedNil(t *testing.T) {
|
||||
set := gset.NewTSet[*Student](true)
|
||||
var s *Student = nil
|
||||
exist := set.AddIfNotExist(s)
|
||||
t.Assert(exist, true)
|
||||
t.Assert(exist, false)
|
||||
|
||||
set2 := gset.NewTSet[*Student](true)
|
||||
set2.RegisterNilChecker(func(student *Student) bool {
|
||||
set2.SetNilChecker(func(student *Student) bool {
|
||||
return student == nil
|
||||
})
|
||||
exist2 := set2.AddIfNotExist(s)
|
||||
@ -621,7 +621,7 @@ func Test_NewTSetWithChecker_TypedNil(t *testing.T) {
|
||||
set := gset.NewTSet[*Student](true)
|
||||
var s *Student = nil
|
||||
exist := set.AddIfNotExist(s)
|
||||
t.Assert(exist, true)
|
||||
t.Assert(exist, false)
|
||||
|
||||
set2 := gset.NewTSetWithChecker[*Student](func(student *Student) bool {
|
||||
return student == nil
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"github.com/emirpasic/gods/v2/trees/avltree"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gvar"
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
@ -52,7 +53,7 @@ func NewAVLKVTree[K comparable, V any](comparator func(v1, v2 K) int, safe ...bo
|
||||
// The parameter `checker` is used to specify whether the given value is nil.
|
||||
func NewAVLKVTreeWithChecker[K comparable, V any](comparator func(v1, v2 K) int, checker NilChecker[V], safe ...bool) *AVLKVTree[K, V] {
|
||||
t := NewAVLKVTree[K, V](comparator, safe...)
|
||||
t.RegisterNilChecker(checker)
|
||||
t.SetNilChecker(checker)
|
||||
return t
|
||||
}
|
||||
|
||||
@ -78,11 +79,11 @@ func NewAVLKVTreeWithCheckerFrom[K comparable, V any](comparator func(v1, v2 K)
|
||||
return tree
|
||||
}
|
||||
|
||||
// RegisterNilChecker registers a custom nil checker function for the map values.
|
||||
// SetNilChecker registers a custom nil checker function for the map values.
|
||||
// This function is used to determine if a value should be considered as nil.
|
||||
// The nil checker function takes a value of type V and returns a boolean indicating
|
||||
// whether the value should be treated as nil.
|
||||
func (tree *AVLKVTree[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
func (tree *AVLKVTree[K, V]) SetNilChecker(nilChecker NilChecker[V]) {
|
||||
tree.mu.Lock()
|
||||
defer tree.mu.Unlock()
|
||||
tree.nilChecker = nilChecker
|
||||
@ -90,12 +91,12 @@ func (tree *AVLKVTree[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
|
||||
// isNil checks whether the given value is nil.
|
||||
// It first checks if a custom nil checker function is registered and uses it if available,
|
||||
// otherwise it performs a standard nil check using any(v) == nil.
|
||||
func (tree *AVLKVTree[K, V]) isNil(value V) bool {
|
||||
// otherwise it falls back to the default empty.IsNil function.
|
||||
func (tree *AVLKVTree[K, V]) isNil(v V) bool {
|
||||
if tree.nilChecker != nil {
|
||||
return tree.nilChecker(value)
|
||||
return tree.nilChecker(v)
|
||||
}
|
||||
return any(value) == nil
|
||||
return empty.IsNil(v)
|
||||
}
|
||||
|
||||
// Clone clones and returns a new tree from current tree.
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"github.com/emirpasic/gods/v2/trees/btree"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gvar"
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
@ -51,7 +52,7 @@ func NewBKVTree[K comparable, V any](m int, comparator func(v1, v2 K) int, safe
|
||||
// The parameter `checker` is used to specify whether the given value is nil.
|
||||
func NewBKVTreeWithChecker[K comparable, V any](m int, comparator func(v1, v2 K) int, checker NilChecker[V], safe ...bool) *BKVTree[K, V] {
|
||||
t := NewBKVTree[K, V](m, comparator, safe...)
|
||||
t.RegisterNilChecker(checker)
|
||||
t.SetNilChecker(checker)
|
||||
return t
|
||||
}
|
||||
|
||||
@ -77,11 +78,11 @@ func NewBKVTreeWithCheckerFrom[K comparable, V any](m int, comparator func(v1, v
|
||||
return tree
|
||||
}
|
||||
|
||||
// RegisterNilChecker registers a custom nil checker function for the map values.
|
||||
// SetNilChecker registers a custom nil checker function for the map values.
|
||||
// This function is used to determine if a value should be considered as nil.
|
||||
// The nil checker function takes a value of type V and returns a boolean indicating
|
||||
// whether the value should be treated as nil.
|
||||
func (tree *BKVTree[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
func (tree *BKVTree[K, V]) SetNilChecker(nilChecker NilChecker[V]) {
|
||||
tree.mu.Lock()
|
||||
defer tree.mu.Unlock()
|
||||
tree.nilChecker = nilChecker
|
||||
@ -89,12 +90,12 @@ func (tree *BKVTree[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
|
||||
// isNil checks whether the given value is nil.
|
||||
// It first checks if a custom nil checker function is registered and uses it if available,
|
||||
// otherwise it performs a standard nil check using any(v) == nil.
|
||||
func (tree *BKVTree[K, V]) isNil(value V) bool {
|
||||
// otherwise it falls back to the default empty.IsNil function.
|
||||
func (tree *BKVTree[K, V]) isNil(v V) bool {
|
||||
if tree.nilChecker != nil {
|
||||
return tree.nilChecker(value)
|
||||
return tree.nilChecker(v)
|
||||
}
|
||||
return any(value) == nil
|
||||
return empty.IsNil(v)
|
||||
}
|
||||
|
||||
// Clone clones and returns a new tree from current tree.
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"github.com/emirpasic/gods/v2/trees/redblacktree"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gvar"
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
@ -47,7 +48,7 @@ func NewRedBlackKVTree[K comparable, V any](comparator func(v1, v2 K) int, safe
|
||||
// The parameter `checker` is used to specify whether the given value is nil.
|
||||
func NewRedBlackKVTreeWithChecker[K comparable, V any](comparator func(v1, v2 K) int, checker NilChecker[V], safe ...bool) *RedBlackKVTree[K, V] {
|
||||
t := NewRedBlackKVTree[K, V](comparator, safe...)
|
||||
t.RegisterNilChecker(checker)
|
||||
t.SetNilChecker(checker)
|
||||
return t
|
||||
}
|
||||
|
||||
@ -96,11 +97,11 @@ func RedBlackKVTreeInitFrom[K comparable, V any](tree *RedBlackKVTree[K, V], com
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterNilChecker registers a custom nil checker function for the map values.
|
||||
// SetNilChecker registers a custom nil checker function for the map values.
|
||||
// This function is used to determine if a value should be considered as nil.
|
||||
// The nil checker function takes a value of type V and returns a boolean indicating
|
||||
// whether the value should be treated as nil.
|
||||
func (tree *RedBlackKVTree[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
func (tree *RedBlackKVTree[K, V]) SetNilChecker(nilChecker NilChecker[V]) {
|
||||
tree.mu.Lock()
|
||||
defer tree.mu.Unlock()
|
||||
tree.nilChecker = nilChecker
|
||||
@ -108,12 +109,12 @@ func (tree *RedBlackKVTree[K, V]) RegisterNilChecker(nilChecker NilChecker[V]) {
|
||||
|
||||
// isNil checks whether the given value is nil.
|
||||
// It first checks if a custom nil checker function is registered and uses it if available,
|
||||
// otherwise it performs a standard nil check using any(v) == nil.
|
||||
func (tree *RedBlackKVTree[K, V]) isNil(value V) bool {
|
||||
// otherwise it falls back to the default empty.IsNil function.
|
||||
func (tree *RedBlackKVTree[K, V]) isNil(v V) bool {
|
||||
if tree.nilChecker != nil {
|
||||
return tree.nilChecker(value)
|
||||
return tree.nilChecker(v)
|
||||
}
|
||||
return any(value) == nil
|
||||
return empty.IsNil(v)
|
||||
}
|
||||
|
||||
// SetComparator sets/changes the comparator for sorting.
|
||||
|
||||
@ -29,9 +29,10 @@ func Test_KVAVLTree_TypedNil(t *testing.T) {
|
||||
avlTree.Set(i, s)
|
||||
}
|
||||
}
|
||||
t.Assert(avlTree.Size(), 10)
|
||||
t.Assert(avlTree.Size(), 5)
|
||||
|
||||
avlTree2 := gtree.NewAVLKVTree[int, *Student](gutil.ComparatorTStr[int], true)
|
||||
avlTree2.RegisterNilChecker(func(student *Student) bool {
|
||||
avlTree2.SetNilChecker(func(student *Student) bool {
|
||||
return student == nil
|
||||
})
|
||||
for i := 0; i < 10; i++ {
|
||||
@ -62,9 +63,10 @@ func Test_KVBTree_TypedNil(t *testing.T) {
|
||||
btree.Set(i, s)
|
||||
}
|
||||
}
|
||||
t.Assert(btree.Size(), 10)
|
||||
t.Assert(btree.Size(), 5)
|
||||
|
||||
btree2 := gtree.NewBKVTree[int, *Student](100, gutil.ComparatorTStr[int], true)
|
||||
btree2.RegisterNilChecker(func(student *Student) bool {
|
||||
btree2.SetNilChecker(func(student *Student) bool {
|
||||
return student == nil
|
||||
})
|
||||
for i := 0; i < 10; i++ {
|
||||
@ -95,10 +97,10 @@ func Test_KVRedBlackTree_TypedNil(t *testing.T) {
|
||||
redBlackTree.Set(i, s)
|
||||
}
|
||||
}
|
||||
t.Assert(redBlackTree.Size(), 10)
|
||||
redBlackTree2 := gtree.NewRedBlackKVTree[int, *Student](gutil.ComparatorTStr[int], true)
|
||||
t.Assert(redBlackTree.Size(), 5)
|
||||
|
||||
redBlackTree2.RegisterNilChecker(func(student *Student) bool {
|
||||
redBlackTree2 := gtree.NewRedBlackKVTree[int, *Student](gutil.ComparatorTStr[int], true)
|
||||
redBlackTree2.SetNilChecker(func(student *Student) bool {
|
||||
return student == nil
|
||||
})
|
||||
for i := 0; i < 10; i++ {
|
||||
@ -128,7 +130,8 @@ func Test_NewKVAVLTreeWithChecker_TypedNil(t *testing.T) {
|
||||
avlTree.Set(i, s)
|
||||
}
|
||||
}
|
||||
t.Assert(avlTree.Size(), 10)
|
||||
t.Assert(avlTree.Size(), 5)
|
||||
|
||||
avlTree2 := gtree.NewAVLKVTreeWithChecker[int, *Student](gutil.ComparatorTStr[int], func(student *Student) bool {
|
||||
return student == nil
|
||||
}, true)
|
||||
@ -160,7 +163,8 @@ func Test_NewKVBTreeWithChecker_TypedNil(t *testing.T) {
|
||||
btree.Set(i, s)
|
||||
}
|
||||
}
|
||||
t.Assert(btree.Size(), 10)
|
||||
t.Assert(btree.Size(), 5)
|
||||
|
||||
btree2 := gtree.NewBKVTreeWithChecker[int, *Student](100, gutil.ComparatorTStr[int], func(student *Student) bool {
|
||||
return student == nil
|
||||
}, true)
|
||||
@ -192,7 +196,8 @@ func Test_NewRedBlackKVTreeWithChecker_TypedNil(t *testing.T) {
|
||||
redBlackTree.Set(i, s)
|
||||
}
|
||||
}
|
||||
t.Assert(redBlackTree.Size(), 10)
|
||||
t.Assert(redBlackTree.Size(), 5)
|
||||
|
||||
redBlackTree2 := gtree.NewRedBlackKVTreeWithChecker[int, *Student](gutil.ComparatorTStr[int], func(student *Student) bool {
|
||||
return student == nil
|
||||
}, true)
|
||||
|
||||
@ -179,7 +179,7 @@ func (c *Client) updateLocalValue(ctx context.Context) (err error) {
|
||||
}
|
||||
|
||||
// AddWatcher adds a watcher for the specified configuration file.
|
||||
func (c *Client) AddWatcher(name string, f func(ctx context.Context)) {
|
||||
func (c *Client) AddWatcher(name string, f gcfg.WatcherFunc) {
|
||||
c.watchers.Add(name, f)
|
||||
}
|
||||
|
||||
@ -193,6 +193,11 @@ func (c *Client) GetWatcherNames() []string {
|
||||
return c.watchers.GetNames()
|
||||
}
|
||||
|
||||
// IsWatching checks whether the watcher with the specified name is registered.
|
||||
func (c *Client) IsWatching(name string) bool {
|
||||
return c.watchers.IsWatching(name)
|
||||
}
|
||||
|
||||
// notifyWatchers notifies all watchers.
|
||||
func (c *Client) notifyWatchers(ctx context.Context) {
|
||||
c.watchers.Notify(ctx)
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/apolloconfig/agollo/v4 v4.3.1
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -207,7 +207,7 @@ func (c *Client) startAsynchronousWatch(plan *watch.Plan) {
|
||||
}
|
||||
|
||||
// AddWatcher adds a watcher for the specified configuration file.
|
||||
func (c *Client) AddWatcher(name string, f func(ctx context.Context)) {
|
||||
func (c *Client) AddWatcher(name string, f gcfg.WatcherFunc) {
|
||||
c.watchers.Add(name, f)
|
||||
}
|
||||
|
||||
@ -221,6 +221,11 @@ func (c *Client) GetWatcherNames() []string {
|
||||
return c.watchers.GetNames()
|
||||
}
|
||||
|
||||
// IsWatching checks whether the watcher with the specified name is registered.
|
||||
func (c *Client) IsWatching(name string) bool {
|
||||
return c.watchers.IsWatching(name)
|
||||
}
|
||||
|
||||
// notifyWatchers notifies all watchers.
|
||||
func (c *Client) notifyWatchers(ctx context.Context) {
|
||||
c.watchers.Notify(ctx)
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/consul/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/hashicorp/consul/api v1.24.0
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2
|
||||
)
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
k8s.io/api v0.33.4
|
||||
k8s.io/apimachinery v0.33.4
|
||||
k8s.io/client-go v0.33.4
|
||||
|
||||
@ -199,7 +199,7 @@ func (c *Client) startAsynchronousWatch(ctx context.Context, namespace string, w
|
||||
}
|
||||
|
||||
// AddWatcher adds a watcher for the specified configuration file.
|
||||
func (c *Client) AddWatcher(name string, f func(ctx context.Context)) {
|
||||
func (c *Client) AddWatcher(name string, f gcfg.WatcherFunc) {
|
||||
c.watchers.Add(name, f)
|
||||
}
|
||||
|
||||
@ -213,6 +213,11 @@ func (c *Client) GetWatcherNames() []string {
|
||||
return c.watchers.GetNames()
|
||||
}
|
||||
|
||||
// IsWatching checks whether the watcher with the specified name is registered.
|
||||
func (c *Client) IsWatching(name string) bool {
|
||||
return c.watchers.IsWatching(name)
|
||||
}
|
||||
|
||||
// notifyWatchers notifies all watchers.
|
||||
func (c *Client) notifyWatchers(ctx context.Context) {
|
||||
c.watchers.Notify(ctx)
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.3
|
||||
)
|
||||
|
||||
|
||||
@ -152,7 +152,7 @@ func (c *Client) addWatcher() error {
|
||||
}
|
||||
|
||||
// AddWatcher adds a watcher for the specified configuration file.
|
||||
func (c *Client) AddWatcher(name string, f func(ctx context.Context)) {
|
||||
func (c *Client) AddWatcher(name string, f gcfg.WatcherFunc) {
|
||||
c.watchers.Add(name, f)
|
||||
}
|
||||
|
||||
@ -166,6 +166,11 @@ func (c *Client) GetWatcherNames() []string {
|
||||
return c.watchers.GetNames()
|
||||
}
|
||||
|
||||
// IsWatching checks whether the watcher with the specified name is registered.
|
||||
func (c *Client) IsWatching(name string) bool {
|
||||
return c.watchers.IsWatching(name)
|
||||
}
|
||||
|
||||
// notifyWatchers notifies all watchers.
|
||||
func (c *Client) notifyWatchers(ctx context.Context) {
|
||||
c.watchers.Notify(ctx)
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/polaris/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/polarismesh/polaris-go v1.6.1
|
||||
)
|
||||
|
||||
|
||||
@ -187,7 +187,7 @@ func (c *Client) startAsynchronousWatch(ctx context.Context, changeChan <-chan m
|
||||
}
|
||||
|
||||
// AddWatcher adds a watcher for the specified configuration file.
|
||||
func (c *Client) AddWatcher(name string, f func(ctx context.Context)) {
|
||||
func (c *Client) AddWatcher(name string, f gcfg.WatcherFunc) {
|
||||
c.watchers.Add(name, f)
|
||||
}
|
||||
|
||||
@ -201,6 +201,11 @@ func (c *Client) GetWatcherNames() []string {
|
||||
return c.watchers.GetNames()
|
||||
}
|
||||
|
||||
// IsWatching checks whether the watcher with the specified name is registered.
|
||||
func (c *Client) IsWatching(name string) bool {
|
||||
return c.watchers.IsWatching(name)
|
||||
}
|
||||
|
||||
// notifyWatchers notifies all watchers.
|
||||
func (c *Client) notifyWatchers(ctx context.Context) {
|
||||
c.watchers.Notify(ctx)
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.0.15
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/shopspring/decimal v1.3.1
|
||||
)
|
||||
|
||||
@ -108,7 +108,7 @@ func (d *Driver) doMergeInsert(
|
||||
one = list[0]
|
||||
oneLen = len(one)
|
||||
charL, charR = d.GetChars()
|
||||
conflictKeySet = gset.New(false)
|
||||
conflictKeySet = gset.NewStrSet(false)
|
||||
|
||||
// queryHolders: Handle data with Holder that need to be merged
|
||||
// queryValues: Handle data that need to be merged
|
||||
|
||||
@ -6,7 +6,7 @@ replace github.com/gogf/gf/v2 => ../../../
|
||||
|
||||
require (
|
||||
gitee.com/chunanyong/dm v1.8.12
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -307,7 +307,7 @@ func (d *Driver) doMergeInsert(
|
||||
one = list[0]
|
||||
oneLen = len(one)
|
||||
charL, charR = d.GetChars()
|
||||
conflictKeySet = gset.New(false)
|
||||
conflictKeySet = gset.NewStrSet(false)
|
||||
|
||||
// queryHolders: Handle data with Holder that need to be merged
|
||||
// queryValues: Handle data that need to be merged
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
require (
|
||||
gitee.com/opengauss/openGauss-connector-go-pq v1.0.7
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/google/uuid v1.6.0
|
||||
)
|
||||
|
||||
|
||||
@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/drivers/mariadb/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.10.0
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/mssql/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/microsoft/go-mssqldb v1.7.1
|
||||
)
|
||||
|
||||
|
||||
@ -102,7 +102,7 @@ func (d *Driver) doMergeInsert(
|
||||
one = list[0]
|
||||
oneLen = len(one)
|
||||
charL, charR = d.GetChars()
|
||||
conflictKeySet = gset.New(false)
|
||||
conflictKeySet = gset.NewStrSet(false)
|
||||
|
||||
// queryHolders: Handle data with Holder that need to be merged
|
||||
// queryValues: Handle data that need to be merged
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/go-sql-driver/mysql v1.7.1
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/drivers/oceanbase/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.10.0
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/oracle/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/sijms/go-ora/v2 v2.7.10
|
||||
)
|
||||
|
||||
|
||||
@ -181,7 +181,7 @@ func (d *Driver) doMergeInsert(
|
||||
one = list[0]
|
||||
oneLen = len(one)
|
||||
charL, charR = d.GetChars()
|
||||
conflictKeySet = gset.New(false)
|
||||
conflictKeySet = gset.NewStrSet(false)
|
||||
|
||||
// queryHolders: Handle data with Holder that need to be upsert
|
||||
// queryValues: Handle data that need to be upsert
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/pgsql/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/lib/pq v1.10.9
|
||||
)
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/glebarez/go-sqlite v1.21.2
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/sqlitecgo/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/mattn/go-sqlite3 v1.14.17
|
||||
)
|
||||
|
||||
|
||||
@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/drivers/tidb/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.10.0
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/metric/otelmetric/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
go.opentelemetry.io/contrib/instrumentation/runtime v0.63.0
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/nosql/redis/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/redis/go-redis/v9 v9.12.1
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
go.opentelemetry.io/otel/trace v1.38.0
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/consul/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/hashicorp/consul/api v1.26.1
|
||||
)
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/etcd/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
go.etcd.io/etcd/client/v3 v3.5.17
|
||||
google.golang.org/grpc v1.59.0
|
||||
)
|
||||
|
||||
@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/registry/file/v2
|
||||
|
||||
go 1.23.0
|
||||
|
||||
require github.com/gogf/gf/v2 v2.9.8
|
||||
require github.com/gogf/gf/v2 v2.10.0
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.5.0 // indirect
|
||||
|
||||
@ -1,24 +1,25 @@
|
||||
# GoFrame Nacos Registry
|
||||
|
||||
|
||||
Use `nacos` as service registration and discovery management.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
go get -u -v github.com/gogf/gf/contrib/registry/nacos/v2
|
||||
```
|
||||
|
||||
suggested using `go.mod`:
|
||||
|
||||
```
|
||||
require github.com/gogf/gf/contrib/registry/nacos/v2 latest
|
||||
```
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
### Reference example
|
||||
|
||||
[server](../../../example/registry/nacos/http/server/main.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@ -44,6 +45,7 @@ func main() {
|
||||
```
|
||||
|
||||
[client](../../../example/registry/nacos/http/client/main.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@ -78,4 +80,3 @@ func main() {
|
||||
## License
|
||||
|
||||
`GoFrame Nacos` is licensed under the [MIT License](../../../LICENSE), 100% free and open-source, forever.
|
||||
|
||||
|
||||
@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/registry/nacos/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.3
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.5
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -267,8 +267,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.3 h1:lvkBZcYkKENLVR1ubO+vGxTP2L4VtVSArLvYZKuu4Pk=
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.3/go.mod h1:ygUBdt7eGeYBt6Lz2HO3wx7crKXk25Mp80568emGMWU=
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.5 h1:Hux7C4N4rWhwBF5Zm4yyYskrs9VTgrRTA8DZjoEhQTs=
|
||||
github.com/nacos-group/nacos-sdk-go/v2 v2.3.5/go.mod h1:ygUBdt7eGeYBt6Lz2HO3wx7crKXk25Mp80568emGMWU=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
|
||||
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
|
||||
|
||||
@ -82,7 +82,7 @@ func New(address string, opts ...constant.ClientOption) (reg *Registry) {
|
||||
return
|
||||
}
|
||||
|
||||
// New creates and returns registry with Config.
|
||||
// NewWithConfig creates and returns registry with Config.
|
||||
func NewWithConfig(ctx context.Context, config Config) (reg *Registry, err error) {
|
||||
// Data validation.
|
||||
err = g.Validator().Data(config).Run(ctx)
|
||||
|
||||
@ -19,7 +19,7 @@ import (
|
||||
)
|
||||
|
||||
// Search searches and returns services with specified condition.
|
||||
func (reg *Registry) Search(ctx context.Context, in gsvc.SearchInput) (result []gsvc.Service, err error) {
|
||||
func (reg *Registry) Search(_ context.Context, in gsvc.SearchInput) (result []gsvc.Service, err error) {
|
||||
if in.Prefix == "" && in.Name != "" {
|
||||
in.Prefix = gsvc.NewServiceWithName(in.Name).GetPrefix()
|
||||
}
|
||||
|
||||
@ -17,7 +17,7 @@ import (
|
||||
|
||||
// Register registers `service` to Registry.
|
||||
// Note that it returns a new Service if it changes the input Service with custom one.
|
||||
func (reg *Registry) Register(ctx context.Context, service gsvc.Service) (registered gsvc.Service, err error) {
|
||||
func (reg *Registry) Register(_ context.Context, service gsvc.Service) (registered gsvc.Service, err error) {
|
||||
metadata := map[string]string{}
|
||||
endpoints := service.GetEndpoints()
|
||||
|
||||
@ -67,7 +67,7 @@ func (reg *Registry) Register(ctx context.Context, service gsvc.Service) (regist
|
||||
}
|
||||
|
||||
// Deregister off-lines and removes `service` from the Registry.
|
||||
func (reg *Registry) Deregister(ctx context.Context, service gsvc.Service) (err error) {
|
||||
func (reg *Registry) Deregister(_ context.Context, service gsvc.Service) (err error) {
|
||||
c := reg.client
|
||||
|
||||
for _, endpoint := range service.GetEndpoints() {
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/polaris/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
github.com/polarismesh/polaris-go v1.6.1
|
||||
)
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/go-zookeeper/zk v1.0.3
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
golang.org/x/sync v0.16.0
|
||||
)
|
||||
|
||||
|
||||
@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/rpc/grpcx/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/registry/file/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/registry/file/v2 v2.10.0
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
go.opentelemetry.io/otel/trace v1.38.0
|
||||
google.golang.org/grpc v1.64.1
|
||||
|
||||
@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/sdk/httpclient/v2
|
||||
|
||||
go 1.23.0
|
||||
|
||||
require github.com/gogf/gf/v2 v2.9.8
|
||||
require github.com/gogf/gf/v2 v2.10.0
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.5.0 // indirect
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlpgrpc/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlphttp/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.10.0
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0
|
||||
|
||||
@ -294,6 +294,9 @@ type DB interface {
|
||||
// SetMaxConnLifeTime sets the maximum amount of time a connection may be reused.
|
||||
SetMaxConnLifeTime(d time.Duration)
|
||||
|
||||
// SetMaxIdleConnTime sets the maximum amount of time a connection may be idle before being closed.
|
||||
SetMaxIdleConnTime(d time.Duration)
|
||||
|
||||
// ===========================================================================
|
||||
// Utility methods.
|
||||
// ===========================================================================
|
||||
@ -510,24 +513,25 @@ type StatsItem interface {
|
||||
|
||||
// Core is the base struct for database management.
|
||||
type Core struct {
|
||||
db DB // DB interface object.
|
||||
ctx context.Context // Context for chaining operation only. Do not set a default value in Core initialization.
|
||||
group string // Configuration group name.
|
||||
schema string // Custom schema for this object.
|
||||
debug *gtype.Bool // Enable debug mode for the database, which can be changed in runtime.
|
||||
cache *gcache.Cache // Cache manager, SQL result cache only.
|
||||
links *gmap.Map // links caches all created links by node.
|
||||
logger glog.ILogger // Logger for logging functionality.
|
||||
config *ConfigNode // Current config node.
|
||||
localTypeMap *gmap.StrAnyMap // Local type map for database field type conversion.
|
||||
dynamicConfig dynamicConfig // Dynamic configurations, which can be changed in runtime.
|
||||
innerMemCache *gcache.Cache // Internal memory cache for storing temporary data.
|
||||
db DB // DB interface object.
|
||||
ctx context.Context // Context for chaining operation only. Do not set a default value in Core initialization.
|
||||
group string // Configuration group name.
|
||||
schema string // Custom schema for this object.
|
||||
debug *gtype.Bool // Enable debug mode for the database, which can be changed in runtime.
|
||||
cache *gcache.Cache // Cache manager, SQL result cache only.
|
||||
links *gmap.KVMap[ConfigNode, *sql.DB] // links caches all created links by node.
|
||||
logger glog.ILogger // Logger for logging functionality.
|
||||
config *ConfigNode // Current config node.
|
||||
localTypeMap *gmap.StrAnyMap // Local type map for database field type conversion.
|
||||
dynamicConfig dynamicConfig // Dynamic configurations, which can be changed in runtime.
|
||||
innerMemCache *gcache.Cache // Internal memory cache for storing temporary data.
|
||||
}
|
||||
|
||||
type dynamicConfig struct {
|
||||
MaxIdleConnCount int
|
||||
MaxOpenConnCount int
|
||||
MaxConnLifeTime time.Duration
|
||||
MaxIdleConnTime time.Duration
|
||||
}
|
||||
|
||||
// DoCommitInput is the input parameters for function DoCommit.
|
||||
@ -940,6 +944,9 @@ func NewByGroup(group ...string) (db DB, err error) {
|
||||
)
|
||||
}
|
||||
|
||||
// linksChecker is the checker function for links map.
|
||||
var linksChecker = func(v *sql.DB) bool { return v == nil }
|
||||
|
||||
// newDBByConfigNode creates and returns an ORM object with given configuration node and group name.
|
||||
//
|
||||
// Very Note:
|
||||
@ -956,7 +963,7 @@ func newDBByConfigNode(node *ConfigNode, group string) (db DB, err error) {
|
||||
group: group,
|
||||
debug: gtype.NewBool(),
|
||||
cache: gcache.New(),
|
||||
links: gmap.New(true),
|
||||
links: gmap.NewKVMapWithChecker[ConfigNode, *sql.DB](linksChecker, true),
|
||||
logger: glog.New(),
|
||||
config: node,
|
||||
localTypeMap: gmap.NewStrAnyMap(true),
|
||||
@ -965,6 +972,7 @@ func newDBByConfigNode(node *ConfigNode, group string) (db DB, err error) {
|
||||
MaxIdleConnCount: node.MaxIdleConnCount,
|
||||
MaxOpenConnCount: node.MaxOpenConnCount,
|
||||
MaxConnLifeTime: node.MaxConnLifeTime,
|
||||
MaxIdleConnTime: node.MaxIdleConnTime,
|
||||
},
|
||||
}
|
||||
if v, ok := driverMap[node.Type]; ok {
|
||||
@ -1122,7 +1130,7 @@ func (c *Core) getSqlDb(master bool, schema ...string) (sqlDb *sql.DB, err error
|
||||
|
||||
// Cache the underlying connection pool object by node.
|
||||
var (
|
||||
instanceCacheFunc = func() any {
|
||||
instanceCacheFunc = func() *sql.DB {
|
||||
if sqlDb, err = c.db.Open(node); err != nil {
|
||||
return nil
|
||||
}
|
||||
@ -1144,6 +1152,9 @@ func (c *Core) getSqlDb(master bool, schema ...string) (sqlDb *sql.DB, err error
|
||||
} else {
|
||||
sqlDb.SetConnMaxLifetime(defaultMaxConnLifeTime)
|
||||
}
|
||||
if c.dynamicConfig.MaxIdleConnTime > 0 {
|
||||
sqlDb.SetConnMaxIdleTime(c.dynamicConfig.MaxIdleConnTime)
|
||||
}
|
||||
return sqlDb
|
||||
}
|
||||
// it here uses NODE VALUE not pointer as the cache key, in case of oracle ORA-12516 error.
|
||||
@ -1151,7 +1162,7 @@ func (c *Core) getSqlDb(master bool, schema ...string) (sqlDb *sql.DB, err error
|
||||
)
|
||||
if instanceValue != nil && sqlDb == nil {
|
||||
// It reads from instance map.
|
||||
sqlDb = instanceValue.(*sql.DB)
|
||||
sqlDb = instanceValue
|
||||
}
|
||||
if node.Debug {
|
||||
c.db.SetDebug(node.Debug)
|
||||
|
||||
@ -113,19 +113,17 @@ func (c *Core) Close(ctx context.Context) (err error) {
|
||||
if err = c.cache.Close(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
c.links.LockFunc(func(m map[any]any) {
|
||||
c.links.LockFunc(func(m map[ConfigNode]*sql.DB) {
|
||||
for k, v := range m {
|
||||
if db, ok := v.(*sql.DB); ok {
|
||||
err = db.Close()
|
||||
if err != nil {
|
||||
err = gerror.WrapCode(gcode.CodeDbOperationError, err, `db.Close failed`)
|
||||
}
|
||||
intlog.Printf(ctx, `close link: %s, err: %v`, k, err)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
delete(m, k)
|
||||
err = v.Close()
|
||||
if err != nil {
|
||||
err = gerror.WrapCode(gcode.CodeDbOperationError, err, `db.Close failed`)
|
||||
}
|
||||
intlog.Printf(ctx, `close link: %s, err: %v`, gconv.String(k), err)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
delete(m, k)
|
||||
}
|
||||
})
|
||||
return
|
||||
|
||||
@ -108,6 +108,11 @@ type ConfigNode struct {
|
||||
// Optional field
|
||||
MaxConnLifeTime time.Duration `json:"maxLifeTime"`
|
||||
|
||||
// MaxIdleConnTime specifies the maximum idle time of a connection before being closed
|
||||
// This is Go 1.15+ feature: sql.DB.SetConnMaxIdleTime
|
||||
// Optional field
|
||||
MaxIdleConnTime time.Duration `json:"maxIdleTime"`
|
||||
|
||||
// QueryTimeout specifies the maximum execution time for DQL operations
|
||||
// Optional field
|
||||
QueryTimeout time.Duration `json:"queryTimeout"`
|
||||
@ -353,6 +358,16 @@ func (c *Core) SetMaxConnLifeTime(d time.Duration) {
|
||||
c.dynamicConfig.MaxConnLifeTime = d
|
||||
}
|
||||
|
||||
// SetMaxIdleConnTime sets the maximum amount of time a connection may be idle before being closed.
|
||||
//
|
||||
// Idle connections may be closed lazily before reuse.
|
||||
//
|
||||
// If d <= 0, connections are not closed due to a connection's idle time.
|
||||
// This is Go 1.15+ feature: sql.DB.SetConnMaxIdleTime.
|
||||
func (c *Core) SetMaxIdleConnTime(d time.Duration) {
|
||||
c.dynamicConfig.MaxIdleConnTime = d
|
||||
}
|
||||
|
||||
// GetConfig returns the current used node configuration.
|
||||
func (c *Core) GetConfig() *ConfigNode {
|
||||
var configNode = c.getConfigNodeFromCtx(c.db.GetCtx())
|
||||
|
||||
@ -30,14 +30,14 @@ func (item *localStatsItem) Stats() sql.DBStats {
|
||||
// Stats retrieves and returns the pool stat for all nodes that have been established.
|
||||
func (c *Core) Stats(ctx context.Context) []StatsItem {
|
||||
var items = make([]StatsItem, 0)
|
||||
c.links.Iterator(func(k, v any) bool {
|
||||
var (
|
||||
node = k.(ConfigNode)
|
||||
sqlDB = v.(*sql.DB)
|
||||
)
|
||||
c.links.Iterator(func(k ConfigNode, v *sql.DB) bool {
|
||||
// Create a local copy of k to avoid loop variable address re-use issue
|
||||
// In Go, loop variables are re-used with the same memory address across iterations,
|
||||
// directly using &k would cause all localStatsItem instances to share the same address
|
||||
node := k
|
||||
items = append(items, &localStatsItem{
|
||||
node: &node,
|
||||
stats: sqlDB.Stats(),
|
||||
stats: v.Stats(),
|
||||
})
|
||||
return true
|
||||
})
|
||||
|
||||
@ -8,6 +8,7 @@ package gdb_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
@ -1189,3 +1190,40 @@ func Test_IsConfigured(t *testing.T) {
|
||||
t.Assert(result, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ConfigNode_ConnectionPoolSettings(t *testing.T) {
|
||||
// Test connection pool configuration fields
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Save original config and restore after test
|
||||
originalConfig := gdb.GetAllConfig()
|
||||
defer func() {
|
||||
gdb.SetConfig(originalConfig)
|
||||
}()
|
||||
|
||||
// Reset config
|
||||
gdb.SetConfig(make(gdb.Config))
|
||||
|
||||
testNode := gdb.ConfigNode{
|
||||
Host: "127.0.0.1",
|
||||
Port: "3306",
|
||||
User: "root",
|
||||
Pass: "123456",
|
||||
Name: "test_db",
|
||||
Type: "mysql",
|
||||
MaxIdleConnCount: 10,
|
||||
MaxOpenConnCount: 100,
|
||||
MaxConnLifeTime: 30 * time.Second,
|
||||
MaxIdleConnTime: 10 * time.Second,
|
||||
}
|
||||
|
||||
err := gdb.AddConfigNode("pool_test", testNode)
|
||||
t.AssertNil(err)
|
||||
|
||||
result := gdb.GetAllConfig()
|
||||
t.Assert(len(result), 1)
|
||||
t.Assert(result["pool_test"][0].MaxIdleConnCount, 10)
|
||||
t.Assert(result["pool_test"][0].MaxOpenConnCount, 100)
|
||||
t.Assert(result["pool_test"][0].MaxConnLifeTime, 30*time.Second)
|
||||
t.Assert(result["pool_test"][0].MaxIdleConnTime, 10*time.Second)
|
||||
})
|
||||
}
|
||||
|
||||
@ -142,6 +142,11 @@ func Test_Core_SetMaxConnections(t *testing.T) {
|
||||
testDuration := time.Hour
|
||||
core.SetMaxConnLifeTime(testDuration)
|
||||
t.Assert(core.dynamicConfig.MaxConnLifeTime, testDuration)
|
||||
|
||||
// Test SetMaxIdleConnTime
|
||||
idleTimeDuration := 30 * time.Minute
|
||||
core.SetMaxIdleConnTime(idleTimeDuration)
|
||||
t.Assert(core.dynamicConfig.MaxIdleConnTime, idleTimeDuration)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@ -21,7 +21,7 @@ import (
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
)
|
||||
|
||||
type ContentType string
|
||||
type ContentType = string
|
||||
|
||||
const (
|
||||
ContentTypeJSON ContentType = `json`
|
||||
@ -35,23 +35,40 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
defaultSplitChar = '.' // Separator char for hierarchical data access.
|
||||
// Separator char for hierarchical data access.
|
||||
defaultSplitChar = '.'
|
||||
)
|
||||
|
||||
// Json is the customized JSON struct.
|
||||
type Json struct {
|
||||
mu rwmutex.RWMutex
|
||||
p *any // Pointer for hierarchical data access, it's the root of data in default.
|
||||
c byte // Char separator('.' in default).
|
||||
vc bool // Violence Check(false in default), which is used to access data when the hierarchical data key contains separator char.
|
||||
|
||||
// Pointer for hierarchical data access, it's the root of data in default.
|
||||
p *any
|
||||
|
||||
// Char separator('.' in default).
|
||||
c byte
|
||||
|
||||
// Violence Check(false in default),
|
||||
// which is used to access data when the hierarchical data key contains separator char.
|
||||
vc bool
|
||||
}
|
||||
|
||||
// Options for Json object creating/loading.
|
||||
type Options struct {
|
||||
Safe bool // Mark this object is for in concurrent-safe usage. This is especially for Json object creating.
|
||||
Tags string // Custom priority tags for decoding, eg: "json,yaml,MyTag". This is especially for struct parsing into Json object.
|
||||
Type ContentType // Type specifies the data content type, eg: json, xml, yaml, toml, ini.
|
||||
StrNumber bool // StrNumber causes the Decoder to unmarshal a number into an any as a string instead of as a float64.
|
||||
// Mark this object is for in concurrent-safe usage. This is especially for Json object creating.
|
||||
Safe bool
|
||||
|
||||
// Custom priority tags for decoding, eg: "json,yaml,MyTag".
|
||||
// This is specially for struct parsing into Json object.
|
||||
Tags string
|
||||
|
||||
// Type specifies the data content type, eg: json, xml, yaml, toml, ini.
|
||||
Type ContentType
|
||||
|
||||
// StrNumber causes the Decoder to unmarshal a number into an any as a string instead of as a float64.
|
||||
// This is specially for json content parsing into Json object.
|
||||
StrNumber bool
|
||||
}
|
||||
|
||||
// iInterfaces is used for type assert api for Interfaces().
|
||||
|
||||
@ -161,56 +161,85 @@ func loadContentWithOptions(data []byte, options Options) (*Json, error) {
|
||||
if len(data) == 0 {
|
||||
return NewWithOptions(nil, options), nil
|
||||
}
|
||||
if options.Type == "" {
|
||||
options.Type, err = checkDataType(data)
|
||||
var (
|
||||
checkType ContentType
|
||||
decodedData any
|
||||
)
|
||||
if options.Type != "" {
|
||||
checkType = gstr.TrimLeft(options.Type, ".")
|
||||
} else {
|
||||
checkType, err = checkDataType(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
options.Type = ContentType(gstr.TrimLeft(
|
||||
string(options.Type), "."),
|
||||
)
|
||||
switch options.Type {
|
||||
switch checkType {
|
||||
case ContentTypeJSON, ContentTypeJs:
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
if options.StrNumber {
|
||||
decoder.UseNumber()
|
||||
}
|
||||
if err = decoder.Decode(&result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch result.(type) {
|
||||
case string, []byte:
|
||||
return nil, gerror.Newf(`json decoding failed for content: %s`, data)
|
||||
}
|
||||
return NewWithOptions(result, options), nil
|
||||
|
||||
case ContentTypeXML:
|
||||
data, err = gxml.ToJson(data)
|
||||
decodedData, err = gxml.Decode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewWithOptions(decodedData, options), nil
|
||||
|
||||
case ContentTypeYaml, ContentTypeYml:
|
||||
data, err = gyaml.ToJson(data)
|
||||
decodedData, err = gyaml.Decode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewWithOptions(decodedData, options), nil
|
||||
|
||||
case ContentTypeToml:
|
||||
data, err = gtoml.ToJson(data)
|
||||
decodedData, err = gtoml.Decode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewWithOptions(decodedData, options), nil
|
||||
|
||||
case ContentTypeIni:
|
||||
data, err = gini.ToJson(data)
|
||||
decodedData, err = gini.Decode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewWithOptions(decodedData, options), nil
|
||||
|
||||
case ContentTypeProperties:
|
||||
data, err = gproperties.ToJson(data)
|
||||
decodedData, err = gproperties.Decode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewWithOptions(decodedData, options), nil
|
||||
|
||||
default:
|
||||
err = gerror.NewCodef(
|
||||
gcode.CodeInvalidParameter,
|
||||
`unsupported type "%s" for loading`,
|
||||
options.Type,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// ignore some duplicated types, like js and yml,
|
||||
// which are not necessary shown in error message.
|
||||
allSupportedTypes := []string{
|
||||
ContentTypeJSON,
|
||||
ContentTypeXML,
|
||||
ContentTypeYaml,
|
||||
ContentTypeToml,
|
||||
ContentTypeIni,
|
||||
ContentTypeProperties,
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
if options.StrNumber {
|
||||
decoder.UseNumber()
|
||||
}
|
||||
if err = decoder.Decode(&result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch result.(type) {
|
||||
case string, []byte:
|
||||
return nil, gerror.Newf(`json decoding failed for content: %s`, data)
|
||||
}
|
||||
return NewWithOptions(result, options), nil
|
||||
return nil, gerror.NewCodef(
|
||||
gcode.CodeInvalidParameter,
|
||||
`unsupported type "%s" for loading, all supported types: %s`,
|
||||
options.Type, gstr.Join(allSupportedTypes, ", "),
|
||||
)
|
||||
}
|
||||
|
||||
// checkDataType automatically checks and returns the data type for `content`.
|
||||
@ -247,33 +276,104 @@ func checkDataType(data []byte) (ContentType, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// isXMLContent checks whether given content is XML format.
|
||||
// XML format is easy to be identified using regular expression.
|
||||
func isXMLContent(data []byte) bool {
|
||||
return gregex.IsMatch(`^\s*<.+>[\S\s]+<.+>\s*$`, data)
|
||||
}
|
||||
|
||||
// isYamlContent checks whether given content is YAML format.
|
||||
func isYamlContent(data []byte) bool {
|
||||
return !gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*"""[\s\S]+"""`, data) &&
|
||||
!gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*'''[\s\S]+'''`, data) &&
|
||||
((gregex.IsMatch(`^[\n\r]*[\w\-\s\t]+\s*:\s*".+"`, data) ||
|
||||
gregex.IsMatch(`^[\n\r]*[\w\-\s\t]+\s*:\s*\w+`, data)) ||
|
||||
(gregex.IsMatch(`[\n\r]+[\w\-\s\t]+\s*:\s*".+"`, data) ||
|
||||
gregex.IsMatch(`[\n\r]+[\w\-\s\t]+\s*:\s*\w+`, data)))
|
||||
// x = y
|
||||
// "x.x" = "y"
|
||||
tomlFormat1 := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*"""[\s\S]+"""`, data)
|
||||
if tomlFormat1 {
|
||||
return false
|
||||
}
|
||||
// "x.x" = '''
|
||||
// y
|
||||
// '''
|
||||
tomlFormat2 := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*'''[\s\S]+'''`, data)
|
||||
if tomlFormat2 {
|
||||
return false
|
||||
}
|
||||
|
||||
// content starts with:
|
||||
// x : "y"
|
||||
yamlFormat1 := gregex.IsMatch(`^[\n\r]*[\w\-\s\t]+\s*:\s+".+"`, data)
|
||||
|
||||
// content starts with:
|
||||
// x : y
|
||||
yamlFormat2 := gregex.IsMatch(`^[\n\r]*[\w\-\s\t]+\s*:\s+\w+`, data)
|
||||
|
||||
// line starts with:
|
||||
// x : "y"
|
||||
yamlFormat3 := gregex.IsMatch(`[\n\r]+[\w\-\s\t]+\s*:\s+".+"`, data)
|
||||
|
||||
// line starts with:
|
||||
// x : y
|
||||
yamlFormat4 := gregex.IsMatch(`[\n\r]+[\w\-\s\t]+\s*:\s+\w+`, data)
|
||||
|
||||
// content starts with:
|
||||
// "x" : "y"
|
||||
yamlFormat5 := gregex.IsMatch(`^[\n\r]*".+":\s+".+"`, data)
|
||||
|
||||
// line starts with:
|
||||
// "x" : y
|
||||
yamlFormat6 := gregex.IsMatch(`[\n\r]+".+":\s+\w+`, data)
|
||||
|
||||
return yamlFormat1 || yamlFormat2 || yamlFormat3 || yamlFormat4 || yamlFormat5 || yamlFormat6
|
||||
}
|
||||
|
||||
// isTomlContent checks whether given content is TOML format.
|
||||
func isTomlContent(data []byte) bool {
|
||||
return !gregex.IsMatch(`^[\s\t\n\r]*;.+`, data) &&
|
||||
!gregex.IsMatch(`[\s\t\n\r]+;.+`, data) &&
|
||||
!gregex.IsMatch(`[\n\r]+[\s\t\w\-]+\.[\s\t\w\-]+\s*=\s*.+`, data) &&
|
||||
(gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*".+"`, data) ||
|
||||
gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*\w+`, data))
|
||||
// content starts with:
|
||||
// ; comment line
|
||||
contentStartsWithSemicolonComment := gregex.IsMatch(`^[\s\t\n\r]*;.+`, data)
|
||||
if contentStartsWithSemicolonComment {
|
||||
return false
|
||||
}
|
||||
// line starts with:
|
||||
// ; comment line
|
||||
lineStartsWithSemicolonComment := gregex.IsMatch(`[\s\t\n\r]+;.+`, data)
|
||||
if lineStartsWithSemicolonComment {
|
||||
return false
|
||||
}
|
||||
|
||||
// line starts with, this should not be toml format:
|
||||
// key.with.dot = value
|
||||
keyWithDot := gregex.IsMatch(`[\n\r]+[\s\t\w\-]+\.[\s\t\w\-]+\s*=\s*.+`, data)
|
||||
if keyWithDot {
|
||||
return false
|
||||
}
|
||||
|
||||
// line starts with:
|
||||
// key = value
|
||||
// key = "value"
|
||||
// "key" = "value"
|
||||
// "key" = value
|
||||
tomlFormat1 := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*".+"`, data)
|
||||
tomlFormat2 := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*\w+`, data)
|
||||
return tomlFormat1 || tomlFormat2
|
||||
}
|
||||
|
||||
// isIniContent checks whether given content is INI format.
|
||||
func isIniContent(data []byte) bool {
|
||||
return gregex.IsMatch(`\[[\w\.]+\]`, data) &&
|
||||
(gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*".+"`, data) ||
|
||||
gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*\w+`, data))
|
||||
// no section like: [section], but ini format must have sections.
|
||||
hasBrackets := gregex.IsMatch(`\[[\w\.]+\]`, data)
|
||||
if !hasBrackets {
|
||||
return false
|
||||
}
|
||||
iniFormat1 := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*".+"`, data)
|
||||
iniFormat2 := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*\w+`, data)
|
||||
return iniFormat1 || iniFormat2
|
||||
}
|
||||
|
||||
// isPropertyContent checks whether given content is Properties format.
|
||||
func isPropertyContent(data []byte) bool {
|
||||
return gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*\w+`, data)
|
||||
// line starts with:
|
||||
// key = value
|
||||
// "key" = value
|
||||
propertyFormat := gregex.IsMatch(`[\n\r]*[\s\t\w\-\."]+\s*=\s*\w+`, data)
|
||||
return propertyFormat
|
||||
}
|
||||
|
||||
@ -29,7 +29,7 @@ func LoadPath(path string, options Options) (*Json, error) {
|
||||
path = p
|
||||
}
|
||||
if options.Type == "" {
|
||||
options.Type = ContentType(gfile.Ext(path))
|
||||
options.Type = gfile.Ext(path)
|
||||
}
|
||||
return loadContentWithOptions(gfile.GetBytesWithCache(path), options)
|
||||
return loadContentWithOptions(gfile.GetBytes(path), options)
|
||||
}
|
||||
|
||||
@ -418,3 +418,13 @@ DBINFO.password=password
|
||||
t.AssertNE(err, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML_For_I18n(t *testing.T) {
|
||||
var data = []byte(gtest.DataContent("yaml", "i18n-issue.yaml"))
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.LoadContent(data)
|
||||
t.AssertNil(err)
|
||||
j.SetViolenceCheck(true)
|
||||
t.Assert(j.Get("resourceUsage.workflow").String(), "workflow")
|
||||
})
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user