Documentation ¶
Index ¶
- Constants
- Variables
- func Background(s *string, colorCode *int, format *string)
- func Bold(s *string, colorCode *int, format *string)
- func Bright(s *string, colorCode *int, format *string)
- func IsNop(w io.Writer) bool
- func NopCloser() io.Closer
- func NopOutput() io.Writer
- func Print(v interface{}) (int, error)
- func Println(v interface{}) (int, error)
- func Remove(printerName string)
- func Reversed(s *string, colorCode *int, format *string)
- func Rich(s string, colorCode int, options ...RichOption) string
- func Scan(r io.Reader, addNewLine bool) (cancel func())
- func SupportColors(w io.Writer) bool
- func Underline(s *string, colorCode *int, format *string)
- func Wrap(printFn interface{}) io.Writer
- func WriteRich(w io.Writer, s string, colorCode int, options ...RichOption)
- type Ctx
- type Handler
- type Hijacker
- type Marshaled
- type Marshaler
- type MarshalerFunc
- type OutputAdapters
- func (a *OutputAdapters) Print(print func(v interface{})) io.Writer
- func (a *OutputAdapters) PrintVardiadic(print func(v ...interface{})) io.Writer
- func (a *OutputAdapters) Printf(printf func(format string, args ...interface{})) io.Writer
- func (a *OutputAdapters) Println(println func(s string), newLine bool) io.Writer
- type PrintResult
- type Printer
- func (p *Printer) AddOutput(writers ...io.Writer) *Printer
- func (p *Printer) EnableDirectOutput() *Printer
- func (p *Printer) Flush() ([]byte, error)
- func (p *Printer) Handle(h func(PrintResult)) *Printer
- func (p *Printer) Hijack(cb func(ctx *Ctx)) *Printer
- func (p *Printer) Marshal(marshaler Marshaler) *Printer
- func (p *Printer) MarshalFunc(marshaler func(v interface{}) ([]byte, error)) *Printer
- func (p *Printer) Print(v interface{}) (int, error)
- func (p *Printer) Println(v interface{}) (int, error)
- func (p *Printer) Priority(prio int) *Printer
- func (p *Printer) Scan(r io.Reader, addNewLine bool) (cancel func())
- func (p *Printer) SetOutput(writers ...io.Writer) *Printer
- func (p *Printer) SetSync(useLocks bool) *Printer
- func (p *Printer) Store(v interface{}, appendNewLine bool) error
- func (p *Printer) WithMarshalers(marshalers ...Marshaler) *Printer
- func (p *Printer) Write(b []byte) (n int, err error)
- func (p *Printer) WriteTo(v interface{}, w io.Writer, appendNewLine bool) ([]byte, error)
- type Registry
- func (reg *Registry) Get(printerName string) *Printer
- func (reg *Registry) Print(v interface{}) (n int, err error)
- func (reg *Registry) Println(v interface{}) (n int, err error)
- func (reg *Registry) Register(printerName string, output io.Writer) *Printer
- func (reg *Registry) RegisterPrinter(printer *Printer) *Registry
- func (reg *Registry) Remove(printerName string) *Registry
- func (reg *Registry) Scan(r io.Reader, addNewLine bool) (cancel func())
- type RichOption
Examples ¶
Constants ¶
const ( Black = 30 + iota Red Green Yellow Blue Magenta Cyan White Gray = White ColorReset = 0 )
Standard color codes, any color code can be passed to `Rich` package-level function, when the destination terminal supports.
const Version = "0.0.10"
Version is the current PIO version.
Variables ¶
var ( // ErrCanceled is returned when a hijacker canceled a specific print action. ErrCanceled = errors.New("canceled") // ErrSkipped it returned from marshaler or hijacker // when the content should be skipped and printer should avoid printing it. ErrSkipped = errors.New("skipped") // ErrHandled can be returned from a hijacker to specify // that the hijacker handled the write operation itself, // therefore pio does not need to do anything else. ErrHandled = errors.New("handled") )
var ( // JSON returns the JSON encoding of Printer#Print%v. // A shortcut for `encoding/json#Marshal` JSON = MarshalerFunc(json.Marshal) // JSONIndent returns the JSON encoding of Printer#Print%v. // A shortcut for `encoding/json#MarshalIndent(v, ""," ")` JSONIndent = MarshalerFunc(func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") }) // XML returns the XML encoding of Printer#Print%v. // A shortcut for `encoding/xml#Marshal` XML = MarshalerFunc(xml.Marshal) // XMLIndent returns the XML encoding of Printer#Print%v. // A shortcut for `encoding/xml#MarshalIndent(v, ""," ")` XMLIndent = MarshalerFunc(func(v interface{}) ([]byte, error) { return xml.MarshalIndent(v, "", " ") }) )
var Default = NewRegistry()
Default returns the default, package-level registry instance.
var ErrMarshalNotFound = errors.New("no marshaler found for this type of dat")
ErrMarshalNotFound or ErrSkipped can be used to skip a specific printer's output operation.
var ErrMarshalNotResponsible = errors.New("this marshaler is not responsible for this type of data")
ErrMarshalNotResponsible retruns from a marshaler when it's not responsible and should continue to the next marshaler.
var NewLine = []byte("\n")
NewLine is a slice of bytes which controls the how a new line should be presented.
Defaults to \n.
var OutputFrom = OutputAdapters{}
OutputFrom is a variable which contains some helpers that can convert some forms of output to compatible `io.Writer` in order to be passed to the `NewPrinter` or `Register` functions.
var Text = MarshalerFunc(func(v interface{}) ([]byte, error) { if b, ok := v.([]byte); ok { return b, nil } if s, ok := v.(string); ok { return []byte(s), nil } return nil, ErrMarshalNotResponsible })
Text is a Text marshaler, it converts string to a compatible form of []byte.
var ( // TotalPrinters holds the number of // the total printers created, either by // `NewPrinter`, `NewTextPrinter`, `Register` or `RegisterPrinter` TotalPrinters int32 )
Functions ¶
func Background ¶ added in v0.0.3
Background marks the color to background. See `Reversed` too.
func Bold ¶ added in v0.0.3
Bold adds a "bold" decoration to the colorful text. See `Underline` and `Reversed` too.
func Print ¶
Print accepts a value of "v", tries to marshal its contents and flushes the result to all available printers.
func Println ¶
Println accepts a value of "v", tries to marshal its contents and flushes the result to all available printers, it adds a new line at the ending, the result doesn't contain this new line, therefore result's contnets kept as expected.
func Remove ¶
func Remove(printerName string)
Remove deletes a printer item from the printers collection by its name.
func Reversed ¶ added in v0.0.3
Reversed adds a "reversed" decoration to the colorful text. This means that the background will be the foreground and the foreground will be the background color.
See `Bold` and `Underline` too.
func Rich ¶ added in v0.0.3
func Rich(s string, colorCode int, options ...RichOption) string
Rich accepts "s" text and a "colorCode" (e.g. `Black`, `Green`, `Magenta`, `Cyan`...) and optional formatters and returns a colorized (and decorated) string text that it's ready to be printed through a compatible terminal.
Look: - Bright - Background - Bold - Underline - Reversed
Example ¶
fmt.Println(Rich("black", Black)) fmt.Println(Rich("cyan", Cyan)) fmt.Println(Rich("background cyan", Cyan, Background, )) fmt.Println(Rich("bright yellow", Yellow, Bright, )) fmt.Println(Rich("bright bold magenta", Magenta, Bright, Bold, )) fmt.Println(Rich("bold cyan", Cyan, Bold, )) fmt.Println(Rich("bold underline reversed bright cyan", Cyan, Bright, Bold, Underline, Reversed, )) fmt.Println(Rich("extended 256-color custom color: 153 (blue-ish)", 153)) fmt.Println(Rich("extended 256-color custom bright reversed color: 153 (blue-ish)", 153, Bright, Reversed, ))
Output: �[30mblack�[0m �[36mcyan�[0m �[46mbackground cyan�[0m �[33;1mbright yellow�[0m �[35;1m�[1mbright bold magenta�[0m �[36m�[1mbold cyan�[0m �[36;1m�[7m�[4m�[1mbold underline reversed bright cyan�[0m �[38;5;153mextended 256-color custom color: 153 (blue-ish)�[0m �[38;5;153;1m�[7mextended 256-color custom bright reversed color: 153 (blue-ish)�[0m
func Scan ¶
Scan scans everything from "r" and prints its new contents to the printers, forever or until the returning "cancel" is fired, once.
func SupportColors ¶ added in v0.0.4
SupportColors reports whether the "w" io.Writer is not a file and it does support colors.
func Underline ¶ added in v0.0.3
Underline adds an "underline" decoration to the colorful text. See `Bold` and `Reversed` too.
func Wrap ¶
Wrap returns a new output based on the "printfFn" if not a compatible output found then it will return a writer which writes nothing.
To check if the wrapping worked you can check if the result `io.Writer` `IsNop`, i.e: std's log.Panicf is not a compatible interface
output := Output(log.Panicf)
if IsNop(output) { // conversation failed, do something or panic. }
Types ¶
type Ctx ¶
type Ctx struct { // Printer is the current Printer which this ctx is owned by. Printer *Printer // Value is the argument passed to the `Printer#Print`. // // Value shoult not be changed. Value interface{} // contains filtered or unexported fields }
Ctx is the current context of the Printer's hijacker, should not be used inside goroutines, exiting this hijacker allows the Printer to continue its execution.
func (*Ctx) MarshalValue ¶
MarshalValue marshals the `Value` and skips the marshal operation on the `Printer#Print` state.
Remember that if `MarshalValue` called after a `SetResult` then it will not operate a marshaling and return the stored result instead.
type Handler ¶
type Handler func(PrintResult)
Handler is the signature implemented by callers that want to be notified about the results that are being printed to the Printer's output.
Look `Printer#Handle` for more.
type Hijacker ¶
type Hijacker func(*Ctx)
Hijacker is the signature implemented by callers that want to hijack the Print method.
Look `Printer#Hijack` for more.
type Marshaled ¶
Marshaled or (especially British, marshalled) is an interface which is implemented by values that can marshal theirselves.
It's like Marshaler but it doesn't takes an argument.
type Marshaler ¶
Marshaler is the interface implemented by types that can marshal themselves into valid output.
type MarshalerFunc ¶
MarshalerFunc is the signature implemented by callers that are responsible to marshal "v" into valid printable result.
Look `Printer#Marshal` for more.
func (MarshalerFunc) Marshal ¶
func (m MarshalerFunc) Marshal(v interface{}) ([]byte, error)
Marshal makes the Marshaler compatible with the standard golang's marshalers, so a marshaler created for a Printer, can be used on std packages as well.
type OutputAdapters ¶
type OutputAdapters struct{}
OutputAdapters is a struct which contains some forms of output and convert them to a compatible `io.Writer` in order to be passed to the `NewPrinter` or `Register` functions.
func (*OutputAdapters) Print ¶
func (a *OutputAdapters) Print(print func(v interface{})) io.Writer
Print converts a func(v interface{}) to a compatible `io.Writer`.
func (*OutputAdapters) PrintVardiadic ¶
func (a *OutputAdapters) PrintVardiadic(print func(v ...interface{})) io.Writer
PrintVardiadic converts a func(v ...interface{}) to a compatible `io.Writer`.
type PrintResult ¶
PrintResult contains some useful information for a `Print` or `WriteTo` action that are available inside handlers.
func (PrintResult) IsFailure ¶
func (p PrintResult) IsFailure() bool
IsFailure returns true if result's content is not safe to read or it's available, otherwise false.
func (PrintResult) IsOK ¶
func (p PrintResult) IsOK() bool
IsOK returns true if result's content is available, otherwise false.
type Printer ¶
type Printer struct { Name string IsTerminal bool // if Chained is true then the parent `Registry#Print` // will continue to search for a compatible printer // even if this printer succeed to print the contents. Chained bool Output io.Writer // These three will complete the interface of the: // https://golang.org/pkg/io/#ReadWriteCloser // in order to make possible to use everything inside the `io` package. // i.e // https://golang.org/pkg/io/#example_MultiWriter // https://golang.org/pkg/io/#example_TeeReader (piping) io.Reader io.Writer io.Closer // DirectOutput will output the contents and flush them as fast as possible, // without storing them to the buffer to complete the `ReadWriteCloser` std interface. // Enable this if you need performance and you don't use the standard functions like `TeeReader`. DirectOutput bool // contains filtered or unexported fields }
Printer is responsible to print the end result.
func Get ¶
Get returns a Printer based on the "printerName". If printer with this name can't be found then this function will return nil, so a check for nil is always a good practice.
func NewPrinter ¶
NewPrinter returns a new named printer if "output" is nil then it doesn't prints anywhere.
If "name" is empty then it will be filled with "printer_$printers.len".
If the marshaler is nil, meaning that this writer's result will never being proceed, caller should add a marshaler using the `Marshal` function.
Look `OutputFrom` too.
func NewTextPrinter ¶
NewTextPrinter same as NewPrinter but registers a text marshaler, no matter what kind of "output", which converts string type to a compatible form of slice of bytes.
If "name" is empty then it will be filled with "printer_$printers.len".
Look `OutputFrom` too.
func Register ¶
Register creates and registers a new Printer based on a name(string) and an "output"(io.Writer).
If a printer with the same `Name` is already registered then it will be overridden by this new "printer".
Look `OutputFrom` too.
Returns the just created Printer.
func (*Printer) AddOutput ¶
AddOutput adds one or more io.Writer to the Printer. Returns itself.
Look `OutputFrom` and `Wrap` too.
func (*Printer) EnableDirectOutput ¶
EnableDirectOutput will output the contents and flush them as fast as possible, without storing them to the buffer to complete the `ReadWriteCloser` std interface. Enable this if you need performance and you don't use the standard functions like `TeeReader`. Returns itself.
func (*Printer) Handle ¶
func (p *Printer) Handle(h func(PrintResult)) *Printer
Handle adds a callback which is called whenever a `Print` is successfully executed, it's being executed after the contents are written to its output.
The callback accepts the final result, can be used as an easy, pluggable, access to all the logs passed to the `Print`. i.e: `Handle(func(result PrintResult){ fmt.Printf("%s\n", result.Contents)})`
Returns itself.
func (*Printer) Hijack ¶
Hijack registers a callback which is executed when ever `Print` or `WriteTo` is called, this callback can intercept the final result which will be written or be printed.
Returns itself.
func (*Printer) MarshalFunc ¶
MarshalFunc adds a "marshaler" to the printer. Returns itself.
func (*Printer) Print ¶
Print of a Printer accepts a value of "v", tries to marshal its contents and flushes the result to the Printer's output.
If "v" implements the `Marshaler` type, then this marshaler is called automatically, first.
Print -> Store[Marshal -> err != nil && result -> Hijack(result) -> Write(result)] -> Flush[Printer.Write(buf) and Handle(buf)]
Returns how much written and an error on failure.
func (*Printer) Println ¶
Println accepts a value of "v", tries to marshal its contents and flushes the result to this "p" Printer, it adds a new line at the ending, the result doesn't contain this new line, therefore result's contents kept as expected.
func (*Printer) Priority ¶
Priority changes the order of this printer. Higher value means that the `Registry#Print` will try to print first from this printer. Default order is 0 for all printers.
Returns it self.
func (*Printer) Scan ¶
Scan scans everything from "r" and prints its new contents to the "p" Printer, forever or until the returning "cancel" is fired, once.
func (*Printer) SetOutput ¶
SetOutput sets accepts one or more io.Writer and set a multi-writter instance to the Printer's Output. Returns itself.
Look `OutputFrom` too.
func (*Printer) Store ¶
Store will store-only the contents of "v". Returns a PrintResult type in order to the final contents be accessible by third-party tools.
If you want to Print and Flush to the Printer's Output use `Print` instead.
If "appendNewLine" is true then it writes a new line to the Printer's output. Note that it doesn't concat it to the returning PrintResult, therefore the "appendNewLine" it is not affect the rest of the implementation like custom hijackers and handlers.
func (*Printer) WithMarshalers ¶
WithMarshalers same as `Marshal` but accepts more than one marshalers and returns the Printer itself in order to be used side by side with the creational function.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the Printer(s) container.
It can be used as follows: reg := NewRegistry().
RegisterPrinter(NewPrinter("err", os.Stderr)). RegisterPrinter(NewPrinter("default", os.Stdout)). Print("something")
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry returns an empty printer Registry.
Note that: Registry have a zero value, so it can be declared with a simple `var` keyword and without pointer.
func RegisterPrinter ¶
RegisterPrinter registers an already-created printer to the registry.
If a printer with the same `Name` is already registered then it will be overridden by this new "printer".
Returns the Registry, therefore it can be used as builder.
func (*Registry) Get ¶
Get returns a Printer based on the "printerName". If printer with this name can't be found then this function will return nil, so a check for nil is always a good practice.
func (*Registry) Print ¶
Print accepts a value of "v", tries to marshal its contents and flushes the result to all available printers.
func (*Registry) Println ¶
Println accepts a value of "v", tries to marshal its contents and flushes the result to all available printers, it adds a new line at the ending, the result doesn't contain this new line, therefore result's contents kept as expected.
func (*Registry) Register ¶
Register creates and registers a new Printer based on a name(string) and an "output"(io.Writer).
If "printerName" is empty then it will be filled with "printer_$printers.len".
If a printer with the same `Printer#Name` is already registered then it will be overridden by this new "printer".
Look `OutputFrom` too.
Returns the just created Printer.
func (*Registry) RegisterPrinter ¶
RegisterPrinter registers an already-created printer to the registry.
If `Printer#Name` is empty then it will be filled with "printer_$printers.len".
If a printer with the same `Printer#Name` is already registered then it will be overridden by this new "printer".
Returns this Registry, therefore it can be used as builder.
type RichOption ¶ added in v0.0.5
RichOption declares a function which can be passed to the `Rich` function to modify a text.
Builtin options are defined below: - `Bright` - `Background` - `Bold` - `Underline` and - `Reversed`.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
integrations/logrus
Package logrus registers the global logrus logger to the pio ecosystem, install logrus first:
|
Package logrus registers the global logrus logger to the pio ecosystem, install logrus first: |