vox

package module
v0.0.0-...-a42b0b0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2018 License: MIT Imports: 14 Imported by: 4

README

GoDoc Go Report Card Build Status

Vox is a Go package designed to help make terminal/console applications more attractive.

It is a collection of small helper functions that aid in printing various pieces of information to the console.

  • Various predefined and common printing tasks like printing property key/value pairs, result responses, etc.
  • Print JSON data with syntax highlighting
  • Easily print colorized output
  • Display real time progress bars for tasks
  • Easy helper functions for printing various types of messages: Alerts, errors, debug messages, etc.
  • Control the output and input streams to help during application testing.

Usage

import "github.com/5sigma/vox"

Printing with color

There are a number of functions that allow printing arbitrary text with colors such as Printc, Printlnc, and Sprintc. These all take a color as their first argument and printable objects after them. They will also append a color reset to the end.

  vox.Printlnc(vox.Red, "Hello, I am red")

Printing complex color coded text can be slightly more complicated. The basic printing functions will remove their color codes for output Pipelines that are considered Plain, such as the FilePipeline. To print complex color coded text something like this could be used:

vox.Print("I am")
vox.Printc(vox.Green, "green ")
vox.Print(" and ")
vox.Printc(vox.Red, " red", vox.ResetColor)
vox..Print("\n")

Although a better solution maybe to use the PrintRich and PrintPlain functions which will only output to plain or non plain Pipelines.

vox.PrintRich("I am ", vox.Green, "green ", vox.ResetColor, " and ", vox.Red, "red", vox.ResetColor)
vox.PrintPlain("I am green and red)
Colors

The following color constants exist, along with a ResetColor constant:

  • Black
  • Red
  • Green
  • Yellow
  • Blue
  • Magenta
  • Cyan
  • White

Loglevel functions

The loglevel functions print standard types of messages (debug, error, alert, info) colored and formatted. See the package documentation for their definitions.

vox.Debug("hai")
vox.Alert("oh no")
vox.Info("this thing happened")
vox.Error("whoops")

Printing results

Prints a key and a result string depending on if the error value is nil.

err := writeFile()
vox.PrintResult("Writing file", err)

Task: [OK] Task2: [FAIL]

  • Error messsage Task3: [OK]

Printing property lists

Prints a key and value and pads them to align on the edges of the screen.

vox.PrintResult("Name", user.Name)
vox.PrintResult("Email", user.Email)
Key:                                   some value
Key:                                   some value
Key:                                   some value

Prompting for input

Prompting for a basic string response from the user:

result := vox.Prompt("Enter a response", "none")
vox.Println("You entered ", result)

Prompting for a boolean response:

result := vox.PromptBool("Are you sure", false)
if !result {
  return
}

Prompting for a choice of options:

choices := []string{"Option 1", "Option 2", "Option 3"}
resultIndex := vox.PromptChoice("Choose an option", choices, 0)

Displaying progress

The progress bar is controlled using StartProgress, IncProgress, and SetProgress.

vox.StartProgress(0, len(myTasks))
for _, t := range myTasks {
  err := doTask(myTask)
  if err != nil {
    vox.Error(err.Error())
    break
  }
  vox.IncProgress()
}
vox.StopProgress()

Testing

A testing pipeline is provided that directs all output into an internal string slice. It also provides utility functions to make accessing values easier.

v := vox.New()
pipline = vox.TestPipeline{}
v.SetPipelines(pipeline)
v.Print("test")
if (pipeline.Last() != "test" {
  t.Error("not test")
}

A Test helper function is provided to make this easier:

pipeline := vox.Test()

An example test

func AskForFile() string {
	return vox.Prompt("Enter a file", "")
}

func TestReadConfig(t *testing.T) {
	// setup for testing
	pipeline = vox.Test()

	// verify an error output
	err := checkFile()
	if pipeline.Last() != fmt.Sprint(vox.Red, "No config file found.") {
		t.Errorf("Error message not printed: %s", pipeline.Last())
	}

	// Asks user for a file path
	SendInput("test.txt")
	name := AskForFile()

	// Builds a config file
	SetupFile(name)


	err = checkFile()
	if err != nil {
		t.Errorf("Could not load config file: %s", err.Error())
	}
	if pipeline.Last() != "Config file read" {
		t.Error("Value missmatch: %s", pipeline.Last())
	}
}

Documentation

Overview

Vox is a Go package designed to help make terminal/console applications more attractive.

It is a collection of small helper functions that aid in printing various pieces of information to the console.

- Various predefined and common printing tasks like printing property key/value pairs, result responses, etc.

- Print JSON data with syntax highlighting

- Easily print colorized output

- Display real time progress bars for tasks

- Easy helper functions for printing various types of messages: Alerts, errors, debug messages, etc.

- Control the output and input streams to help during application testing.

Printing to the screen

There are a number of output functions to print data to the screen with out without coloring. Most of the output functions accept an a series of string parts that are combined together. Color constants can be interlaced between these parts to color the output.

vox.Println(vox.Red, "Some read text", vox.ResetColor)

There are also a number of "LogLevel" type functions that easily color the output.

vox.Alert("A warning")
vox.Errorf("An error occured: %s", err.Error())
vox.Debug(""A debug message")

Prompting for input

There are several helper functions for gathering input from the console.

strResponse := vox.Prompt("a message", "a default value")
boolResponse := vox.PromptBool("a message", true)
choices := []string{"option 1", "option 2"}
choiceIndex := vox.PromptChoice("A message", choices, 1)

Pipelines

Vox offers pipelines as a way of configuring one or more output streams. Four built in pipelines are provided with the package:

- ConsolePipeline - This is the default Pipeline set for any vox instance. This pipeline will present colored output to standard out.

- FilePipeline - This pipeline will redirect all data to a local file. This pipeline uses plain output, without color codes.

- TestPipeline - All output will be internally stored in a string slice and utility functions are provided to make accessing values easier. This pipeline should be used for unit tests.

- WriterPipeline - This is a generic pipeline that allows you to specifiy any writer that implements the io.Writer interface.

Testing

A testing pipeline is provided that directs all output into an internal string slice. It also provides utility functions to make accessing values easier.

v := vox.New()
pipline = vox.TestPipeline{}
v.SetPipelines(pipeline)
v.Print("test")
if (pipeline.Last() != "test" {
	t.Error("not test")
}

A Test helper function is provided to make this easier:

pipeline := vox.Test()

You can use the `SendInput` function. SendInput must be called before any prompt function, so that the data is ready in the buffer when `Prompt` is called.

func AskForFile() string {
	return vox.Prompt("Enter a file", "")
}

func TestReadConfig(t *testing.T) {
	// setup for testing
	pipeline = vox.Test()

	// verify an error output
	err := checkFile()
	if pipeline.Last() != fmt.Sprint(vox.Red, "No config file found.") {
		t.Errorf("Error message not printed: %s", pipeline.Last())
	}

	// Asks user for a file path
	SendInput("test.txt")
	name := AskForFile()

	// Builds a config file
	SetupFile(name)

	err = checkFile()
	if err != nil {
		t.Errorf("Could not load config file: %s", err.Error())
	}
	if pipeline.Last() != "Config file read" {
		t.Error("Value missmatch: %s", pipeline.Last())
	}
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// Back - Black terminal color constant. This can be used as a string inside any of the output functions
	Black = Color{0}

	// Red - Red terminal color constant. This can be used as a string inside any of the output functions
	Red = Color{1}

	// Green - Green terminal color constant. This can be used as a string inside any of the output functions
	Green = Color{2}

	// Yellow - Yellow terminal color constant. This can be used as a string inside any of the output functions
	Yellow = Color{3}

	// Blue - Blue terminal color constant. This can be used as a string inside any of the output functions
	Blue = Color{4}

	// Magenta - Magenta terminal color constant. This can be used as a string inside any of the output functions
	Magenta = Color{5}

	// Cyan - Cyan terminal color constant. This can be used as a string inside any of the output functions
	Cyan = Color{6}

	// White - White terminal color constant. This can be used as a string inside any of the output functions
	White = Color{7}

	// ResetColor - Resets the terminal back to its default color. This can be used as a string inside any of the output functions
	ResetColor = Color{9}
)

Functions

func AddPipeline

func AddPipeline(p Pipeline)

AddPipeline adds a new pipeline to the logger

func Alert

func Alert(args ...interface{})

Alert - Print an info output. Console output is colored yellow.

func Alertf

func Alertf(format string, args ...interface{})

Alertf - Print an info output. Console output is colored yellow.

func ClearInput

func ClearInput()

ClearInput - Clears the input buffer. Useful during testing.

func Debug

func Debug(args ...interface{})

Debug - Print an debug output. Debug output is not colored.

func Debugf

func Debugf(format string, args ...interface{})

Debugf - Print an debug output. Debug output is not colored.

func Error

func Error(args ...interface{})

Error - Print output as an error. Console output is colored red.

func Errorf

func Errorf(format string, args ...interface{})

Errorf - Print error output. Console output is colored red.

func Fatal

func Fatal(args ...interface{})

Fatal - Prints an error message and then exits the application.

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf - Prints an error message and then exits the application.

func IncProgress

func IncProgress()

IncProgress - Increment the current progress value by name. If the new Current value is equal to the Max value StopProgress will be called automatically.

func Info

func Info(args ...interface{})

Info - Print an info output. Console output is colored white.

func Infof

func Infof(format string, args ...interface{})

Infof - Print an info output. Console output is colored white.

func Print

func Print(s ...interface{})

Print - Prints a number of variables.

func PrintJSON

func PrintJSON(contentBytes []byte)

PrintJSON - Prints a byte array contianing JSON content. This output will be color coded and syntax highlighted. It is also reformatted with indentation.

func PrintPlain

func PrintPlain(c Color, s ...interface{})

PrintPlain will only print to plain pipelines, such as the FilePipeline

func PrintProperty

func PrintProperty(name, value string)

PrintProperty - Prints a property name and value. The value will be right aligned.

func PrintResult

func PrintResult(desc string, err error)

PrintResult - Prints a name and a result message. If an error is passed it will result in a failure message ex. If nil is passed as the second argument it will result in a success. The status code will also be right aligned and color coded based on the result.

func PrintRich

func PrintRich(c Color, s ...interface{})

PrintRich will only print to non plain pipelines. It is safe to embed color codes in this function.

func Printc

func Printc(c Color, s ...interface{})

Printc - sends the string results of the objects prefixed with a color code. For plain pipelines the color code will be stripped out.

func Printf

func Printf(format string, s ...interface{})

Printf - Prints a formatted string using a template and as series of variables.

func Println

func Println(s ...interface{})

Println - Prints a number of tokens ending with a new line.

func Printlnc

func Printlnc(c Color, s ...interface{})

Printlnc - Prints a number of tokens followed by a new line. This output is also wrapped in a color code and a reset.

func Prompt

func Prompt(name, defaultVal string) string

Prompt - Gets input from the input stream. By default Stdin. If an empty string is sent the default value will be returned.

func PromptBool

func PromptBool(message string, defaultVal bool) bool

PromptBool - Prompts the user for a boolean response.

func PromptChoice

func PromptChoice(msg string, choices []string, defaultIdx int) string

PromptChoice - Prompts for a choice of a series of options from the user.

func SendInput

func SendInput(str string) error

SendInput - Writes data into the input stream. Used for testing.

func SetInput

func SetInput(in *os.File)

SetInput - Sets the input stream for VOX. This is mainly used for testing.

func SetPipelines

func SetPipelines(p Pipeline)

SetPipelines replaces all pipelines with the passed pipeline

func SetProgress

func SetProgress(current int)

SetProgress - Sets the current progress value.

func Sprintc

func Sprintc(c Color, args ...interface{}) string

Sprintc - Creates a string in a given color. The color code prepends the string and a reset code is appended to it.

func StartProgress

func StartProgress(current, max int)

StartProgress - Start outputing a progressbar.

func StopProgress

func StopProgress()

StopProgress - Stops outputing a progress bar and closes associated writers. This is called automatically if the Current value equals, or exceeds, the maximum value.

Types

type Color

type Color struct {
	// contains filtered or unexported fields
}

Color - A structure which represents a single color. This structure should not need to be used directly. Variables for each color are exported in the package.

func (Color) String

func (c Color) String() string

type ConsolePipeline

type ConsolePipeline struct{}

ConsolePipeline a log pipeline that outputs directly to STDERR

func (*ConsolePipeline) Config

func (c *ConsolePipeline) Config() *PipelineConfig

Config returns the pipeline configuration

func (*ConsolePipeline) Initialize

func (c *ConsolePipeline) Initialize() error

Initialize has no logic for a ConsolePipeline

func (*ConsolePipeline) Write

func (c *ConsolePipeline) Write(b []byte) (int, error)

Write sends data to the output Stdout

type FilePipeline

type FilePipeline struct {
	Filepath string
	// contains filtered or unexported fields
}

FilePipeline sends output into a local file

func (*FilePipeline) Close

func (f *FilePipeline) Close()

Close closes the file pointer

func (*FilePipeline) Config

func (f *FilePipeline) Config() *PipelineConfig

Config returns the pipline configuration

func (*FilePipeline) Initialize

func (f *FilePipeline) Initialize() error

Initialize opens the local file for reading

func (*FilePipeline) Write

func (f *FilePipeline) Write(b []byte) (int, error)

Write sends the data to the local filepath

type Pipeline

type Pipeline interface {
	Config() *PipelineConfig
	Write([]byte) (int, error)
	Initialize() error
}

Pipeline represents a specific log pipeline

type PipelineConfig

type PipelineConfig struct {
	// Plain - If set to true all color information and some formatting will be
	// stripped from the output. This is normally used for outputs directed towards
	// files.
	Plain bool
}

PipelineConfig is the configuration for a pipeline The pipeline config should be returned from the Config function for any pipeline structure.

type TestPipeline

type TestPipeline struct {
	LogLines []string
	Plain    bool
}

TestPipeline a pipeline that can be used in tests

func Test

func Test() *TestPipeline

Test - Sets up vox to print and read from in memory locations for testing.

func (*TestPipeline) All

func (t *TestPipeline) All() string

All returns all output data

func (*TestPipeline) Clear

func (t *TestPipeline) Clear()

Clear removes all items in the pipelines buffer

func (*TestPipeline) Config

func (t *TestPipeline) Config() *PipelineConfig

Config returns the pipline configuration

func (*TestPipeline) Initialize

func (t *TestPipeline) Initialize() error

Initialize sets up the testing pipeline

func (*TestPipeline) Last

func (t *TestPipeline) Last() string

Last returns the last section of data sent

func (*TestPipeline) Write

func (t *TestPipeline) Write(b []byte) (int, error)

type Vox

type Vox struct {
	// contains filtered or unexported fields
}

Vox - The main class for Vox all functions are called from this object. Direct functions use an auto generated Vox object.

func New

func New() *Vox

New - creates a new Vox instance. This can be used as an alternative to the singletone instance. If multiple Vox instances are needed.

func (*Vox) AddPipeline

func (v *Vox) AddPipeline(p Pipeline)

AddPipeline adds a new pipeline to the logger

func (*Vox) Alert

func (v *Vox) Alert(args ...interface{})

Alert - Print an info output. Console output is colored yellow.

func (*Vox) Alertf

func (v *Vox) Alertf(format string, args ...interface{})

Alertf - Print an info output. Console output is colored yellow.

func (*Vox) Debug

func (v *Vox) Debug(args ...interface{})

Debug - Print an debug output. Debug output is not colored.

func (*Vox) Debugf

func (v *Vox) Debugf(format string, args ...interface{})

Debugf - Print an debug output. Debug output is not colored.

func (*Vox) Error

func (v *Vox) Error(args ...interface{})

Error - Print output as an error. Console output is colored red.

func (*Vox) Errorf

func (v *Vox) Errorf(format string, args ...interface{})

Errorf - Print error output. Console output is colored red.

func (*Vox) Fatal

func (v *Vox) Fatal(args ...interface{})

Fatal - Prints an error message and then exits the application.

func (*Vox) Fatalf

func (v *Vox) Fatalf(format string, args ...interface{})

Fatalf - Prints an error message and then exits the application.

func (*Vox) IncProgress

func (v *Vox) IncProgress()

IncProgress - Increment the current progress value by name. If the new Current value is equal to the Max value StopProgress will be called automatically.

func (*Vox) Info

func (v *Vox) Info(args ...interface{})

Info - Print an info output. Console output is colored white.

func (*Vox) Infof

func (v *Vox) Infof(format string, args ...interface{})

Infof - Print an info output. Console output is colored white.

func (*Vox) Print

func (v *Vox) Print(s ...interface{})

Print - Prints a number of variables.

func (*Vox) PrintJSON

func (v *Vox) PrintJSON(contentBytes []byte)

PrintJSON - Prints a byte array contianing JSON content. This output will be color coded and syntax highlighted. It is also reformatted with indentation.

func (*Vox) PrintPlain

func (v *Vox) PrintPlain(s ...interface{})

PrintPlain will only print to non plain pipelines. It is safe to embed color codes in this function.

func (*Vox) PrintProperty

func (v *Vox) PrintProperty(name, value string)

PrintProperty - Prints a property name and value. The value will be right aligned.

func (*Vox) PrintResult

func (v *Vox) PrintResult(desc string, err error)

PrintResult - Prints a name and a result message. If an error is passed it will result in a failure message ex. If nil is passed as the second argument it will result in a success. The status code will also be right aligned and color coded based on the result.

func (*Vox) PrintRich

func (v *Vox) PrintRich(s ...interface{})

PrintRich will only print to non plain pipelines. It is safe to embed color codes in this function.

func (*Vox) Printc

func (v *Vox) Printc(c Color, s ...interface{})

Printc - sends the string results of the objects prefixed with a color code. For plain pipelines the color code will be stripped out.

func (*Vox) Printf

func (v *Vox) Printf(format string, s ...interface{})

Printf - Prints a formatted string using a template and as series of variables.

func (*Vox) Println

func (v *Vox) Println(s ...interface{})

Println - Prints a number of tokens ending with a new line.

func (*Vox) Printlnc

func (v *Vox) Printlnc(c Color, s ...interface{})

Printlnc - Prints a number of tokens followed by a new line. This output is also wrapped in a color code and a reset.

func (*Vox) Prompt

func (v *Vox) Prompt(name, defaultValue string) string

Prompt - Gets input from the input stream. By default Stdin. If an empty string is sent the default value will be returned.

func (*Vox) PromptBool

func (v *Vox) PromptBool(message string, defaultVal bool) bool

PromptBool - Prompts the user for a boolean response.

func (*Vox) PromptChoice

func (v *Vox) PromptChoice(msg string, choices []string, defIdx int) string

PromptChoice - Prompts for a choice of a series of options from the user.

func (*Vox) SendInput

func (v *Vox) SendInput(str string) error

SendInput - Writes data into the input stream. Used for testing.

func (*Vox) SetInput

func (v *Vox) SetInput(in *os.File)

SetInput - Sets the input stream for VOX. This is mainly used for testing.

func (*Vox) SetPipelines

func (v *Vox) SetPipelines(p Pipeline)

SetPipelines replaces all pipelines with the passed pipeline

func (*Vox) SetProgress

func (v *Vox) SetProgress(current int)

SetProgress - Sets the current progress value.

func (*Vox) StartProgress

func (v *Vox) StartProgress(current, max int)

StartProgress - Start outputing a progressbar.

func (*Vox) StopProgress

func (v *Vox) StopProgress()

StopProgress - Stops outputing a progress bar and closes associated writers. This is called automatically if the Current value equals, or exceeds, the maximum value.

func (*Vox) Test

func (v *Vox) Test() *TestPipeline

Test - Sets up vox to print and read from in memory locations for testing.

func (*Vox) Write

func (v *Vox) Write(p []byte) (n int, err error)

Write writes data into the log

type WriterPipeline

type WriterPipeline struct {
	Writer io.Writer
	Plain  bool
}

WriterPipeline implements a generic pipeline powered by an io.Writer stream

func (*WriterPipeline) Config

func (w *WriterPipeline) Config() *PipelineConfig

Config returns a configuration for the pipeline. Plain is specified on the pipeline itself and patched into the configuration.

func (*WriterPipeline) Initialize

func (w *WriterPipeline) Initialize() error

Initialize has no logic in a WriterPipeline

func (*WriterPipeline) Write

func (w *WriterPipeline) Write(b []byte) (int, error)

Write sends data into the specified writer.

Jump to

Keyboard shortcuts

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