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
+5 -51
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
}