Skip to content

Commit

Permalink
droplets: refactor how to assign resources (#1500)
Browse files Browse the repository at this point in the history
This refactors how we move created resources to projects to make it
generic-ish. As long as the resource implements the `URN()` method, we
can use a helper that performs the assign resources call.

This is not quite ideal due to how the commands are architected. Because
we double-wrap the raw godo resources (first in a wrapper struct, then
in the type alias for a slice of those wrapped structs), Go's type
system isn't able to recognize those slices as implementing a slice of
`urner` interfaces. What it can do though, is recognize each individual
element of those slices as implementing the `urner` interface, so the
method I created will only accept a single `urner`, despite the call to
assign resources accepting an slice of URNs.

I think the tradeoff is worth it, since each command that can support
the projects functionality can use the same `moveToProject`, and what we
lose in efficiency by having multiple calls to assign resources in some
instances, we gain in consistency.
  • Loading branch information
bentranter authored Jan 26, 2024
1 parent 1856794 commit 5d5b24a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
16 changes: 16 additions & 0 deletions commands/command_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,19 @@ func (c *CmdConfig) Display(d displayers.Displayable) error {

return dc.Display()
}

// An urner implements the URN method, wihich returns a valid uniform resource
// name.
type urner interface {
URN() string
}

// moveToProject moves the given resource to the project with the given
// project UUID.
func (c *CmdConfig) moveToProject(projectUUID string, u urner) error {
if projectUUID == "" {
return nil
}
_, err := c.Projects().AssignResources(projectUUID, []string{u.URN()})
return err
}
8 changes: 2 additions & 6 deletions commands/droplets.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,12 +335,8 @@ func RunDropletCreate(c *CmdConfig) error {
}
}

if projectUUID != "" {
dropletURNs := make([]string, 0, len(createdList))
for _, createdDroplet := range createdList {
dropletURNs = append(dropletURNs, createdDroplet.URN())
}
if _, err := c.Projects().AssignResources(projectUUID, dropletURNs); err != nil {
for _, createdDroplet := range createdList {
if err := c.moveToProject(projectUUID, createdDroplet); err != nil {
return err
}
}
Expand Down

0 comments on commit 5d5b24a

Please sign in to comment.