configparser

package module
v0.0.0-...-fc81059 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2024 License: MIT Imports: 12 Imported by: 38

README

go-configparser Go

Go implementation of the Python ConfigParser class.

This can parse Python-compatible ConfigParser config files, including support for option interpolation.

Setup

  import (
    "github.com/bigkevmcd/go-configparser"
  )

Parsing configuration files

It's easy to parse a configuration file.

  p, err := configparser.NewConfigParserFromFile("example.cfg")
  if err != nil {
    ...
  }

Methods

The ConfigParser implements most of the Python ConfigParser API

  v, err := p.Get("section", "option")
  err = p.Set("section", "newoption", "value")

  s := p.Sections()

Interpolation

The ConfigParser implements interpolation in the same format as the Python implementation.

Given the configuration

  [DEFAULTS]
  dir: testing

  [testing]
  something: %(dir)s/whatever
  v, err := p.GetInterpolated("testing, something")

It's also possible to override the values to use when interpolating values by providing a Dict to lookup values in.

  d := make(configparser.Dict)
  d["dir"] = "/a/non/existent/path"
  result, err := p.GetInterpolatedWithVars("testing", "something", d)

Will get testing/whatever as the value

Options

The ConfigParser supports almost all custom options available in the Python version.

  • Delimiters - allows to set custom key-value pair delimiters.
  • CommentPrefixes - allows to set custom comment line prefix. If line starts with one of the given Prefixes it will be passed during parsing.
  • InlineCommentPrefixes - allows to set custom inline comment delimiter. This option checks if the line contains any of the given Prefixes and if so, splits the string by the prefix and returns the 0 index of the slice.
  • MultilinePrefixes - allows to set custom multiline values prefixes. This option checks if the line starts with one of the given Prefixes and if so, counts it as a part of the current value.
  • Strict - if set to true, parser will return new wrapped ErrAlreadyExist for duplicates of sections or options in one source.
  • AllowEmptyLines - if set to true allows multiline values to include empty lines as their part. Otherwise the value will be parsed until an empty line or the line which does not start with one of the allowed multiline prefixes.
  • Interpolation - allows to set custom behaviour for values interpolation. Interface was added, which defaults to chainmap.ChainMap instance.
type Interpolator interface {
	Add(...chainmap.Dict)
	Len() int
	Get(string) string
}
  • Converters - allows to set custom values parsers.
type ConvertFunc func(string) (any, error)

ConvertFunc can modify requested value if needed e.g.,

package main

import (
	"fmt"
	"strings"

	"github.com/bigkevmcd/go-configparser"
)

func main() {
	stringConv := func(s string) (any, error) {
		return s + "_updated", nil
	}

	conv := configparser.Converter{
		configparser.String: stringConv,
	}

	p, err := configparser.ParseReaderWithOptions(
		strings.NewReader("[section]\noption=value\n\n"),
		configparser.Converters(conv),
	)
	// handle err

	v, err := p.Get("section", "option")
	// handle err

	fmt.Println(v == "value_updated") // true
}

Those functions triggered inside ConfigParser.Get* methods if presented and wraps the return value.

NOTE: Since ConvertFunc returns any, the caller should guarantee type assertion to the requested type after custom processing!

type Converter map[string]ConvertFunc

Converter is a map type, which supports int (for int64), string, bool, float (for float64) keys.


Default options, which are always preset:

func defaultOptions() *options {
	return &options{
		interpolation:     chainmap.New(),
		defaultSection:    defaultSectionName,
		delimiters:        ":=",
		commentPrefixes:   Prefixes{"#", ";"},
		multilinePrefixes: Prefixes{"\t", " "},
		converters: Converter{
			StringConv: defaultGet,
			IntConv:    defaultGetInt64,
			FloatConv:  defaultGetFloat64,
			BoolConv:   defaultGetBool,
		},
	}
}

Documentation

Index

Constants

View Source
const (
	StringConv = iota
	IntConv
	FloatConv
	BoolConv
)

Predefined types for Converter.

Variables

This section is empty.

Functions

func AllowEmptyLines

func AllowEmptyLines(o *options)

AllowEmptyLines allows empty lines in multiline values.

func AllowNoValue

func AllowNoValue(o *options)

AllowNoValue allows option with no value to be saved as empty line.

func CommentPrefixes

func CommentPrefixes(pr Prefixes) optFunc

CommentPrefixes sets a slice of comment prefixes. Lines of configuration file which starts with the first match in this slice will be skipped.

func Converters

func Converters(conv Converter) optFunc

Converters sets custom convertion functions. Will apply to return value of the Get* methods instead of the default convertion.

NOTE: the caller should guarantee type assetion to the requested type after custom processing or the method will panic.

func DefaultSection

func DefaultSection(n string) optFunc

DefaultSection sets the name of the default section.

func Delimiters

func Delimiters(d string) optFunc

Delimiters sets a string of delimiters for option-value pairs.

func InlineCommentPrefixes

func InlineCommentPrefixes(pr Prefixes) optFunc

InlineCommentPrefixes sets a slice of inline comment delimiters. When parsing a value, it will be split with the first match in this slice.

func Interpolation

func Interpolation(i Interpolator) optFunc

Interpolation sets custom interpolator.

func MultilinePrefixes

func MultilinePrefixes(pr Prefixes) optFunc

MultilinePrefixes sets a slice of prefixes, which will define multiline value.

func Strict

func Strict(o *options)

Strict prohibits the duplicates of options and values.

Types

type Config

type Config map[string]*Section

Config represents a Python style configuration file.

type ConfigParser

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

ConfigParser ties together a Config and default values for use in interpolated configuration values.

func New

func New() *ConfigParser

New creates a new ConfigParser.

func NewConfigParserFromFile

func NewConfigParserFromFile(filename string) (*ConfigParser, error)

NewConfigParserFromFile creates a new ConfigParser struct populated from the supplied filename.

func NewWithDefaults

func NewWithDefaults(defaults Dict) (*ConfigParser, error)

NewWithDefaults allows creation of a new ConfigParser with a pre-existing Dict.

func NewWithOptions

func NewWithOptions(opts ...optFunc) *ConfigParser

NewWithOptions creates a new ConfigParser with options.

func Parse

func Parse(filename string) (*ConfigParser, error)

Parse takes a filename and parses it into a ConfigParser value.

func ParseReader

func ParseReader(in io.Reader) (*ConfigParser, error)

ParseReader parses a ConfigParser from the provided input.

func ParseReaderWithOptions

func ParseReaderWithOptions(in io.Reader, opts ...optFunc) (*ConfigParser, error)

ParseReaderWithOptions parses a ConfigParser from the provided input with given options.

func ParseWithOptions

func ParseWithOptions(filename string, opts ...optFunc) (*ConfigParser, error)

ParseWithOptions takes a filename and parses it into a ConfigParser value with given options.

func (*ConfigParser) AddSection

func (p *ConfigParser) AddSection(section string) error

AddSection creates a new section in the configuration.

Returns an error if a section by the specified name already exists. Returns an error if the specified name DEFAULT or any of its case-insensitive variants. Returns nil if no error and the section is created

func (*ConfigParser) Defaults

func (p *ConfigParser) Defaults() Dict

Defaults returns the items in the map used for default values.

func (*ConfigParser) Get

func (p *ConfigParser) Get(section, option string) (string, error)

Get returns string value for the named option.

Returns an error if a section does not exist. Returns an error if the option does not exist either in the section or in the defaults.

func (*ConfigParser) GetBool

func (p *ConfigParser) GetBool(section, option string) (bool, error)

GetBool returns bool representation of the named option.

Returns an error if a section does not exist. Returns an error if the option does not exist either in the section or in the defaults.

func (*ConfigParser) GetFloat64

func (p *ConfigParser) GetFloat64(section, option string) (float64, error)

GetFloat64 returns float64 representation of the named option.

Returns an error if a section does not exist. Returns an error if the option does not exist either in the section or in the defaults.

func (*ConfigParser) GetInt64

func (p *ConfigParser) GetInt64(section, option string) (int64, error)

GetInt64 returns int64 representation of the named option.

Returns an error if a section does not exist. Returns an error if the option does not exist either in the section or in the defaults.

func (*ConfigParser) GetInterpolated

func (p *ConfigParser) GetInterpolated(section, option string) (string, error)

GetInterpolated returns a string value for the named option.

All % interpolations are expanded in the return values, based on the defaults passed into the constructor and the DEFAULT section.

func (*ConfigParser) GetInterpolatedWithVars

func (p *ConfigParser) GetInterpolatedWithVars(section, option string, v Dict) (string, error)

GetInterpolatedWithVars returns a string value for the named option.

All % interpolations are expanded in the return values, based on the defaults passed into the constructor and the DEFAULT section. Additional substitutions may be provided using the 'v' argument, which must be a Dict whose contents contents override any pre-existing defaults.

func (*ConfigParser) HasOption

func (p *ConfigParser) HasOption(section, option string) (bool, error)

HasOption checks if section contains option.

func (*ConfigParser) HasSection

func (p *ConfigParser) HasSection(section string) bool

HasSection returns true if the named section is present in the configuration.

The DEFAULT section is not acknowledged.

func (*ConfigParser) Items

func (p *ConfigParser) Items(section string) (Dict, error)

Items returns a copy of the section Dict not including the Defaults.

NOTE: This is different from the Python version which returns a list of tuples.

func (*ConfigParser) ItemsWithDefaults

func (p *ConfigParser) ItemsWithDefaults(section string) (Dict, error)

ItemsWithDefaults returns a copy of the named section Dict including any values from the Defaults.

NOTE: This is different from the Python version which returns a list of tuples

func (*ConfigParser) ItemsWithDefaultsInterpolated

func (p *ConfigParser) ItemsWithDefaultsInterpolated(section string) (Dict, error)

ItemsWithDefaultsInterpolated returns a copy of the dict for the section.

func (*ConfigParser) Options

func (p *ConfigParser) Options(section string) ([]string, error)

Options returns a list of option mames for the given section name.

Returns an error if the section does not exist.

func (*ConfigParser) ParseReader

func (p *ConfigParser) ParseReader(in io.Reader) error

ParseReader parses data into ConfigParser from provided reader.

func (*ConfigParser) RemoveOption

func (p *ConfigParser) RemoveOption(section, option string) error

RemoveOption removes option from the section.

func (*ConfigParser) RemoveSection

func (p *ConfigParser) RemoveSection(section string) error

RemoveSection removes given section from the ConfigParser.

func (*ConfigParser) SaveWithDelimiter

func (p *ConfigParser) SaveWithDelimiter(filename, delimiter string) error

SaveWithDelimiter writes the current state of the ConfigParser to the named file with the specified delimiter.

func (*ConfigParser) Sections

func (p *ConfigParser) Sections() []string

Sections returns a list of section names, excluding [DEFAULT].

func (*ConfigParser) Set

func (p *ConfigParser) Set(section, option, value string) error

Set puts the given option into the named section.

Returns an error if the section does not exist.

type ConvertFunc

type ConvertFunc func(string) (any, error)

ConvertFunc is a custom datatype converter.

type Converter

type Converter map[int]ConvertFunc

Converter contains custom convert functions for available types. The caller should guarantee type assertion to the requested type after custom processing!

type Dict

type Dict map[string]string

Dict is a simple string->string map.

func (Dict) Keys

func (d Dict) Keys() []string

Keys returns a sorted slice of keys

type Interpolator

type Interpolator interface {
	Add(...chainmap.Dict)
	Len() int
	Get(string) string
}

Interpolator defines interpolation instance. For more details, check chainmap.ChainMap realisation.

type Prefixes

type Prefixes []string

Prefixes stores available prefixes for comments.

func (Prefixes) HasPrefix

func (pr Prefixes) HasPrefix(str string) bool

HasPrefix checks if str starts with any of the prefixes.

func (Prefixes) Split

func (pr Prefixes) Split(str string) string

Split splits str with the first prefix found. Returns original string if no matches.

type Section

type Section struct {
	Name string
	// contains filtered or unexported fields
}

Section represent each section of the configuration file.

func (*Section) Add

func (s *Section) Add(key, value string) error

Add adds new key-value pair to the section.

func (*Section) Get

func (s *Section) Get(key string) (string, error)

Get returns value of an option with the given key.

Returns an error if the option does not exist either in the section or in the defaults.

func (*Section) Items

func (s *Section) Items() Dict

Items returns a Dict with the key-value pairs.

func (*Section) Options

func (s *Section) Options() []string

Options returns a slice of option names.

func (*Section) Remove

func (s *Section) Remove(key string) error

Remove removes option with the given name from the section.

Returns an error if the option does not exist either in the section or in the defaults.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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