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

     1  package command
     2  
     3  import (
     4  	"github.com/spf13/cobra"
     5  	"github.com/tomwright/dasel/internal"
     6  	"github.com/tomwright/dasel/internal/selfupdate"
     7  	"os"
     8  )
     9  
    10  // NewRootCMD returns the root command for use with cobra.
    11  func NewRootCMD() *cobra.Command {
    12  	cmd := &cobra.Command{
    13  		Use:           "dasel",
    14  		Short:         "Query and modify data structures using selector strings.",
    15  		SilenceErrors: true,
    16  		SilenceUsage:  true,
    17  	}
    18  	cmd.Version = internal.Version
    19  	cmd.AddCommand(
    20  		selectCommand(),
    21  		putCommand(),
    22  		deleteCommand(),
    23  		updateCommand(selfupdate.NewUpdater(internal.Version)),
    24  		validateCommand(),
    25  	)
    26  	return cmd
    27  }
    28  
    29  // ChangeDefaultCommand checks to see if the current os.Args target a valid subcommand.
    30  // If they do not they are adjusted to target the given command.
    31  // If any of the blacklisted args are set in os.Args, no action is taken.
    32  func ChangeDefaultCommand(cmd *cobra.Command, command string, blacklistedArgs ...string) {
    33  	if len(os.Args) > 1 {
    34  		potentialCommand := os.Args[1]
    35  
    36  		// The completion command is registered internally during execution so cmd.Commands() can't
    37  		// pick it up here.
    38  		subCommands := []string{"completion", "__complete"}
    39  		for _, subCmd := range cmd.Commands() {
    40  			subCommands = append(subCommands, append(subCmd.Aliases, subCmd.Name())...)
    41  		}
    42  
    43  		for _, availableCommand := range subCommands {
    44  			if availableCommand == potentialCommand {
    45  				return
    46  			}
    47  		}
    48  		for _, arg := range os.Args {
    49  			for _, blacklistedArg := range blacklistedArgs {
    50  				if arg == blacklistedArg {
    51  					return
    52  				}
    53  			}
    54  		}
    55  		os.Args = append([]string{os.Args[0], command}, os.Args[1:]...)
    56  	}
    57  }