Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions pkg/generator/gen_main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package generator

import (
"io"
"path/filepath"
"text/template"
)

const (
// sdkImport is the operator-sdk import path.
sdkImport = "github.com/coreos/operator-sdk/pkg/sdk"
main = "main"
)

// Main contains all the customized data needed to generate cmd/<projectName>/main.go for a new operator
// when pairing with mainTmpl template.
type Main struct {
// imports
OperatorSDKImport string
APIImport string
StubImport string

// Service defintion in pkg/apis/..
ServicePlural string
Service string
}

// renderMain generates the cmd/<projectName>/main.go file given a repo path ("github.com/coreos/play"), apiVersion ("v1alpha1"),
// projectName ("play"), service ("PlayService"), and servicePlural ("PlayServicePlural").
//
// for example:
// renderMain(w, "github.com/coreos/play", "v1alpha1", "play", "PlayService", "PlayServicePlural" )
// output:
//
// package main
//
// import (
// "context"
//
// sdk "github.com/coreos/operator-sdk/pkg/sdk"
// api "github.com/coreos/play/pkg/apis/play/v1alpha1"
// stub "github.com/coreos/play/pkg/stub"
// )
//
// func main() {
// namespace := "default"
// sdk.Watch(api.PlayServicePlural, namespace, api.PlayService)
// sdk.Handle(&stub.Handler{})
// sdk.Run(context.TODO())
// }
//
func renderMain(w io.Writer, repo, version, projectName, service, servicePlural string) error {
t := template.New("cmd/<projectName>/main.go")
t, err := t.Parse(mainTmpl)
if err != nil {
return err
}

m := Main{
OperatorSDKImport: sdkImport,
APIImport: filepath.Join(repo, apisDir, projectName, version),
StubImport: filepath.Join(repo, stubDir),
ServicePlural: servicePlural,
Service: service,
}
return t.Execute(w, m)
}
20 changes: 20 additions & 0 deletions pkg/generator/main_tmpl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package generator

// mainTmpl is the template for cmd/main.go.
const mainTmpl = `package main

import (
"context"

sdk "{{.OperatorSDKImport}}"
api "{{.APIImport}}"
stub "{{.StubImport}}"
)

func main() {
namespace := "default"
sdk.Watch(api.{{.ServicePlural}}, namespace, api.{{.Service}})
sdk.Handle(&stub.Handler{})
sdk.Run(context.TODO())
}
`