mirror of
https://github.com/jesseduffield/lazygit.git
synced 2025-07-31 14:24:25 +03:00
Return an error if node to be updated is not a scalar
This commit is contained in:
@ -29,7 +29,9 @@ func UpdateYamlValue(yamlBytes []byte, path []string, value string) ([]byte, err
|
|||||||
return yamlBytes, errors.New("yaml document is not a dictionary")
|
return yamlBytes, errors.New("yaml document is not a dictionary")
|
||||||
}
|
}
|
||||||
|
|
||||||
updateYamlNode(body, path, value)
|
if err := updateYamlNode(body, path, value); err != nil {
|
||||||
|
return yamlBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
// Convert the updated YAML node back to YAML bytes.
|
// Convert the updated YAML node back to YAML bytes.
|
||||||
updatedYAMLBytes, err := yaml.Marshal(body)
|
updatedYAMLBytes, err := yaml.Marshal(body)
|
||||||
@ -41,17 +43,19 @@ func UpdateYamlValue(yamlBytes []byte, path []string, value string) ([]byte, err
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Recursive function to update the YAML node.
|
// Recursive function to update the YAML node.
|
||||||
func updateYamlNode(node *yaml.Node, path []string, value string) {
|
func updateYamlNode(node *yaml.Node, path []string, value string) error {
|
||||||
if len(path) == 0 {
|
if len(path) == 0 {
|
||||||
|
if node.Kind != yaml.ScalarNode {
|
||||||
|
return errors.New("yaml node is not a scalar")
|
||||||
|
}
|
||||||
node.Value = value
|
node.Value = value
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
key := path[0]
|
key := path[0]
|
||||||
for i := 0; i < len(node.Content)-1; i += 2 {
|
for i := 0; i < len(node.Content)-1; i += 2 {
|
||||||
if node.Content[i].Value == key {
|
if node.Content[i].Value == key {
|
||||||
updateYamlNode(node.Content[i+1], path[1:], value)
|
return updateYamlNode(node.Content[i+1], path[1:], value)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,4 +67,5 @@ func updateYamlNode(node *yaml.Node, path []string, value string) {
|
|||||||
Kind: yaml.ScalarNode,
|
Kind: yaml.ScalarNode,
|
||||||
Value: value,
|
Value: value,
|
||||||
})
|
})
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -66,6 +66,14 @@ func TestUpdateYamlValue(t *testing.T) {
|
|||||||
expectedOut: "42\n",
|
expectedOut: "42\n",
|
||||||
expectedErr: "yaml document is not a dictionary",
|
expectedErr: "yaml document is not a dictionary",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "trying to update a note that is not a scalar",
|
||||||
|
in: "foo: [1, 2, 3]\n",
|
||||||
|
path: []string{"foo"},
|
||||||
|
value: "bar",
|
||||||
|
expectedOut: "foo: [1, 2, 3]\n",
|
||||||
|
expectedErr: "yaml node is not a scalar",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
|
Reference in New Issue
Block a user