RunSetVar executes the set var command logic
(f factory.Factory, cobraCmd *cobra.Command, args []string)
| 49 | |
| 50 | // RunSetVar executes the set var command logic |
| 51 | func (cmd *varCmd) RunSetVar(f factory.Factory, cobraCmd *cobra.Command, args []string) error { |
| 52 | // Set config root |
| 53 | log := f.GetLog() |
| 54 | configLoader, err := f.NewConfigLoader(cmd.ConfigPath) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | configExists, err := configLoader.SetDevSpaceRoot(log) |
| 59 | if err != nil { |
| 60 | return err |
| 61 | } |
| 62 | if !configExists { |
| 63 | return errors.New(message.ConfigNotFound) |
| 64 | } |
| 65 | |
| 66 | // Load config and find all variables in it |
| 67 | variableParser := &variableParser{} |
| 68 | c, err := configLoader.LoadWithParser(context.Background(), nil, nil, variableParser, cmd.ToConfigOptions(), log) |
| 69 | if err != nil { |
| 70 | return err |
| 71 | } |
| 72 | |
| 73 | // Set vars |
| 74 | for _, v := range args { |
| 75 | if v == "" { |
| 76 | continue |
| 77 | } |
| 78 | |
| 79 | // check if variable can be set |
| 80 | splitted := strings.SplitN(v, "=", 2) |
| 81 | if len(splitted) < 2 { |
| 82 | return errors.Errorf("Unexpected variable format. Expected key=value, got %s", v) |
| 83 | } else if variable.IsPredefinedVariable(splitted[0]) { |
| 84 | return errors.Errorf("cannot set predefined variable %s", splitted[0]) |
| 85 | } |
| 86 | |
| 87 | found := false |
| 88 | for _, u := range variableParser.Used { |
| 89 | if u.Name == splitted[0] { |
| 90 | found = true |
| 91 | break |
| 92 | } |
| 93 | } |
| 94 | if !found { |
| 95 | allowedVarsArr := []string{} |
| 96 | for _, v := range variableParser.Used { |
| 97 | allowedVarsArr = append(allowedVarsArr, v.Name) |
| 98 | } |
| 99 | |
| 100 | return errors.Errorf("variable %s is not allowed. Allowed vars: %+v", splitted[0], allowedVarsArr) |
| 101 | } |
| 102 | |
| 103 | // try to find it in definitions |
| 104 | for _, def := range variableParser.Definitions { |
| 105 | if def.Name == splitted[0] { |
| 106 | if def.Command != "" || len(def.Commands) > 0 || def.Source == latest.VariableSourceCommand || def.Source == latest.VariableSourceEnv || def.Source == latest.VariableSourceNone { |
| 107 | return errors.Errorf("cannot set variable %s, because variable is not loaded from cache. Please change variable type to cache it", def.Name) |
| 108 | } |
no test coverage detected