Skip to content

Using Arguments

John edited this page Nov 30, 2024 · 2 revisions

Arguments are the strings - separated by spaces - that come after the command name itself. They are ordered, and can be optional or required and/or list.

package main

import (
  "fmt"
  "github.com/DrSmithFr/go-console"
  "github.com/DrSmithFr/go-console/input/argument"
  "github.com/DrSmithFr/go-console/input/option"
)

func main() {

  // Declare the command with a struct
  cmd := go_console.Script{
    Description: "This is a test command",
    Arguments: []go_console.Argument{
      {
        Description: "The last name of the user",
        Name:        "name",
        Value:       argument.Required,
      },
    },
    Options: []go_console.Option{
      {
        Description: "The last name of the user",
        Name:        "foo",
        Shortcut:    "f",
        Value:       option.None,
      },
    },
  }
  // Build the command before using it
  cmd.Build()

  //
  // You now have access to a last_name argument in your command:
  //

  text := fmt.Sprintf("Hi %s", cmd.Input.Argument("name"))

  lastName := cmd.Input.Argument("last_name")

  if lastName != "" {
    text = fmt.Sprintf("%s %s", text, lastName)
  }

  // Using the Output as an io.Writer
  _, err := fmt.Fprintf(cmd.Output, "%s", text)

  if err != nil {
    panic(err)
  }

  // Using the Output Methode
  cmd.Output.Print("!")
}

The command can now be used in either of the following ways:

go run command-script John
> Hi John!

go run command John Smith
> Hi John Daligault!

It is also possible to let an argument take a list of values (imagine you want to greet all your friends). Only the last argument can be a list:

package main

import (
  "fmt"
  "github.com/DrSmithFr/go-console/input/argument"
  "github.com/DrSmithFr/go-console"
)

func main() {
  cmd := go_console.
    NewScript().
    AddInputArgument(
      argument.
        New("names", argument.List | argument.Required).
        SetDescription("Who do you want to greet?"),
    ).
    Build()

  //
  // You can access the names argument as an array:
  //

  names := cmd.Input.ArgumentList("names")

  for _, name := range names {
    cmd.PrintText(fmt.Sprintf("Hi %s!", name))
  }
}

To use this, specify as many names as you want:

go run command-script John Alex Fred

There are three argument variants you can use:

argument.Required

The argument is mandatory. The command doesn't run if the argument isn't provided;

argument.Optional

The argument is optional and therefore can be omitted. This is the default behavior of arguments;

argument.List

The argument can contain any number of values. For that reason, it must be used at the end of the argument list.

You can combine List with Required and Optional like this:

cmd := go_console.
  NewScript().
  AddInputArgument(
    argument.
      New("names", argument.List | argument.Required),
  ).
  Build()
Clone this wiki locally