format

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 13 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package format names the output formats a command-line tool offers through an --output flag and writes the structured ones.

A Format is a name such as "json" or "csv". A Set is the list of formats one command accepts; Set.Parse validates a flag value against it, and Value plugs that check into a flag parser. Default holds the formats this package knows how to classify: text, json, yaml, csv, tsv and markdown. A tool may add formats of its own, such as Format("ics"), to the set it accepts.

WriteJSON and WriteYAML write the same view of a value. YAML is produced from the JSON encoding, so json struct tags are the single source of truth for both formats: field names, omitted fields, custom MarshalJSON methods and field order are the same in either output. Neither writes a control character raw: one in a string is escaped, so the output is as safe to print on a terminal as it is to parse.

Escape sequences belong in text output only. Markdown, CSV and TSV are pasted or parsed verbatim, and JSON and YAML are read by programs, so Format.Colored reports false for all of them whatever --color says.

Index

Examples

Constants

This section is empty.

Variables

View Source
var Default = Set{Text, JSON, YAML, CSV, TSV, Markdown}

Default is every format this package classifies, text first.

View Source
var ErrNotStructured = errors.New("format is not structured")

ErrNotStructured is returned by Write for a format other than JSON or YAML.

View Source
var ErrUnknown = errors.New("unknown output format")

ErrUnknown is wrapped by the error Set.Parse returns for a value that names no accepted format.

Functions

func Write

func Write(w io.Writer, f Format, v any) error

Write writes v in format f, which must be JSON or YAML.

func WriteJSON

func WriteJSON(w io.Writer, v any) error

WriteJSON writes v as JSON indented by two spaces, followed by a newline. Unlike json.MarshalIndent it leaves <, > and & as they are: the output is read in a terminal or by a program, not embedded in HTML.

The output carries no control character but the newlines between its lines, so it is as safe to print on a terminal as it is to parse: besides the C0 controls, which encoding/json escapes, DEL and the C1 controls (U+007F–U+009F) are written as \u escapes too. A terminal takes U+009B for ESC [ and U+009D for ESC ], and encoding/json leaves both raw. Every string still decodes to the value it was.

Example
package main

import (
	"os"

	"github.com/mittwald/cli-kit/format"
)

type release struct {
	Name    string   `json:"name"`
	Version string   `json:"version"`
	Stable  bool     `json:"stable"`
	Tags    []string `json:"tags,omitempty"`
}

func main() {
	_ = format.WriteJSON(os.Stdout, release{Name: "cli-kit", Version: "0.1.0", Stable: true})
}
Output:
{
  "name": "cli-kit",
  "version": "0.1.0",
  "stable": true
}

func WriteYAML

func WriteYAML(w io.Writer, v any) error

WriteYAML writes the view WriteJSON writes, as YAML. The value goes through its JSON encoding first, so the json tags stay the single source of truth for field names, omitted fields and the formatting custom MarshalJSON methods apply. The JSON is then decoded into an ordered map, so fields keep the order the struct defines instead of being sorted.

Scalars whose plain YAML form would read back as another type (a time, a date, a boolean, a number, null) are quoted, and sequences are indented under their key. A string that spans lines is a literal block.

The output carries no control character but the line breaks of its structure and of literal blocks, so it is as safe to print on a terminal as it is to parse. A string with any other control character — C0, DEL or C1, a tab or a carriage return as much as ESC or BEL — is written double quoted with that character escaped (\x1b, \a, \t, \u009b), and so are the line and paragraph separators U+2028 and U+2029, which YAML 1.1 readers take for line breaks, and U+FFFE and U+FFFF, which YAML does not allow. Such a string reads back as the string it was.

A string is double-quoted, too, where its plain form or a literal block would read back as something else: a key that spans lines; a string that spans lines but is made only of line breaks and spaces, starts its first line with text with a space, or ends its last line with one; .inf or .nan, which read back as numbers; a string starting with "? ", which reads back as a mapping; "<<" and "=", which YAML 1.1 reads as a merge and a default value; and, where it starts a line at the left margin as a key or the whole document, a string starting with "---" or "...", which mark documents, or with a byte order mark, which a reader drops.

Example
package main

import (
	"os"

	"github.com/mittwald/cli-kit/format"
)

type release struct {
	Name    string   `json:"name"`
	Version string   `json:"version"`
	Stable  bool     `json:"stable"`
	Tags    []string `json:"tags,omitempty"`
}

func main() {
	_ = format.WriteYAML(os.Stdout, release{Name: "cli-kit", Version: "0.1.0", Tags: []string{"go", "cli"}})
}
Output:
name: cli-kit
version: 0.1.0
stable: false
tags:
  - go
  - cli

Types

type Format

type Format string

Format is the name of an output format, as given to an --output flag.

const (
	// Text is human-readable output, usually a drawn table. It is the only
	// format that may be painted.
	Text Format = "text"
	// JSON is indented JSON.
	JSON Format = "json"
	// YAML is block-style YAML carrying the same view as JSON.
	YAML Format = "yaml"
	// CSV is comma-separated records (RFC 4180).
	CSV Format = "csv"
	// TSV is tab-separated records, never quoted.
	TSV Format = "tsv"
	// Markdown is a GitHub-flavored pipe table.
	Markdown Format = "markdown"
)

The formats this package classifies.

func Parse

func Parse(value string) (Format, error)

Parse reads value as one of the formats in Default. See Set.Parse.

func (Format) Colored

func (f Format) Colored(w io.Writer) bool

Colored reports whether output in format f written to w may be painted: only text output is, and only when term.Colored allows it for w. The empty Format counts as text.

func (Format) IsDelimited

func (f Format) IsDelimited() bool

IsDelimited reports whether f is a record format (CSV or TSV): a header record and one record per row, and nothing else.

func (Format) IsStructured

func (f Format) IsStructured() bool

IsStructured reports whether f is a format for programs to read (JSON or YAML), which carries the data and none of the prose a text view adds.

func (Format) IsVerbatim

func (f Format) IsVerbatim() bool

IsVerbatim reports whether f is text another program or document takes as it stands (markdown, CSV, TSV). Such output must never carry escape sequences, even under --color=always, and should carry the table alone.

func (Format) String

func (f Format) String() string

String returns the flag spelling of f.

type Set

type Set []Format

Set is the list of formats a command accepts, in the order help text and shell completion list them.

func (Set) Contains

func (s Set) Contains(f Format) bool

Contains reports whether s holds f.

func (Set) Names

func (s Set) Names() []string

Names returns the flag spellings of the formats in s, for shell completion.

func (Set) Parse

func (s Set) Parse(value string) (Format, error)

Parse reads value as one of the formats in s. Matching ignores case and surrounding space, and accepts the aliases yml, md, table and txt for a format s holds. The error for any other value names every accepted format.

Example
package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/format"
)

func main() {
	accepted := format.Set{format.Text, format.JSON, format.Format("ics")}
	f, err := accepted.Parse("ICS")
	fmt.Println(f, err)
	_, err = accepted.Parse("yaml")
	fmt.Println(err)
}
Output:
ics <nil>
unknown output format "yaml": want one of text, json, ics

func (Set) String

func (s Set) String() string

String returns the formats in s as a comma-separated list for help text.

type Value

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

Value is a flag value that accepts the formats of one Set. It implements the Set, String and Type methods of pflag.Value and the Set and String methods of flag.Value, so it works with either package.

func NewValue

func NewValue(target *Format, def Format, allowed Set) *Value

NewValue returns a flag value that stores into target, starting at def, and accepts the formats in allowed (or Default when allowed is nil).

func (*Value) Allowed

func (v *Value) Allowed() Set

Allowed returns the formats the value accepts, for shell completion.

func (*Value) Set

func (v *Value) Set(value string) error

Set parses value and stores it.

func (*Value) String

func (v *Value) String() string

String returns the stored format.

func (*Value) Type

func (v *Value) Type() string

Type names the value kind for pflag's help output.

Jump to

Keyboard shortcuts

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