mirror of
https://github.com/taigrr/yq
synced 2025-01-18 04:53:17 -08:00
Compare commits
16 Commits
3.2.3
...
new-merge2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88e99e5336 | ||
|
|
a8cfccd3af | ||
|
|
3355e80d85 | ||
|
|
f528b28938 | ||
|
|
5b7b390a33 | ||
|
|
4f12e09e78 | ||
|
|
ee732fbf0b | ||
|
|
1507f929a2 | ||
|
|
fea8510061 | ||
|
|
b380ea2892 | ||
|
|
d66a709213 | ||
|
|
2fc39b3865 | ||
|
|
ee07edbd88 | ||
|
|
b11661a1be | ||
|
|
eac218980e | ||
|
|
80e7f46538 |
13
README.md
13
README.md
@@ -23,7 +23,16 @@ brew install yq
|
|||||||
```
|
```
|
||||||
choco install yq
|
choco install yq
|
||||||
```
|
```
|
||||||
Supported by @chillum
|
Supported by @chillum (https://chocolatey.org/packages/yq)
|
||||||
|
|
||||||
|
### Alpine Linux
|
||||||
|
- Enable community repo by adding ```$MIRROR/alpine/v$VERSION/community``` to ```/etc/apk/repositories```
|
||||||
|
- Update database index with ```apk update```
|
||||||
|
- Install yq with ```apk add yq```
|
||||||
|
|
||||||
|
Supported by Tuan Hoang
|
||||||
|
https://pkgs.alpinelinux.org/package/edge/community/x86/yq
|
||||||
|
|
||||||
|
|
||||||
### Ubuntu and other Linux distros supporting `snap` packages:
|
### Ubuntu and other Linux distros supporting `snap` packages:
|
||||||
```
|
```
|
||||||
@@ -55,7 +64,7 @@ sudo add-apt-repository ppa:rmescandon/yq
|
|||||||
sudo apt update
|
sudo apt update
|
||||||
sudo apt install yq -y
|
sudo apt install yq -y
|
||||||
```
|
```
|
||||||
Supported by @rmescandon
|
Supported by @rmescandon (https://launchpad.net/~rmescandon/+archive/ubuntu/yq)
|
||||||
|
|
||||||
### Go Get:
|
### Go Get:
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ var defaultValue = ""
|
|||||||
var indent = 2
|
var indent = 2
|
||||||
var overwriteFlag = false
|
var overwriteFlag = false
|
||||||
var autoCreateFlag = true
|
var autoCreateFlag = true
|
||||||
var appendFlag = false
|
var arrayMergeStrategyFlag = "update"
|
||||||
|
var commentsMergeStrategyFlag = "setWhenBlank"
|
||||||
var verbose = false
|
var verbose = false
|
||||||
var version = false
|
var version = false
|
||||||
var docIndex = "0"
|
var docIndex = "0"
|
||||||
|
|||||||
66
cmd/merge.go
66
cmd/merge.go
@@ -11,14 +11,14 @@ func createMergeCmd() *cobra.Command {
|
|||||||
var cmdMerge = &cobra.Command{
|
var cmdMerge = &cobra.Command{
|
||||||
Use: "merge [initial_yaml_file] [additional_yaml_file]...",
|
Use: "merge [initial_yaml_file] [additional_yaml_file]...",
|
||||||
Aliases: []string{"m"},
|
Aliases: []string{"m"},
|
||||||
Short: "yq m [--inplace/-i] [--doc/-d index] [--overwrite/-x] [--append/-a] sample.yaml sample2.yaml",
|
Short: "yq m [--inplace/-i] [--doc/-d index] [--overwrite/-x] [--arrayMerge/-a strategy] sample.yaml sample2.yaml",
|
||||||
Example: `
|
Example: `
|
||||||
yq merge things.yaml other.yaml
|
yq merge things.yaml other.yaml
|
||||||
yq merge --inplace things.yaml other.yaml
|
yq merge --inplace things.yaml other.yaml
|
||||||
yq m -i things.yaml other.yaml
|
yq m -i things.yaml other.yaml
|
||||||
yq m --overwrite things.yaml other.yaml
|
yq m --overwrite things.yaml other.yaml
|
||||||
yq m -i -x things.yaml other.yaml
|
yq m -i -x things.yaml other.yaml
|
||||||
yq m -i -a things.yaml other.yaml
|
yq m -i -a=append things.yaml other.yaml
|
||||||
yq m -i --autocreate=false things.yaml other.yaml
|
yq m -i --autocreate=false things.yaml other.yaml
|
||||||
`,
|
`,
|
||||||
Long: `Updates the yaml file by adding/updating the path(s) and value(s) from additional yaml file(s).
|
Long: `Updates the yaml file by adding/updating the path(s) and value(s) from additional yaml file(s).
|
||||||
@@ -32,7 +32,17 @@ If append flag is set then existing arrays will be merged with the arrays from e
|
|||||||
cmdMerge.PersistentFlags().BoolVarP(&writeInplace, "inplace", "i", false, "update the yaml file inplace")
|
cmdMerge.PersistentFlags().BoolVarP(&writeInplace, "inplace", "i", false, "update the yaml file inplace")
|
||||||
cmdMerge.PersistentFlags().BoolVarP(&overwriteFlag, "overwrite", "x", false, "update the yaml file by overwriting existing values")
|
cmdMerge.PersistentFlags().BoolVarP(&overwriteFlag, "overwrite", "x", false, "update the yaml file by overwriting existing values")
|
||||||
cmdMerge.PersistentFlags().BoolVarP(&autoCreateFlag, "autocreate", "c", true, "automatically create any missing entries")
|
cmdMerge.PersistentFlags().BoolVarP(&autoCreateFlag, "autocreate", "c", true, "automatically create any missing entries")
|
||||||
cmdMerge.PersistentFlags().BoolVarP(&appendFlag, "append", "a", false, "update the yaml file by appending array values")
|
cmdMerge.PersistentFlags().StringVarP(&arrayMergeStrategyFlag, "arrays", "a", "update", `array merge strategy (update/append/overwrite)
|
||||||
|
update: recursively update arrays by their index
|
||||||
|
append: concatenate arrays together
|
||||||
|
overwrite: replace arrays
|
||||||
|
`)
|
||||||
|
cmdMerge.PersistentFlags().StringVarP(&commentsMergeStrategyFlag, "comments", "", "setWhenBlank", `comments merge strategy (setWhenBlank/ignore/append/overwrite)
|
||||||
|
setWhenBlank: set comment if the original document has no comment at that node
|
||||||
|
ignore: leave comments as-is in the original
|
||||||
|
append: append comments together
|
||||||
|
overwrite: overwrite comments completely
|
||||||
|
`)
|
||||||
cmdMerge.PersistentFlags().StringVarP(&docIndex, "doc", "d", "0", "process document index number (0 based, * for all documents)")
|
cmdMerge.PersistentFlags().StringVarP(&docIndex, "doc", "d", "0", "process document index number (0 based, * for all documents)")
|
||||||
return cmdMerge
|
return cmdMerge
|
||||||
}
|
}
|
||||||
@@ -41,9 +51,9 @@ If append flag is set then existing arrays will be merged with the arrays from e
|
|||||||
* We don't deeply traverse arrays when appending a merge, instead we want to
|
* We don't deeply traverse arrays when appending a merge, instead we want to
|
||||||
* append the entire array element.
|
* append the entire array element.
|
||||||
*/
|
*/
|
||||||
func createReadFunctionForMerge() func(*yaml.Node) ([]*yqlib.NodeContext, error) {
|
func createReadFunctionForMerge(arrayMergeStrategy yqlib.ArrayMergeStrategy) func(*yaml.Node) ([]*yqlib.NodeContext, error) {
|
||||||
return func(dataBucket *yaml.Node) ([]*yqlib.NodeContext, error) {
|
return func(dataBucket *yaml.Node) ([]*yqlib.NodeContext, error) {
|
||||||
return lib.Get(dataBucket, "**", !appendFlag)
|
return lib.GetForMerge(dataBucket, "**", arrayMergeStrategy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,19 +63,59 @@ func mergeProperties(cmd *cobra.Command, args []string) error {
|
|||||||
if len(args) < 1 {
|
if len(args) < 1 {
|
||||||
return errors.New("Must provide at least 1 yaml file")
|
return errors.New("Must provide at least 1 yaml file")
|
||||||
}
|
}
|
||||||
|
var arrayMergeStrategy yqlib.ArrayMergeStrategy
|
||||||
|
|
||||||
|
switch arrayMergeStrategyFlag {
|
||||||
|
case "update":
|
||||||
|
arrayMergeStrategy = yqlib.UpdateArrayMergeStrategy
|
||||||
|
case "append":
|
||||||
|
arrayMergeStrategy = yqlib.AppendArrayMergeStrategy
|
||||||
|
case "overwrite":
|
||||||
|
arrayMergeStrategy = yqlib.OverwriteArrayMergeStrategy
|
||||||
|
default:
|
||||||
|
return errors.New("Array merge strategy must be one of: update/append/overwrite")
|
||||||
|
}
|
||||||
|
|
||||||
|
var commentsMergeStrategy yqlib.CommentsMergeStrategy
|
||||||
|
|
||||||
|
switch commentsMergeStrategyFlag {
|
||||||
|
case "setWhenBlank":
|
||||||
|
commentsMergeStrategy = yqlib.SetWhenBlankCommentsMergeStrategy
|
||||||
|
case "ignore":
|
||||||
|
commentsMergeStrategy = yqlib.IgnoreCommentsMergeStrategy
|
||||||
|
case "append":
|
||||||
|
commentsMergeStrategy = yqlib.AppendCommentsMergeStrategy
|
||||||
|
case "overwrite":
|
||||||
|
commentsMergeStrategy = yqlib.OverwriteCommentsMergeStrategy
|
||||||
|
default:
|
||||||
|
return errors.New("Comments merge strategy must be one of: setWhenBlank/ignore/append/overwrite")
|
||||||
|
}
|
||||||
|
|
||||||
if len(args) > 1 {
|
if len(args) > 1 {
|
||||||
// first generate update commands from the file
|
// first generate update commands from the file
|
||||||
var filesToMerge = args[1:]
|
var filesToMerge = args[1:]
|
||||||
|
|
||||||
for _, fileToMerge := range filesToMerge {
|
for _, fileToMerge := range filesToMerge {
|
||||||
matchingNodes, errorProcessingFile := doReadYamlFile(fileToMerge, createReadFunctionForMerge(), false, 0)
|
matchingNodes, errorProcessingFile := doReadYamlFile(fileToMerge, createReadFunctionForMerge(arrayMergeStrategy), false, 0)
|
||||||
if errorProcessingFile != nil {
|
if errorProcessingFile != nil {
|
||||||
return errorProcessingFile
|
return errorProcessingFile
|
||||||
}
|
}
|
||||||
|
log.Debugf("finished reading for merge!")
|
||||||
for _, matchingNode := range matchingNodes {
|
for _, matchingNode := range matchingNodes {
|
||||||
mergePath := lib.MergePathStackToString(matchingNode.PathStack, appendFlag)
|
log.Debugf("matched node %v", lib.PathStackToString(matchingNode.PathStack))
|
||||||
updateCommands = append(updateCommands, yqlib.UpdateCommand{Command: "update", Path: mergePath, Value: matchingNode.Node, Overwrite: overwriteFlag})
|
yqlib.DebugNode(matchingNode.Node)
|
||||||
|
}
|
||||||
|
for _, matchingNode := range matchingNodes {
|
||||||
|
mergePath := lib.MergePathStackToString(matchingNode.PathStack, arrayMergeStrategy)
|
||||||
|
updateCommands = append(updateCommands, yqlib.UpdateCommand{
|
||||||
|
Command: "merge",
|
||||||
|
Path: mergePath,
|
||||||
|
Value: matchingNode.Node,
|
||||||
|
Overwrite: overwriteFlag,
|
||||||
|
CommentsMergeStrategy: commentsMergeStrategy,
|
||||||
|
// dont update the content for nodes midway, only leaf nodes
|
||||||
|
DontUpdateNodeContent: matchingNode.IsMiddleNode && (arrayMergeStrategy != yqlib.OverwriteArrayMergeStrategy || matchingNode.Node.Kind != yaml.SequenceNode),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ func TestMergeOverwriteCmd(t *testing.T) {
|
|||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
t.Error(result.Error)
|
t.Error(result.Error)
|
||||||
}
|
}
|
||||||
expectedOutput := `a: other # better than the original
|
expectedOutput := `a: other # just the best
|
||||||
b: [3, 4]
|
b: [3, 4]
|
||||||
c:
|
c:
|
||||||
test: 1
|
test: 1
|
||||||
@@ -68,9 +68,36 @@ c:
|
|||||||
test.AssertResult(t, expectedOutput, result.Output)
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMergeOverwriteDeepExampleCmd(t *testing.T) {
|
||||||
|
content := `c:
|
||||||
|
test: 1
|
||||||
|
thing: whatever
|
||||||
|
`
|
||||||
|
filename := test.WriteTempYamlFile(content)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeContent := `c:
|
||||||
|
test: 5
|
||||||
|
`
|
||||||
|
mergeFilename := test.WriteTempYamlFile(mergeContent)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --autocreate=false --overwrite %s %s", filename, mergeFilename))
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedOutput := `c:
|
||||||
|
test: 5
|
||||||
|
thing: whatever
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
func TestMergeAppendCmd(t *testing.T) {
|
func TestMergeAppendCmd(t *testing.T) {
|
||||||
cmd := getRootCommand()
|
cmd := getRootCommand()
|
||||||
result := test.RunCmd(cmd, "merge --autocreate=false --append ../examples/data1.yaml ../examples/data2.yaml")
|
result := test.RunCmd(cmd, "merge --autocreate=false --arrays=append ../examples/data1.yaml ../examples/data2.yaml")
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
t.Error(result.Error)
|
t.Error(result.Error)
|
||||||
}
|
}
|
||||||
@@ -96,7 +123,7 @@ func TestMergeAppendArraysCmd(t *testing.T) {
|
|||||||
defer test.RemoveTempYamlFile(mergeFilename)
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
cmd := getRootCommand()
|
cmd := getRootCommand()
|
||||||
result := test.RunCmd(cmd, fmt.Sprintf("merge --append -d* %s %s", filename, mergeFilename))
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --arrays=append -d* %s %s", filename, mergeFilename))
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
t.Error(result.Error)
|
t.Error(result.Error)
|
||||||
}
|
}
|
||||||
@@ -109,13 +136,56 @@ func TestMergeAppendArraysCmd(t *testing.T) {
|
|||||||
test.AssertResult(t, expectedOutput, result.Output)
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMergeOverwriteAndAppendCmd(t *testing.T) {
|
func TestMergeAliasArraysCmd(t *testing.T) {
|
||||||
|
content := `
|
||||||
|
vars:
|
||||||
|
variable1: &var1 cat
|
||||||
|
|
||||||
|
usage:
|
||||||
|
value1: *var1
|
||||||
|
valueAnother: *var1
|
||||||
|
valuePlain: thing
|
||||||
|
`
|
||||||
|
filename := test.WriteTempYamlFile(content)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeContent := `
|
||||||
|
vars:
|
||||||
|
variable2: &var2 puppy
|
||||||
|
|
||||||
|
usage:
|
||||||
|
value2: *var2
|
||||||
|
valueAnother: *var2
|
||||||
|
valuePlain: *var2
|
||||||
|
`
|
||||||
|
|
||||||
|
mergeFilename := test.WriteTempYamlFile(mergeContent)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
cmd := getRootCommand()
|
cmd := getRootCommand()
|
||||||
result := test.RunCmd(cmd, "merge --autocreate=false --append --overwrite ../examples/data1.yaml ../examples/data2.yaml")
|
result := test.RunCmd(cmd, fmt.Sprintf("merge -x %s %s", filename, mergeFilename))
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
t.Error(result.Error)
|
t.Error(result.Error)
|
||||||
}
|
}
|
||||||
expectedOutput := `a: other # better than the original
|
expectedOutput := `vars:
|
||||||
|
variable1: &var1 cat
|
||||||
|
variable2: &var2 puppy
|
||||||
|
usage:
|
||||||
|
value1: *var1
|
||||||
|
valueAnother: *var2
|
||||||
|
valuePlain: *var2
|
||||||
|
value2: *var2
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeOverwriteAndAppendCmd(t *testing.T) {
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, "merge --autocreate=false --arrays=append --overwrite ../examples/data1.yaml ../examples/data2.yaml")
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
expectedOutput := `a: other # just the best
|
||||||
b: [1, 2, 3, 4]
|
b: [1, 2, 3, 4]
|
||||||
c:
|
c:
|
||||||
test: 1
|
test: 1
|
||||||
@@ -123,13 +193,148 @@ c:
|
|||||||
test.AssertResult(t, expectedOutput, result.Output)
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMergeArraysCmd(t *testing.T) {
|
var commentContentA = `
|
||||||
|
a: valueA1 # commentA1
|
||||||
|
b: valueB1
|
||||||
|
`
|
||||||
|
|
||||||
|
var commentContentB = `
|
||||||
|
a: valueA2 # commentA2
|
||||||
|
b: valueB2 # commentB2
|
||||||
|
c: valueC2 # commentC2
|
||||||
|
`
|
||||||
|
|
||||||
|
func TestMergeCommentsSetWhenBlankCmd(t *testing.T) {
|
||||||
|
filename := test.WriteTempYamlFile(commentContentA)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeFilename := test.WriteTempYamlFile(commentContentB)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
cmd := getRootCommand()
|
cmd := getRootCommand()
|
||||||
result := test.RunCmd(cmd, "merge --append ../examples/sample_array.yaml ../examples/sample_array_2.yaml")
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --comments=setWhenBlank %s %s", filename, mergeFilename))
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
t.Error(result.Error)
|
t.Error(result.Error)
|
||||||
}
|
}
|
||||||
expectedOutput := `[1, 2, 3, 4, 5]
|
|
||||||
|
expectedOutput := `a: valueA1 # commentA1
|
||||||
|
b: valueB1 # commentB2
|
||||||
|
c: valueC2 # commentC2
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeCommentsIgnoreCmd(t *testing.T) {
|
||||||
|
filename := test.WriteTempYamlFile(commentContentA)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeFilename := test.WriteTempYamlFile(commentContentB)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --comments=ignore %s %s", filename, mergeFilename))
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedOutput := `a: valueA1 # commentA1
|
||||||
|
b: valueB1
|
||||||
|
c: valueC2
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeCommentsAppendCmd(t *testing.T) {
|
||||||
|
filename := test.WriteTempYamlFile(commentContentA)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeFilename := test.WriteTempYamlFile(commentContentB)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --comments=append %s %s", filename, mergeFilename))
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedOutput := `a: valueA1 # commentA1 # commentA2
|
||||||
|
b: valueB1 # commentB2
|
||||||
|
c: valueC2 # commentC2
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeCommentsOverwriteCmd(t *testing.T) {
|
||||||
|
filename := test.WriteTempYamlFile(commentContentA)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeFilename := test.WriteTempYamlFile(commentContentB)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --comments=overwrite %s %s", filename, mergeFilename))
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedOutput := `a: valueA1 # commentA2
|
||||||
|
b: valueB1 # commentB2
|
||||||
|
c: valueC2 # commentC2
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeOverwriteArraysTooCmd(t *testing.T) {
|
||||||
|
content := `a: simple # just the best
|
||||||
|
b: [1, 2]
|
||||||
|
c:
|
||||||
|
test: 1
|
||||||
|
`
|
||||||
|
filename := test.WriteTempYamlFile(content)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
mergeContent := `a: things
|
||||||
|
b: [6]`
|
||||||
|
mergeFilename := test.WriteTempYamlFile(mergeContent)
|
||||||
|
defer test.RemoveTempYamlFile(mergeFilename)
|
||||||
|
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, fmt.Sprintf("merge --autocreate=false --arrays=overwrite --overwrite %s %s", filename, mergeFilename))
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedOutput := `a: things # just the best
|
||||||
|
b: [6]
|
||||||
|
c:
|
||||||
|
test: 1
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeRootArraysCmd(t *testing.T) {
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, "merge --arrays=append ../examples/sample_array.yaml ../examples/sample_array_2.yaml")
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
expectedOutput := `- 1
|
||||||
|
- 2
|
||||||
|
- 3
|
||||||
|
- 4
|
||||||
|
- 5
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeOverwriteArraysCmd(t *testing.T) {
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, "merge --arrays=overwrite ../examples/sample_array.yaml ../examples/sample_array_2.yaml")
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
expectedOutput := `- 4
|
||||||
|
- 5
|
||||||
`
|
`
|
||||||
test.AssertResult(t, expectedOutput, result.Output)
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
}
|
}
|
||||||
@@ -145,9 +350,7 @@ func TestMergeCmd_Multi(t *testing.T) {
|
|||||||
another:
|
another:
|
||||||
document: here
|
document: here
|
||||||
a: simple # just the best
|
a: simple # just the best
|
||||||
b:
|
b: [1, 2]
|
||||||
- 1
|
|
||||||
- 2
|
|
||||||
c:
|
c:
|
||||||
test: 1
|
test: 1
|
||||||
---
|
---
|
||||||
@@ -316,9 +519,7 @@ func TestMergeAllowEmptyTargetCmd(t *testing.T) {
|
|||||||
t.Error(result.Error)
|
t.Error(result.Error)
|
||||||
}
|
}
|
||||||
expectedOutput := `a: simple # just the best
|
expectedOutput := `a: simple # just the best
|
||||||
b:
|
b: [1, 2]
|
||||||
- 1
|
|
||||||
- 2
|
|
||||||
c:
|
c:
|
||||||
test: 1
|
test: 1
|
||||||
`
|
`
|
||||||
|
|||||||
@@ -94,6 +94,28 @@ func TestReadUnwrapJsonByDefaultCmd(t *testing.T) {
|
|||||||
test.AssertResult(t, "\"frog\"\n", result.Output)
|
test.AssertResult(t, "\"frog\"\n", result.Output)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReadOutputJsonNonStringKeysCmd(t *testing.T) {
|
||||||
|
|
||||||
|
content := `
|
||||||
|
true: true
|
||||||
|
5:
|
||||||
|
null:
|
||||||
|
0.1: deeply
|
||||||
|
false: things`
|
||||||
|
filename := test.WriteTempYamlFile(content)
|
||||||
|
defer test.RemoveTempYamlFile(filename)
|
||||||
|
|
||||||
|
cmd := getRootCommand()
|
||||||
|
result := test.RunCmd(cmd, fmt.Sprintf("read %s -j", filename))
|
||||||
|
|
||||||
|
if result.Error != nil {
|
||||||
|
t.Error(result.Error)
|
||||||
|
}
|
||||||
|
expectedOutput := `{"5":{"null":{"0.1":"deeply","false":"things"}},"true":true}
|
||||||
|
`
|
||||||
|
test.AssertResult(t, expectedOutput, result.Output)
|
||||||
|
}
|
||||||
|
|
||||||
func TestReadWithAdvancedFilterCmd(t *testing.T) {
|
func TestReadWithAdvancedFilterCmd(t *testing.T) {
|
||||||
cmd := getRootCommand()
|
cmd := getRootCommand()
|
||||||
result := test.RunCmd(cmd, "read ../examples/sample.yaml b.e(name==sam).value")
|
result := test.RunCmd(cmd, "read ../examples/sample.yaml b.e(name==sam).value")
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type readDataFn func(dataBucket *yaml.Node) ([]*yqlib.NodeContext, error)
|
|||||||
|
|
||||||
func createReadFunction(path string) func(*yaml.Node) ([]*yqlib.NodeContext, error) {
|
func createReadFunction(path string) func(*yaml.Node) ([]*yqlib.NodeContext, error) {
|
||||||
return func(dataBucket *yaml.Node) ([]*yqlib.NodeContext, error) {
|
return func(dataBucket *yaml.Node) ([]*yqlib.NodeContext, error) {
|
||||||
return lib.Get(dataBucket, path, true)
|
return lib.Get(dataBucket, path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,7 +512,7 @@ func readUpdateCommands(args []string, expectedArgs int, badArgsMessage string,
|
|||||||
log.Debug("path %v", args[expectedArgs-2])
|
log.Debug("path %v", args[expectedArgs-2])
|
||||||
log.Debug("Value %v", args[expectedArgs-1])
|
log.Debug("Value %v", args[expectedArgs-1])
|
||||||
value := valueParser.Parse(args[expectedArgs-1], customTag, customStyle, anchorName, makeAlias)
|
value := valueParser.Parse(args[expectedArgs-1], customTag, customStyle, anchorName, makeAlias)
|
||||||
updateCommands[0] = yqlib.UpdateCommand{Command: "update", Path: args[expectedArgs-2], Value: value, Overwrite: true, DontUpdateComments: true}
|
updateCommands[0] = yqlib.UpdateCommand{Command: "update", Path: args[expectedArgs-2], Value: value, Overwrite: true, CommentsMergeStrategy: yqlib.IgnoreCommentsMergeStrategy}
|
||||||
} else if len(args) == expectedArgs-1 && allowNoValue {
|
} else if len(args) == expectedArgs-1 && allowNoValue {
|
||||||
// don't update the value
|
// don't update the value
|
||||||
updateCommands = make([]yqlib.UpdateCommand, 1)
|
updateCommands = make([]yqlib.UpdateCommand, 1)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ var (
|
|||||||
GitDescribe string
|
GitDescribe string
|
||||||
|
|
||||||
// Version is main version number that is being run at the moment.
|
// Version is main version number that is being run at the moment.
|
||||||
Version = "3.3.3"
|
Version = "3.3.4"
|
||||||
|
|
||||||
// VersionPrerelease is a pre-release marker for the version. If this is "" (empty string)
|
// VersionPrerelease is a pre-release marker for the version. If this is "" (empty string)
|
||||||
// then it means that it is a final release. Otherwise, this is a pre-release
|
// then it means that it is a final release. Otherwise, this is a pre-release
|
||||||
|
|||||||
@@ -22,13 +22,8 @@ func NewDataNavigator(NavigationStrategy NavigationStrategy) DataNavigator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (n *navigator) Traverse(value *yaml.Node, path []interface{}) error {
|
func (n *navigator) Traverse(value *yaml.Node, path []interface{}) error {
|
||||||
realValue := value
|
|
||||||
emptyArray := make([]interface{}, 0)
|
emptyArray := make([]interface{}, 0)
|
||||||
log.Debugf("Traversing path %v", pathStackToString(path))
|
log.Debugf("Traversing path %v", pathStackToString(path))
|
||||||
if realValue.Kind == yaml.DocumentNode {
|
|
||||||
log.Debugf("its a document! returning the first child")
|
|
||||||
return n.doTraverse(value.Content[0], "", path, emptyArray)
|
|
||||||
}
|
|
||||||
return n.doTraverse(value, "", path, emptyArray)
|
return n.doTraverse(value, "", path, emptyArray)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +34,8 @@ func (n *navigator) doTraverse(value *yaml.Node, head interface{}, tail []interf
|
|||||||
var nodeContext = NewNodeContext(value, head, tail, pathStack)
|
var nodeContext = NewNodeContext(value, head, tail, pathStack)
|
||||||
|
|
||||||
var errorDeepSplatting error
|
var errorDeepSplatting error
|
||||||
if head == "**" && value.Kind != yaml.ScalarNode && n.navigationStrategy.ShouldDeeplyTraverse(nodeContext) {
|
// no need to deeply traverse the DocumentNode, as it's already covered by its first child.
|
||||||
|
if head == "**" && value.Kind != yaml.DocumentNode && value.Kind != yaml.ScalarNode && n.navigationStrategy.ShouldDeeplyTraverse(nodeContext) {
|
||||||
if len(pathStack) == 0 || pathStack[len(pathStack)-1] != "<<" {
|
if len(pathStack) == 0 || pathStack[len(pathStack)-1] != "<<" {
|
||||||
errorDeepSplatting = n.recurse(value, head, tail, pathStack)
|
errorDeepSplatting = n.recurse(value, head, tail, pathStack)
|
||||||
}
|
}
|
||||||
@@ -51,7 +47,11 @@ func (n *navigator) doTraverse(value *yaml.Node, head interface{}, tail []interf
|
|||||||
return errorDeepSplatting
|
return errorDeepSplatting
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(tail) > 0 && value.Kind != yaml.ScalarNode {
|
if value.Kind == yaml.DocumentNode {
|
||||||
|
log.Debugf("its a document, diving into %v", head)
|
||||||
|
DebugNode(value)
|
||||||
|
return n.recurse(value, head, tail, pathStack)
|
||||||
|
} else if len(tail) > 0 && value.Kind != yaml.ScalarNode {
|
||||||
log.Debugf("diving into %v", tail[0])
|
log.Debugf("diving into %v", tail[0])
|
||||||
DebugNode(value)
|
DebugNode(value)
|
||||||
return n.recurse(value, tail[0], tail[1:], pathStack)
|
return n.recurse(value, tail[0], tail[1:], pathStack)
|
||||||
@@ -73,6 +73,7 @@ func (n *navigator) recurse(value *yaml.Node, head interface{}, tail []interface
|
|||||||
nodeContext := NewNodeContext(value, head, tail, pathStack)
|
nodeContext := NewNodeContext(value, head, tail, pathStack)
|
||||||
|
|
||||||
if head == "**" && !n.navigationStrategy.ShouldOnlyDeeplyVisitLeaves(nodeContext) {
|
if head == "**" && !n.navigationStrategy.ShouldOnlyDeeplyVisitLeaves(nodeContext) {
|
||||||
|
nodeContext.IsMiddleNode = true
|
||||||
errorVisitingDeeply := n.navigationStrategy.Visit(nodeContext)
|
errorVisitingDeeply := n.navigationStrategy.Visit(nodeContext)
|
||||||
if errorVisitingDeeply != nil {
|
if errorVisitingDeeply != nil {
|
||||||
return errorVisitingDeeply
|
return errorVisitingDeeply
|
||||||
@@ -108,6 +109,8 @@ func (n *navigator) recurse(value *yaml.Node, head interface{}, tail []interface
|
|||||||
return n.recurse(value.Alias, head, tail, pathStack)
|
return n.recurse(value.Alias, head, tail, pathStack)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
case yaml.DocumentNode:
|
||||||
|
return n.doTraverse(value.Content[0], head, tail, pathStack)
|
||||||
default:
|
default:
|
||||||
return n.navigationStrategy.Visit(nodeContext)
|
return n.navigationStrategy.Visit(nodeContext)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,21 @@ type jsonEncoder struct {
|
|||||||
encoder *json.Encoder
|
encoder *json.Encoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mapKeysToStrings(node *yaml.Node) {
|
||||||
|
|
||||||
|
if node.Kind == yaml.MappingNode {
|
||||||
|
for index, child := range node.Content {
|
||||||
|
if index%2 == 0 { // its a map key
|
||||||
|
child.Tag = "!!str"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, child := range node.Content {
|
||||||
|
mapKeysToStrings(child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func NewJsonEncoder(destination io.Writer, prettyPrint bool, indent int) Encoder {
|
func NewJsonEncoder(destination io.Writer, prettyPrint bool, indent int) Encoder {
|
||||||
var encoder = json.NewEncoder(destination)
|
var encoder = json.NewEncoder(destination)
|
||||||
var indentString = ""
|
var indentString = ""
|
||||||
@@ -73,6 +88,8 @@ func NewJsonEncoder(destination io.Writer, prettyPrint bool, indent int) Encoder
|
|||||||
|
|
||||||
func (je *jsonEncoder) Encode(node *yaml.Node) error {
|
func (je *jsonEncoder) Encode(node *yaml.Node) error {
|
||||||
var dataBucket interface{}
|
var dataBucket interface{}
|
||||||
|
// firstly, convert all map keys to strings
|
||||||
|
mapKeysToStrings(node)
|
||||||
errorDecoding := node.Decode(&dataBucket)
|
errorDecoding := node.Decode(&dataBucket)
|
||||||
if errorDecoding != nil {
|
if errorDecoding != nil {
|
||||||
return errorDecoding
|
return errorDecoding
|
||||||
|
|||||||
@@ -13,12 +13,13 @@ import (
|
|||||||
var log = logging.MustGetLogger("yq")
|
var log = logging.MustGetLogger("yq")
|
||||||
|
|
||||||
type UpdateCommand struct {
|
type UpdateCommand struct {
|
||||||
Command string
|
Command string
|
||||||
Path string
|
Path string
|
||||||
Value *yaml.Node
|
Value *yaml.Node
|
||||||
Overwrite bool
|
Overwrite bool
|
||||||
DontUpdateNodeValue bool
|
DontUpdateNodeValue bool
|
||||||
DontUpdateComments bool
|
DontUpdateNodeContent bool
|
||||||
|
CommentsMergeStrategy CommentsMergeStrategy
|
||||||
}
|
}
|
||||||
|
|
||||||
func KindString(kind yaml.Kind) string {
|
func KindString(kind yaml.Kind) string {
|
||||||
@@ -50,20 +51,23 @@ func DebugNode(value *yaml.Node) {
|
|||||||
}
|
}
|
||||||
encoder.Close()
|
encoder.Close()
|
||||||
log.Debug("Tag: %v, Kind: %v, Anchor: %v", value.Tag, KindString(value.Kind), value.Anchor)
|
log.Debug("Tag: %v, Kind: %v, Anchor: %v", value.Tag, KindString(value.Kind), value.Anchor)
|
||||||
log.Debug("%v", buf.String())
|
log.Debug("Head Comment: %v", value.HeadComment)
|
||||||
|
log.Debug("Line Comment: %v", value.LineComment)
|
||||||
|
log.Debug("FootComment Comment: %v", value.FootComment)
|
||||||
|
log.Debug("\n%v", buf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func pathStackToString(pathStack []interface{}) string {
|
func pathStackToString(pathStack []interface{}) string {
|
||||||
return mergePathStackToString(pathStack, false)
|
return mergePathStackToString(pathStack, UpdateArrayMergeStrategy)
|
||||||
}
|
}
|
||||||
|
|
||||||
func mergePathStackToString(pathStack []interface{}, appendArrays bool) string {
|
func mergePathStackToString(pathStack []interface{}, arrayMergeStrategy ArrayMergeStrategy) string {
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
for index, path := range pathStack {
|
for index, path := range pathStack {
|
||||||
switch path.(type) {
|
switch path.(type) {
|
||||||
case int, int64:
|
case int, int64:
|
||||||
if appendArrays {
|
if arrayMergeStrategy == AppendArrayMergeStrategy {
|
||||||
sb.WriteString("[+]")
|
sb.WriteString("[+]")
|
||||||
} else {
|
} else {
|
||||||
sb.WriteString(fmt.Sprintf("[%v]", path))
|
sb.WriteString(fmt.Sprintf("[%v]", path))
|
||||||
@@ -94,9 +98,7 @@ func mergePathStackToString(pathStack []interface{}, appendArrays bool) string {
|
|||||||
sb.WriteString(".")
|
sb.WriteString(".")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var pathString = sb.String()
|
return sb.String()
|
||||||
log.Debug("got a path string: %v", pathString)
|
|
||||||
return pathString
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func guessKind(head interface{}, tail []interface{}, guess yaml.Kind) yaml.Kind {
|
func guessKind(head interface{}, tail []interface{}, guess yaml.Kind) yaml.Kind {
|
||||||
@@ -134,12 +136,13 @@ func guessKind(head interface{}, tail []interface{}, guess yaml.Kind) yaml.Kind
|
|||||||
}
|
}
|
||||||
|
|
||||||
type YqLib interface {
|
type YqLib interface {
|
||||||
Get(rootNode *yaml.Node, path string, deeplyTraverseArrays bool) ([]*NodeContext, error)
|
Get(rootNode *yaml.Node, path string) ([]*NodeContext, error)
|
||||||
|
GetForMerge(rootNode *yaml.Node, path string, arrayMergeStrategy ArrayMergeStrategy) ([]*NodeContext, error)
|
||||||
Update(rootNode *yaml.Node, updateCommand UpdateCommand, autoCreate bool) error
|
Update(rootNode *yaml.Node, updateCommand UpdateCommand, autoCreate bool) error
|
||||||
New(path string) yaml.Node
|
New(path string) yaml.Node
|
||||||
|
|
||||||
PathStackToString(pathStack []interface{}) string
|
PathStackToString(pathStack []interface{}) string
|
||||||
MergePathStackToString(pathStack []interface{}, appendArrays bool) string
|
MergePathStackToString(pathStack []interface{}, arrayMergeStrategy ArrayMergeStrategy) string
|
||||||
}
|
}
|
||||||
|
|
||||||
type lib struct {
|
type lib struct {
|
||||||
@@ -152,21 +155,28 @@ func NewYqLib() YqLib {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *lib) Get(rootNode *yaml.Node, path string, deeplyTraverseArrays bool) ([]*NodeContext, error) {
|
func (l *lib) Get(rootNode *yaml.Node, path string) ([]*NodeContext, error) {
|
||||||
var paths = l.parser.ParsePath(path)
|
var paths = l.parser.ParsePath(path)
|
||||||
navigationStrategy := ReadNavigationStrategy(deeplyTraverseArrays)
|
navigationStrategy := ReadNavigationStrategy()
|
||||||
navigator := NewDataNavigator(navigationStrategy)
|
navigator := NewDataNavigator(navigationStrategy)
|
||||||
error := navigator.Traverse(rootNode, paths)
|
error := navigator.Traverse(rootNode, paths)
|
||||||
return navigationStrategy.GetVisitedNodes(), error
|
return navigationStrategy.GetVisitedNodes(), error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *lib) GetForMerge(rootNode *yaml.Node, path string, arrayMergeStrategy ArrayMergeStrategy) ([]*NodeContext, error) {
|
||||||
|
var paths = l.parser.ParsePath(path)
|
||||||
|
navigationStrategy := ReadForMergeNavigationStrategy(arrayMergeStrategy)
|
||||||
|
navigator := NewDataNavigator(navigationStrategy)
|
||||||
|
error := navigator.Traverse(rootNode, paths)
|
||||||
|
return navigationStrategy.GetVisitedNodes(), error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *lib) PathStackToString(pathStack []interface{}) string {
|
func (l *lib) PathStackToString(pathStack []interface{}) string {
|
||||||
return pathStackToString(pathStack)
|
return pathStackToString(pathStack)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *lib) MergePathStackToString(pathStack []interface{}, appendArrays bool) string {
|
func (l *lib) MergePathStackToString(pathStack []interface{}, arrayMergeStrategy ArrayMergeStrategy) string {
|
||||||
return mergePathStackToString(pathStack, appendArrays)
|
return mergePathStackToString(pathStack, arrayMergeStrategy)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *lib) New(path string) yaml.Node {
|
func (l *lib) New(path string) yaml.Node {
|
||||||
@@ -182,6 +192,10 @@ func (l *lib) Update(rootNode *yaml.Node, updateCommand UpdateCommand, autoCreat
|
|||||||
var paths = l.parser.ParsePath(updateCommand.Path)
|
var paths = l.parser.ParsePath(updateCommand.Path)
|
||||||
navigator := NewDataNavigator(UpdateNavigationStrategy(updateCommand, autoCreate))
|
navigator := NewDataNavigator(UpdateNavigationStrategy(updateCommand, autoCreate))
|
||||||
return navigator.Traverse(rootNode, paths)
|
return navigator.Traverse(rootNode, paths)
|
||||||
|
case "merge":
|
||||||
|
var paths = l.parser.ParsePath(updateCommand.Path)
|
||||||
|
navigator := NewDataNavigator(MergeNavigationStrategy(updateCommand, autoCreate))
|
||||||
|
return navigator.Traverse(rootNode, paths)
|
||||||
case "delete":
|
case "delete":
|
||||||
var paths = l.parser.ParsePath(updateCommand.Path)
|
var paths = l.parser.ParsePath(updateCommand.Path)
|
||||||
lastBit, newTail := paths[len(paths)-1], paths[:len(paths)-1]
|
lastBit, newTail := paths[len(paths)-1], paths[:len(paths)-1]
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestLib(t *testing.T) {
|
|||||||
array[0] = "a"
|
array[0] = "a"
|
||||||
array[1] = 0
|
array[1] = 0
|
||||||
array[2] = "b"
|
array[2] = "b"
|
||||||
got := subject.MergePathStackToString(array, true)
|
got := subject.MergePathStackToString(array, AppendArrayMergeStrategy)
|
||||||
test.AssertResult(t, `a.[+].b`, got)
|
test.AssertResult(t, `a.[+].b`, got)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
103
pkg/yqlib/merge_navigation_strategy.go
Normal file
103
pkg/yqlib/merge_navigation_strategy.go
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
package yqlib
|
||||||
|
|
||||||
|
import "gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
type ArrayMergeStrategy uint32
|
||||||
|
|
||||||
|
const (
|
||||||
|
UpdateArrayMergeStrategy ArrayMergeStrategy = 1 << iota
|
||||||
|
OverwriteArrayMergeStrategy
|
||||||
|
AppendArrayMergeStrategy
|
||||||
|
)
|
||||||
|
|
||||||
|
type CommentsMergeStrategy uint32
|
||||||
|
|
||||||
|
const (
|
||||||
|
SetWhenBlankCommentsMergeStrategy CommentsMergeStrategy = 1 << iota
|
||||||
|
IgnoreCommentsMergeStrategy
|
||||||
|
OverwriteCommentsMergeStrategy
|
||||||
|
AppendCommentsMergeStrategy
|
||||||
|
)
|
||||||
|
|
||||||
|
func MergeNavigationStrategy(updateCommand UpdateCommand, autoCreate bool) NavigationStrategy {
|
||||||
|
return &NavigationStrategyImpl{
|
||||||
|
visitedNodes: []*NodeContext{},
|
||||||
|
pathParser: NewPathParser(),
|
||||||
|
followAlias: func(nodeContext NodeContext) bool {
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
autoCreateMap: func(nodeContext NodeContext) bool {
|
||||||
|
return autoCreate
|
||||||
|
},
|
||||||
|
visit: func(nodeContext NodeContext) error {
|
||||||
|
node := nodeContext.Node
|
||||||
|
changesToApply := updateCommand.Value
|
||||||
|
|
||||||
|
if node.Kind == yaml.DocumentNode && changesToApply.Kind != yaml.DocumentNode {
|
||||||
|
// when the path is empty, it matches both the top level pseudo document node
|
||||||
|
// and the actual top level node (e.g. map/sequence/whatever)
|
||||||
|
// so when we are updating with no path, make sure we update the right node.
|
||||||
|
node = node.Content[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug("going to update")
|
||||||
|
DebugNode(node)
|
||||||
|
log.Debug("with")
|
||||||
|
DebugNode(changesToApply)
|
||||||
|
|
||||||
|
if updateCommand.Overwrite || node.Value == "" {
|
||||||
|
node.Value = changesToApply.Value
|
||||||
|
node.Tag = changesToApply.Tag
|
||||||
|
node.Kind = changesToApply.Kind
|
||||||
|
node.Style = changesToApply.Style
|
||||||
|
node.Anchor = changesToApply.Anchor
|
||||||
|
node.Alias = changesToApply.Alias
|
||||||
|
|
||||||
|
if !updateCommand.DontUpdateNodeContent {
|
||||||
|
node.Content = changesToApply.Content
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Debug("skipping update as node already has value %v and overwriteFlag is ", node.Value, updateCommand.Overwrite)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch updateCommand.CommentsMergeStrategy {
|
||||||
|
case OverwriteCommentsMergeStrategy:
|
||||||
|
node.HeadComment = changesToApply.HeadComment
|
||||||
|
node.LineComment = changesToApply.LineComment
|
||||||
|
node.FootComment = changesToApply.FootComment
|
||||||
|
case SetWhenBlankCommentsMergeStrategy:
|
||||||
|
if node.HeadComment == "" {
|
||||||
|
node.HeadComment = changesToApply.HeadComment
|
||||||
|
}
|
||||||
|
if node.LineComment == "" {
|
||||||
|
node.LineComment = changesToApply.LineComment
|
||||||
|
}
|
||||||
|
if node.FootComment == "" {
|
||||||
|
node.FootComment = changesToApply.FootComment
|
||||||
|
}
|
||||||
|
case AppendCommentsMergeStrategy:
|
||||||
|
if node.HeadComment == "" {
|
||||||
|
node.HeadComment = changesToApply.HeadComment
|
||||||
|
} else {
|
||||||
|
node.HeadComment = node.HeadComment + "\n" + changesToApply.HeadComment
|
||||||
|
}
|
||||||
|
if node.LineComment == "" {
|
||||||
|
node.LineComment = changesToApply.LineComment
|
||||||
|
} else {
|
||||||
|
node.LineComment = node.LineComment + " " + changesToApply.LineComment
|
||||||
|
}
|
||||||
|
if node.FootComment == "" {
|
||||||
|
node.FootComment = changesToApply.FootComment
|
||||||
|
} else {
|
||||||
|
node.FootComment = node.FootComment + "\n" + changesToApply.FootComment
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug("result")
|
||||||
|
DebugNode(node)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,9 @@ type NodeContext struct {
|
|||||||
Head interface{}
|
Head interface{}
|
||||||
Tail []interface{}
|
Tail []interface{}
|
||||||
PathStack []interface{}
|
PathStack []interface{}
|
||||||
|
// middle nodes are nodes that match along the original path, but not a
|
||||||
|
// target match of the path. This is only relevant when ShouldOnlyDeeplyVisitLeaves is false.
|
||||||
|
IsMiddleNode bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNodeContext(node *yaml.Node, head interface{}, tail []interface{}, pathStack []interface{}) NodeContext {
|
func NewNodeContext(node *yaml.Node, head interface{}, tail []interface{}, pathStack []interface{}) NodeContext {
|
||||||
|
|||||||
37
pkg/yqlib/read_for_merge_navigation_strategy.go
Normal file
37
pkg/yqlib/read_for_merge_navigation_strategy.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package yqlib
|
||||||
|
|
||||||
|
import "gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
func ReadForMergeNavigationStrategy(arrayMergeStrategy ArrayMergeStrategy) NavigationStrategy {
|
||||||
|
return &NavigationStrategyImpl{
|
||||||
|
visitedNodes: []*NodeContext{},
|
||||||
|
pathParser: NewPathParser(),
|
||||||
|
followAlias: func(nodeContext NodeContext) bool {
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
shouldOnlyDeeplyVisitLeaves: func(nodeContext NodeContext) bool {
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
visit: func(nodeContext NodeContext) error {
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
shouldDeeplyTraverse: func(nodeContext NodeContext) bool {
|
||||||
|
if nodeContext.Node.Kind == yaml.SequenceNode && arrayMergeStrategy == OverwriteArrayMergeStrategy {
|
||||||
|
nodeContext.IsMiddleNode = false
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var isInArray = false
|
||||||
|
if len(nodeContext.PathStack) > 0 {
|
||||||
|
var lastElement = nodeContext.PathStack[len(nodeContext.PathStack)-1]
|
||||||
|
switch lastElement.(type) {
|
||||||
|
case int:
|
||||||
|
isInArray = true
|
||||||
|
default:
|
||||||
|
isInArray = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return arrayMergeStrategy == UpdateArrayMergeStrategy || !isInArray
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +1,11 @@
|
|||||||
package yqlib
|
package yqlib
|
||||||
|
|
||||||
func ReadNavigationStrategy(deeplyTraverseArrays bool) NavigationStrategy {
|
func ReadNavigationStrategy() NavigationStrategy {
|
||||||
return &NavigationStrategyImpl{
|
return &NavigationStrategyImpl{
|
||||||
visitedNodes: []*NodeContext{},
|
visitedNodes: []*NodeContext{},
|
||||||
pathParser: NewPathParser(),
|
pathParser: NewPathParser(),
|
||||||
visit: func(nodeContext NodeContext) error {
|
visit: func(nodeContext NodeContext) error {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
shouldDeeplyTraverse: func(nodeContext NodeContext) bool {
|
|
||||||
var isInArray = false
|
|
||||||
if len(nodeContext.PathStack) > 0 {
|
|
||||||
var lastElement = nodeContext.PathStack[len(nodeContext.PathStack)-1]
|
|
||||||
switch lastElement.(type) {
|
|
||||||
case int:
|
|
||||||
isInArray = true
|
|
||||||
default:
|
|
||||||
isInArray = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return deeplyTraverseArrays || !isInArray
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,12 @@ func UpdateNavigationStrategy(updateCommand UpdateCommand, autoCreate bool) Navi
|
|||||||
node.Tag = changesToApply.Tag
|
node.Tag = changesToApply.Tag
|
||||||
node.Kind = changesToApply.Kind
|
node.Kind = changesToApply.Kind
|
||||||
node.Style = changesToApply.Style
|
node.Style = changesToApply.Style
|
||||||
node.Content = changesToApply.Content
|
if !updateCommand.DontUpdateNodeContent {
|
||||||
|
node.Content = changesToApply.Content
|
||||||
|
}
|
||||||
node.Anchor = changesToApply.Anchor
|
node.Anchor = changesToApply.Anchor
|
||||||
node.Alias = changesToApply.Alias
|
node.Alias = changesToApply.Alias
|
||||||
if !updateCommand.DontUpdateComments {
|
if updateCommand.CommentsMergeStrategy != IgnoreCommentsMergeStrategy {
|
||||||
node.HeadComment = changesToApply.HeadComment
|
node.HeadComment = changesToApply.HeadComment
|
||||||
node.LineComment = changesToApply.LineComment
|
node.LineComment = changesToApply.LineComment
|
||||||
node.FootComment = changesToApply.FootComment
|
node.FootComment = changesToApply.FootComment
|
||||||
|
|||||||
@@ -3,9 +3,10 @@
|
|||||||
# This assumes that gonative and gox is installed as per the 'one time setup' instructions
|
# This assumes that gonative and gox is installed as per the 'one time setup' instructions
|
||||||
# at https://github.com/inconshreveable/gonative
|
# at https://github.com/inconshreveable/gonative
|
||||||
|
|
||||||
gox -ldflags "${LDFLAGS}" -output="build/yq_{{.OS}}_{{.Arch}}"
|
|
||||||
|
CGO_ENABLED=0 gox -ldflags "${LDFLAGS}" -output="build/yq_{{.OS}}_{{.Arch}}"
|
||||||
# include non-default linux builds too
|
# include non-default linux builds too
|
||||||
gox -ldflags "${LDFLAGS}" -os=linux -output="build/yq_{{.OS}}_{{.Arch}}"
|
CGO_ENABLED=0 gox -ldflags "${LDFLAGS}" -os=linux -output="build/yq_{{.OS}}_{{.Arch}}"
|
||||||
|
|
||||||
cd build
|
cd build
|
||||||
rhash -r -a . -P -o checksums
|
rhash -r -a . -P -o checksums
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
name: yq
|
name: yq
|
||||||
version: '3.3.3'
|
version: '3.3.4'
|
||||||
summary: A lightweight and portable command-line YAML processor
|
summary: A lightweight and portable command-line YAML processor
|
||||||
description: |
|
description: |
|
||||||
The aim of the project is to be the jq or sed of yaml files.
|
The aim of the project is to be the jq or sed of yaml files.
|
||||||
|
|||||||
Reference in New Issue
Block a user