README ¶
golib - Library of Go packages
- appdata - Package appdata provides access to well known directories for applications.
- cache - Package cache provides LRU cache map functionality.
- cmd - Package cmd provides (sub-)command functionality for command-line programs.
- config - Package config is used to read and write configuration files.
- flag - Package flag facilitates use of the standard library package flag with package config.
- errors - Package errors implements functions for advanced error handling.
- keyring - Package keyring implements functions for accessing and storing passwords in the system's keyring (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux).
- retry - Package retry implements simple retry functionality.
- shlex - Package shlex is used for simple command line splitting.
- terminal - Package terminal provides functionality for terminals.
- editor - Package editor provides simple readline functionality for Go programs.
- trace - Package trace provides a simple tracing facility for Go functions.
- util - Package util contains general utility functions.
Package appdata
import "github.com/billziss-gh/golib/appdata"
Overview
Package appdata provides access to well known directories for applications.
Index
- Constants
- func CacheDir() (string, error)
- func ConfigDir() (string, error)
- func DataDir() (string, error)
- type AppData
Constants
const ErrAppData = "ErrAppData"
func CacheDir
func CacheDir() (string, error)
CacheDir returns the directory where application cache files should be stored.
func ConfigDir
func ConfigDir() (string, error)
ConfigDir returns the directory where application configuration files should be stored.
func DataDir
func DataDir() (string, error)
DataDir returns the directory where application data files should be stored.
type AppData
type AppData interface {
ConfigDir() (string, error)
DataDir() (string, error)
CacheDir() (string, error)
}
var DefaultAppData AppData
Package cache
import "github.com/billziss-gh/golib/cache"
Overview
Package cache provides LRU cache map functionality.
Index
- type Map
- func NewMap(list *MapItem) *Map
- func (cmap *Map) Delete(key string)
- func (cmap *Map) Expire(fn func(list, item *MapItem) bool)
- func (cmap *Map) Get(key string) (*MapItem, bool)
- func (cmap *Map) InitMap(list *MapItem)
- func (cmap *Map) Items() map[string]*MapItem
- func (cmap *Map) Set(key string, newitem *MapItem, expirable bool)
- type MapItem
- func (item *MapItem) Empty()
- func (list *MapItem) Expire(fn func(list, item *MapItem) bool)
- func (item *MapItem) InsertHead(list *MapItem)
- func (item *MapItem) InsertTail(list *MapItem)
- func (item *MapItem) IsEmpty() bool
- func (list *MapItem) Iterate(fn func(list, item *MapItem) bool)
- func (item *MapItem) Remove()
type Map
type Map struct {
// contains filtered or unexported fields
}
Map is a map of key/value pairs that also maintains its items in an LRU (Least Recently Used) list. LRU items may then be expired.
func NewMap
func NewMap(list *MapItem) *Map
NewMap creates a new cache map.
The cache map tracks items in the LRU list specified by the list parameter. If the list parameter is nil then items are tracked in an internal list.
func (*Map) Delete
func (cmap *Map) Delete(key string)
Delete deletes an item by key.
func (*Map) Expire
func (cmap *Map) Expire(fn func(list, item *MapItem) bool)
Expire performs list item expiration using a helper function.
See MapItem.Expire for a full discussion.
func (*Map) Get
func (cmap *Map) Get(key string) (*MapItem, bool)
Get gets an item by key.
Get "touches" the item to show that it was recently used. For this reason Get modifies the internal structure of the cache map and is not safe to be called under a read lock.
func (*Map) InitMap
func (cmap *Map) InitMap(list *MapItem)
InitMap initializes a zero cache map.
The cache map tracks items in the LRU list specified by the list parameter. If the list parameter is nil then items are tracked in an internal list.
func (*Map) Items
func (cmap *Map) Items() map[string]*MapItem
Items returns the internal map of the cache map.
func (*Map) Set
func (cmap *Map) Set(key string, newitem *MapItem, expirable bool)
Set sets an item by key.
Whether the new item can be expired is controlled by the expirable parameter. Expirable items are tracked in an LRU list.
type MapItem
type MapItem struct {
Value interface{}
// contains filtered or unexported fields
}
MapItem is the data structure that is stored in a Map.
func (*MapItem) Empty
func (item *MapItem) Empty()
Empty initializes the list item as empty.
func (*MapItem) Expire
func (list *MapItem) Expire(fn func(list, item *MapItem) bool)
Expire performs list item expiration using a helper function.
Expire iterates over the list and calls the helper function fn() on every list item. The function fn() must perform an expiration test on the list item and perform one of the following:
-
If the list item is not expired, fn() must return false. Expire will then stop the loop iteration.
-
If the list item is expired, fn() has two options. It may remove the item by using item.Remove() (item eviction). Or it may remove the item by using item.Remove() and reinsert the item at the list tail using item.InsertTail(list) (item refresh). In this second case care must be taken to ensure that fn() returns false for some item in the list; otherwise the Expire iteration will continue forever, because the list will never be found empty.
func (*MapItem) InsertHead
func (item *MapItem) InsertHead(list *MapItem)
InsertHead inserts the list item to the head of a list.
func (*MapItem) InsertTail
func (item *MapItem) InsertTail(list *MapItem)
InsertTail inserts the list item to the tail of a list.
func (*MapItem) IsEmpty
func (item *MapItem) IsEmpty() bool
IsEmpty determines if the list item is empty.
func (*MapItem) Iterate
func (list *MapItem) Iterate(fn func(list, item *MapItem) bool)
Iterate iterates over the list using a helper function.
Iterate iterates over the list and calls the helper function fn() on every list item. The function fn() must not modify the list in any way. The function fn() must return true to continue the iteration and false to stop it.
func (*MapItem) Remove
func (item *MapItem) Remove()
Remove removes the list item from any list it is in.
Package cmd
import "github.com/billziss-gh/golib/cmd"
Overview
Package cmd provides (sub-)command functionality for command-line programs. This package works closely with the standard library flag package.
Index
- Variables
- func PrintCmds()
- func Run()
- func UsageFunc(args ...interface{}) func()
- type Cmd
- type CmdMap
Variables
var DefaultCmdMap = NewCmdMap()
DefaultCmdMap is the default command map.
func PrintCmds
func PrintCmds()
PrintCmds prints help text for all commands in the default command map to stderr.
func Run
func Run()
Run parses the command line and executes the specified (sub-)command from the default command map.
func UsageFunc
func UsageFunc(args ...interface{}) func()
UsageFunc returns a usage function appropriate for use with flag.FlagSet.
type Cmd
type Cmd struct {
// Flag contains the command flag set.
Flag *flag.FlagSet
// Main is the function to run when the command is selected.
Main func(cmd *Cmd, args []string)
// Use contains the command usage string.
Use string
// Desc contains the command description.
Desc string
}
Cmd encapsulates a (sub-)command.
func Add
func Add(name string, main func(*Cmd, []string)) *Cmd
Add adds a new command in the default command map.
The name parameter is the command name. However if this parameter contains a space or newline it is interpreted as described below. Consider:
NAME ARGUMENTS
DESCRIPTION
Then the command name becomes "NAME", the command Use field becomes "NAME ARGUMENTS" and the command Desc field becomes "DESCRIPTION".
func (*Cmd) GetFlag
func (self *Cmd) GetFlag(name string) interface{}
GetFlag gets the value of the named flag.
type CmdMap
type CmdMap struct {
// contains filtered or unexported fields
}
CmdMap encapsulates a (sub-)command map.
func NewCmdMap
func NewCmdMap() *CmdMap
NewCmdMap creates a new command map.
func (*CmdMap) Add
func (self *CmdMap) Add(name string, main func(*Cmd, []string)) (cmd *Cmd)
Add adds a new command in the command map.
The name parameter is the command name. However if this parameter contains a space or newline it is interpreted as described below. Consider:
NAME ARGUMENTS
DESCRIPTION
Then the command name becomes "NAME", the command Use field becomes "NAME ARGUMENTS" and the command Desc field becomes "DESCRIPTION".
func (*CmdMap) Get
func (self *CmdMap) Get(name string) *Cmd
Get gets a command by name.
func (*CmdMap) GetNames
func (self *CmdMap) GetNames() []string
GetNames gets all command names.
func (*CmdMap) PrintCmds
func (self *CmdMap) PrintCmds()
PrintCmds prints help text for all commands to stderr.
func (*CmdMap) Run
func (self *CmdMap) Run(flagSet *flag.FlagSet, args []string)
Run parses the command line and executes the specified (sub-)command.
Package config
import "github.com/billziss-gh/golib/config"
Overview
Package config is used to read and write configuration files.
Configuration files are similar to Windows INI files. They store a list of properties (key/value pairs); they may also be grouped into sections.
The basic syntax of a configuration file is as follows:
name1=value1
name2=value2
...
[section]
name3=value3
name4=value4
...
Properties not in a section are placed in the unnamed (empty "") section.
Index
- Variables
- func ReadFunc(reader io.Reader, fn func(sect, name string, valu interface{})) error
- func Write(writer io.Writer, conf Config) error
- func WriteTyped(writer io.Writer, conf TypedConfig) error
- type Config
- type Dialect
- func (dialect *Dialect) Read(reader io.Reader) (Config, error)
- func (dialect *Dialect) ReadFunc(reader io.Reader, fn func(sect, name string, valu interface{})) error
- func (dialect *Dialect) ReadTyped(reader io.Reader) (TypedConfig, error)
- func (dialect *Dialect) Write(writer io.Writer, conf Config) error
- func (dialect *Dialect) WriteTyped(writer io.Writer, conf TypedConfig) error
- type Section
- type TypedConfig
- type TypedSection
Variables
var DefaultDialect = &Dialect{
AssignChars: "=:",
CommentChars: ";#",
ReadEmptyKeys: true,
WriteEmptyKeys: false,
Strict: false,
}
DefaultDialect contains the default configuration dialect. It is compatible with Windows INI files.
func ReadFunc
func ReadFunc(
reader io.Reader, fn func(sect, name string, valu interface{})) error
func Write
func Write(writer io.Writer, conf Config) error
Write writes a configuration to the supplied writer using the default dialect.
func WriteTyped
func WriteTyped(writer io.Writer, conf TypedConfig) error
WriteTyped writes a typed configuration to the supplied writer using the default dialect.
type Config
type Config map[string]Section
Config is used to store a configuration as string properties.
When using Get, Set, Delete to manipulate properties the property names follow the syntax SECTION.PROPNAME
func Read
func Read(reader io.Reader) (Config, error)
Read reads a configuration from the supplied reader using the default dialect.
func (Config) Delete
func (conf Config) Delete(k string)
Delete deletes a property from the configuration.
func (Config) Get
func (conf Config) Get(k string) string
Get gets a property from the configuration.
func (Config) Set
func (conf Config) Set(k string, v string)
Set sets a property in the configuration.
type Dialect
type Dialect struct {
// AssignChars contains the characters used for property assignment.
// The first character in AssignChars is the character used during
// writing.
AssignChars string
// CommentChars contains the characters used for comments.
CommentChars string
// ReadEmptyKeys determines whether to read properties with missing values.
// The properties so created will be interpretted as empty strings for Read
// and boolean true for ReadTyped.
ReadEmptyKeys bool
// WriteEmptyKeys determines whether to write properties with missing values.
// This is only important when writing boolean true properties with
// WriteTyped; these will be written with missing values.
WriteEmptyKeys bool
// Strict determines whether parse errors should be reported.
Strict bool
}
Dialect is used to represent different dialects of configuration files.
func (*Dialect) Read
func (dialect *Dialect) Read(reader io.Reader) (Config, error)
Read reads a configuration from the supplied reader.
func (*Dialect) ReadFunc
func (dialect *Dialect) ReadFunc(
reader io.Reader, fn func(sect, name string, valu interface{})) error
func (*Dialect) ReadTyped
func (dialect *Dialect) ReadTyped(reader io.Reader) (TypedConfig, error)
ReadTyped reads a typed configuration from the supplied reader.
func (*Dialect) Write
func (dialect *Dialect) Write(writer io.Writer, conf Config) error
Write writes a configuration to the supplied writer.
func (*Dialect) WriteTyped
func (dialect *Dialect) WriteTyped(writer io.Writer, conf TypedConfig) error
WriteTyped writes a typed configuration to the supplied writer.
type Section
type Section map[string]string
Section is used to store a configuration section as string properties.
type TypedConfig
type TypedConfig map[string]TypedSection
TypedConfig is used to store a configuration as typed properties.
When using Get, Set, Delete to manipulate properties the property names follow the syntax SECTION.PROPNAME
func ReadTyped
func ReadTyped(reader io.Reader) (TypedConfig, error)
ReadTyped reads a typed configuration from the supplied reader using the default dialect.
func (TypedConfig) Delete
func (conf TypedConfig) Delete(k string)
Delete deletes a property from the configuration.
func (TypedConfig) Get
func (conf TypedConfig) Get(k string) interface{}
Get gets a property from the configuration.
func (TypedConfig) Set
func (conf TypedConfig) Set(k string, v interface{})
Set sets a property in the configuration.
type TypedSection
type TypedSection map[string]interface{}
TypedSection is used to store a configuration section as typed properties.
Package flag
import "github.com/billziss-gh/golib/config/flag"
Overview
Package flag facilitates use of the standard library package flag with package config.
Index
- func Visit(flagSet *flag.FlagSet, section config.TypedSection, names ...string)
- func VisitAll(flagSet *flag.FlagSet, section config.TypedSection, names ...string)
func Visit
func Visit(flagSet *flag.FlagSet, section config.TypedSection, names ...string)
Visit gets the flags present in a command line as a typed configuration section.
func VisitAll
func VisitAll(flagSet *flag.FlagSet, section config.TypedSection, names ...string)
VisitAll gets all flags as a typed configuration section.
Package errors
import "github.com/billziss-gh/golib/errors"
Overview
Package errors implements functions for advanced error handling.
Errors in this package contain a message, a cause (an error that caused this error) and an attachment (any interface{}). Errors also contain information about the program location where they were created.
Errors can be printed using the fmt.Printf verbs %s, %q, %x, %X, %v. In particular the %+v format will print an error complete with its stack trace.
Inspired by https://github.com/pkg/errors
Index
- func Attachment(err error) interface{}
- func Cause(err error) error
- func HasAttachment(err error, attachment interface{}) bool
- func HasCause(err error, cause error) bool
- func New(message string, args ...interface{}) error
func Attachment
func Attachment(err error) interface{}
Attachment will return additional information attached to this error (if any).
func Cause
func Cause(err error) error
Cause will return the error that caused this error (if any).
func HasAttachment
func HasAttachment(err error, attachment interface{}) bool
HasAttachment determines if a particular attachment is in the causal chain of this error.
func HasCause
func HasCause(err error, cause error) bool
HasCause determines if a particular error is in the causal chain of this error.
func New
func New(message string, args ...interface{}) error
New creates an error with a message. Additionally the error may contain a cause (an error that caused this error) and an attachment (any interface{}). New will also record information about the program location where it was called.
Package keyring
import "github.com/billziss-gh/golib/keyring"
Overview
Package keyring implements functions for accessing and storing passwords in the system's keyring (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux).
Index
- Constants
- func Delete(service, user string) error
- func Get(service, user string) (string, error)
- func Set(service, user, pass string) error
- type FileKeyring
- type Keyring
- type OverlayKeyring
- type SystemKeyring
keyring_default.go keyring_file.go keyring_overlay.go keyring_windows.go
Constants
const ErrKeyring = "ErrKeyring"
func Delete
func Delete(service, user string) error
Delete deletes the password for a service and user in the default keyring.
func Get
func Get(service, user string) (string, error)
Get gets the password for a service and user in the default keyring.
func Set
func Set(service, user, pass string) error
Set sets the password for a service and user in the default keyring.
type FileKeyring
type FileKeyring struct {
Path string
Key []byte
// contains filtered or unexported fields
}
FileKeyring is a keyring that stores passwords in a file.
func (*FileKeyring) Delete
func (self *FileKeyring) Delete(service, user string) error
func (*FileKeyring) Get
func (self *FileKeyring) Get(service, user string) (string, error)
func (*FileKeyring) Set
func (self *FileKeyring) Set(service, user, pass string) error
type Keyring
type Keyring interface {
// Get gets the password for a service and user.
Get(service, user string) (string, error)
// Set sets the password for a service and user.
Set(service, user, pass string) error
// Delete deletes the password for a service and user.
Delete(service, user string) error
}
Keyring is the interface that a system-specific or custom keyring must implement.
var DefaultKeyring Keyring
The default keyring.
type OverlayKeyring
type OverlayKeyring struct {
Keyrings []Keyring
// contains filtered or unexported fields
}
OverlayKeyring is a keyring that stores passwords in a hierarchy of keyrings.
func (*OverlayKeyring) Delete
func (self *OverlayKeyring) Delete(service, user string) error
func (*OverlayKeyring) Get
func (self *OverlayKeyring) Get(service, user string) (string, error)
func (*OverlayKeyring) Set
func (self *OverlayKeyring) Set(service, user, pass string) error
type SystemKeyring
type SystemKeyring struct {
}
SystemKeyring implements the system-specific keyring.
func (*SystemKeyring) Delete
func (self *SystemKeyring) Delete(service, user string) (err error)
func (*SystemKeyring) Get
func (self *SystemKeyring) Get(service, user string) (pass string, err error)
func (*SystemKeyring) Set
func (self *SystemKeyring) Set(service, user, pass string) (err error)
Package retry
import "github.com/billziss-gh/golib/retry"
Overview
Package retry implements simple retry functionality.
For example to retry an HTTP request:
func Do(client *http.Client, req *http.Request) (rsp *http.Response, err error) {
retry.Retry(
retry.Count(5),
retry.Backoff(time.Second, time.Second*30),
func(i int) bool {
if 0 < i {
req.Body, err = req.GetBody()
if nil != err {
return false
}
}
rsp, err = client.Do(req)
if nil != err {
return false
}
if 500 <= rsp.StatusCode && nil != req.GetBody {
rsp.Body.Close()
return true
}
return false
})
return
}
Index
- func Backoff(sleep, maxsleep time.Duration) func(int) bool
- func Count(retries int) func(int) bool
- func Retry(actions ...func(int) bool)
func Backoff
func Backoff(sleep, maxsleep time.Duration) func(int) bool
Backoff implements an exponential backoff with jitter.
func Count
func Count(retries int) func(int) bool
Count limits the number of retries performed by Retry.
func Retry
func Retry(actions ...func(int) bool)
Retry performs actions repeatedly until one of the actions returns false.
Package shlex
import "github.com/billziss-gh/golib/shlex"
Overview
Package shlex is used for simple command line splitting.
Both POSIX and Windows dialects are provided.
Index
Constants
const (
Space = rune(' ')
Word = rune('A')
DoubleQuote = rune('"')
SingleQuote = rune('\'')
EmptyRune = rune(-2)
NoEscape = rune(-1)
)
Variables
var Posix = Dialect{
IsSpace: func(r rune) bool {
return ' ' == r || '\t' == r || '\n' == r
},
IsQuote: func(r rune) bool {
return '"' == r || '\'' == r
},
Escape: func(s rune, r, r0 rune) rune {
if '\\' != r {
return NoEscape
}
switch s {
case Space, Word:
if '\n' == r0 || EmptyRune == r0 {
return EmptyRune
}
return r0
case DoubleQuote:
if '\n' == r0 || EmptyRune == r0 {
return EmptyRune
}
if '$' == r0 || '`' == r0 || '"' == r0 || '\\' == r0 {
return r0
}
return NoEscape
default:
return NoEscape
}
},
}
Posix is the POSIX dialect of command line splitting. See https://tinyurl.com/26man79 for guidelines.
var Windows = Dialect{
IsSpace: func(r rune) bool {
return ' ' == r || '\t' == r || '\r' == r || '\n' == r
},
IsQuote: func(r rune) bool {
return '"' == r
},
Escape: func(s rune, r, r0 rune) rune {
switch s {
case Space, Word:
if '\\' == r && '"' == r0 {
return r0
}
return NoEscape
case DoubleQuote:
if ('\\' == r || '"' == r) && '"' == r0 {
return r0
}
return NoEscape
default:
return NoEscape
}
},
LongEscape: func(s rune, r rune, line string) ([]rune, string, rune, int) {
if '\\' != r {
return nil, "", 0, 0
}
var w int
n := 0
for {
r, w = utf8.DecodeRuneInString(line[n:])
n++
if 0 == w || '\\' != r {
break
}
}
if 2 > n {
return nil, "", 0, 0
}
if '"' != r {
return []rune(strings.Repeat("\\", n-1)), line[n-1:], r, w
} else if 0 == n&1 {
return []rune(strings.Repeat("\\", n/2-1)), line[n-1:], '"', 1
} else {
return []rune(strings.Repeat("\\", n/2-1)), line[n-2:], '\\', 1
}
},
}
Windows is the Windows dialect of command line splitting. See https://tinyurl.com/ycdj5ghh for guidelines.
type Dialect
type Dialect struct {
IsSpace func(r rune) bool
IsQuote func(r rune) bool
Escape func(s rune, r, r0 rune) rune
LongEscape func(s rune, r rune, line string) ([]rune, string, rune, int)
}
Dialect represents a dialect of command line splitting.
func (*Dialect) Split
func (dialect *Dialect) Split(line string) (tokens []string)
Split splits a command line into tokens according to the chosen dialect.
Package terminal
import "github.com/billziss-gh/golib/terminal"
Overview
Package terminal provides functionality for terminals.
Index
- Variables
- func AnsiEscapeCode(code string) string
- func Escape(s string, delims string, escape func(string) string) string
- func GetSize(fd uintptr) (int, int, error)
- func IsAnsiTerminal(fd uintptr) bool
- func IsTerminal(fd uintptr) bool
- func NewEscapeWriter(writer io.Writer, delims string, escape func(string) string) io.Writer
- func NewReader(r io.Reader) io.Reader
- func NullEscapeCode(code string) string
- func SetState(fd uintptr, s State) error
- type State
codes.go escape.go reader.go reader_windows.go stdio.go terminal.go terminal_windows.go
Variables
var Stderr io.Writer
var Stdout io.Writer
func AnsiEscapeCode
func AnsiEscapeCode(code string) string
AnsiEscapeCode translates a named escape code to its ANSI equivalent.
func Escape
func Escape(s string, delims string, escape func(string) string) string
Escape replaces escape code instances within a string. Escape codes must be delimited using the delimiters in the delims parameter, which has the syntax "START END". For example, to use {{ and }} as delimiters specify "{{ }}".
For consistency with NewEscapeWriter, Escape will discard an unterminated escape code. For example, if delims is "{{ }}" and the string s is "hello {{world", the resulting string will be "hello ".
func GetSize
func GetSize(fd uintptr) (int, int, error)
GetSize gets the terminal size (cols x rows).
func IsAnsiTerminal
func IsAnsiTerminal(fd uintptr) bool
IsAnsiTerminal determines if the file descriptor describes a terminal that has ANSI capabilities.
func IsTerminal
func IsTerminal(fd uintptr) bool
IsTerminal determines if the file descriptor describes a terminal.
func NewEscapeWriter
func NewEscapeWriter(writer io.Writer, delims string, escape func(string) string) io.Writer
NewEscapeWriter replaces escape code instances within a string. Escape codes must be delimited using the delimiters in the delims parameter, which has the syntax "START END". For example, to use {{ and }} as delimiters specify "{{ }}".
Because NewEscapeWriter is an io.Writer it cannot know when the last Write will be received. For this reason it will discard an unterminated escape code. For example, if delims is "{{ }}" and the string s is "hello {{world", the resulting string will be "hello ".
func NewReader
func NewReader(r io.Reader) io.Reader
NewReader reads terminal input, including special keys.
func NullEscapeCode
func NullEscapeCode(code string) string
NullEscapeCode translates a named escape code to the empty string. It is used to eliminate escape codes.
func SetState
func SetState(fd uintptr, s State) error
type State
type State *state
func GetState
func GetState(fd uintptr) (State, error)
func MakeRaw
func MakeRaw(fd uintptr) (State, error)
MakeRaw puts the terminal in "raw" mode. In this mode the terminal performs minimal processing. The fd should be the file descriptor of the terminal input.
Package editor
import "github.com/billziss-gh/golib/terminal/editor"
Overview
Package editor provides simple readline functionality for Go programs.
Index
- Variables
- func GetLine(prompt string) (string, error)
- func GetPass(prompt string) (string, error)
- type Editor
- type History
- func NewHistory() *History
- func (self *History) Add(line string)
- func (self *History) Clear()
- func (self *History) Delete(id int)
- func (self *History) Enum(id int, fn func(id int, line string) bool)
- func (self *History) Get(id int, dir int) (int, string)
- func (self *History) Len() int
- func (self *History) Read(reader io.Reader) (err error)
- func (self *History) Reset()
- func (self *History) SetCap(cap int)
- func (self *History) Write(writer io.Writer) (err error)
Variables
var DefaultEditor = NewEditor(os.Stdin, os.Stdout)
DefaultEditor is the default Editor.
func GetLine
func GetLine(prompt string) (string, error)
GetLine gets a line from the terminal.
func GetPass
func GetPass(prompt string) (string, error)
GetPass gets a password from the terminal.
type Editor
type Editor struct {
// contains filtered or unexported fields
}
Editor is a command line editor with history and completion handling.
func NewEditor
func NewEditor(in *os.File, out *os.File) *Editor
NewEditor creates a new editor.
func (*Editor) GetLine
func (self *Editor) GetLine(prompt string) (string, error)
GetLine gets a line from the terminal.
func (*Editor) GetPass
func (self *Editor) GetPass(prompt string) (string, error)
GetPass gets a password from the terminal.
func (*Editor) History
func (self *Editor) History() *History
History returns the editor's command line history.
func (*Editor) SetCompletionHandler
func (self *Editor) SetCompletionHandler(handler func(line string) []string)
SetCompletionHandler sets a completion handler.
type History
type History struct {
// contains filtered or unexported fields
}
History maintains a buffer of command lines.
func NewHistory
func NewHistory() *History
NewHistory creates a new history buffer.
func (*History) Add
func (self *History) Add(line string)
Add adds a new command line to the history buffer.
func (*History) Clear
func (self *History) Clear()
Clear clears all command lines from the history buffer.
func (*History) Delete
func (self *History) Delete(id int)
Delete deletes a command line from the history buffer. The special id's of 0 or -1 mean to delete the first or last command line respectively.
func (*History) Enum
func (self *History) Enum(id int, fn func(id int, line string) bool)
Enum enumerates all command lines in the history buffer starting at id. The special id's of 0 or -1 mean to start the enumeration with the first or last command line respectively.
func (*History) Get
func (self *History) Get(id int, dir int) (int, string)
Get gets a command line from the history buffer.
Command lines are identified by an integer id. The special id's of 0 or -1 mean to retrieve the first or last command line respectively. The dir parameter is used to determine which command line to retrieve relative to the one identified by id: 0 is the current command line, +1 is the next command line, -1 is the previous command line, etc. When retrieving command lines the history is treated as a circular buffer.
func (*History) Len
func (self *History) Len() int
Len returns the length of the history buffer.
func (*History) Read
func (self *History) Read(reader io.Reader) (err error)
Read reads command lines from a reader into the history buffer.
func (*History) Reset
func (self *History) Reset()
Reset fully resets the history buffer.
func (*History) SetCap
func (self *History) SetCap(cap int)
SetCap sets the capacity (number of command lines) of the history buffer.
func (*History) Write
func (self *History) Write(writer io.Writer) (err error)
Write writes command lines to a writer from the history buffer.
Package trace
import "github.com/billziss-gh/golib/trace"
Overview
Package trace provides a simple tracing facility for Go functions. Given the function below, program execution will be traced whenever the function is entered or exited.
func fn(p1 ptype1, p2 ptype2, ...) (r1 rtyp1, r2 rtype2, ...) {
defer trace.Trace(0, "TRACE", p1, p2)(&r1, &r2)
// ...
}
The trace facility is disabled unless the variable Verbose is true and the environment variable GOLIB_TRACE is set to a pattern matching one of the traced functions. A pattern is a a comma-separated list of file-style patterns containing wildcards such as * and ?.
Index
- Variables
- func Trace(skip int, prfx string, vals ...interface{}) func(vals ...interface{})
- func Tracef(skip int, form string, vals ...interface{})
Variables
var (
Verbose = false
Pattern = os.Getenv("GOLIB_TRACE")
Logger = log.New(terminal.Stderr, "", log.LstdFlags)
)
func Trace
func Trace(skip int, prfx string, vals ...interface{}) func(vals ...interface{})
func Tracef
func Tracef(skip int, form string, vals ...interface{})
Package util
import "github.com/billziss-gh/golib/util"
Overview
Package util contains general utility functions.
Index
- func ReadAeData(path string, key []byte) (data []byte, err error)
- func ReadData(path string) (data []byte, err error)
- func ReadFunc(path string, fn func(*os.File) (interface{}, error)) (data interface{}, err error)
- func WriteAeData(path string, perm os.FileMode, data []byte, key []byte) (err error)
- func WriteData(path string, perm os.FileMode, data []byte) (err error)
- func WriteFunc(path string, perm os.FileMode, fn func(*os.File) error) (err error)
func ReadAeData
func ReadAeData(path string, key []byte) (data []byte, err error)
func ReadData
func ReadData(path string) (data []byte, err error)
func ReadFunc
func ReadFunc(path string, fn func(*os.File) (interface{}, error)) (data interface{}, err error)
func WriteAeData
func WriteAeData(path string, perm os.FileMode, data []byte, key []byte) (err error)
func WriteData
func WriteData(path string, perm os.FileMode, data []byte) (err error)
func WriteFunc
func WriteFunc(path string, perm os.FileMode, fn func(*os.File) error) (err error)
Directories ¶
Path | Synopsis |
---|---|
Package appdata provides access to well known directories for applications.
|
Package appdata provides access to well known directories for applications. |
Package cache provides LRU cache map functionality.
|
Package cache provides LRU cache map functionality. |
Package cmd provides (sub-)command functionality for command-line programs.
|
Package cmd provides (sub-)command functionality for command-line programs. |
Package config is used to read and write configuration files.
|
Package config is used to read and write configuration files. |
flag
Package flag facilitates use of the standard library package flag with package config.
|
Package flag facilitates use of the standard library package flag with package config. |
Package errors implements functions for advanced error handling.
|
Package errors implements functions for advanced error handling. |
Package keyring implements functions for accessing and storing passwords in the system's keyring (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux).
|
Package keyring implements functions for accessing and storing passwords in the system's keyring (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux). |
Package retry implements simple retry functionality.
|
Package retry implements simple retry functionality. |
Package shlex is used for simple command line splitting.
|
Package shlex is used for simple command line splitting. |
Package terminal provides functionality for terminals.
|
Package terminal provides functionality for terminals. |
editor
Package editor provides simple readline functionality for Go programs.
|
Package editor provides simple readline functionality for Go programs. |
Package trace provides a simple tracing facility for Go functions.
|
Package trace provides a simple tracing facility for Go functions. |
Package util contains general utility functions.
|
Package util contains general utility functions. |