github.com/tomwright/dasel@v1.27.3/internal/command/put_object_internal.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/spf13/cobra"
     6  	"github.com/tomwright/dasel/internal/oflag"
     7  	"github.com/tomwright/dasel/storage"
     8  	"io"
     9  	"strings"
    10  )
    11  
    12  type putObjectOpts struct {
    13  	File                string
    14  	Out                 string
    15  	ReadParser          string
    16  	WriteParser         string
    17  	Parser              string
    18  	Selector            string
    19  	InputTypes          []string
    20  	InputValues         []string
    21  	Reader              io.Reader
    22  	Writer              io.Writer
    23  	Multi               bool
    24  	Compact             bool
    25  	MergeInputDocuments bool
    26  	EscapeHTML          bool
    27  }
    28  
    29  func getMapFromTypesValues(inputTypes []string, inputValues []string) (map[string]interface{}, error) {
    30  	if len(inputTypes) != len(inputValues) {
    31  		return nil, fmt.Errorf("exactly %d types are required, got %d", len(inputValues), len(inputTypes))
    32  	}
    33  
    34  	updateValue := map[string]interface{}{}
    35  
    36  	for k, arg := range inputValues {
    37  		splitArg := strings.Split(arg, "=")
    38  		name := splitArg[0]
    39  		value := strings.Join(splitArg[1:], "=")
    40  		parsedValue, err := parseValue(value, inputTypes[k])
    41  		if err != nil {
    42  			return nil, fmt.Errorf("could not parse value [%s]: %w", name, err)
    43  		}
    44  		updateValue[name] = parsedValue
    45  	}
    46  
    47  	return updateValue, nil
    48  }
    49  
    50  func runPutObjectCommand(opts putObjectOpts, cmd *cobra.Command) error {
    51  	readParser, err := getReadParser(opts.File, opts.ReadParser, opts.Parser)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	rootNode, err := getRootNode(getRootNodeOpts{
    56  		File:                opts.File,
    57  		Parser:              readParser,
    58  		Reader:              opts.Reader,
    59  		MergeInputDocuments: opts.MergeInputDocuments,
    60  	}, cmd)
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	updateValue, err := getMapFromTypesValues(opts.InputTypes, opts.InputValues)
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	if opts.Multi {
    71  		if err := rootNode.PutMultiple(opts.Selector, updateValue); err != nil {
    72  			return fmt.Errorf("could not put object multi value: %w", err)
    73  		}
    74  	} else {
    75  		if err := rootNode.Put(opts.Selector, updateValue); err != nil {
    76  			return fmt.Errorf("could not put object value: %w", err)
    77  		}
    78  	}
    79  
    80  	writeParser, err := getWriteParser(readParser, opts.WriteParser, opts.Parser, opts.Out, opts.File, "")
    81  	if err != nil {
    82  		return err
    83  	}
    84  
    85  	writeOptions := []storage.ReadWriteOption{
    86  		storage.EscapeHTMLOption(opts.EscapeHTML),
    87  	}
    88  
    89  	if opts.Compact {
    90  		writeOptions = append(writeOptions, storage.PrettyPrintOption(false))
    91  	}
    92  
    93  	if err := writeNodeToOutput(writeNodeToOutputOpts{
    94  		Node:   rootNode,
    95  		Parser: writeParser,
    96  		File:   opts.File,
    97  		Out:    opts.Out,
    98  		Writer: opts.Writer,
    99  	}, cmd, writeOptions...); err != nil {
   100  		return fmt.Errorf("could not write output: %w", err)
   101  	}
   102  
   103  	return nil
   104  }
   105  
   106  func putObjectCommand() *cobra.Command {
   107  	typeList := oflag.NewStringList()
   108  
   109  	cmd := &cobra.Command{
   110  		Use:   "object -f <file> -s <selector> <value>",
   111  		Short: "Put an object in the given document.",
   112  		Args:  cobra.MinimumNArgs(1),
   113  		RunE: func(cmd *cobra.Command, args []string) error {
   114  			opts := putObjectOpts{
   115  				File:        cmd.Flag("file").Value.String(),
   116  				Out:         cmd.Flag("out").Value.String(),
   117  				ReadParser:  cmd.Flag("read").Value.String(),
   118  				WriteParser: cmd.Flag("write").Value.String(),
   119  				Parser:      cmd.Flag("parser").Value.String(),
   120  				Selector:    cmd.Flag("selector").Value.String(),
   121  				InputTypes:  typeList.Strings,
   122  				InputValues: args,
   123  			}
   124  			opts.Multi, _ = cmd.Flags().GetBool("multiple")
   125  			opts.Compact, _ = cmd.Flags().GetBool("compact")
   126  			opts.MergeInputDocuments, _ = cmd.Flags().GetBool("merge-input-documents")
   127  			opts.EscapeHTML, _ = cmd.Flags().GetBool("escape-html")
   128  
   129  			if opts.Selector == "" && len(opts.InputValues) > 0 {
   130  				opts.Selector = opts.InputValues[0]
   131  				opts.InputValues = opts.InputValues[1:]
   132  			}
   133  			return runPutObjectCommand(opts, cmd)
   134  		},
   135  	}
   136  
   137  	cmd.Flags().VarP(typeList, "type", "t", "Types of the variables in the object.")
   138  
   139  	return cmd
   140  }