fx

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 9 Imported by: 0

README

climate/fx

Small {}-style formatting with ANSI and time tokens.

fx is a tiny formatter for CLI output. It replaces {} placeholders with values, supports colour and style tokens such as {red} and {bold}, can insert date and time values with tokens like {time} and {stamp}, and includes plain-text rendering helpers for logs and file output.

Installation

go get github.com/grimdork/climate/fx

Usage

Basic formatting
package main

import "github.com/grimdork/climate/fx"

func main() {
	fx.Println("Hello, {}!", "Boss")
	fx.Print("Count: {}", 42)

	s := fx.Sprint("Joined: {} and {}", "first", "second")
	plain := fx.RenderPlain("{green}OK{@} {}", "done")
	_ = s
	_ = plain
}
Colours and styles
fx.Println("{red}Error:{@} {}", "file not found")
fx.Println("{bold}{yellow}Warning:{@} something happened")
fx.Println("{success}Done{@}")

Tokens are case-insensitive. Use {@} or {reset} to clear formatting.

Log-safe output

RenderPlain, Log, and Logln strip ANSI escape codes from the result.

fx.Logln("{magenta}Coloured in the terminal, plain in logs{@}")
plain := fx.RenderPlain("{red}Error:{@} {}", "boom")

If you want to write to your own destination, use the writer variants:

fx.Fprint(w, "{green}Status:{@} {}", "ready")
fx.Flogln(w, "{magenta}Plain in logs{@}")
Time tokens
fx.Println("[{time}] Started")
fx.Println("Zone: {tzname} ({tzoffset})")
fx.Println("Stamp: {stamp}")

Available value tokens include:

  • {date} and {tzdate}
  • {time} and {stamp}
  • {logstamp}
  • {year}, {month}, {monthnum}, {day}
  • {dow} / {dayofweek}
  • {hour}, {min}, {sec}
  • {tzoffset}, {tzsecs}, {tzname}

Some timezone tokens accept a :utc modifier, such as {tzoffset:utc}.

Notes

  • {} is replaced by the next argument.
  • Extra arguments are appended with spaces.
  • Missing arguments leave {} unchanged.
  • []byte is emitted as a string.
  • Common slices are joined with , and no brackets.
  • error values and types with a String() string method use their own string output.
  • Common string-key and int-key maps are rendered as {key=value} pairs.
  • Unsupported values render as <unsupported> unless they provide their own string or text output.
  • Unknown tokens are left unchanged.
  • Setting NO_COLOR suppresses ANSI output automatically.

Aliases

Predefined aliases:

  • dangerred bold
  • warningyellow bold
  • infoblue
  • successgreen
  • muteddim

You can add your own:

fx.AddAlias("note", "magenta italic")
fx.Println("{note}Remember this{@}")

Aliases are safe to add and remove at runtime.

Custom tokens

Register your own tokens with AddToken:

fx.AddToken("app", func(mod string) (string, bool) {
	if mod == "short" {
		return "climate", true
	}
	if mod == "" {
		return "github.com/grimdork/climate", true
	}
	return "", false
})

fx.Println("Running {app:short}")

Escaping and custom delimiters

Double a delimiter to emit it literally:

fx.Sprint("{{red}}") // "{red}"
fx.Sprint("{{}}")    // "{}"

Use SprintWithDelims if you want a different single-byte delimiter pair:

fx.SprintWithDelims("<", ">", "<red>Hello<@> <>", "world")

Render options

Use RenderWithOptions when you want to change behaviour for a single call:

out := fx.RenderWithOptions(fx.Options{SortMaps: true}, "{}", map[string]int{
	"b": 2,
	"a": 1,
})
// out == "{a=1, b=2}"

ANSI stripping

s := fx.Sprint("{green}OK{@}")
plain := fx.StripANSI(s)

Zero dependencies

Uses only the Go standard library.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAlias

func AddAlias(name, expansion string)

AddAlias registers or updates an alias. Name is case-insensitive.

func AddToken

func AddToken(name string, fn TokenFunc)

AddToken registers or updates a token renderer. Name is case-insensitive.

func DeleteAlias

func DeleteAlias(name string)

DeleteAlias removes a registered alias. Name is case-insensitive.

func DeleteToken

func DeleteToken(name string)

DeleteToken removes a registered token renderer. Name is case-insensitive.

func Flog

func Flog(w io.Writer, format string, args ...any)

Flog writes the rendered output to w with ANSI sequences stripped.

func Flogln

func Flogln(w io.Writer, format string, args ...any)

Flogln writes the rendered output to w with ANSI sequences stripped and ensures a trailing newline.

func Fprint

func Fprint(w io.Writer, format string, args ...any)

Fprint writes the rendered output to w with no automatic newline.

func Fprintln

func Fprintln(w io.Writer, format string, args ...any)

Fprintln writes the rendered output to w and ensures a trailing newline.

func Log

func Log(format string, args ...any)

Log writes the formatted output but with ANSI sequences stripped (useful for logs).

func Logln

func Logln(format string, args ...any)

Logln like Log but ensures a trailing newline.

func Print

func Print(format string, args ...any)

Print writes the formatted output to stdout (no automatic newline).

func Println

func Println(format string, args ...any)

Println writes the formatted output to stdout and ensures a trailing newline. If the formatted text already ends with a newline, it is not doubled.

func Render

func Render(format string, args ...any) string

Render formats a string using the default options.

func RenderPlain

func RenderPlain(format string, args ...any) string

RenderPlain formats a string and strips ANSI escape sequences from the result.

func RenderPlainWithOptions

func RenderPlainWithOptions(opts Options, format string, args ...any) string

RenderPlainWithOptions formats a string using the provided options and strips ANSI.

func RenderWithOptions

func RenderWithOptions(opts Options, format string, args ...any) string

RenderWithOptions formats a string using the provided options.

func Sprint

func Sprint(format string, args ...any) string

Sprint returns a formatted string using {} placeholders. Each {} is replaced by the next argument's string representation. If there are more args than placeholders they are appended separated by spaces. If there are fewer args than placeholders the remaining {} are left as-is.

func SprintWithDelims

func SprintWithDelims(open, close string, format string, args ...any) string

SprintWithDelims is like Sprint but uses the provided open/close single-character delimiters instead of { and } (e.g. '<' and '>'). If open or close are not single bytes the call falls back to Sprint.

func StripANSI

func StripANSI(s string) string

StripANSI removes common ANSI SGR escape sequences (like \x1b[31m) from s.

Types

type Options

type Options struct {
	// SortMaps sorts supported map keys alphabetically/numerically before rendering.
	SortMaps bool
	// DisableColour suppresses ANSI output for built-in colour/style tokens.
	// NO_COLOR also disables colour automatically.
	DisableColour bool
}

Options control rendering behaviour.

type TokenFunc

type TokenFunc func(modifier string) (string, bool)

TokenFunc renders a named token. The modifier is the optional text after a colon, such as the "utc" in {tzoffset:utc}. The boolean reports whether the modifier was accepted.

Jump to

Keyboard shortcuts

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