cobra_ui

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2024 License: MIT Imports: 8 Imported by: 0

README

cobra-ui

The cobra-ui package empowers developers to craft immersive and interactive user interfaces seamlessly into their terminal applications (cobra-ui is a cross platform UI that can be integrated easily with Cobra CLIs Cobra or other CLI tools )

Features

  • File Input with Pagination: Facilitate the selection of files from a directory with built-in pagination support (10 files/page). Users can navigate through large sets of files seamlessly.

  • Error Handling: Handle errors gracefully during user interactions. When a handler encounters an error, it returns an error object containing relevant information about the error. The UI displays the error message to the user and prompts the question again.

  • Single-Choice Questions: Allow users to select one option from a list of choices.

  • Text Input Questions: Prompt users to enter text-based inputs.

  • Password Input Questions: Securely collect password inputs from users, hiding the entered characters for privacy.

  • Multiple choices Pagination: Automatically paginate choices for choice questions with more than 10 options, ensuring a smooth user experience without overwhelming them with too many choices at once.

  • Each question can have separately its own string cursor, question text color and its own handler (the default cursor if not specified is ->)

FilePath Example

package main

import (
	"fmt"

	"github.com/fatih/color"
	"github.com/sabouaram/cobra_ui"
)

func main() {
	var selectedFile string
	ui := cobra_ui.New()
	ui.SetQuestions([]cobra_ui.Question{
		{
			Text:     "Select a file:",
			Color:    color.FgCyan,
			FilePath: true,
			Handler: func(filePath string) error {
				selectedFile = filePath
				return nil
			},
		},
	})
	ui.RunInteractiveUI()
	fmt.Printf("Selected file full path: %s\n", selectedFile)
}

FilePath

Choices Question Example

package main

import (
	"fmt"

	"github.com/fatih/color"
	"github.com/sabouaram/cobra_ui"
)

func main() {
	var choice string
	ui := cobra_ui.New()
	ui.SetQuestions([]cobra_ui.Question{
		{
			CursorStr: "==>",
			Color:     color.FgCyan,
			Text:      "What is your preferred programming language?",
			Options:   []string{"Go", "Python", "JavaScript", "Java"},
			Handler: func(input string) error {
				choice = input
				return nil
			},
		},
	})
	ui.RunInteractiveUI()
	fmt.Printf("Selected choice: %s\n", choice)
}


Options

Text Input Example


package main

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/sabouaram/cobra_ui"
)

func main() {

	var (
		age int
		err error
	)

	tui := cobra_ui.New()
	tui.SetQuestions([]cobra_ui.Question{
		{
			Text: "Enter your age: ",
			Handler: func(input string) error {
				age, err = strconv.Atoi(input)
				if err != nil {
					return errors.New("age must be an integer - retry")
				}
				return nil
			},
		},
	})
	tui.RunInteractiveUI()
	fmt.Printf("Your entered age is %d \n", age)
}


Input

Password Input Example

package main

import (
	"fmt"

	"github.com/sabouaram/cobra_ui"
)

func main() {

	var (
		passwordEntered bool
		pwd             string
	)

	ui := cobra_ui.New()
	ui.SetQuestions([]cobra_ui.Question{
		{
			Text:         "Enter your password: ",
			PasswordType: true,
			Handler: func(password string) error {
				passwordEntered = true
				pwd = password
				return nil
			},
		},
	})
	ui.RunInteractiveUI()
	if passwordEntered == true {
		fmt.Printf("Password entered => %s\n", pwd)
	}

}

Password

UI with Cobra Example

package main

import (
	"fmt"

        "github.com/sabouaram/cobra_ui"
	"github.com/spf13/cobra"
)

var choice string
var rootCmd = &cobra.Command{
	Use:   "myapp",
	Short: "A sample cobra cli app",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Welcome to my cobra cli app!")
		fmt.Println("Thank you for choosing ", choice)
	},
}

func main() {

	ui := cobra_ui.New()
	ui.SetQuestions([]cobra_ui.Question{
		{
			Text:    "What is your preferred programming language?",
			Options: []string{"Go", "Python", "JavaScript"},
			Handler: func(input string) error {
				choice = input
				return nil
			},
		},
	})

	ui.SetCobra(rootCmd)
	ui.BeforeRun()

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Question

type Question struct {
	Text         string
	Options      []string
	FilePath     bool
	PasswordType bool
	Handler      func(string) error
	Color        color.Attribute
	CursorStr    string
}

Question represents an interactive question that can be asked in the UI. It supports various input types like text, file selection, password entry, and single-choice options.

Fields:

  • Text: The question to be displayed to the user.
  • Options: A list of available options for single-choice questions. If empty, the user is expected to provide a text input.
  • FilePath: If true, the question prompts the user to select a file from a directory (with built-in pagination support).
  • PasswordType: If true, the input will be hidden for security, typically used for password entries.
  • Handler: A callback function that handles the user's input. It receives the input string and returns an error if the input is invalid or if there's an issue processing the input.
  • Color: Defines the text color of the question. Uses `color.Attribute` from the `github.com/fatih/color` package.
  • CursorStr: The string used as a cursor or pointer in the UI when navigating through options. If not specified, the default cursor (`->`) is used.

type UI

type UI interface {

	// SetQuestions sets the list of questions to be presented during the UI interaction.
	// Parameters:
	// - questions: A slice of Question structs representing the questions to display.
	SetQuestions(questions []Question)

	// RunInteractiveUI starts the interactive UI by running a Bubble Tea program.
	// It initializes the index and cursor, then starts the UI loop.
	RunInteractiveUI()

	// SetCobra links a Cobra command with the UI.
	// Parameters:
	// - cobra: The Cobra command instance to link with the UI.
	SetCobra(cobra *cobra.Command)

	// AfterPreRun sets the PreRun hook for Cobra to execute the interactive UI after the PreRun logic.
	// If PreRun is already defined, it ensures the original logic is preserved.
	AfterPreRun()

	// BeforePreRun sets the PreRun hook for Cobra to execute the interactive UI before the PreRun logic.
	// If PreRun is already defined, it ensures the UI is executed first and the original logic is preserved.
	BeforePreRun()

	// AfterRun sets the Run hook for Cobra to execute the interactive UI after the command's main logic.
	// If Run is already defined, it ensures the original logic is preserved and the UI is run afterward.
	AfterRun()

	// BeforeRun sets the Run hook for Cobra to execute the interactive UI before the command's main logic.
	// If Run is already defined, it ensures the UI is executed first and preserves the original logic.
	BeforeRun()
}

UI defines the methods required to handle an interactive user interface (UI) for terminal applications. It provides functionalities for setting up questions, running the UI, and integrating with Cobra CLI commands.

Methods:

  • SetQuestions: Allows setting a list of questions to be presented to the user. Each question can prompt the user for different types of inputs, such as file selection, text input, or multiple-choice options.
  • RunInteractiveUI: Starts the interactive UI session, displaying the configured questions to the user and collecting their responses.
  • SetCobra: Integrates the UI with a Cobra CLI command. This method links the interactive UI with a Cobra command, enabling the UI to run within the Cobra CLI's lifecycle.
  • AfterPreRun: This method is called after Cobra's PreRun phase, allowing for any additional setup or initialization that should occur after the PreRun function of a Cobra command.
  • BeforePreRun: This method is called before Cobra's PreRun phase, allowing the UI to perform setup tasks or make adjustments before the Cobra command's PreRun is executed.
  • AfterRun: Called after Cobra's Run phase, providing an opportunity for any post-execution steps or cleanup.
  • BeforeRun: Called before Cobra's Run phase, enabling setup or preparation tasks before the Cobra command is executed.

func New

func New() UI

New creates a new instance of the UI interface. It returns a concrete implementation of the UI, which can be used to set up and run an interactive user interface in terminal applications.

The returned UI allows developers to configure questions, run the UI, and integrate it with Cobra commands.

Example usage:

ui := cobra_ui.New()
ui.SetQuestions([]cobra_ui.Question{
    {
        Text: "What is your preferred programming language?",
        Options: []string{"Go", "Python", "JavaScript", "Java"},
        Handler: func(input string) error {
            fmt.Printf("Selected language: %s\n", input)
            return nil
        },
    },
})
ui.RunInteractiveUI()

Returns: - UI: A new instance of the UI interface, which can be configured and run.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL