1
0
mirror of https://github.com/rancher/norman.git synced 2025-08-25 10:28:37 +00:00

Enhance Move and add SetValue

This commit is contained in:
Darren Shepherd 2017-11-15 16:40:20 -07:00
parent 80024df694
commit b69f96a775
2 changed files with 62 additions and 17 deletions

View File

@ -10,7 +10,9 @@ import (
)
type Move struct {
From, To string
From, To string
DestDefined bool
NoDeleteFromField bool
}
func (m Move) FromInternal(data map[string]interface{}) {
@ -26,22 +28,12 @@ func (m Move) ToInternal(data map[string]interface{}) {
}
func (m Move) ModifySchema(s *types.Schema, schemas *types.Schemas) error {
internalSchema, err := getInternal(s)
if err != nil {
return err
}
_, _, fromInternalField, ok, err := getField(internalSchema, schemas, m.From)
fromSchema, _, fromField, ok, err := getField(s, schemas, m.From)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("missing field %s on internal schema %s", m.From, internalSchema.ID)
}
fromSchema, _, _, _, err := getField(s, schemas, m.From)
if err != nil {
return err
return fmt.Errorf("failed to find field %s on schema %s", m.From, s.ID)
}
toSchema, toFieldName, toField, ok, err := getField(s, schemas, m.To)
@ -49,14 +41,18 @@ func (m Move) ModifySchema(s *types.Schema, schemas *types.Schemas) error {
return err
}
_, ok = toSchema.ResourceFields[toFieldName]
if ok && !strings.Contains(m.To, "/") {
if ok && !strings.Contains(m.To, "/") && !m.DestDefined {
return fmt.Errorf("field %s already exists on schema %s", m.To, s.ID)
}
delete(fromSchema.ResourceFields, m.From)
if !m.NoDeleteFromField {
delete(fromSchema.ResourceFields, m.From)
}
toField.CodeName = convert.Capitalize(toFieldName)
toSchema.ResourceFields[toFieldName] = fromInternalField
if !m.DestDefined {
toField.CodeName = convert.Capitalize(toFieldName)
toSchema.ResourceFields[toFieldName] = fromField
}
return nil
}

View File

@ -0,0 +1,49 @@
package mapper
import (
"fmt"
"strings"
"github.com/rancher/norman/types"
)
type SetValue struct {
From, To string
Value interface{}
IfEq interface{}
}
func (s SetValue) FromInternal(data map[string]interface{}) {
v, ok := GetValue(data, strings.Split(s.From, "/")...)
if !ok {
return
}
if v == s.IfEq {
PutValue(data, s.Value, strings.Split(s.To, "/")...)
}
}
func (s SetValue) ToInternal(data map[string]interface{}) {
v, ok := GetValue(data, strings.Split(s.To, "/")...)
if !ok {
return
}
if v == s.Value {
PutValue(data, s.IfEq, strings.Split(s.From, "/")...)
}
}
func (s SetValue) ModifySchema(schema *types.Schema, schemas *types.Schemas) error {
_, _, _, ok, err := getField(schema, schemas, s.To)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("failed to find defined field for %s on schemas %s", s.To, schema.ID)
}
return nil
}