Skip to content

Commit af605e7

Browse files
authored
Generate less boilerplate code when making a new Go module (viamrobotics#4668)
This is a follow-up to viamrobotics#4455. Nearly all modules can really have a 1-line `main` function, rather than all the boilerplate that gets generated in the current version. Tried locally: running `./main module generate` can make a new codebase whose `main.go` looks like this: ```go package main import ( "branch-module-one-space/models" "go.viam.com/rdk/module" "go.viam.com/rdk/resource" "go.viam.com/rdk/components/audioinput" ) func main() { // ModularMain can take multiple APIModel arguments, if your module implements multiple models. module.ModularMain(resource.APIModel{ audioinput.API, models.BranchModelOnespace}) } ``` Running `make` not only successfully compiles everything, but `main.go` gets cleaned up like this (note the reordering of the imports, and the space removed from the `APIModel` constructor): ```go package main import ( "branch-module-one-space/models" "go.viam.com/rdk/components/audioinput" "go.viam.com/rdk/module" "go.viam.com/rdk/resource" ) func main() { // ModularMain can take multiple APIModel arguments, if your module implements multiple models. module.ModularMain(resource.APIModel{audioinput.API, models.BranchModelOnespace}) } ```
1 parent bb61a06 commit af605e7

File tree

1 file changed

+3
-26
lines changed

1 file changed

+3
-26
lines changed

cli/module_generate/_templates/go/tmpl-main.go

+3-26
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,12 @@ package main
22

33
import (
44
"{{.ModuleName}}/models"
5-
"context"
6-
"go.viam.com/rdk/logging"
75
"go.viam.com/rdk/module"
8-
"go.viam.com/utils"
6+
"go.viam.com/rdk/resource"
97
"go.viam.com/rdk/{{.ResourceType}}s/{{.ResourceSubtype}}"
10-
118
)
129

1310
func main() {
14-
utils.ContextualMain(mainWithArgs, module.NewLoggerFromArgs("{{.ModuleName}}"))
15-
}
16-
17-
func mainWithArgs(ctx context.Context, args []string, logger logging.Logger) error {
18-
{{.ModuleCamel}}, err := module.NewModuleFromArgs(ctx)
19-
if err != nil {
20-
return err
21-
}
22-
23-
if err = {{.ModuleCamel}}.AddModelFromRegistry(ctx, {{.ResourceSubtype}}.API, models.{{.ModelPascal}}); err != nil {
24-
return err
25-
}
26-
27-
28-
err = {{.ModuleCamel}}.Start(ctx)
29-
defer {{.ModuleCamel}}.Close(ctx)
30-
if err != nil {
31-
return err
32-
}
33-
34-
<-ctx.Done()
35-
return nil
11+
// ModularMain can take multiple APIModel arguments, if your module implements multiple models.
12+
module.ModularMain(resource.APIModel{ {{.ResourceSubtype}}.API, models.{{.ModelPascal}}})
3613
}

0 commit comments

Comments
 (0)