1
0
mirror of https://github.com/taigrr/yq synced 2025-01-18 04:53:17 -08:00
This commit is contained in:
Mike Farah
2020-11-06 14:37:01 +11:00
parent b290a65602
commit 2edf64182b
9 changed files with 129 additions and 89 deletions

View File

@@ -4,29 +4,16 @@ import (
logging "gopkg.in/op/go-logging.v1"
)
var customTag = ""
var printMode = "v"
var printLength = false
var unwrapScalar = true
var customStyle = ""
var anchorName = ""
var makeAlias = false
var writeInplace = false
var writeScript = ""
var sourceYamlFile = ""
var outputToJSON = false
var exitStatus = false
var explodeAnchors = false
var forceColor = false
var forceNoColor = false
var colorsEnabled = false
var defaultValue = ""
var indent = 2
var printDocSeparators = true
var overwriteFlag = false
var autoCreateFlag = true
var arrayMergeStrategyFlag = "update"
var commentsMergeStrategyFlag = "setWhenBlank"
var nullInput = false
var verbose = false
var version = false
var shellCompletion = ""

View File

@@ -0,0 +1,66 @@
package cmd
import (
"container/list"
"os"
"github.com/mikefarah/yq/v4/pkg/yqlib"
"github.com/spf13/cobra"
)
func createEvaluateSequenceCommand() *cobra.Command {
var cmdEvalSequence = &cobra.Command{
Use: "eval-seq [expression] [yaml_file1]...",
Aliases: []string{"es"},
Short: "Apply expression to each document in each yaml file given in sequence",
Example: `
yq es '.a.b | length' file1.yml file2.yml
yq es < sample.yaml
yq es -n '{"a": "b"}'
`,
Long: "Evaluate Sequence:\nIterate over each yaml document, apply the expression and print the results, in sequence.",
RunE: evaluateSequence,
}
return cmdEvalSequence
}
func evaluateSequence(cmd *cobra.Command, args []string) error {
// 0 args, read std in
// 1 arg, null input, process expression
// 1 arg, read file in sequence
// 2+ args, [0] = expression, file the rest
var matchingNodes *list.List
var err error
stat, _ := os.Stdin.Stat()
pipingStdIn := (stat.Mode() & os.ModeCharDevice) == 0
switch len(args) {
case 0:
if pipingStdIn {
matchingNodes, err = yqlib.Evaluate("-", "")
} else {
cmd.Println(cmd.UsageString())
return nil
}
case 1:
if nullInput {
matchingNodes, err = yqlib.EvaluateExpression(args[0])
} else {
matchingNodes, err = yqlib.Evaluate(args[0], "")
}
}
cmd.SilenceUsage = true
if err != nil {
return err
}
out := cmd.OutOrStdout()
fileInfo, _ := os.Stdout.Stat()
if forceColor || (!forceNoColor && (fileInfo.Mode()&os.ModeCharDevice) != 0) {
colorsEnabled = true
}
printer := yqlib.NewPrinter(outputToJSON, unwrapScalar, colorsEnabled, indent, printDocSeparators)
return printer.PrintResults(matchingNodes, out)
}

View File

@@ -1,11 +1,9 @@
package cmd
import (
"errors"
"fmt"
"os"
"github.com/mikefarah/yq/v4/pkg/yqlib"
"github.com/spf13/cobra"
logging "gopkg.in/op/go-logging.v1"
)
@@ -34,51 +32,9 @@ func New() *cobra.Command {
return fmt.Errorf("Unknown variant %v", shellCompletion)
}
}
// if len(args) == 0 {
// cmd.Println(cmd.UsageString())
// return nil
// }
cmd.SilenceUsage = true
cmd.Println(cmd.UsageString())
return nil
var treeCreator = yqlib.NewPathTreeCreator()
expression := ""
if len(args) > 0 {
expression = args[0]
}
pathNode, err := treeCreator.ParsePath(expression)
if err != nil {
return err
}
if outputToJSON {
explodeOp := yqlib.Operation{OperationType: yqlib.Explode}
explodeNode := yqlib.PathTreeNode{Operation: &explodeOp}
pipeOp := yqlib.Operation{OperationType: yqlib.Pipe}
pathNode = &yqlib.PathTreeNode{Operation: &pipeOp, Lhs: pathNode, Rhs: &explodeNode}
}
matchingNodes, err := yqlib.Evaluate("-", pathNode)
if err != nil {
return err
}
if exitStatus && matchingNodes.Len() == 0 {
cmd.SilenceUsage = true
return errors.New("No matches found")
}
out := cmd.OutOrStdout()
fileInfo, _ := os.Stdout.Stat()
if forceColor || (!forceNoColor && (fileInfo.Mode()&os.ModeCharDevice) != 0) {
colorsEnabled = true
}
printer := yqlib.NewPrinter(outputToJSON, unwrapScalar, colorsEnabled, indent, printDocSeparators)
return printer.PrintResults(matchingNodes, out)
},
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.SetOut(cmd.OutOrStdout())
@@ -100,6 +56,8 @@ func New() *cobra.Command {
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose mode")
rootCmd.PersistentFlags().BoolVarP(&outputToJSON, "tojson", "j", false, "output as json. Set indent to 0 to print json in one line.")
rootCmd.PersistentFlags().BoolVarP(&nullInput, "null-input", "n", false, "Don't read input, simply evaluate the expression given. Useful for creating yaml docs from scratch.")
rootCmd.PersistentFlags().IntVarP(&indent, "indent", "I", 2, "sets indent level for output")
rootCmd.Flags().BoolVarP(&version, "version", "V", false, "Print version information and quit")
@@ -107,10 +65,6 @@ func New() *cobra.Command {
rootCmd.PersistentFlags().BoolVarP(&forceColor, "colors", "C", false, "force print with colors")
rootCmd.PersistentFlags().BoolVarP(&forceNoColor, "no-colors", "M", false, "force print with no colors")
// rootCmd.PersistentFlags().StringVarP(&docIndex, "doc", "d", "0", "process document index number (0 based, * for all documents)")
rootCmd.PersistentFlags().StringVarP(&printMode, "printMode", "p", "v", "print mode (v (values, default), p (paths), pv (path and value pairs)")
rootCmd.PersistentFlags().StringVarP(&defaultValue, "defaultValue", "D", "", "default value printed when there are no results")
rootCmd.AddCommand(createEvaluateSequenceCommand())
return rootCmd
}