Skip to content

Instantly share code, notes, and snippets.

@gulducat
Created March 29, 2023 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gulducat/0bae6123ae5bddaca050e7626ad0467e to your computer and use it in GitHub Desktop.
Save gulducat/0bae6123ae5bddaca050e7626ad0467e to your computer and use it in GitHub Desktop.
mitchellh/cli with a little UI prompt
package main
import (
"log"
"os"
"github.com/mitchellh/cli"
)
func main() {
ui := &cli.BasicUi{
Reader: os.Stdin,
Writer: os.Stdout,
ErrorWriter: os.Stderr,
}
commands := map[string]cli.CommandFactory{
"cool": func() (cli.Command, error) {
return CoolCommand{Ui: ui}, nil
},
}
c := &cli.CLI{
Args: os.Args[1:],
Commands: commands,
}
code, err := c.Run()
if err != nil {
log.Fatal(err)
}
os.Exit(code)
}
type CoolCommand struct {
Ui cli.Ui
}
func (c CoolCommand) Help() string {
return "help thyself"
}
func (c CoolCommand) Synopsis() string {
return c.Help()
}
func (c CoolCommand) Run(_ []string) int {
resp, err := c.Ui.Ask("hi how are you?")
if err != nil {
c.Ui.Error("uh oh: " + err.Error())
return 1
}
c.Ui.Info("neat, glad to hear that you are " + resp)
return 0
}
❯ go run .
Usage: app [--version] [--help] <command> [<args>]
Available commands are:
cool help thyself
❯ go run . cool
hi how are you? great! # it pauses for prompt here
neat, glad to hear that you are great!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment