For a go CLI tool that I am building with cobra-cli, I’d love to have infix commands and operators, like
myapp <arg1> to <arg2>
Where to is the command that performs a method with both args.
My approaches have been taking 1 argument with the main cmd, which is then set globally, and the second is given with “to”. This does not work (in my implementation). I also just tried having 2 arguments for “to”, but due to their positions, it doesn’t work.
The first approach stops after taken arg 1, and does not perform “to” anymore. Is this kind of functionality possible with libraries? Or should one build something specific for this usecase?
var (
Version string // This will be set from main.go
verbose bool
stationFrom string
)
var rootCmd = &cobra.Command{
Use: "commandlijn <station1>",
Short: "A brief description of your application",
Long: ``,
Args: cobra.MinimumNArgs(1), // Expect at least one argument, but allow subcommands
Run: func(cmd *cobra.Command, args []string) {
stationFrom = args[0] // Store the departure station
fmt.Println("Has taken 1 arg")
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
// Define the --version flag
rootCmd.Flags().BoolP("version", "V", false, "Print the version number and exit")
// Define other flags
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose output")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
toCmd
var toCmd = &cobra.Command{
Use: "to <station2>",
Short: "Finds connections between two stations",
Long: `The 'to' command allows you to find train connections between two stations.
You need to specify the departure station and the arrival station.`,
Args: cobra.ExactArgs(1), // Only expect one argument for the destination station
Run: func(cmd *cobra.Command, args []string) {
stationTo := args[0] // Get the destination station
fmt.Println("doesn't reach")
2