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 ¶
Default is every format this package classifies, text first.
var ErrNotStructured = errors.New("format is not structured")
ErrNotStructured is returned by Write for a format other than JSON or YAML.
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 WriteJSON ¶
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 ¶
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 (Format) Colored ¶
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 ¶
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 ¶
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 ¶
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.
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) Parse ¶
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
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 ¶
NewValue returns a flag value that stores into target, starting at def, and accepts the formats in allowed (or Default when allowed is nil).