cli

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2021 License: MIT Imports: 11 Imported by: 2

README

gorepotemplate

Tricky and fun utilities for Go programs.


GitHub Workflow Status Codecov

Contributor Covenant

Twitter Follow GitHub followers


Getting Started

Prerequisites

Developed with $( go version; ). Go is extremely backwards compatible and semver stable. Nearly any v1.x should work fine.


Installation

To use this repo as a template for your own project:

gh repo create -y --public --template "https://github.com/skeptycal/gorepotemplate"

Clone this repo to test and contribute:

# add repo to $GOPATH (xxxxxx is your computer login username)
go get github.com/xxxxxx/gorepotemplate

cd ${GOPATH}/src/github.com/xxxxxx/gorepotemplate

# test results and coverage info
./go.test.sh

# install as a utility package
go install

Use the Issues and PR templates on the GitHub repo page to contribute.


Basic Usage

This is a copy of the example script available in the cmd/example/gorepotemplate folder:

package main

import "github.com/skeptycal/gorepotemplate"

func main() {
    gorepotemplate.Example()
}

To try it out:

# change to the sample folder
cd cmd/example/gorepotemplate

# run the main.go program
go run ./main.go

# to compile as an executable
go build

Code of Conduct and Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us. Please read the Code of Conduct for details before submitting anything.


Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.


Contributors and Inspiration

  • Michael Treanor (GitHub / Twitter) - Initial work, updates, maintainer
  • Francesc Campoy - Inspiration and great YouTube videos!

See also the list of contributors who participated in this project.


License

Licensed under the MIT https://opensource.org/licenses/MIT - see the LICENSE file for details.

Documentation

Overview

Package cli contains utility functions for dealing with cli commands within Go.

The main component is the CLI interface that implements cli features through the Terminal struct. Reference: github.com/skeptycal/cli

The ansi color terminal support is provided by the ansi package. Reference: github.com/skeptycal/ansi

Index

Constants

View Source
const (
	BLACK = iota
	RED
	GREEN
	YELLOW
	BLUE
	MAGENTA
	CYAN
	WHITE
)

List of possible colors

View Source
const PCT = 0x8000 << shift
View Source
const (
	Reset string = ansi.Reset
)
View Source
const ResetColor = "\033[32m"

ResetColor - Reset to default color

View Source
const ResetLineConst = "\r\033[K"

ResetLineConst - Return cursor to start of line and clean it

Variables

View Source
var (
	ResetBytes   []byte = ansi.ResetBytes
	InverseBytes string = simpleEncode(ansi.Inverse)
)

Screen - Global screen buffer Its not recommended write to buffer dirrectly, use package Print,Printf,Println fucntions instead.

Functions

func Background

func Background(str string, color int) string

Background - Change background color of string:

tm.Background("string", tm.RED)

func BasicEncode

func BasicEncode(b interface{}) string

BasicEncode encodes a basic (3-4 bit) ANSI color code. The code may be passed in as a byte, int, uint, float32, float64, or string and will be converted to the best guess of a byte (uint8) value before encoding.

It is best to use a byte value ...

The format is "\x1b[%dm"

func Bold

func Bold(str string) string

Bold - Make bold

func CheckIfTerminal added in v0.3.0

func CheckIfTerminal(w io.Writer) bool

func Clear

func Clear()

Clear screen

func Color

func Color(str string, color int) string

Color - Apply given color to string:

tm.Color("RED STRING", tm.RED)

func Columns

func Columns() int

Columns returns the number of columns in the terminal, similar to the COLUMNS environment variable on macOS and Linux systems.

func Context

func Context(data string, idx, max int) string

func CurrentHeight

func CurrentHeight() int

CurrentHeight gets current height. Line count in Screen buffer.

func Flush

func Flush()

Flush buffer and ensure that it will not overflow screen

func GetWinSize added in v0.3.0

func GetWinSize() (*unix.Winsize, error)

GetWinSize returns device caps for the terminal. The Winsize struct returned includes:

Row, Col, Xpixel, and Ypixel.

func GetXY

func GetXY(x int, y int) (int, int)

GetXY gets relative or absolute coordinates To get relative, set PCT flag to number:

// Get 10% of total width to `x` and 20 to y
x, y = tm.GetXY(10|tm.PCT, 20)

func Height

func Height() int

Height gets console height

func Highlight

func Highlight(str, substr string, color int) string

func HighlightRegion

func HighlightRegion(str string, from, to, color int) string

func MoveCursor

func MoveCursor(x int, y int)

MoveCursor - Move cursor to given position

func MoveCursorBackward

func MoveCursorBackward(bias int)

MoveCursorBackward - Move cursor backward relative the current position

func MoveCursorDown

func MoveCursorDown(bias int)

MoveCursorDown - Move cursor down relative the current position

func MoveCursorForward

func MoveCursorForward(bias int)

MoveCursorForward - Move cursor forward relative the current position

func MoveCursorUp

func MoveCursorUp(bias int)

MoveCursorUp - Move cursor up relative the current position

func MoveTo

func MoveTo(str string, x int, y int) (out string)

MoveTo - Move string to possition

func NewLogger

func NewLogger() *logrus.Logger

NewLogger creates a new logrus logger that is compatible with the go log package and has terminal stderr defaults set.

Configuration should be set by changing `Formatter`, `Out` and `Hooks` directly on the default logger instance. You can also just instantiate your own directly:

import logrus "github.com/sirupsen/logrus"

var log = &logrus.Logger{
  Out: os.Stderr,
  Formatter: new(logrus.TextFormatter),
  Hooks: make(logrus.LevelHooks),
  Level: logrus.DebugLevel,
}

It's recommended to make this a global instance called `log`.

func Print

func Print(a ...interface{}) (n int, err error)

func Printf

func Printf(format string, a ...interface{}) (n int, err error)

func Println

func Println(a ...interface{}) (n int, err error)

func ResetLine

func ResetLine(str string) (out string)

ResetLine returns carrier to start of line

func Width

func Width() int

Width gets console width

func Wrap

func Wrap(s string, width int) string

Wrap splits a string into lines no longer than width.

Types

type Ansi

type Ansi = ansi.Ansi

type AnsiColor

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

func (AnsiColor) String

func (a AnsiColor) String() string

type CLI

type CLI interface {
	io.Writer
	io.StringWriter
	String() string
	Print(args ...interface{}) (n int, err error)
	Printf(format string, args ...interface{}) (n int, err error)
	Println(args ...interface{}) (n int, err error)
	SetColor(color ansi.Ansi)
	Reset() (n int, err error)
	CLIControls
}

CLI implements an ANSI compatible terminal interface.

func New

func New() CLI

New returns a new ANSI compatible terminal interface based on os.Stdout with ANSI support enabled by default.

func NewFromWriter

func NewFromWriter(w io.Writer) CLI

func NewStderr

func NewStderr(w io.Writer) CLI

type CLIControls

type CLIControls interface {
	CLS()
	ClearLine()
	Hr()
	Br()
	CursorControls
	UseColor(b bool)
	DevMode(b bool)
}

type CursorControls

type CursorControls interface {
	Up(n int)
	Down(n int)
	Left(n int)
	Right(n int)
	Show()
	Hide()
}

type Terminal

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

func (*Terminal) Br

func (t *Terminal) Br()

Br creates a line break.

func (*Terminal) CLS

func (t *Terminal) CLS()

CLS clears the screen.

func (*Terminal) ClearLine

func (t *Terminal) ClearLine()

ClearLine clears moves the cursor to the start of the the current line and clears the line.

func (*Terminal) CursorX

func (t *Terminal) CursorX(x int)

CursorX moves the cursor horizontally to x.

func (*Terminal) DevMode

func (t *Terminal) DevMode(b bool)

DevMode manually sets the Dev mode to true (for debugging) or false (for production). Default is false.

func (*Terminal) Down

func (t *Terminal) Down(n int)

Down moves the cursor n cells to down.

func (*Terminal) Hide

func (t *Terminal) Hide()

Hide the cursor.

func (*Terminal) Hr

func (t *Terminal) Hr()

Hr creates a hard return using the default character.

func (*Terminal) Left

func (t *Terminal) Left(n int)

Left moves the cursor n cells to left.

func (*Terminal) LineBreak

func (t *Terminal) LineBreak(c string)

LineBreak creates a CLI line break (dotted line, underline, etc.) by repeating the string c enough times to span the screen width.

This is useful in delimiting lines of text in terminal output.

func (*Terminal) NextLine

func (t *Terminal) NextLine(n int)

NextLine moves the cursor to beginning of the line n lines down.

func (*Terminal) PreviousLine

func (t *Terminal) PreviousLine(n int)

PreviousLine moves the cursor to beginning of the line n lines up.

func (*Terminal) Print

func (t *Terminal) Print(args ...interface{}) (n int, err error)

Print wraps args in ANSI 8-bit color codes (256 color codes)

func (*Terminal) Printf

func (t *Terminal) Printf(fmtString string, args ...interface{}) (n int, err error)

Printf wraps args in ANSI 8-bit color codes (256 color codes)

func (*Terminal) Println

func (t *Terminal) Println(args ...interface{}) (n int, err error)

Println wraps args in ANSI 8-bit color codes (256 color codes) and adds a newline character

func (*Terminal) Reset

func (t *Terminal) Reset() (n int, err error)

Reset sets the ANSI foreground, background, and effect to default.

func (*Terminal) Right

func (t *Terminal) Right(n int)

Right moves the cursor n cells to right.

func (*Terminal) SetColor

func (t *Terminal) SetColor(color Ansi)

SetColor sets the ANSI foreground, background, and effect codes for upcoming output.

func (*Terminal) Show

func (t *Terminal) Show()

Show the cursor.

func (*Terminal) String

func (t *Terminal) String() string

String describes the terminal. If devMode is true, it generates a list of dev info.

func (*Terminal) Up

func (t *Terminal) Up(n int)

Up moves the cursor n cells to up.

func (*Terminal) UseColor

func (t *Terminal) UseColor(b bool)

UseColor manually sets the use of ANSI color output to true or false.

func (*Terminal) Write

func (t *Terminal) Write(p []byte) (n int, err error)

Write writes len(p) bytes from p to the Terminal data stream. The bytes are wrapped in ansi escape codes using the current Terminal colorBytes field and the Reset constant. This ensures that the terminal is not left in an unknown state if other programs write to it concurrently.

It returns the number of bytes written from p (0 <= n <= len(p)). The bytes sent to set and reset ANSI escape codes are not included in the returned value. This maintains compatibility with the io.Writer interface.

Any error encountered that caused the write to stop early is also returned. Write returns io.ErrShortWrite if n < len(p) and no other explicit error was identified.

As specified by io.Writer, Write does not modify the slice data, even temporarily and does not retain p.

func (*Terminal) WriteString

func (t *Terminal) WriteString(s string) (n int, err error)

WriteString writes the contents of s to the underlying data stream.

It uses the io.Writer interface and follows standard conventions:

It returns the number of bytes written from s (0 <= n <= len(s)) and any error encountered that caused the write to stop early. WriteString must return a non-nil error if it returns n < len(s). Write must not modify the string data, even temporarily.

Implementations must not retain s.

Directories

Path Synopsis
cmd
examples/cli command
Package terminal provides information about the state of the terminal.
Package terminal provides information about the state of the terminal.

Jump to

Keyboard shortcuts

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