Skip to content

Commit 9e044a2

Browse files
committed
refactor: optmize code and fix some bug
1 parent 745f771 commit 9e044a2

File tree

27 files changed

+285
-477
lines changed

27 files changed

+285
-477
lines changed

.note.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
```go
2+
// REST captures naming conventions and helper metadata for generating REST resources.
3+
type REST struct {
4+
SingularName string // Singular form of the kind (e.g., "CronJob").
5+
PluralName string // Plural form of the kind (e.g., "CronJobs").
6+
SingularLower string // Singular name in lower format (e.g., "cronjob").
7+
PluralLower string // Plural name in lower format (e.g., "cronjobs").
8+
SingularLowerFirst string // Singular name in lowerCamel (first letter lower) (e.g., "cronJob").
9+
PluralLowerFirst string // Plural name in lowerCamel (first letter lower) (e.g., "cronJobs").
10+
11+
GORMModel string // Name of the associated GORM model (e.g., "CronJobModel").
12+
MapModelToAPIFunc string // Function name to map the model to the API (e.g., "ModelToCronJobV1").
13+
MapAPIToModelFunc string // Function name to map the API to the model (e.g., "CronJobV1ToCronJobM").
14+
BusinessFactoryName string // Name of the business layer factory.
15+
FileName string // Name of the generated Go file.
16+
}
17+
```

.todo

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,11 @@
55
[] 支持以下子命令
66
[] uplift或者gsemver
77
[] 生成的项目支持 swagger 及 各个语言的 SDK
8+
[] 支持 helm chart
9+
[] 支持单个 yaml 文件
10+
[] 支持osbuilder create job 命令
11+
[] 支持 jobService
12+
[] 其他变更:
13+
- conversion 变更
14+
- xxxx
15+
- slog secretName -> secret_name

internal/osbuilder/file/proto.go

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import (
88
"regexp"
99
"strings"
1010
"unicode/utf8"
11+
12+
"github.com/duke-git/lancet/v2/strutil"
13+
"github.com/gobuffalo/flect"
1114
)
1215

1316
func applyUpdates(src string, kind string, grpcServiceName string, importPath string) (string, bool, error) {
@@ -86,13 +89,16 @@ func addImportProto(src string, importPath string) (string, bool, error) {
8689
}
8790

8891
func addRPCsToAPIServer(src string, kind string, grpcServiceName string) (string, bool, error) {
92+
pluralKind := flect.Pluralize(strutil.UpperFirst(strutil.CamelCase(kind)))
93+
8994
var (
90-
reServiceOpen = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*service[ \t]+%s[ \t]*\{`, grpcServiceName))
91-
reCreate = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Create%s[ \t]*\(`, kind))
92-
reUpdate = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Update%s[ \t]*\(`, kind))
93-
reDelete = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Delete%s[ \t]*\(`, kind))
94-
reGet = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Get%s[ \t]*\(`, kind))
95-
reList = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+List%s[ \t]*\(`, kind))
95+
reServiceOpen = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*service[ \t]+%s[ \t]*\{`, grpcServiceName))
96+
reCreate = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Create%s[ \t]*\(`, kind))
97+
reUpdate = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Update%s[ \t]*\(`, kind))
98+
reDelete = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Delete%s[ \t]*\(`, kind))
99+
reDeleteCollection = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Delete%s[ \t]*\(`, pluralKind))
100+
reGet = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+Get%s[ \t]*\(`, kind))
101+
reList = regexp.MustCompile(fmt.Sprintf(`(?m)^[ \t]*rpc[ \t]+List%s[ \t]*\(`, kind))
96102
)
97103

98104
loc := reServiceOpen.FindStringIndex(src)
@@ -121,6 +127,7 @@ func addRPCsToAPIServer(src string, kind string, grpcServiceName string) (string
121127
hasCreate := reCreate.FindStringIndex(body) != nil
122128
hasUpdate := reUpdate.FindStringIndex(body) != nil
123129
hasDelete := reDelete.FindStringIndex(body) != nil
130+
hasDeleteCollection := reDeleteCollection.FindStringIndex(body) != nil
124131
hasGet := reGet.FindStringIndex(body) != nil
125132
hasList := reList.FindStringIndex(body) != nil
126133

@@ -154,6 +161,11 @@ func addRPCsToAPIServer(src string, kind string, grpcServiceName string) (string
154161
b.WriteString(fmt.Sprintf("rpc Delete%s(Delete%sRequest) returns (Delete%sResponse);\n", kind, kind, kind))
155162
needUpdate = true
156163
}
164+
if !hasDeleteCollection {
165+
b.WriteString(insIndent)
166+
b.WriteString(fmt.Sprintf("rpc Delete%s(Delete%sRequest) returns (Delete%sResponse);\n", pluralKind, pluralKind, pluralKind))
167+
needUpdate = true
168+
}
157169
if !hasGet {
158170
b.WriteString(insIndent)
159171
b.WriteString(fmt.Sprintf("rpc Get%s(Get%sRequest) returns (Get%sResponse);\n", kind, kind, kind))

internal/osbuilder/helper/helper.go

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"resty.dev/v3"
2424

2525
"github.com/onexstack/osbuilder/internal/osbuilder/file"
26+
"github.com/onexstack/osbuilder/internal/osbuilder/known"
2627
_ "github.com/onexstack/osbuilder/internal/osbuilder/statik"
2728
"github.com/onexstack/osbuilder/internal/osbuilder/types"
2829
)
@@ -305,19 +306,43 @@ func HasOTel() func([]*types.WebServer) bool {
305306
}
306307
}
307308

309+
func HasMemoryStorageType() func([]*types.WebServer) bool {
310+
return func(servers []*types.WebServer) bool {
311+
for _, server := range servers {
312+
if server.StorageType == known.StorageTypeMemory {
313+
return true
314+
}
315+
}
316+
return false
317+
}
318+
}
319+
320+
func ExtractProjectPrefix() func(string) string {
321+
return func(projectName string) string {
322+
// Split string by "-", take the first part
323+
parts := strings.Split(projectName, "-")
324+
if len(parts) > 0 {
325+
return parts[0]
326+
}
327+
return projectName // If no "-", return original string
328+
}
329+
}
330+
308331
func GetTemplateFuncMap() template.FuncMap {
309332
return template.FuncMap{
310-
"kind": Kind(),
311-
"kinds": Kinds(),
312-
"capitalize": Capitalize(),
313-
"lowerkind": SingularLower(),
314-
"lowerkinds": SingularLowers(),
315-
"currentYear": CurrentYear(),
316-
"underscore": ToUnderscore(),
317-
"hasGRPC": HasGRPC(),
318-
"hasGin": HasGin(),
319-
"hasOTel": HasOTel(),
320-
"hasServiceRegistry": HasServiceRegistry(),
333+
"kind": Kind(),
334+
"kinds": Kinds(),
335+
"capitalize": Capitalize(),
336+
"lowerkind": SingularLower(),
337+
"lowerkinds": SingularLowers(),
338+
"currentYear": CurrentYear(),
339+
"underscore": ToUnderscore(),
340+
"hasGRPC": HasGRPC(),
341+
"hasGin": HasGin(),
342+
"hasOTel": HasOTel(),
343+
"hasServiceRegistry": HasServiceRegistry(),
344+
"extractProjectPrefix": ExtractProjectPrefix(),
345+
"hasMemoryStorageType": HasMemoryStorageType(),
321346
}
322347
}
323348

internal/osbuilder/statik/statik.go

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/osbuilder/tpl/project.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,8 @@ webServers:
6868
# - nacos:支持 nacos 注册中心
6969
# 默认 none
7070
serviceRegistry: none
71+
# 是否生成异步任务执行引擎相关代码,如果设置为true,会生成以下代码
72+
# 1. 在 cmd/ 目录下,新增一个 mb-job 组件
73+
# 2. 自动生成 CronJob 和 Job 资源
74+
jobService:
75+
binaryName: mb-job

internal/osbuilder/tpl/project/Makefile.unstructed

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ APIROOT=$(PROJ_ROOT_DIR)/pkg/api
1111
ROOT_PACKAGE={{.D.ModuleName}}
1212
DOCKERFILE_DIR=$(PROJ_ROOT_DIR)/build/docker
1313
REGISTRY_PREFIX ?= {{.D.RegistryPrefix}}
14+
{{- if hasMemoryStorageType .WebServers }}
15+
CGO_ENABLED ?= 1
16+
{{- else}}
17+
CGO_ENABLED ?= 0
18+
{{- end}}
1419
{{- if eq .Metadata.Image.DockerfileMode "combined" }}
1520
# Set to 1 to use Dockerfile.runtime-only when building images
1621
RUNTIME_ONLY ?= 0
@@ -119,7 +124,7 @@ export USAGE_OPTIONS
119124
# Define other required phony targets
120125
#
121126

122-
.PHONY: build.multiarch
127+
.PHONY: build.multiarch
123128
build.multiarch: $(foreach p,$(PLATFORMS),$(addprefix build., $(addprefix $(p)., $(BINS)))) ## Build all applications with all supported arch.
124129

125130
.PHONY: build
@@ -132,7 +137,7 @@ build.%: ## 编译 Go 源码.
132137
$(eval ARCH := $(word 2,$(subst _, ,$(PLATFORM))))
133138
@echo "===========> Building binary $(COMMAND) $(VERSION) for $(OS) $(ARCH)"
134139
@mkdir -p $(OUTPUT_DIR)/platforms/$(OS)/$(ARCH)
135-
@CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build $(GO_BUILD_FLAGS) \
140+
@CGO_ENABLED=$(CGO_ENABLED) GOOS=$(OS) GOARCH=$(ARCH) go build $(GO_BUILD_FLAGS) \
136141
-o $(OUTPUT_DIR)/platforms/$(OS)/$(ARCH)/$(COMMAND)$(GO_OUT_EXT) \
137142
$(ROOT_PACKAGE)/cmd/$(COMMAND)
138143

internal/osbuilder/tpl/project/cmd/mb-apiserver/app/options/options.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -155,14 +155,14 @@ func (o *ServerOptions) AddFlags(fs *pflag.FlagSet) {
155155
{{- if eq .Web.ServiceRegistry "polaris" }}
156156
o.PolarisOptions.AddFlags(fs)
157157
{{- end}}
158-
{{- if .Web.WithOTel}}
158+
{{- if .Web.WithOTel}}
159159
o.OTelOptions.AddFlags(fs)
160160
{{- if or (eq .Web.WebFramework "grpc") (eq .Web.WebFramework "grpc-gateway")}}
161161
fs.StringVar(&o.MetricsAddr, "metrics-addr", o.MetricsAddr, "The address to expose the Prometheus /metrics endpoint.")
162-
{{- end}}
163-
{{- else}}
162+
{{- end}}
163+
{{- else}}
164164
o.SlogOptions.AddFlags(fs)
165-
{{- end}}
165+
{{- end}}
166166
}
167167

168168
// Complete completes all the required options.
@@ -202,15 +202,15 @@ func (o *ServerOptions) Validate() error {
202202
{{- if eq .Web.ServiceRegistry "polaris" }}
203203
errs = append(errs, o.PolarisOptions.Validate()...)
204204
{{- end}}
205-
{{- if .Web.WithOTel}}
205+
{{- if .Web.WithOTel}}
206206
errs = append(errs, o.OTelOptions.Validate()...)
207207
{{- if or (eq .Web.WebFramework "grpc") (eq .Web.WebFramework "grpc-gateway")}}
208208
// Validate metrics address format.
209209
if o.MetricsAddr == "" {
210210
errs = append(errs, fmt.Errorf("metrics-addr cannot be empty"))
211211
}
212212
{{- end}}
213-
{{- else}}
213+
{{- else}}
214214

215215
errs = append(errs, o.SlogOptions.Validate()...)
216216
{{- end}}
@@ -246,7 +246,7 @@ func (o *ServerOptions) Config() (*{{.Web.Name}}.Config, error) {
246246
PolarisOptions: o.PolarisOptions,
247247
{{- end}}
248248
{{- if or (eq .Web.WebFramework "grpc") (eq .Web.WebFramework "grpc-gateway")}}
249-
{{- if .Web.WithOTel}}
249+
{{- if .Web.WithOTel}}
250250
MetricsAddr: o.MetricsAddr,
251251
{{- end}}
252252
{{- end}}

internal/osbuilder/tpl/project/cmd/mb-apiserver/app/server.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,19 +55,19 @@ func NewWebServerCommand() *cobra.Command {
5555

5656
// Validate command-line options
5757
if err := opts.Validate(); err != nil {
58-
return fmt.Errorf("invalid options: %w", err)
59-
}
58+
return fmt.Errorf("invalid options: %w", err)
59+
}
6060

6161
{{- if .Web.WithOTel}}
62+
// Initialize and configure OpenTelemetry providers based on enabled signals
6263
if err := opts.OTelOptions.Apply(); err != nil {
63-
return err
64-
}
65-
defer func() {
66-
_ = opts.OTelOptions.Shutdown(ctx)
67-
}()
64+
return err
65+
}
66+
// Ensure OpenTelemetry resources are properly cleaned up on application shutdown
67+
defer func() { _ = opts.OTelOptions.Shutdown(ctx) }()
6868
{{- else}}
6969
if err := opts.SlogOptions.Apply(); err != nil {
70-
return err
70+
return err
7171
}
7272
{{- end}}
7373

internal/osbuilder/tpl/project/configs/mb-apiserver.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ timeout: 30s # 服务端超时
77
{{- if .WithOTel }}
88
metrics-addr: 0.0.0.0:29090
99
{{- end}}
10-
grpc:
10+
grpc:
1111
port: 6666
1212
timeout: 30s
1313
{{- end}}
@@ -32,17 +32,17 @@ otel:
3232
time-format: "2006-01-02 15:04:05"
3333
output: stdout # 支持 stdout, stderr, or file path
3434
{{- end}}
35-
{{- if eq .ServiceRegistry "polaris" }}
35+
{{- if eq .ServiceRegistry "polaris" }}
3636
polaris:
3737
addr: 127.0.0.1:8091
3838
timeout: 30s
3939
retry-count: 3
4040
provider:
4141
namespace: {{$.D.ProjectName}}
4242
service: {{.BinaryName}}
43-
{{- end}}
43+
{{- end}}
4444
{{- if or (eq .StorageType "mysql") (eq .StorageType "mariadb") }}
45-
mysql:
45+
mysql:
4646
addr: 127.0.0.1:3306
4747
username: onex
4848
password: "onex(#)666"

0 commit comments

Comments
 (0)