Documentation
¶
Overview ¶
Package formatter defines the interface for config file formatters.
A Formatter transforms source bytes into a canonically formatted version. Each formatter implementation lives in its own sub-package (e.g., formatter/json, formatter/yaml) and is registered on the filetype.FileType it handles.
Design constraints:
- Stateless: Format may be called concurrently on different files.
- Idempotent: Format(Format(x, opts), opts) == Format(x, opts).
- Comment-preserving: output must contain every comment from the input.
- Consistent output: all formatters report issues using the same message shape so cfv's output looks like one tool, not a patchwork.
Index ¶
- func IsFormatted(f Formatter, src []byte, opts Options) (bool, error)
- func NormalizeLineEndings(data []byte, ending LineEnding) []byte
- type EditorConfig
- type ErrSkipped
- type Formatter
- type IndentStyle
- type LineEnding
- type Options
- type PrettierConfig
- type QuoteStyle
- type SequenceIndent
- type Taplo
- type TaploFormatting
- type TrailingCommas
- type XMLWhitespace
- type Yamlfmt
- type YamlfmtFormatter
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsFormatted ¶
IsFormatted reports whether src is already in canonical form. This is a convenience function: it runs Format and compares the result byte-for-byte with the input.
func NormalizeLineEndings ¶
func NormalizeLineEndings(data []byte, ending LineEnding) []byte
NormalizeLineEndings converts line endings in data to the requested style.
LineEndingDefault and LineEndingLF are both treated as LF (no-ops if the input already uses LF). LineEndingCRLF replaces bare \n with \r\n, leaving existing \r\n sequences untouched.
Types ¶
type EditorConfig ¶
type EditorConfig struct {
// contains filtered or unexported fields
}
EditorConfig resolves .editorconfig settings for individual files.
EditorConfig resolution is per-file: the properties that apply depend on the file's path (glob sections) and on the .editorconfig files found walking up from its directory (stopping at root = true). The zero value is not usable; use NewEditorConfig.
Safe for concurrent use.
func NewEditorConfig ¶
func NewEditorConfig() *EditorConfig
NewEditorConfig returns an EditorConfig backed by a cached parser, so .editorconfig files shared by many source files are only parsed once.
func (*EditorConfig) Apply ¶
func (e *EditorConfig) Apply(opts *Options, path string)
Apply overlays the .editorconfig properties that apply to path onto opts. Properties that are absent, unset, or not representable as an Option are left alone.
A malformed or unreadable .editorconfig is ignored rather than reported — it is not the file being formatted, and failing the run over someone else's editor settings is worse than using the defaults.
type ErrSkipped ¶
type ErrSkipped struct {
Reason string
}
ErrSkipped indicates the formatter cannot process this file but it is not a syntax error. The file should be reported to the user with the reason but not counted as a failure or formatted.
func (*ErrSkipped) Error ¶
func (e *ErrSkipped) Error() string
Error implements the error interface.
type Formatter ¶
type Formatter interface {
// Format returns the canonically formatted version of src.
// If src is already canonical, Format returns src unchanged (byte-equal).
// Returns an error if src cannot be parsed (unparseable input is not
// a formatting issue — it's a syntax error handled by the validator).
Format(src []byte, opts Options) ([]byte, error)
}
Formatter transforms source bytes into canonically formatted output.
Implementations must be stateless and safe for concurrent use. Implementations must preserve all comments present in the source.
type IndentStyle ¶
type IndentStyle int
IndentStyle selects between spaces and tabs.
const ( // IndentDefault means the formatter uses its own convention. IndentDefault IndentStyle = iota // IndentSpaces uses spaces for indentation. IndentSpaces // IndentTabs uses tabs for indentation. IndentTabs )
type LineEnding ¶
type LineEnding int
LineEnding selects the line terminator.
const ( // LineEndingDefault uses the formatter's convention (typically LF). LineEndingDefault LineEnding = iota // LineEndingLF uses \n. LineEndingLF // LineEndingCRLF uses \r\n. LineEndingCRLF )
type Options ¶
type Options struct {
// IndentStyle selects spaces or tabs. Zero value = format default.
IndentStyle IndentStyle
// IndentWidth is spaces per indent level. Ignored when IndentStyle is Tabs.
// Zero value = format default.
IndentWidth int
// FinalNewline ensures the file ends with exactly one newline.
FinalNewline bool
// LineEnding selects the line terminator for output.
LineEnding LineEnding
// SortKeys sorts object/map keys alphabetically when true.
SortKeys bool
// MaxLineWidth is the target maximum line width. 0 = no limit.
// Formatters use this as a hint, not a hard constraint.
MaxLineWidth int
// QuoteStyle controls quoting of string scalars.
// Only applies to formats with multiple quoting conventions (YAML).
// JSON always uses double quotes per spec; this field is ignored for JSON.
QuoteStyle QuoteStyle
// XMLWhitespaceSensitivity controls XML whitespace handling.
// Ignore: reformat all indentation (default for config files).
// Preserve: only modify existing indentation, never insert newlines.
XMLWhitespaceSensitivity XMLWhitespace
// XMLSelfClosingSpace adds a space before /> in self-closing tags.
// true: <br /> ; false: <br/>
XMLSelfClosingSpace bool
// TrailingCommas controls trailing commas on multiline collections.
// Only applies to formats that permit them (JSONC).
TrailingCommas TrailingCommas
// IndentSequences controls whether YAML sequences used as mapping values
// receive an additional indentation level.
IndentSequences SequenceIndent
}
Options controls formatting behavior. Each formatter uses the fields that apply to its format and ignores the rest. Zero values mean "use the format-specific default."
Options are resolved by the CLI before being passed to a formatter:
CLI flags > .cfv.toml [format.<type>] > .cfv.toml [format] > format-specific config > .editorconfig > hardcoded defaults
func DefaultFormatOptions ¶
func DefaultFormatOptions() Options
DefaultFormatOptions returns the global default formatting options. These are overridden by .cfv.toml [format] settings and per-format overrides in .cfv.toml [format.<type>].
Zero values mean "use the format-specific default," so this only sets options that have a universal reasonable default.
func LoadFixtureOptions ¶
LoadFixtureOptions reads a JSON sidecar file to override formatting options. The file maps Options field names to values. Zero-value fields in the JSON are left at their default from baseOpts.
Example opts.json:
{"IndentStyle": 2, "IndentWidth": 4}
IndentStyle values: 0=IndentDefault, 1=IndentSpaces, 2=IndentTabs LineEnding values: 0=LineEndingDefault, 1=LineEndingLF, 2=LineEndingCRLF TrailingCommas values: 0=TrailingCommasPreserve, 1=TrailingCommasAll, 2=TrailingCommasNone
If the file does not exist, baseOpts is returned unchanged.
type PrettierConfig ¶
type PrettierConfig struct {
// contains filtered or unexported fields
}
PrettierConfig resolves .prettierrc settings for individual files.
Resolution is per-file: cfv walks up from the file's directory and uses the nearest directory containing a supported .prettierrc variant. Unlike .editorconfig, prettier configs are not merged across directory levels — the closest file found entirely determines the result.
The zero value is not usable; use NewPrettierConfig.
Safe for concurrent use.
func NewPrettierConfig ¶
func NewPrettierConfig() *PrettierConfig
NewPrettierConfig returns a PrettierConfig backed by a cache, so a .prettierrc shared by many source files is only parsed once.
func (*PrettierConfig) Apply ¶
func (p *PrettierConfig) Apply(opts *Options, path string)
Apply overlays the resolved .prettierrc properties for path onto opts. Properties that are absent, unset, or not representable as an Option are left alone. A missing, malformed, or unsupported (JS-based) config is ignored rather than reported.
type QuoteStyle ¶
type QuoteStyle int
QuoteStyle controls string scalar quoting.
const ( // QuotePreserve keeps the original quoting style from the source. QuotePreserve QuoteStyle = iota // QuoteDouble forces double-quoted strings. QuoteDouble // QuoteSingle forces single-quoted strings. QuoteSingle )
type SequenceIndent ¶
type SequenceIndent int
SequenceIndent controls indentation of YAML sequences under mapping keys.
const ( // SequenceIndentDefault means the formatter uses its own convention. SequenceIndentDefault SequenceIndent = iota // SequenceIndentEnabled indents sequences one level under mapping keys. SequenceIndentEnabled // SequenceIndentDisabled keeps sequence indicators aligned with the key's // value indentation. SequenceIndentDisabled )
type Taplo ¶
type Taplo struct {
Formatting TaploFormatting `toml:"formatting"`
}
Taplo is a parsed taplo.toml. It only applies to TOML files.
func LoadTaplo ¶
LoadTaplo returns the taplo configuration found by walking up from startDir, or nil if there is none. taplo.toml is preferred over .taplo.toml.
A malformed or unreadable file yields nil rather than an error: it is not the file being formatted, and another tool's config should not fail the run. Apply is a no-op on a nil *Taplo, so callers need no nil check.
type TaploFormatting ¶
type TaploFormatting struct {
IndentString *string `toml:"indent_string"`
ColumnWidth *int `toml:"column_width"`
TrailingNewline *bool `toml:"trailing_newline"`
ReorderKeys *bool `toml:"reorder_keys"`
CRLF *bool `toml:"crlf"`
ArrayTrailingComma *bool `toml:"array_trailing_comma"`
}
TaploFormatting mirrors the [formatting] table of a taplo.toml, limited to the options cfv can represent. A nil field means the option is unset.
Options cfv has no equivalent for (align_entries, align_comments, compact_arrays, compact_inline_tables, array_auto_expand, array_auto_collapse) are ignored, so cfv may still diverge from taplo on those specific behaviors.
type TrailingCommas ¶
type TrailingCommas int
TrailingCommas controls trailing commas on multiline collections.
const ( // TrailingCommasPreserve matches the style already used by the file: // a file with any trailing comma gets them everywhere, a file with // none keeps none. TrailingCommasPreserve TrailingCommas = iota // TrailingCommasAll always adds trailing commas. It is the JSONC default, // matching Prettier's trailingComma: "all" behavior. TrailingCommasAll // TrailingCommasNone always removes trailing commas. TrailingCommasNone )
type XMLWhitespace ¶
type XMLWhitespace int
XMLWhitespace controls XML whitespace sensitivity.
const ( // XMLWhitespaceIgnore treats all whitespace as insignificant. // The formatter inserts newlines and indentation freely. // Default for config files (POM, .csproj, plist). XMLWhitespaceIgnore XMLWhitespace = iota // XMLWhitespacePreserve only modifies existing indentation. // Never inserts or removes newlines. Safe for XHTML/SVG. XMLWhitespacePreserve )
type Yamlfmt ¶
type Yamlfmt struct {
Formatter YamlfmtFormatter `yaml:"formatter"`
}
Yamlfmt is a parsed .yamlfmt config. It only applies to YAML files.
func LoadYamlfmt ¶
LoadYamlfmt returns the yamlfmt configuration found by walking up from startDir, or nil if there is none. .yamlfmt is preferred over .yamlfmt.yaml.
A malformed or unreadable file yields nil rather than an error: it is not the file being formatted, and another tool's config should not fail the run. Apply is a no-op on a nil *Yamlfmt, so callers need no nil check.
type YamlfmtFormatter ¶
type YamlfmtFormatter struct {
Indent *int `yaml:"indent"`
LineEnding *string `yaml:"line_ending"`
MaxLineLength *int `yaml:"max_line_length"`
}
YamlfmtFormatter mirrors the formatter: table of a .yamlfmt config, limited to the options cfv can represent. A nil field means the option is unset.
Options cfv has no equivalent for (include_document_start, retain_line_breaks, pad_line_comments, and other yamlfmt-only knobs) are ignored.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package envfmt provides a Formatter for .env files.
|
Package envfmt provides a Formatter for .env files. |
|
Package hclfmt provides a Formatter for HCL (HashiCorp Configuration Language) files.
|
Package hclfmt provides a Formatter for HCL (HashiCorp Configuration Language) files. |
|
Package inifmt provides a Formatter for INI files.
|
Package inifmt provides a Formatter for INI files. |
|
Package jsoncfmt provides a Formatter for JSONC (JSON with Comments) files.
|
Package jsoncfmt provides a Formatter for JSONC (JSON with Comments) files. |
|
Package jsonfmt provides a Formatter for JSON files.
|
Package jsonfmt provides a Formatter for JSON files. |
|
Package propfmt provides a Formatter for Java .properties files.
|
Package propfmt provides a Formatter for Java .properties files. |
|
Package tomlfmt provides a Formatter for TOML files.
|
Package tomlfmt provides a Formatter for TOML files. |
|
Package xmlfmt provides a Formatter for XML files.
|
Package xmlfmt provides a Formatter for XML files. |
|
Package yamlfmt provides a Formatter for YAML files.
|
Package yamlfmt provides a Formatter for YAML files. |