cli

package
v0.0.0-...-24ca9bf Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2022 License: MIT Imports: 17 Imported by: 0

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 CLI applications written in Go.

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

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

Index

Constants

View Source
const (
	NewLine                  string = "\n" // Newline character
	Tab                      string = "\t" // Tab character
	Space                           = " "  // Space character
	DefaultScreenWidthString        = "80"
	DefaultHeadByteLength           = 79
	DefaultTailByteLength           = 20
	DefaultHeadLineLength           = 5
	DefaultTailLineLength           = 5
)
View Source
const (
	NormalMode os.FileMode = 0644
	DirMode    os.FileMode = 0755
)
View Source
const PCT = 0x8000 << shift

Variables

View Source
var (

	// DEBUG flag to enable debug logging and features
	DEBUG = true

	// Terminal flag to enable CLI terminal display
	IsTerminal = terminal.IsTerminal(int(os.Stdout.Fd()))
)
View Source
var (

	// user home directory
	HOME = envvars.HOME

	// current working directory
	PWD = envvars.PWD

	// Initial column width of CLI terminal display
	COLUMNS = 80

	// Initial row height of CLI terminal display
	ROWS = 24
)

environment variables

View Source
var (
	ErrNotImplemented = errors.New("not implemented")
	ErrNoForceFlag    = errors.New("no -force flag")
)
View Source
var (
	DefaultDebugFlag  = false
	DefaultInFile     = "./gilist.txt"
	DefaultOutFile    = "../gitignore_gen.go"
	DefaultConfigFile = ".gosimple.conf"
)

//////// Flags defaults

View Source
var (
	DebugFlag   = Flags.Bool("debug", false, "turn on debug mode")
	ForceFlag   = Flags.Bool("force", false, "force writing to file")
	VerboseFlag = Flags.Bool("verbose", false, "turn on verbose mode")
	QuietFlag   = Flags.Bool("quiet", false, "turn on quiet mode")
	InFile      = Flags.String("in", DefaultInFile, "name of input file")
	OutFile     = Flags.String("out", DefaultOutFile, "name of output file")
	ConfigFile  = Flags.String("config", DefaultConfigFile, "name of config file")
	LogLevel    = &logLevelFlag{defaultLogLevel}
)

//////// cli Flags

View Source
var Col = t.Col
View Source
var (
	DbColor string = "\033[1;31m" // ANSI dbecho code

)

Flags is a flag.FlagSet that can be inherited or modified.

View Source
var (
	// Global errorlogger instance
	Log = errorlogger.New()
)

errorlogger

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

Functions

func Atoi

func Atoi(s string) int

Atoi returns the integer representation of s. If any error occurs, 0 is returned.

func Background

func Background(str string, color int) string

Background - Change background color of string:

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

func Bold

func Bold(str string) string

Bold - Make bold

func Box

func Box(args ...any) (n int, err error)

func Br

func Br()

Br prints a blank line to os.Stdout.

func CheckIfTerminal

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 Cols

func Cols() 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 Cr

func Cr(c string)

Cr prints a screen-wide character pattern.

func CurrentHeight

func CurrentHeight() int

CurrentHeight gets current height. Line count in Screen buffer.

func DbEcho

func DbEcho(args ...any) (n int, err error)

DbEcho formats using the default formats for its operands and writes to debugWriter. Spaces are always added between operands and a newline is appended. This is equivalent to fmt.Println behavior, not fmt.Print behavior.

It returns the number of bytes written and any write error encountered.

DbEcho sends output based on DebugFlag setting and Log level >= 2. If the first argument is a string and contains at least one % symbol, it is used as a format string for a DbEchof() version of this function.

func DbEchoNoLn

func DbEchoNoLn(args ...any) (n int, err error)

DbEchoNoLn formats using the default formats for its operands and writes to debugWriter. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

DbEchoNoLn sends output based on DebugFlag setting and Log level >= 2.

Behavior is opposite of Print vs. Println in that the default DbEcho behavior is to add a Newline and the default DbEchoNoLn behavior is to leave all arguments unchanged. This function writes only the arguments; no formatting or updates are done; no newlines are added.

func DbEchof

func DbEchof(format string, args ...any) (n int, err error)

DbEchof formats according to a format specifier and writes to debugWriter. It returns the number of bytes written and any write error encountered.

DbEcho sends output based on DebugFlag setting and Log level >= 2.

As a convenience, if the final character in the format string is not a Newline, then one is added.

func FileWriteCloser

func FileWriteCloser(filename string, truncate bool) (io.WriteCloser, error)

FileWriteCloser returns an io.FileWriteCloser from the given filename. The file is truncated upon opening if truncate is true. Otherwise, the file is opened in append mode. If the file does not exist, a new file is created.

As a precaution, the writer uses os.Stdout unless the -force (ForceFlag) CLI option is enabled.

func Flag

func Flag(flag *flag.Flag) any

func Flush

func Flush()

Flush buffer and ensure that it will not overflow screen

func FlushNoOverflow

func FlushNoOverflow() error

Flush buffer and ensure that it will not overflow screen

func Fr

func Fr()

Fr prints a screen-wide footer underline using the footerChar string contained in the package options. The screen width is updated by the Columns() function.

func GetFileList

func GetFileList(path string, pattern, exclude []string, recurse bool) ([]string, error)

GetFileList returns a list of files in the specified path that match any of the specified patterns while excluding those that match the specified exclude list.

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 Getenv

func Getenv(envVarName string, defaultValue string) (retval string)

Getenv returns the value of the string while replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by defaultValue.

d := Getenv("${HOME}/.config")
fmt.Println(d)
// /Users/skeptycal/.config
func Head[E any](s []E) []E

Head returns the first n elements of a sequence. If n is longer than s, s is returned unchanged. The default value of n is used. If another value of n is needed, use HeadN(s S, n int).

func HeadN

func HeadN[E any](s []E, n int) []E

Head returns the first n elements of a sequence s. If n is longer than s, s is returned unchanged.

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 Hr

func Hr()

Hr prints a screen-wide header underline using the headerChar string contained in the package options. The screen width is updated by the Columns() function.

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 NewWriteCloserCLI

func NewWriteCloserCLI(w any) io.WriteCloser

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 ReadFileCli

func ReadFileCli(filename string) string

GetDataCli gets the contents of filename and returns the string version. In the Cli version, any error results in log.Fatal().

func ResetLine

func ResetLine(str string) (out string)

ResetLine returns carrier to start of line

func Rows

func Rows() int

Rows returns the number of rows in the terminal,

func StatCli

func StatCli(filename string) os.FileInfo

StatCli returns the os.FileInfo from filename. In the Cli version, any error results in log.Fatal().

func Tail

func Tail[E any](s []E) []E

Tail returns the last n elements of a sequence. If n is longer than s, s is returned unchanged. The default value of n is used. If another value of n is needed, use TailN(s S, n int).

func TailN

func TailN[E any](s []E, n int) []E

Tail returns the last n elements of a sequence s. If n is longer than s, s is returned unchanged.

func Vprint

func Vprint(args ...any) (int, error)

Vprint sends output based on VerboseFlag setting and Log level >= 4. If the first argument is a string and contains at least one % symbol, it is used as a format string for a Printf version of this function.

func Vprintf

func Vprintf(format string, args ...any) (int, error)

Vprintf sends output based on VerboseFlag setting and Log level >= 4. The first argument is a format string for a Printf version of the Vprint function.

func Vprintln

func Vprintln(args ...any) (int, error)

Vprintln sends output based on VerboseFlag setting and Log level >= 4. A trailing newline is appended to the output.

If the first argument is a string and contains at least one % symbol, it is used as a format string for a Printf version of this function.

func Width

func Width() int

Width gets console width

func WriteFile

func WriteFile(filename, s string) (n int, err error)

WriteFile writes the string to filename. As a precaution, the writer uses os.Stdout unless the -force (ForceFlag) CLI option is enabled.

func WriteString

func WriteString(w io.Writer, s string) (n int, err error)

WriteString writes the string to w. It implements the io.StringWriter interface.

As a precaution, the writer uses os.Stdout unless the -force (ForceFlag) CLI option is enabled.

func XPixels

func XPixels() int

func YPixels

func YPixels() int

Types

type CLI

type CLI interface {
	io.Writer
	io.StringWriter
	fmt.Stringer
	Printer
	terminal.CLIControls
	SetColor(color ansi.AnsiColor)
	Reset() (n int, err error)
}

CLI implements an ANSI compatible terminal interface.

type Getter

type Getter interface {
	Value
	Get() any
}

type Printer

type Printer interface {
	Print(args ...interface{}) (n int, err error)
	Printf(format string, args ...interface{}) (n int, err error)
	Println(args ...interface{}) (n int, err error)
}

Printer implements the common printer interface elements Print, Printf, and Println

type Value

type Value interface {
	String() string
	Set(string) error
}

Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)

If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes -name equivalent to -name=true rather than using the next command-line argument.

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

Reference: standard library flag package

Directories

Path Synopsis
Package ansi provides an extensive set of ANSI escape codes for use in command line interfaces (CLIs) using industry standard well-documented terminal commands.
Package ansi provides an extensive set of ANSI escape codes for use in command line interfaces (CLIs) using industry standard well-documented terminal commands.
cmd
Package errorlogger implements error logging to a variety of output formats.
Package errorlogger implements error logging to a variety of output formats.
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