Help us shape the future of Go! Take the 2026 Go Developer Survey

dsky

package module
v0.0.0-...-3cbe8bb Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2015 License: Apache-2.0 Imports: 9 Imported by: 0

README

dsky GoDoc Build Status

Dsky (DISS-key) is a UI framework for building powerful terminal applications. It provides a CLI, based on Cobra and set of UI components. Dsky powers almost all of OvrClk's tools.

Features

Racer currently supports Cobra 0.0.9 and adds the below additionaly functionality:

  • Command organization based on help topic foo:bar
  • Tabled Output formatting helpers
  • Interactive UI components - Normal Prompts, Password Prompts, Progress Bar
  • Terminal Text Styling - Foreground and Background colors with Style Emphasis

Cobra provides:

  • Fully posix compliant flags (including short & long versions)
  • Nested sub commands
  • Global, local and cascading flags
  • Easy generation of applications & commands with cobra create appname & cobra add cmdname
  • Intelligent suggestions (app srver.. did you mean app server)
  • Automatic help generation for commands and flags
  • Automatic detailed help for app help [command]
  • Automatic help flag recognition of -h, --help, etc.
  • Automatically generated bash autocomplete for your application
  • Automatically generated man pages for your application
  • Command aliases so you can change things without breaking them
  • The flexibilty to define your own help, usage, etc
  • Optional tight integration with viper for 12 factor apps

Help Topics

Racer organizes help based on a namespace, the below is the output for OvrClk command utility built using racer:

$ ovrclk help

Utility to manage your clusters and applications on ovrclk

Usage: ovrclk COMMAND [<args>..] [options]

Primary help topics, type "ovrclk help TOPIC" for more details:

  apps        create, deploy and manage applications
  auth        login, logout and display vpn and token
  clusters    launch, teardown and manage clusters
  config      set and unset config variables for apps
  logs        display application and storage logs
  releases    deploy, revert and manage app releases
  storage     attach, detach and manage storage appliances
  users       add, remove and manage users

Additional topics:

  datacenters display datacenters
  regions     display regions
  version     display version
$ ovrclk clusters help
List all clusters

Usage: ovrclk clusters [options]

Options:

  -h, --help=false: help for clusters

General Options:

  -s, --server="": The address and port of the ovrclk API server
  -t, --token="": Bearer token for authenticating with the API server

Additional commands, type "ovrclk COMMAND --help" for more details:

  clusters:up [SELECTOR]                   Launch a new cluster. The selector could either be a region or a datacenter name
  clusters:info --cluster=<name>           Display info for the cluster
  clusters:down --cluster=<name>           Teardown the cluster
  clusters:rename NEWNAME --cluster=<name> Rename the cluster
  clusters:update --cluster=<name>         Update the cluster

UI Components

Table Output
type hacker struct {
	Name     string
	Birthday string
	Bio      string
}

var hackers = []hacker{
	{"Ada Lovelace", "December 10, 1815", "Ada was a British mathematician and writer, chiefly known for her work on Charles Babbage's early mechanical general-purpose computer, the Analytical Engine"},
	{"Alan Turing", "23 June, 1912", "Alan was a British pioneering computer scientist, mathematician, logician, cryptanalyst and theoretical biologist"},
}

table := ui.NewTable("NAME", "BIRTHDATE", "BIO")
table.MaxCellWidth = 20
for _, hacker := range hackers {
  table.AddRow(hacker.Name, hacker.Birthday, hacker.Bio)
}
ui.Printer().Add(table).Print()
NAME          BIRTHDATE         BIO
Ada Lovelace  December 10, 1815 Ada was a British...
Alan Turing   23 June, 1912     Alan was a Britis...
Progress Bar
count := 5000
bar := ui.NewProgressBar(count).Start()
for i := 0; i < count; i++ {
  bar.Increment()
  time.Sleep(time.Millisecond)
}
bar.FinishPrint("The End!")
963 / 5000 [=====================>---------------------------------] 39.26 % 3s
Hidden Input Prompt
var password string
racer.UI().Prompter().PromptHiddenString(&password, "Password: ")
Terminal Styling
fmt.Println(ui.Color().Green("bold green with white background", ui.StyleBold, ui.ColorWhiteBg))
fmt.Println(ui.Color().Red("underline red", ui.StyleUnderline))
fmt.Println(ui.Color().Yellow("dim yellow", ui.StyleDim))
fmt.Println(ui.Color().Cyan("inverse cyan", ui.StyleInverse))
fmt.Println(ui.Color().Blue("bold underline dim blue", ui.StyleBold, ui.StyleUnderline, ui.StyleDim))

color output

More Examples

See examples under /examples for full examples

Credits

The framework is a composition, with library contributions from:

Documentation

Overview

Package dsky is a library for creating powerful modern CLI applications. It based on Cobra

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultCLI = New(nil)

DefaultCLI is the default CLI for the package

Functions

func Execute

func Execute() error

Execute executes the DefaultCLI. It binds usage function and runs the root command.

func Printer

func Printer() *ui.BufferedPrinter

Printer returns the printer for the Default CLI

func UI

func UI() ui.UserInterface

UI reeturns the Default UI

Types

type ByName

type ByName struct{ Topics }

ByName implements sort.Interface by providing Less and using the Len and Swap methods of the embedded Topic value.

func (ByName) Less

func (t ByName) Less(i, j int) bool

type CLI

type CLI struct {
	// Topics are a list a of Help Topics
	Topics

	// NoIteractive flag determines the interactive mode of the CLI
	NoInteractive bool

	// NoColor when true does not display colors
	NoColor bool
	// contains filtered or unexported fields
}

CLI represent the Racer CLI library

Example
package main

import (
	"fmt"
	"github.com/gosuri/dsky"
	"github.com/gosuri/dsky/ui"
	"github.com/spf13/cobra"
)

type Cluster struct {
	Name, Datacenter string
	Size             int
}

var clusters = []Cluster{
	{"dev", "sfo1", 1},
	{"prod", "sfo2", 3},
}

type App struct {
	Name, Size string
	Deployed   bool
}

var apps = []App{
	{"frontend", "7MB", true},
	{"api", "6MB", false},
}

func main() {
	root := &cobra.Command{
		Short: "Utility to manage your clusters and applications on ovrclk",
		Use:   "ovrclk COMMAND [<args>..] [options]",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.DebugFlags()
			cmd.Help()
		},
	}

	dsky.SetRoot(root)

	dsky.AddTopic("apps", "create, deploy and manage applications", true)

	appsCmd := &cobra.Command{
		Use:   "apps",
		Short: "List all apps",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.DebugFlags()
			dsky.Printer().Add(ui.NewTitle("Apps"))
			table := ui.NewTable("NAME", "SIZE", "DEPLOYED")
			for _, a := range apps {
				table.AddRow(a.Name, a.Size, a.Deployed)
			}
			dsky.Printer().Add(table).Flush()
		},
	}
	dsky.AddCommand(appsCmd)

	appsInfo := &cobra.Command{
		Use:     "apps:info",
		Short:   "Display info for the app",
		Long:    "Show detailed app information. For more info visit http://example.com/foo",
		Aliases: []string{"info"},
		Example: "ovrclk apps:info -a foo",
		Run: func(cmd *cobra.Command, args []string) {
			app := apps[0]
			dsky.Printer().Add(ui.NewTitle(fmt.Sprintf("%s (app)", app.Name)))
			table := ui.NewTable()
			table.AddRow("Name:", app.Name)
			table.AddRow("Size:", app.Size)
			table.AddRow("Deployed:", app.Deployed)
			dsky.Printer().Add(table).Flush()
		},
	}
	var acinfo string
	appsInfo.Flags().StringVarP(&acinfo, "cluster", "c", "", "Show cluster info")
	dsky.AddCommand(appsInfo)

	newApp := &App{}
	appsCreate := &cobra.Command{
		Use:     "apps:create",
		Short:   "Create an app",
		Aliases: []string{"create"},
		Run: func(cmd *cobra.Command, args []string) {
			dsky.UI().Prompt().String(&newApp.Name, "Application Name: ")
			if newApp.Name == "" {
				fmt.Println("Error: app name is required")
				return
			}

			fmt.Printf("=> creating app (%s) \n", newApp.Name)
			dsky.UI().Printer().Add(ui.NewTitle(fmt.Sprintf("%s (app)", newApp.Name)))
			table := new(ui.Table)
			table.AddRow("Name:", newApp.Name)
			table.AddRow("Size:", newApp.Size)
			table.AddRow("Deployed:", newApp.Deployed)
			dsky.Printer().Add(table).Flush()
		},
	}
	appsCreate.Flags().StringVarP(&newApp.Name, "name", "a", "", "App name")
	dsky.AddCommand(appsCreate)

	dsky.AddTopic("clusters", "create, teardown and manage clusters", false)
	clusters := &cobra.Command{
		Use:   "clusters",
		Short: "Manage clusters",
		Run: func(cmd *cobra.Command, args []string) {
			dsky.Printer().Add(ui.NewTitle("Clusters"))
			table := ui.NewTable("NAME", "DATACENTER", "SIZE")
			for _, c := range clusters {
				table.AddRow(c.Name, c.Datacenter, c.Size)
			}
			dsky.Printer().Add(table).Flush()
		},
	}
	dsky.AddCommand(clusters)

	clusterLaunch := &cobra.Command{
		Use:   "clusters:launch",
		Short: "Launch a cluster",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf("inside clusters:launch with Args: %v\n", args)
		},
	}
	var dc string
	clusterLaunch.Flags().StringVarP(&dc, "datacenter", "d", "", "datacenter for the cluster")
	dsky.AddCommand(clusterLaunch)

	// Global flags
	var host string
	root.PersistentFlags().StringVarP(&host, "server", "s", "", "The address and port of the ovrclk API server")
	dsky.Execute()
}

func AddCommand

func AddCommand(cmd *cobra.Command) *CLI

AddCommand register a cobra command with the default CLI

func AddTopic

func AddTopic(name, desc string, primary bool) *CLI

AddTopic adds a help topic to the default CLI

func New

func New(root *cobra.Command) *CLI

New returns an instance of the CLI and registers the root command

func SetRoot

func SetRoot(root *cobra.Command) *CLI

SetRoot registers the command as the root command for the default CLI

func (*CLI) AddCommand

func (c *CLI) AddCommand(cmd *cobra.Command) *CLI

AddCommand register a cobra command with the CLI

func (*CLI) AddTopic

func (c *CLI) AddTopic(name, desc string, primary bool) *CLI

AddTopic adds a help topic to the CLI

func (*CLI) Bind

func (c *CLI) Bind() *CLI

Bind binds the usage function and global flags to the command

func (*CLI) Execute

func (c *CLI) Execute() error

Execute binds usage function and runs the root command

func (*CLI) Name

func (c *CLI) Name() string

Name returns the first part of the cmd.Use

func (*CLI) Printer

func (c *CLI) Printer() *ui.BufferedPrinter

Printer returns the printer for the CLI

func (*CLI) Root

func (c *CLI) Root() *cobra.Command

Root returns the command associated with the cli

func (*CLI) SetRoot

func (c *CLI) SetRoot(root *cobra.Command) *CLI

SetRoot registers the command as root command

func (*CLI) SetUI

func (c *CLI) SetUI(ui ui.UserInterface) *CLI

func (*CLI) UI

func (c *CLI) UI() ui.UserInterface

func (*CLI) UsageFunc

func (cli *CLI) UsageFunc(c *cobra.Command) error

UsageFunc provides usage information for topics and commands

type Topic

type Topic struct {
	// Name is the name of the topic
	Name string

	// Desc is the description of the topic
	Desc string

	// Primary indicates if the topic a primary topic
	Primary bool

	// Commands are commands associated with the topic
	Commands []*cobra.Command

	// RootCmdPath is the path of the root command
	RootCmdPath string
}

Topic represents a command help topic

func (*Topic) NamePadding

func (t *Topic) NamePadding() int

Returns the padding required for the name when rending topic usage

type Topics

type Topics []*Topic

Topics represnet a list of help topics

func (Topics) Additional

func (t Topics) Additional() Topics

Additional returns the additional topics in the list

func (Topics) Len

func (t Topics) Len() int

Len returns the number of topics in Topics list

func (Topics) Primary

func (t Topics) Primary() Topics

Primary returns the Primary help topics from the topic list

func (Topics) Swap

func (t Topics) Swap(i, j int)

Swap swaps topic i with topic j

func (Topics) TopicNamePadding

func (t Topics) TopicNamePadding() int

Returns the padding required for the name when rendering main help

Directories

Path Synopsis
examples
color command
full command
progressbar command
table command
pkg
ui
Pacakge UI provides user iteraction functionality to the CLI
Pacakge UI provides user iteraction functionality to the CLI
pb

Jump to

Keyboard shortcuts

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