ini

package module
v0.0.2 Latest Latest
Warning

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

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

README

ini

GoDoc Go Report Card

This repository provides Go package that implements a basic INI file parser. The interface is intentionally and aggressively minimalistic, providing only the high-level structure of the input in the form of comments, section headings, and key-value pairs.

Documentation

Overview

Package ini implements a basic INI file parser.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(r io.Reader, h Handler) error

Parse scans the INI data from r and invokes the callbacks on h with the results. If h reports an error, parsing stops and that error is returned to the caller of Parse. Errors in syntax have concrete type *SyntaxError, and may be asserted to that type to recover location and name details.

The INI syntax supported by Parse ignores blank lines and removes leading and trailing whitespace from keys, section names, and values. Whole-line comments are prefixed with a semicolon:

; this is a comment

Section headers are enclosed in square brackets, and permit horizontal whitespace:

[section header]

Key-value pairs allow whitespace where sensible:

key1=first value
key2 = second value

Keys and section names may contain whitespace, which is normalized. Each run of whitespace inside the key or section name is replaced by one Unicode space (32) character. Whitespace is not normalized within values:

; "a long key" has value "value   village"
a    long     key = value   village

Keys may have multiple values, indicated by indentation:

; letter has values alpha, bravo, charlie
letter = alpha
    bravo
    charlie

; number has values 1, 2, 3
number =
    1
    2
    3

A bare key that is not indented is assigned an empty value, so the following are equivalent:

foo
foo=
foo =

Note that these rules imply you cannot have a multi-valued key with an empty string as one of its values.

Parse does not check for duplication among section headers or keys; the caller is responsible for any validation that is required. Line continuations with trailing backslashes are not currently supported. String quotation is not currently supported.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/creachadair/ini"
)

func main() {
	const iniFile = `
;
; This is an example INI file.
;
   file description = A list of users

[user 1]
name=Alice Jones
role=sender

[user 2]

  name = Bob Smith
  role = receiver

[ user 3 ]
name   = Eve
role   = eavesdropper
morals = 

; note multiple values
tools = deception
  deceit
  man in the middle attacks

; EOF
`
	var commentLines []int // record where comments occurred

	if err := ini.Parse(strings.NewReader(iniFile), ini.Handler{
		// Comment is called for each comment in the file.  If nil, comments will
		// be discarded.
		Comment: func(loc ini.Location, text string) error {
			// loc provides the location of the element in the file.
			commentLines = append(commentLines, loc.Line)
			return nil
		},

		// Section is called for each section header. If nil, section headers
		// will not be reported but will still be tracked in Location.
		Section: func(loc ini.Location, name string) error {
			fmt.Printf("New section: %s (was %q)\n", name, loc.Section)
			return nil
		},

		// KeyValue is called for each key-value pair. A key will have at least
		// one value (possibly ""). A Location includes the label of the most
		// recent section.
		KeyValue: func(loc ini.Location, key string, values []string) error {
			for i, val := range values {
				fmt.Printf("%-2d %q %s=%s\n", loc.Line+i, loc.Section, key, val)
			}
			return nil
		},
	}); err != nil {
		log.Fatalf("Parse: %v", err)
	}
	fmt.Println("\nComment lines:", commentLines)

}
Output:
5  "" file description=A list of users
New section: user 1 (was "")
8  "user 1" name=Alice Jones
9  "user 1" role=sender
New section: user 2 (was "user 1")
13 "user 2" name=Bob Smith
14 "user 2" role=receiver
New section: user 3 (was "user 2")
17 "user 3" name=Eve
18 "user 3" role=eavesdropper
19 "user 3" morals=
22 "user 3" tools=deception
23 "user 3" tools=deceit
24 "user 3" tools=man in the middle attacks

Comment lines: [2 3 4 21 26]

Types

type Handler

type Handler struct {
	// Comment delivers the contents of a comment. The comment text includes the
	// leading delimiter, but leading and trailing whitespace are removed.
	Comment func(loc Location, text string) error

	// Section delivers a section header. Whitespace in name is normalized.  The
	// loc.Section field contains the name of the most recent section label
	// prior to this one.
	Section func(loc Location, name string) error

	// KeyValue delivers the values for a single key. Whitespace in the key name
	// is normalized. The values slice will not be empty, but will contain ""
	// for a key with only one empty value.
	KeyValue func(loc Location, key string, values []string) error
}

Handler is a structure containing options and callbacks used by the parser to process INI contents. If a callback reports an error, parsing stops and that error is returned to the caller of Parse. Any callback that is nil will be skipped without error.

type Location

type Location struct {
	Line    int    // line number, 1-based
	Section string // most recent section name (or "")
}

A Location describes the physical location of an input element.

type SyntaxError

type SyntaxError struct {
	Location        // where the error occurred
	Desc     string // general description of the error
	Key      string // if applicable, the key or name affected
}

SyntaxError is the concrete type of error values denoting syntax problems with INI input.

func (*SyntaxError) Error

func (s *SyntaxError) Error() string

Jump to

Keyboard shortcuts

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