6
6
"os"
7
7
"strings"
8
8
9
+ "github.com/google/yamlfmt"
9
10
"github.com/google/yamlfmt/formatters/basic"
10
11
"github.com/mikefarah/yq/v4/pkg/yqlib"
11
12
"github.com/sirupsen/logrus"
@@ -15,13 +16,26 @@ import (
15
16
// EvaluateExpression evaluates the yq expression, and returns the modified yaml.
16
17
func EvaluateExpression (expression string , content []byte ) ([]byte , error ) {
17
18
logrus .Debugf ("Evaluating yq expression: %q" , expression )
19
+ formatter , err := yamlfmtBasicFormatter ()
20
+ if err != nil {
21
+ return nil , err
22
+ }
23
+ // `ApplyFeatures()` is being called directly before passing content to `yqlib`.
24
+ // This results in `ApplyFeatures()` being called twice with `FeatureApplyBefore`:
25
+ // once here and once inside `formatter.Format`.
26
+ // Currently, calling `ApplyFeatures()` with `FeatureApplyBefore` twice is not an issue,
27
+ // but future changes to `yamlfmt` might cause problems if it is called twice.
28
+ contentModified , err := formatter .Features .ApplyFeatures (content , yamlfmt .FeatureApplyBefore )
29
+ if err != nil {
30
+ return nil , err
31
+ }
18
32
tmpYAMLFile , err := os .CreateTemp ("" , "lima-yq-*.yaml" )
19
33
if err != nil {
20
34
return nil , err
21
35
}
22
36
tmpYAMLPath := tmpYAMLFile .Name ()
23
37
defer os .RemoveAll (tmpYAMLPath )
24
- _ , err = tmpYAMLFile .Write (content )
38
+ _ , err = tmpYAMLFile .Write (contentModified )
25
39
if err != nil {
26
40
tmpYAMLFile .Close ()
27
41
return nil , err
@@ -70,7 +84,7 @@ func EvaluateExpression(expression string, content []byte) ([]byte, error) {
70
84
return nil , err
71
85
}
72
86
73
- return yamlfmt (out .Bytes ())
87
+ return formatter . Format (out .Bytes ())
74
88
}
75
89
76
90
func Join (yqExprs []string ) string {
@@ -80,17 +94,23 @@ func Join(yqExprs []string) string {
80
94
return strings .Join (yqExprs , " | " )
81
95
}
82
96
83
- func yamlfmt ( content [] byte ) ([] byte , error ) {
97
+ func yamlfmtBasicFormatter ( ) (* basic. BasicFormatter , error ) {
84
98
factory := basic.BasicFormatterFactory {}
85
99
config := map [string ]interface {}{
86
- "indentless_arrays" : true ,
87
- "line_ending" : "lf" , // prefer LF even on Windows
88
- "pad_line_comments" : 2 ,
89
- "retain_line_breaks" : true , // does not affect to the output because yq removes empty lines before formatting
100
+ "indentless_arrays" : true ,
101
+ "line_ending" : "lf" , // prefer LF even on Windows
102
+ "pad_line_comments" : 2 ,
103
+ "retain_line_breaks" : true ,
104
+ "retain_line_breaks_single" : false ,
90
105
}
106
+
91
107
formatter , err := factory .NewFormatter (config )
92
108
if err != nil {
93
109
return nil , err
94
110
}
95
- return formatter .Format (content )
111
+ basicFormatter , ok := formatter .(* basic.BasicFormatter )
112
+ if ! ok {
113
+ return nil , fmt .Errorf ("unexpected formatter type: %T" , formatter )
114
+ }
115
+ return basicFormatter , nil
96
116
}
0 commit comments