resources: Add NewNamedResource helper

This makes the common pattern of NewResource, SetName, easier. It also
makes it less likely for you to forget to use SetName.
This commit is contained in:
James Shubin
2017-06-17 17:32:52 -04:00
parent e341256627
commit 0dadf3d78a
8 changed files with 41 additions and 36 deletions

View File

@@ -52,7 +52,8 @@ func RegisterResource(kind string, fn func() Res) {
registeredResources[kind] = fn
}
// NewResource returns an empty resource object from a registered kind.
// NewResource returns an empty resource object from a registered kind. It
// errors if the resource kind doesn't exist.
func NewResource(kind string) (Res, error) {
fn, ok := registeredResources[kind]
if !ok {
@@ -64,6 +65,21 @@ func NewResource(kind string) (Res, error) {
return res, nil
}
// NewNamedResource returns an empty resource object from a registered kind. It
// also sets the name. It is a wrapper around NewResource. It also errors if the
// name is empty.
func NewNamedResource(kind, name string) (Res, error) {
if name == "" {
return nil, fmt.Errorf("resource name is empty")
}
res, err := NewResource(kind)
if err != nil {
return nil, err
}
res.SetName(name)
return res, nil
}
//go:generate stringer -type=ResState -output=resstate_stringer.go
// The ResState type represents the current activity state of each resource.