From 5d5b24a66d8e54de9703ce330258e53d3c343fbd Mon Sep 17 00:00:00 2001 From: Ben Tranter Date: Fri, 26 Jan 2024 14:36:35 -0500 Subject: [PATCH] droplets: refactor how to assign resources (#1500) 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. --- commands/command_config.go | 16 ++++++++++++++++ commands/droplets.go | 8 ++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/commands/command_config.go b/commands/command_config.go index b1ff12ffc..a89d87f50 100644 --- a/commands/command_config.go +++ b/commands/command_config.go @@ -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 +} diff --git a/commands/droplets.go b/commands/droplets.go index 56e111896..eaf158694 100644 --- a/commands/droplets.go +++ b/commands/droplets.go @@ -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 } }