Output line comments in Lua output

This commit is contained in:
Kim Alvefur 2023-08-05 15:55:26 +02:00
parent e756ac2c5a
commit b839c0ea92
3 changed files with 25 additions and 5 deletions

View File

@ -17,7 +17,7 @@ yq -o=lua '.' sample.yml
will output will output
```lua ```lua
return { return {
["country"] = "Australia"; ["country"] = "Australia"; -- this place
["cities"] = { ["cities"] = {
"Sydney", "Sydney",
"Melbourne", "Melbourne",
@ -47,7 +47,7 @@ yq -o=lua '.' sample.yml
will output will output
```lua ```lua
return { return {
country = "Australia"; country = "Australia"; -- this place
cities = { cities = {
"Sydney", "Sydney",
"Melbourne", "Melbourne",

View File

@ -134,6 +134,13 @@ func (le *luaEncoder) encodeArray(writer io.Writer, node *yaml.Node) error {
if err != nil { if err != nil {
return err return err
} }
if child.LineComment != "" {
sansPrefix, _ := strings.CutPrefix(child.LineComment, "#")
err = writeString(writer, " --"+sansPrefix)
if err != nil {
return err
}
}
} }
le.indent-- le.indent--
if len(node.Content) != 0 { if len(node.Content) != 0 {
@ -214,6 +221,20 @@ func (le *luaEncoder) encodeMap(writer io.Writer, node *yaml.Node) error {
} }
} }
} }
if child.LineComment != "" {
sansPrefix, _ := strings.CutPrefix(child.LineComment, "#")
err = writeString(writer, strings.Repeat(" ", i%2)+"--"+sansPrefix)
if err != nil {
return err
}
if (i % 2) == 0 {
// newline and indent after comments on keys
err = le.writeIndent(writer)
if err != nil {
return err
}
}
}
} }
le.indent-- le.indent--
if len(node.Content) != 0 { if len(node.Content) != 0 {

View File

@ -19,9 +19,8 @@ cities:
- Melbourne - Melbourne
- Brisbane - Brisbane
- Perth`, - Perth`,
// TODO comments, -- this place
expected: `return { expected: `return {
["country"] = "Australia"; ["country"] = "Australia"; -- this place
["cities"] = { ["cities"] = {
"Sydney", "Sydney",
"Melbourne", "Melbourne",
@ -43,7 +42,7 @@ cities:
- Brisbane - Brisbane
- Perth`, - Perth`,
expected: `return { expected: `return {
country = "Australia"; country = "Australia"; -- this place
cities = { cities = {
"Sydney", "Sydney",
"Melbourne", "Melbourne",