Help us shape the future of Go! Take the 2026 Go Developer Survey

nestext

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2021 License: Apache-2.0 Imports: 9 Imported by: 4

README

nestext

Processing NestedText (NestedText: A Human Friendly Data Format) in Go.

A description of NestedText by the authors:

NestedText is a file format for holding structured data that is to be entered, edited, or viewed by people. It allows data to be organized into a nested collection of dictionaries, lists, and strings without the need for quoting or escaping. In this way it is similar to JSON, YAML and TOML, but without the complexity and risk of YAML and without the syntactic clutter of JSON and TOML. NestedText is both simple and natural.

To get a feel for the NestedText format, take a look at the following example (shortended version from the NestedText site):

# Contact information for our officers

president:
    name: Katheryn McDaniel
    address:
        > 138 Almond Street
        > Topeka, Kansas 20697
    phone:
        cell: 1-210-555-5297
        home: 1-210-555-8470
        # Katheryn prefers that we always call her on her cell phone.
    email: KateMcD@aol.com
    additional roles:
        - board member

vice president:
    name: Margaret Hodge
    …

NestedText does not interpret any data types (unlike YAML), nor does it impose a schema. All of that has to be done by the application.

Decoding

Parse(…) is the top-level API:

input := `
# Example for a NestedText dict
a: Hello
b: World
`

result, err := nestext.Parse(strings.NewReader(input))
if err != nil {
    log.Fatal("parsing failed")
}
fmt.Printf("result = %#v\n", result)

will yield:

result = map[string]interface {}{"a":"Hello", "b":"World"}

Clients may use tools like mitchellh/mapstructure or knadh/koanf for further processing.

Encoding

Sub-package ntenc provides an encoder-API:

var config = map[string]interface{}{
    "timeout": 20,
    "ports":   []interface{}{6483, 8020, 9332},
}

n, err := ntenc.Encode(config, os.Stdout)
fmt.Println("------------------------------")
fmt.Printf("%d bytes written, error: %v", n, err != nil)

will yield:

ports:
  - 6483
  - 8020
  - 9332
timeout: 20
------------------------------
46 bytes written, error: false

Status

Tested with NestedText test suite for Version 3.1.0.

Documentation

Overview

Package nestext provides tools for processing NestedText, a human friendly data format. For more information on NestedText see https://nestedtext.org .

To get a feel for the NestedText format, take a look at the following example (shortended version from the NestedText site):

# Contact information for our officers

president:
   name: Katheryn McDaniel
   address:
      > 138 Almond Street
      > Topeka, Kansas 20697
   phone:
      cell: 1-210-555-5297
      home: 1-210-555-8470
         # Katheryn prefers that we always call her on her cell phone.
   email: KateMcD@aol.com
   additional roles:
      - board member

vice president:
   name: Margaret Hodge
   …

NestedText is somewhat reminiscent of YAML, without the complexity of the latter and without the sometimes confusing details of interpretation. NestedText does not interpret any data types (unlike YAML), nor does it impose a schema. All of that has to be done by the application.

Parsing NestedText

Parse is the top-level API:

input := `
# Example for a NestedText dict
a: Hello
b: World
`

result, err := Parse(strings.NewReader(input))
if err != nil {
    log.Fatal("parsing failed")
}
fmt.Printf("result = %#v\n", result)

will yield:

result = map[string]interface {}{"a":"Hello", "b":"World"}

Clients may use tools like `mitchellh/mapstructure` or `knadh/koanf` for further processing.

Encoding to NestedText

Sub-package `ntenc` provides a NestedText encoder.

Index

Examples

Constants

View Source
const (
	NoError       = 0
	ErrCodeUsage  = 1   // errorneous API call
	ErrCodeIO     = 10  // error will wrap an underlying I/O error
	ErrCodeSchema = 100 // schema violation; error may wrap an underlying error

	// all errors rooted in format violations have code >= ErrCodeFormat
	ErrCodeFormat               = 200 + iota // NestedText format error
	ErrCodeFormatNoInput                     // NestedText format error: no input present
	ErrCodeFormatToplevelIndent              // NestedText format error: top-level item was indented
	ErrCodeFormatIllegalTag                  // NestedText format error: tag not recognized
)

We use a custom error type which contains a numeric error code.

Variables

This section is empty.

Functions

func Parse

func Parse(r io.Reader, opts ...Option) (interface{}, error)

Parse reads a NestedText input source and outputs a resulting hierarchy of values. Values are stored as strings, []interface{} or map[string]interface{} respectively. The concrete resulting top-level type depends on the top-level NestedText input type.

If a non-nil error is returned, it will be of type NestedTextError.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/npillmayer/nestext"
)

func main() {
	address := `
name: Katheryn McDaniel
address:
  > 138 Almond Street
  > Topeka, Kansas 20697
phone:
  cell: 1-210-555-5297
  home: 1-210-555-8470
    # Katheryn prefers that we always call her on her cell phone.
email: KateMcD@aol.com
additional roles:
  - board member
`

	// parse address input and print out e-mail item
	result, err := nestext.Parse(strings.NewReader(address))
	if err != nil {
		panic(err)
	}
	m := result.(map[string]interface{})
	fmt.Printf("Katheryn's e-mail: %v\n", m["email"])
}
Output:
Katheryn's e-mail: KateMcD@aol.com

Types

type NestedTextError

type NestedTextError struct {
	Code         int // error code
	Line, Column int // error position
	// contains filtered or unexported fields
}

NestedTextError is a custom error type for working with NestedText instances.

func MakeNestedTextError

func MakeNestedTextError(code int, errMsg string) NestedTextError

MakeNestedTextError creates a NestedTextError with a given error code and message.

func WrapError

func WrapError(code int, errMsg string, err error) NestedTextError

WrapError wraps an error into a NestedTextError

func (NestedTextError) Error

func (e NestedTextError) Error() string

Error produces an error message from a NestedText error.

func (NestedTextError) Unwrap

func (e NestedTextError) Unwrap() error

Unwrap returns an optionally present underlying error condition, e.g., an I/O-Error.

type Option

type Option _Option

Option is a type to influence the behaviour of the parsing process. Multiple options may be passed to `Parse(…)`.

func KeepLegacyBidi

func KeepLegacyBidi(keep bool) Option

KeepLegacyBidi requests the parser to keep Unicode LTR and RTL markers.

Attention: This option is not yet functional!

func TopLevel

func TopLevel(top string) Option

TopLevel determines the top-level type of the return value from parsing. Possible values are "list" and "dict". "list" will force the result to be an []interface{} (of possibly one item), while "dict" will force the result to be of type map[string]interface.

For "dict", if the result is not a dict naturally, it will be wrapped in a map with a single key = "nestedtext". However, if the dict-option is given with a suffix (separated by '.'), the suffix string will be used as the top-level key. In this case, even naturally parsed dicts will be wrapped into a map with a single key (= the suffix to "dict.").

Use as:

nestext.Parse(reader, nestext.TopLevel("dict.config"))

This will result in a return-value of map[string]interface{} with a single entry map["config"] = …

The default is for the parsing-result to be of the natural type corresponding to the top-level item of the input source. Option-strings other than "list" and "dict"/"dict.<suffix>" will result in an error returned by Parse(…).

Directories

Path Synopsis
Package ntenc implements encoding of configuration data into NestedText format.
Package ntenc implements encoding of configuration data into NestedText format.

Jump to

Keyboard shortcuts

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