Skip to content

Commit

Permalink
Merge pull request #11 from SoftIron/set_ctx_values
Browse files Browse the repository at this point in the history
feat: ability to set specific context fields
  • Loading branch information
masonkatz authored May 30, 2024
2 parents 0d81bc5 + 2965770 commit b2e52a3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 23 deletions.
2 changes: 2 additions & 0 deletions cloud/instance/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ type Template struct {
MemoryMax string
MemoryResizeMode string
MemorySlots string
Name string
NIC []NIC
NICAlias []NICAlias
NICDefault string
Expand Down Expand Up @@ -156,6 +157,7 @@ type Context struct {
Network bool
SSHPublicKey string
Target string
ProjectName string
}

// OS is the API payload based on the legacy xmlrpc backend.
Expand Down
66 changes: 43 additions & 23 deletions cloud/instance/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,35 +232,55 @@ func newInstanceContext(m map[string]any) (*Context, error) {
var dst Context

for key, value := range m {
if v, ok := value.(string); ok {
switch key {
case "DISK_ID":
n, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("invalid DISK_ID value %q: %w", v, err)
}
dst.DiskID = n
case "FIRMWARE":
dst.Firmware = v
case "GUESTOS":
dst.GuestOS = v
case "NETWORK":
b, err := api.Str2Bool(v)
if err != nil {
return nil, fmt.Errorf("invalid NETWORK value %q: %w", v, err)
}
dst.Network = b
case "SSH_PUBLIC_KEY":
dst.SSHPublicKey = v
case "TARGET":
dst.Target = v
}
err := dst.Set(key, value)
if err != nil {
return nil, err
}
}

return &dst, nil
}

// Set sets a key:value for the given context
// The key must match known fields and named with capital letters with underscores
// e.g. DISK_ID, SSH_PUBLIC_KEY, etc.
func (c *Context) Set(key string, value any) error {
return setContextValue(c, key, value)
}

func setContextValue(dst *Context, key string, value any) error {
if v, ok := value.(string); ok {
switch key {
case "DISK_ID":
n, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("invalid DISK_ID value %q: %w", v, err)
}
dst.DiskID = n
case "FIRMWARE":
dst.Firmware = v
case "GUESTOS":
dst.GuestOS = v
case "NETWORK":
b, err := api.Str2Bool(v)
if err != nil {
return fmt.Errorf("invalid NETWORK value %q: %w", v, err)
}
dst.Network = b
case "SSH_PUBLIC_KEY":
dst.SSHPublicKey = v
case "TARGET":
dst.Target = v
case "PROJECT_NAME":
dst.ProjectName = v
default:
return fmt.Errorf("unknown key: %s", key)
}
}

return nil
}

func newInstanceCPUModel(m map[string]any) *CPUModel {
var dst CPUModel

Expand Down

0 comments on commit b2e52a3

Please sign in to comment.