pot

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2018 License: MIT Imports: 5 Imported by: 1

README

Package pot (Pieces of Text) provides a lightweight text serialization parser that is intended to be used together with Go's encoding.TextUnmarshaler interface.

Further information is available in the package documentation.

Please see the LICENSE file for details about licensing.

Documentation

Overview

Package pot (Pieces of Text) provides a lightweight text serialization parser that is intended to be used together with Go's encoding.TextUnmarshaler interface.

There is only de-serialization support, it's easy enough to generate properly formated POT directly from a encoding.Textmarshaler.

Format

The POT format is similar to JSON but with some differences required by the application that POT was created for.

There are two compound types, a dictionary and a list and two string types. The dictionary type may hold duplicate keys and the key order is maintained. This makes it more of an itemized list than a dictionary type. The list type simply holds a sequence of other types.

There are no numeric or boolean types, all parsing eventually produces strings. It's up to an applications TextUnmarshaler functions to parse these strings. Strings are separated by space, strings may contain space if quoted or escaped.

The characters that may be used for keys in dictionaries are artificially limited similar to variable names in most programming languages. The characters a-z, A-Z, 0-9 are allowed in any position, the character '-' is allowed in any position but the first. Dictionary keys are delimited by values by ':'.

Syntax Examples

Dictionaries:

{ fruit: orange price: 10.5 }

{ animal:	zebra
  class:	mammal
  weight-range: [ 240kg 370kg ] }

Lists:

[ this is a list with seven strings ]

[ "this is a list with one string" ]

Strings:

this-is-a-string
"this is a string"

Escape Codes

The escape character is '\'. Characters '{', '}', '[', ']', ':', ' ' must be quoted or escaped in strings. Characters '\' and '"' must be escaped in strings. Additionally '\n' produces a new-line, '\r' a carriage return and '\t' a tab.

Usage

Create a new root level parser and call parser.Next() until it returns nil or an error. There is also ParserScanner type that wraps a parser interface to provide a bufio.Scanner like API

Example:

parser := pot.NewParser([]byte("{ fruit: orange price: 10.5 }"))
parse(parser)

func parse(parser pot.Parser) {
	switch parser := parser.(type) {
	case *pot.DictKey:
		fmt.Printf("%s ", parser)
	case *pot.String:
		fmt.Printf("%s ", parser)
	}
	var node pot.Parser
	var err error
	for node, err = parser.Next(); node != nil; node, err = parser.Next() {
		parse(node)
	}
	if err != nil {
		fmt.Printf("error: %s\n", err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrettyPrint

func PrettyPrint(pot []byte) ([]byte, error)

Pretty print POT text buffer. Returns a byte slice or an error on parsing errors.

Example
testPrettyPrint(examplePrint1)
Output:

words
as
root
parser
strings
[ and a list ]
{
    a: dictionary
    that: {
        should:   be
        indented: [ properly { and: { dictionaries: [ in a ] list: that } } [ "should not" ] ]
    }
}
{
    a:          dictionary
    that:       contains
    an:         empty
    dictionary: { }
}
{
}

Types

type Dict

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

Dictionary parser.

func NewDictParser

func NewDictParser(pot []byte) *Dict

Create a new dictionary parser parsing the supplied text.

func (*Dict) Bytes

func (dict *Dict) Bytes() []byte

Get text the parser was initialized with.

func (*Dict) IsEmpty

func (dict *Dict) IsEmpty() bool

Check if the parser has consumed all data.

func (*Dict) Location

func (dict *Dict) Location() Location

Get parser start location in the original text input.

func (*Dict) Name

func (dict *Dict) Name() string

func (*Dict) Next

func (dict *Dict) Next() (parser Parser, err error)

Get the next parser or nil on end of input or an error. Every even call returns a key which is of type DictKey. Every odd call returns a value which may be a Dict, List or String.

type DictKey

type DictKey String

Dictionary key type. A unique "string" type is used to be able to separate keys from string values in type switches.

func (*DictKey) Bytes

func (key *DictKey) Bytes() []byte

Get text the parser was initialized with.

func (*DictKey) Location

func (key *DictKey) Location() Location

Get parser start location in the original text input.

func (*DictKey) Name

func (key *DictKey) Name() string

func (*DictKey) Next

func (key *DictKey) Next() (Parser, error)

Returns nil as keys does not contain sub parsers.

func (*DictKey) String

func (key *DictKey) String() string

Format as a POT dictionary key.

type List

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

List parser.

func NewListParser

func NewListParser(pot []byte) *List

Create a new list parser parsing the supplied text.

func (*List) Bytes

func (list *List) Bytes() []byte

Get text the parser was initialized with.

func (*List) Location

func (list *List) Location() Location

Get parser start location in the original text input.

func (*List) Name

func (list *List) Name() string

func (*List) Next

func (list *List) Next() (Parser, error)

Get the next parser or nil on end of input or an error. The returned parser may be a Dict, List or String.

type Location

type Location struct {
	Line   uint32 // Line number counting from zero.
	Column uint32 // Column number counting from zero.
}

Parser location in text input.

func (*Location) Add

func (location *Location) Add(other *Location) *Location

Add two locations together. An application can use this to adjust location information provided by the parser.

func (Location) Errorf

func (location Location) Errorf(format string, a ...interface{}) *ParseError

Format an error with the parser location in text input.

func (Location) String

func (location Location) String() string

Implements fmt.Stringer

type ParseError

type ParseError struct {
	Identifier string
	Location   Location
	Message    string
}

Parse error containing location information and optional identifier (file name or similar).

func (*ParseError) Error

func (err *ParseError) Error() string

Implements error.

type Parser

type Parser interface {
	// Parser name.
	Name() string

	// Get the next parser, nil or an error.
	Next() (Parser, error)

	// Get text the parser was initialized with.
	Bytes() []byte

	// Get parser start location in the original text input.
	// The location is reset when using NewParser, NewDictParser or NewListParser.
	Location() Location
}

Parser interface implemented by Dict, DictKey, List and String parsers.

func NewParser

func NewParser(pot []byte) Parser

Create a new root level parser parsing the supplied text.

type ParserScanner

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

Wraps a parser to provide a bufio.Scanner like API for easy parsing.

func NewParserScanner

func NewParserScanner(parser Parser) *ParserScanner

Create a new scanner operating on parser.

func (*ParserScanner) Err

func (scanner *ParserScanner) Err() error

Returns the first error that occured while scanning. This should be called after Scan() has returned false to check for errors.

func (*ParserScanner) InjectError

func (scanner *ParserScanner) InjectError(err error)

Inject an error into the scanner. This will cause the scanner to abort parser iteration and the injected error will be returned by the Err method.

func (*ParserScanner) Scan

func (scanner *ParserScanner) Scan() bool

Scan the parser for a sub parser. Returns true if a sub parser was found.

func (*ParserScanner) SubParser

func (scanner *ParserScanner) SubParser() Parser

Returns the previously scanned sub parser.

type Root

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

Root level parser capable of parsing multiple root level objects from the same text input.

func (*Root) Bytes

func (root *Root) Bytes() []byte

Get text the parser was initialized with.

func (*Root) Location

func (root *Root) Location() Location

Get parser start location in the original text input.

func (*Root) Name

func (root *Root) Name() string

func (*Root) Next

func (root *Root) Next() (Parser, error)

Get the next parser or nil on end of input or an error. The returned parser may be a Dict, List or String.

type String

type String parserBuf

String parser.

func (*String) Bytes

func (str *String) Bytes() []byte

Get text the parser was initialized with.

func (*String) Location

func (str *String) Location() Location

Get parser start location in the original text input.

func (*String) Name

func (str *String) Name() string

func (*String) Next

func (str *String) Next() (Parser, error)

Returns nil as strings does not contain sub parsers.

func (*String) String

func (str *String) String() string

Format as a POT string value.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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