toml

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2021 License: MIT Imports: 14 Imported by: 22

README

TOML decoder for Go

This package provides a TOML parser/decoder for go. It has been written to offer an interface almost similar to the one of the xml and json packages of the standard library.

On top of that, this package/repository provides commands to manipulate TOML documents.

installation

$ go get github.com/midbel/toml

This package has no external dependencies (except the stdlib).

Consider the following TOML document:

addr    = "0.0.0.0:12345"
version = 3

[[client]]
user   = "user0"
passwd = "temp123;"
roles  = ["user", "admin"]

  [client.access]
  host    = "10.0.1.1:10015"
  request = 10

[[client]]
user   = "user1"
passwd = "temp321;"
roles  = ["guest"]

  [client.access]
  host    = "10.0.1.2:100015"
  request = 50

[[group]]
addr   = "224.0.0.1:31001"
digest = false

[[group]]
addr   = "239.192.0.1:31001"
digest = true

it can then be decoded with:

  type Client struct {
    User string
    Passwd string
    Roles []string
    Access struct {
      Host string
      Req  int `toml:"request"`
    }
  }

  func loadConfig(file string) error {
    r, err := os.Open(file)
    if err != nil {
      return err
      fmt.Fprintln(os.Stderr, err)
      os.Exit(1)
    }
    defer r.Close()
    cfg := struct{
      Address string `toml:"addr"`
      Version int
      Clients []Client `toml:"client"`
      Groups  []struct{
        Address string `toml:"addr"`
        Request int
      } `toml:"group"`
    }{}
    if err := toml.Decode(r, &cfg); err != nil {
      return err
    }
    // use cfg
  }

  // or
  func loadConfig (file string) (map[string]interface{}, error) {
    // without opening the file
    var doc map[string]interface{}
    if err := toml.DecodeFile(file, &doc); err != nil {
      return nil, err
    }
    return doc, nil
  }
Commands
tomlfmt

the command help you to rewrite a toml document with you preferences given in the options.

Some of its options are:

  • removing comments from document
  • align/nest tables and sub tables
  • transform inline table into regular tables
  • change base of all integers
  • change formatting of all floats
  • keep format of values from original document
  • choose indentation type (tab by default, number of space)

By default, the command will always re align the key to all have the same width.

Unless specified, the command will output the "rewritten" document to stdout. Specified the -w to "replace" the source document with its rewritten version.

to use it:

# build
$ cd <path>
$ go build -o bin/tomlfmt .

# execute
$ tomlfmt [options] <document.toml>
tomldump

the command shows you how the parser will understand your document if it is valid.

to use it:

# build
$ cd <path>
$ go build -o bin/tomldump .

# execute
$ tomldump <document.toml>

Documentation

Index

Constants

View Source
const (
	TokEOF rune = -(iota) + 1
	TokNL
	TokIdent
	TokString
	TokBasic
	TokLiteral
	TokBasicMulti
	TokLiteralMulti
	TokInteger
	TokFloat
	TokBool
	TokDate
	TokDatetime
	TokTime
	TokComment
	TokIllegal
	TokBegArray
	TokEndArray
	TokBegInline
	TokEndInline
	TokBegRegularTable
	TokEndRegularTable
	TokBegArrayTable
	TokEndArrayTable
	TokEqual
	TokDot
	TokComma
	TokNewline
)

Variables

View Source
var ErrUndefined = errors.New("undefined")

Functions

func Decode

func Decode(r io.Reader, v interface{}) error

Decode a TOML document from r and writes the decoded values into v.

func DecodeFile

func DecodeFile(file string, v interface{}) error

Decode a TOML document from the given file and writes the decode values into v. See Decode for more information about the decoding process.

func Dump

func Dump(n Node)

Dump the given Node to stdout.

Types

type Array

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

func (*Array) Append

func (a *Array) Append(n Node)

func (*Array) Pos

func (a *Array) Pos() Position

func (*Array) String

func (a *Array) String() string

type FormatRule

type FormatRule func(*Formatter) error

func WithArray

func WithArray(format string) FormatRule

Tell the formatter how to reformat arrays. By default, array with 0 or 1 element will always be written on the same line.

func WithComment

func WithComment(with bool) FormatRule

Tell the formatter to keep comments from the original document when rewritting.

func WithEOL

func WithEOL(format string) FormatRule

Tell the formatter which sequence of character to use to write the end of line.

func WithEmpty

func WithEmpty(with bool) FormatRule

Tell the formatter to keep empty table when rewritting the document.

func WithFloat

func WithFloat(format string, underscore int) FormatRule

Tell the formatter how to format floating point number and where to write an underscore to make it more readable (if needed)

func WithInline

func WithInline(inline bool) FormatRule

Tell the formatter to reformat (array of) inline table(s) to (array of) regular table(s)

func WithNest

func WithNest(with bool) FormatRule

Tell the formatter to indent nested sub table(s). If not set, all tables will be aligned.

func WithNumber

func WithNumber(format string, underscore int) FormatRule

Tell the formatter which base to use to rewrite integer number and where to write an underscore to make it more readable (if needed)

func WithRaw

func WithRaw(with bool) FormatRule

Tell the formatter to keep the format of the values as found in the original document. Using this option disables other options that format values.

func WithTab

func WithTab(tab int) FormatRule

Set the character to indent lines. If tab is let to 0, tab character will be used otherwise one or multiple space(s)

func WithTime

func WithTime(millis int, utc bool) FormatRule

Tell the formatter to use the precision of millisecond to use and if it is needed to convert offset datetime to UTC.

type Formatter

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

Formatter is responsible to rewrite a TOML document according to the settings given by user.

func NewFormatter

func NewFormatter(doc string, rules ...FormatRule) (*Formatter, error)

Create a new Formatter that will rewrite the TOML document doc according to the rules specify.

func (*Formatter) Format

func (f *Formatter) Format(w io.Writer) error

Reformat the document

type Literal

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

func (*Literal) Pos

func (i *Literal) Pos() Position

func (*Literal) String

func (i *Literal) String() string

type Node

type Node interface {
	Pos() Position
	fmt.Stringer
	// contains filtered or unexported methods
}

func Parse

func Parse(r io.Reader) (Node, error)

type Option

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

func (*Option) Pos

func (o *Option) Pos() Position

func (*Option) String

func (o *Option) String() string

type Parser

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

func (*Parser) Parse

func (p *Parser) Parse() (Node, error)

type Position

type Position struct {
	Line   int
	Column int
}

func (Position) IsValid

func (p Position) IsValid() bool

func (Position) IsZero

func (p Position) IsZero() bool

func (Position) Less

func (p Position) Less(other Position) bool

func (Position) String

func (p Position) String() string

type ScanFunc

type ScanFunc func(*Scanner) ScanFunc

type Scanner

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

func NewScanner

func NewScanner(r io.Reader) (*Scanner, error)

func (*Scanner) Scan

func (s *Scanner) Scan() Token

type Setter added in v1.0.1

type Setter interface {
	Set(string) error
}

type Table

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

func (*Table) Pos

func (t *Table) Pos() Position

func (*Table) String

func (t *Table) String() string

type Token

type Token struct {
	Literal string
	Raw     string
	Type    rune
	Pos     Position
}

func (Token) IsIdent

func (t Token) IsIdent() bool

func (Token) IsNumber

func (t Token) IsNumber() bool

func (Token) IsTime

func (t Token) IsTime() bool

func (Token) IsValid

func (t Token) IsValid() bool

func (Token) String

func (t Token) String() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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