put comments on key node instead

This commit is contained in:
Mike Farah 2022-10-26 13:24:36 +11:00
parent fe27ddedc0
commit 7eccbe5902
2 changed files with 46 additions and 8 deletions

View File

@ -2,5 +2,9 @@
# things and stuff # things and stuff
this.is = a properties file this.is = a properties file
this.cat.0 = free
# this one is important
# another thing # another thing
this.another = a properties file this.cat.1 = meow

View File

@ -2,6 +2,7 @@ package yqlib
import ( import (
"bytes" "bytes"
"fmt"
"io" "io"
"strconv" "strconv"
"strings" "strings"
@ -47,17 +48,50 @@ func (dec *propertiesDecoder) processComment(c string) string {
return "# " + c return "# " + c
} }
func (dec *propertiesDecoder) applyProperty(properties *properties.Properties, context Context, key string) error { func (dec *propertiesDecoder) applyPropertyComments(context Context, path []interface{}, comments []string) error {
assignmentOp := &Operation{OperationType: assignOpType, Preferences: assignPreferences{}}
rhsCandidateNode := &CandidateNode{
Path: path,
Node: &yaml.Node{
Tag: "!!str",
Value: fmt.Sprintf("%v", path[len(path)-1]),
HeadComment: dec.processComment(strings.Join(comments, "\n")),
Kind: yaml.ScalarNode,
},
}
rhsCandidateNode.Node.Tag = guessTagFromCustomType(rhsCandidateNode.Node)
rhsOp := &Operation{OperationType: valueOpType, CandidateNode: rhsCandidateNode}
assignmentOpNode := &ExpressionNode{
Operation: assignmentOp,
LHS: createTraversalTree(path, traversePreferences{}, true),
RHS: &ExpressionNode{Operation: rhsOp},
}
_, err := dec.d.GetMatchingNodes(context, assignmentOpNode)
return err
}
// TODO: test comment on array
func (dec *propertiesDecoder) applyProperty(context Context, properties *properties.Properties, key string) error {
value, _ := properties.Get(key) value, _ := properties.Get(key)
path := parsePropKey(key) path := parsePropKey(key)
IMPROVEMENT - target the key node with the comment, set as a header comment instead. propertyComments := properties.GetComments(key)
if len(propertyComments) > 0 {
err := dec.applyPropertyComments(context, path, propertyComments)
if err != nil {
return nil
}
}
rhsNode := &yaml.Node{ rhsNode := &yaml.Node{
Value: value, Value: value,
Tag: "!!str", Tag: "!!str",
Kind: yaml.ScalarNode, Kind: yaml.ScalarNode,
LineComment: dec.processComment(strings.Join(properties.GetComments(key), "\n")),
} }
rhsNode.Tag = guessTagFromCustomType(rhsNode) rhsNode.Tag = guessTagFromCustomType(rhsNode)
@ -111,7 +145,7 @@ func (dec *propertiesDecoder) Decode() (*CandidateNode, error) {
context = context.SingleChildContext(rootMap) context = context.SingleChildContext(rootMap)
for _, key := range properties.Keys() { for _, key := range properties.Keys() {
if err := dec.applyProperty(properties, context, key); err != nil { if err := dec.applyProperty(context, properties, key); err != nil {
return nil, err return nil, err
} }