Created
March 29, 2023 19:14
-
-
Save gulducat/0bae6123ae5bddaca050e7626ad0467e to your computer and use it in GitHub Desktop.
mitchellh/cli with a little UI prompt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
❯ 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