formatter

package
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2020 License: Apache-2.0 Imports: 15 Imported by: 5

Documentation

Overview

Package formatter implements “replacement fields” surrounded by curly braces {} format strings.

Built-in functions

Simple example:

formatted, err := formatter.Format("{italic}{red}{blink}blinky :){blink | off} no blinky :({default}")

Built-in text functions

List of built-in functions:

reset      - All text attributes off
normal 	   - All text attributes off, alias to reset
default    - All text attributes off, alias to reset
bold       - Bold text
faint      - Faint text
italic     - Italic text
underline  - Underline text
overline   - Overline text
blink      - Blink text
invert     - Swap foreground and background colors
hide       - Hide text
strike     - Strike text
off        - Disable specific text attribute. Example: blink | off

Built-in string functions

List of built-in functions:

upper      - Transform provided string to upper case. Example: upper "text"
lower      - Transform provided string to lower case. Example: lower "TEXT"
capitalize - Capitalize provided string. Example: capitalize "text"

Built-in color functions

List of built-in functions:

black      - Black color
red        - Red color
green      - Green color
yellow     - Yellow color
blue       - Blue color
magenta    - Magenta color
cyan       - Cyan color
white      - White color
gray       - Gray color
rgb        - 24-bit color, 3 arguments (red, green, blue), integer values between 0-255
color      - Set color, 1 argument, color name like "red" or RGB HEX value in "0xXXXXXX" format
bright     - Make color bright, used with standard color function. Example: green | bright
foreground - Set as foreground color (default). Example: blue | foreground
background - Set as background color. Example: cyan | background

Built-in OS functions

List of built-in functions:

ip         - Get outbound (local) IP address
user       - Get current user name
executable - Get current executable path
cwd        - Get current working directory path
hostname   - Get hostname
env        - Get environment variable
expand     - Get and expand environment variable
uid        - Get user ID
gid        - Get group ID
euid       - Get effective user ID
egid       - Get effective group ID
pid        - Get process ID
ppid       - Get parent process ID
bell       - Make a sound

Built-in time functions

List of built-in functions:

now        - Get current time
rfc3339    - Format time to RFC 3339. Example: now | rfc3339
iso8601    - Format time to ISO 8601. Example: now | iso8601

Built-in path functions

List of built-in functions:

absolute   - Returns an absolute representation of path
base       - Returns the last element of path. Example: base "/dir/dir/file"
clean      - Returns the shortest path name equivalent to path by purely lexical processing
directory  - Returns all but the last element of path, typically the path's directory
extension  - Returns the file name extension used by path. Example: extension "/dir/dir/file.ext"

Built-in object functions

List of built-in functions:

fields    - Print also struct field names for given object. Example: p | fields
json      - Marshal object to JSON. Example: p | json
indent    - Indent marshaled JSON. Example: p | json | indent

Index

Examples

Constants

View Source
const (
	DefaultPlaceholder      = "p"
	DefaultLeftDelimiter    = "{"
	DefaultRightDelimiter   = "}"
	ForceEscapeSequencesEnv = "FORCE_ESCAPE_SEQUENCES"
)

These constants define default values used by formatter.

Variables

View Source
var Current = user.Current // nolint: gochecknoglobals

Current is used only in testing and mocking.

View Source
var Dial = net.Dial // nolint: gochecknoglobals

Dial is used only in testing and mocking.

Functions

func AreEscapeSequencesSupported added in v1.4.0

func AreEscapeSequencesSupported() bool

AreEscapeSequencesSupported returns true if environment supports ANSI escape sequences. Otherwise, it returns false.

func Format

func Format(message string, arguments ...interface{}) (string, error)

Format formats string.

Example (AutomaticPlaceholder)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("Automatic placeholder {p}:{p}:{p}():", "dir/file", 1, "func1")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Automatic placeholder dir/file:1:func1():
Example (BackgroundBrightColors)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("With background bright colors {cyan | bright | background}cyan{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Example (BackgroundColors)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("With background colors {yellow | background}yellow{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Example (BackgroundRGB)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("With background RGB {rgb 255 165 0 | background}funky{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Example (BrightColors)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("With bright colors {magenta | bright}magenta{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Example (Colors)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("With colors {red}red{normal} {green}green{normal} {blue}blue{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Example (MixedPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	objectPointer := &struct {
		X int
		Y int
		Z int
	}{
		X: 2,
		Z: 6,
		Y: 3,
	}

	formatted, err := formatter.Format("Mixed placeholders {.X}.{p}.{.Y}.{.Z} {p1} {p0}", objectPointer, "b", "c", nil)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Mixed placeholders 2.{2 3 6}.3.6 b {2 3 6} c <nil>
Example (NamedPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("Named placeholders {file}:{line}:{function}():", formatter.Named{
		"line":     3,
		"function": "func1",
		"file":     "dir/file",
	})

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Named placeholders dir/file:3:func1():
Example (ObjectAutomaticPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	object1 := struct {
		X int
	}{
		X: 1,
	}

	object2 := struct {
		Message string
	}{
		Message: "msg",
	}

	formatted, err := formatter.Format("{p.X} {p.Message}", object1, object2)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

1 msg
Example (ObjectPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	object := struct {
		Line     int
		Function string
		File     string
	}{
		Line:     4,
		Function: "func1",
		File:     "dir/file",
	}

	formatted, err := formatter.Format("Object placeholders {.File}:{.Line}:{.Function}():", object)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Object placeholders dir/file:4:func1():
Example (ObjectPointerPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	objectPointer := &struct {
		X int
		Y int
		Z int
	}{
		X: 4,
		Z: 3,
		Y: 1,
	}

	formatted, err := formatter.Format("Object placeholders {.X}.{.Y}.{.Z}", objectPointer)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Object placeholders 4.1.3
Example (ObjectPositionalPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	object1 := struct {
		X int
	}{
		X: 1,
	}

	object2 := struct {
		Y int
	}{
		Y: 2,
	}

	formatted, err := formatter.Format("{p1.Y} {p0.X}", object1, object2)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

2 1
Example (PositionalPlaceholders)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("Positional placeholders {p1}:{p0}:{p2}():", 2, "dir/file", "func1")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Positional placeholders dir/file:2:func1():
Example (Rgb)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("With RGB {rgb 255 165 0}funky{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Example (WithArguments)
formatted, err := formatter.Format("With arguments", 3, nil, 4.5, true, "arg1", []byte{}, Error("error"))

if err != nil {
	panic(err)
}

fmt.Println(formatted)
Output:

With arguments 3 <nil> 4.5 true arg1 [] error
Example (WithoutArguments)
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.Format("Without arguments")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Without arguments

func FormatWriter

func FormatWriter(writer io.Writer, message string, arguments ...interface{}) error

FormatWriter formats string to writer.

Example
package main

import (
	"bytes"
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	buffer := new(bytes.Buffer)

	if err := formatter.FormatWriter(buffer, "Writer {p2}", 3, "foo", "bar"); err != nil {
		panic(err)
	}

	fmt.Println(buffer.String())
}
Output:

Writer bar 3 foo

func MustFormat added in v1.1.0

func MustFormat(message string, arguments ...interface{}) string

MustFormat is like Format but panics if provided message cannot be formatted. It simplifies safe initialization of global variables holding formatted strings.

Example
fmt.Println(formatter.MustFormat("With arguments", 3, nil, false, 4.5, "text", []byte{}, Error("error")))
Output:

With arguments 3 <nil> false 4.5 text [] error

Types

type Formatter

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

Formatter defines a formatter object that formats string using “replacement fields” surrounded by curly braces {}.

func New

func New() *Formatter

New creates a new formatter object.

func (*Formatter) AddFunction

func (f *Formatter) AddFunction(name string, function interface{}) *Formatter

AddFunction adds template function used by formatter.

func (*Formatter) AddFunctions

func (f *Formatter) AddFunctions(functions Functions) *Formatter

AddFunctions adds template functions used by formatter.

func (*Formatter) AreEscapeSequencesEnabled added in v1.4.0

func (f *Formatter) AreEscapeSequencesEnabled() bool

AreEscapeSequencesEnabled returns true if escape sequences are allowed in formatted messages. Otherwise, it returns false.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	f := formatter.New()

	fmt.Println(f.DisableEscapeSequences().AreEscapeSequencesEnabled())
	fmt.Println(f.EnableEscapeSequences().AreEscapeSequencesEnabled())
}
Output:

false
true

func (*Formatter) DisableEscapeSequences added in v1.4.0

func (f *Formatter) DisableEscapeSequences() *Formatter

DisableEscapeSequences removes ANSI escape sequences in formatted messages.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.New().DisableEscapeSequences().Format("{rgb 255 134 5 | background}Escape sequences disabled{normal}")

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Escape sequences disabled

func (*Formatter) EnableEscapeSequences added in v1.4.0

func (f *Formatter) EnableEscapeSequences() *Formatter

EnableEscapeSequences allows ANSI escape sequences in formatted messages.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	fmt.Println(formatter.New().EnableEscapeSequences().AreEscapeSequencesEnabled())
}
Output:

true

func (*Formatter) Format

func (f *Formatter) Format(message string, arguments ...interface{}) (string, error)

Format formats string.

func (*Formatter) FormatWriter

func (f *Formatter) FormatWriter(writer io.Writer, message string, arguments ...interface{}) error

FormatWriter formats string to writer.

func (*Formatter) GetDelimiters

func (f *Formatter) GetDelimiters() (left, right string)

GetDelimiters returns delimiters used by formatter. Default is {}.

func (*Formatter) GetFunction

func (f *Formatter) GetFunction(name string) interface{}

GetFunction returns template function used by formatter.

func (*Formatter) GetFunctions

func (f *Formatter) GetFunctions() Functions

GetFunctions returns template functions used by formatter.

func (*Formatter) GetLeftDelimiter

func (f *Formatter) GetLeftDelimiter() string

GetLeftDelimiter returns left delimiter used by formatter. Default is {.

func (*Formatter) GetPlaceholder

func (f *Formatter) GetPlaceholder() string

GetPlaceholder returns placeholder string prefix used for automatic and positional placeholders to format string. Default is p.

func (*Formatter) GetRightDelimiter

func (f *Formatter) GetRightDelimiter() string

GetRightDelimiter returns right delimiter used by formatter. Default is }.

func (*Formatter) MustFormat added in v1.1.0

func (f *Formatter) MustFormat(message string, arguments ...interface{}) string

MustFormat is like Format but panics if provided message cannot be formatted. It simplifies safe initialization of global variables holding formatted strings.

func (*Formatter) RemoveFunction

func (f *Formatter) RemoveFunction(name string) *Formatter

RemoveFunction removes template function used by formatter.

func (*Formatter) RemoveFunctions

func (f *Formatter) RemoveFunctions(names []string) *Formatter

RemoveFunctions removes template functions used by formatter.

func (*Formatter) Reset

func (f *Formatter) Reset() *Formatter

Reset resets formatter to default state.

func (*Formatter) ResetDelimiters

func (f *Formatter) ResetDelimiters() *Formatter

ResetDelimiters resets delimiters used by formatter to default values.

func (*Formatter) ResetFunctions

func (f *Formatter) ResetFunctions() *Formatter

ResetFunctions resets template functions used by formatter.

func (*Formatter) ResetLeftDelimiter

func (f *Formatter) ResetLeftDelimiter() *Formatter

ResetLeftDelimiter resets left delimiter used by formatter to default value.

func (*Formatter) ResetPlaceholder

func (f *Formatter) ResetPlaceholder() *Formatter

ResetPlaceholder resets placeholder to default value.

func (*Formatter) ResetRightDelimiter

func (f *Formatter) ResetRightDelimiter() *Formatter

ResetRightDelimiter resets right delimiter used by formatter to default value.

func (*Formatter) SetDelimiters

func (f *Formatter) SetDelimiters(left, right string) *Formatter

SetDelimiters sets delimiters used by formatter. Default is {}.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.New().SetDelimiters("<", ">").Format("Custom delimiters <p1> <p0>", "4", 3)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Custom delimiters 3 4

func (*Formatter) SetEscapeSequences added in v1.4.0

func (f *Formatter) SetEscapeSequences(escapeSequences bool) *Formatter

SetEscapeSequences enables or disables ANSI escape sequences in formatted messages.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	f := formatter.New()

	fmt.Println(f.SetEscapeSequences(false).AreEscapeSequencesEnabled())
	fmt.Println(f.SetEscapeSequences(true).AreEscapeSequencesEnabled())
}
Output:

false
true

func (*Formatter) SetFunctions

func (f *Formatter) SetFunctions(functions Functions) *Formatter

SetFunctions sets template functions used by formatter.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	functions := formatter.Functions{
		"str": func() string {
			return "text"
		},
		"number": func() int {
			return 3
		},
		"boolean": func() bool {
			return true
		},
		"floating": func() float64 {
			return 4.5
		},
	}

	formatted, err := formatter.New().SetFunctions(functions).Format("Custom functions {str} {p} {number} {boolean} {floating}", 5)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Custom functions text 5 3 true 4.5

func (*Formatter) SetLeftDelimiter

func (f *Formatter) SetLeftDelimiter(delimiter string) *Formatter

SetLeftDelimiter sets left delimiter used by formatter. Default is {.

func (*Formatter) SetPlaceholder

func (f *Formatter) SetPlaceholder(placeholder string) *Formatter

SetPlaceholder sets placeholder string prefix used for automatic and positional placeholders to format string. Default is p.

Example
package main

import (
	"fmt"

	"gitlab.com/tymonx/go-formatter/formatter"
)

func main() {
	formatted, err := formatter.New().SetPlaceholder("arg").Format("Custom placeholder {arg1} {arg0}", "2", 3)

	if err != nil {
		panic(err)
	}

	fmt.Println(formatted)
}
Output:

Custom placeholder 3 2

func (*Formatter) SetRightDelimiter

func (f *Formatter) SetRightDelimiter(delimiter string) *Formatter

SetRightDelimiter sets right delimiter used by formatter. Default is }.

type Functions

type Functions map[string]interface{}

Functions defines a map of template functions.

type Named

type Named map[string]interface{}

Named defines named arguments.

Jump to

Keyboard shortcuts

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