This library provides you with a interactive shell powered by bubbletea by executing cobra, allowing you to build powerful interactive terminal based shell applications.
Create a root command as you would normally with cobra, attaching your various commands to it.
Then pass it to the shell.New
function to create a new shell.
package main
import (
tea "github.com/charmbracelet/bubbletea"
"github.com/DomBlack/bubble-shell"
"github.com/spf13/cobra"
)
func main() {
// Create the root command which we can attach everything to
rootCmd := &cobra.Command{}
// Create a command to add to the root command
myCmd := &cobra.Command{
Use: "hi",
RunE: func(cmd *cobra.Command, args []string) error {
cmd.OutOrStdout().Write([]byte("Hello World\n"))
return nil
},
}
rootCmd.AddCommand(myCmd)
// Create the shell
shell := shell.New(rootCmd)
// Run the shell
p := tea.NewProgram(shell)
if _, err := p.Run(); err != nil {
panic(err)
}
}
In this example, a user will be given an interactive shell with a single command hi
which will print Hello World
when
run.
The shell.New
function takes a number of options to configure the shell, which are detailed below. Full documentaton
for them can be seen in options.go.
By default the shell will save the history of commands to .bubble-shell-history
in the user's home directory, however
using these two options you can change this behaviour, either providing your own filename or disabling history entirely.
You can use this option to customise the key bindings used by the shell. The default key bindings are located in the keymap package.
You can use this option to customise the styles used by the shell. The default styles are located in the styles package.
By default the shell will filter out stack traces from the github.com/DomBlack/bubble-shell
package and other related
packages when rendering the stack traces of errors to the user. You can use these options to customise this behaviour,
either by providing your own list of packages to filter out, or by adding to the default list.
- The shell supports autocompletion of commands and arguments, so ideally implement a
ValidArgsFunction
function orValidArgs
property on your command. - If you implement your commands using
RunE
rather thanRun
you can then return an error to bubble-shell which will be displayed to the user. If the error carries a stack trace, it will be displayed to the user. (I recommend using cockroachdb/errors to create errors with stack traces by default). - If you need a context use
cmd.Context()
rather than creating your own. This is because the shell will cancel the context when the user pressesCtrl+C
. - If you want to display a message to the user, use
cmd.OutOrStdout()
rather thanfmt.Println("Hello World")
. While both will be captured and returned to the user, the former will be streamed to the user as it is written, while theos.Stdout
andos.Stderr
streams are buffered and only displayed when the command completes.