configparser

package module
v0.0.0-...-2593eb8 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2021 License: BSD-3-Clause Imports: 10 Imported by: 1

README

Configparser

This is a fork of https://github.com/alyu/configparser

The original libray focuses on parsing ini files into memory, and re-serializing to disk while preserving comments and whitespace. To achieve that, the in-memory has some quirks which most people probably don't want.

This fork breaks the writing config files functionality in order to get a more sensible config reading experience. That said, there are still plenty of quirks, making this only useful for a handful of carefully picked use cases.

You should probably not use this library

Known quirks and problems (mainly inherited from upstream):

  • Since values are unquoted strings, it is effectively impossibly to truly distinguish comments from values. We simply split keys from values at the first '=' and consider any "#" to mark a comment. Any other chars are allowed.
  • parsed values preserve file comments (but there's now an api to strip them. see below)
  • empty section names are legal.
  • section markers like [[[foo[][] are legal, though hard to reason about. (this one results in a section named foo[)
  • sections without any options are legal.
  • Any characters are allowed in section names
  • epmty lines result in options with empty names
  • Lines with nothing but comments result in "options" with the whole line (including comment delimiter) as name.

Most of these issues can, and should, be worked around in the caller by doing strict validation checking, based on your use case.

Main differences with upstream

  • parsed section names no longer include file comments
  • global section is kept separate so you can distinguish it from a section named "global".
  • stricter validation and parsing of section headers
  • add method to retrieve values without comments (ValueOfWithoutComments() )
  • add lots of unit tests (see extra_test.go)
  • only "=" is allowed as key-value delimiter (not ":" because our values may contain it)
  • only "#" is allowed to start comments (not ";" because our values may contain it)

Documentation

Overview

Package configparser provides a simple parser for reading/writing configuration (INI) files.

Supports reading/writing the INI file format in addition to:

  • Reading/writing duplicate section names (ex: MySQL NDB engine's config.ini)
  • Options without values (ex: can be used to group a set of hostnames)
  • Options without a named section (ex: a simple option=value file)
  • Find sections with regexp pattern matching on section names, ex: dc1.east.webservers where regex is '.webservers'
  • # as comment delimiter
  • = as value delimiter
Example

Read and modify a configuration file

package main

import (
	"fmt"
	"github.com/grafana/configparser"
	"log"
)

func main() {
	config, err := configparser.ReadFile("/etc/config.ini")
	if err != nil {
		log.Fatal(err)
	}
	// Print the full configuration
	fmt.Println(config)

	// get a section
	section, err := config.Section("MYSQLD DEFAULT")
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("TotalSendBufferMemory=%s\n", section.ValueOf("TotalSendBufferMemory"))

		// set new value
		var oldValue = section.SetValueFor("TotalSendBufferMemory", "256M")
		fmt.Printf("TotalSendBufferMemory=%s, old value=%s\n", section.ValueOf("TotalSendBufferMemory"), oldValue)

		// delete option
		oldValue = section.Delete("DefaultOperationRedoProblemAction")
		fmt.Println("Deleted DefaultOperationRedoProblemAction: " + oldValue)

		// add new options
		section.Add("innodb_buffer_pool_size", "64G")
		section.Add("innodb_buffer_pool_instances", "8")
	}

	// add a new section and options
	section = config.NewSection("NDBD MGM")
	section.Add("NodeId", "2")
	section.Add("HostName", "10.10.10.10")
	section.Add("PortNumber", "1186")
	section.Add("ArbitrationRank", "1")

	// find all sections ending with .webservers
	sections, err := config.Find(".webservers$")
	if err != nil {
		log.Fatal(err)
	}
	for _, section := range sections {
		fmt.Print(section)
	}
	// or
	config.PrintSection("dc1.webservers")

	sections, err = config.Delete("NDB_MGMD DEFAULT")
	if err != nil {
		log.Fatal(err)
	}
	// deleted sections
	for _, section := range sections {
		fmt.Print(section)
	}

	options := section.Options()
	fmt.Println(options["HostName"])

	// save the new config. the original will be renamed to /etc/config.ini.bak
	err = configparser.Save(config, "/etc/config.ini")
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var Delimiter = "="

Delimiter is the delimiter to be used between section key and values when rendering an option string

Functions

func Save

func Save(c *Configuration, filePath string) (err error)

Save the Configuration to file. Creates a backup (.bak) if file already exists.

Types

type Configuration

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

Configuration represents a configuration file with its sections and options.

func NewConfiguration

func NewConfiguration() *Configuration

NewConfiguration returns a new Configuration instance with an empty file path.

func Read

func Read(fd io.Reader, filePath string) (*Configuration, error)

Read reads the given reader into a new Configuration filePath is set for any future persistency but is not used for reading

func ReadFile

func ReadFile(filePath string) (*Configuration, error)

ReadFile parses a specified configuration file and returns a Configuration instance.

func (*Configuration) AllSections

func (c *Configuration) AllSections() (*Section, []*Section, error)

AllSections returns the global, as well as a slice of all non-global sections.

func (*Configuration) Delete

func (c *Configuration) Delete(regex string) (sections []*Section, err error)

Delete deletes the specified non-global sections matched by a regex name and returns the deleted sections.

func (*Configuration) FilePath

func (c *Configuration) FilePath() string

FilePath returns the configuration file path.

func (*Configuration) Find

func (c *Configuration) Find(regex string) ([]*Section, error)

Find returns a slice of non-global Sections matching the regexp against the section name.

func (*Configuration) GlobalSection

func (c *Configuration) GlobalSection() *Section

GlobalSection returns the global section

func (*Configuration) NewSection

func (c *Configuration) NewSection(fqn string) *Section

NewSection creates and adds a new non-global Section with the specified name.

func (*Configuration) PrintSection

func (c *Configuration) PrintSection(fqn string) error

PrintSection prints a text representation of all non-global sections matching the fully qualified section name.

func (*Configuration) Section

func (c *Configuration) Section(fqn string) (*Section, error)

Section returns the first non-global section matching the fully qualified section name.

func (*Configuration) Sections

func (c *Configuration) Sections(fqn string) ([]*Section, error)

Sections returns a slice of non-global Sections matching the fully qualified section name.

func (*Configuration) SetFilePath

func (c *Configuration) SetFilePath(filePath string)

SetFilePath sets the Configuration file path.

func (*Configuration) String

func (c *Configuration) String() string

String returns the text representation of a parsed configuration file.

func (*Configuration) StringValue

func (c *Configuration) StringValue(section, option string) (value string, err error)

StringValue returns the string value for the specified non-global section and option.

func (*Configuration) Write

func (c *Configuration) Write(fd io.Writer) error

type Section

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

A Section in a configuration.

func (*Section) Add

func (s *Section) Add(option string, value string) (oldValue string)

Add adds a new option to the section. Adding an existing option will overwrite the old one. The old value is returned

func (*Section) Delete

func (s *Section) Delete(option string) (value string)

Delete removes the specified option from the section and returns the deleted option's value.

func (*Section) Exists

func (s *Section) Exists(option string) (ok bool)

Exists returns true if the option exists

func (*Section) Name

func (s *Section) Name() string

Name returns the name of the section

func (*Section) OptionNames

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

OptionNames returns a slice of option names in the same order as they were parsed.

func (*Section) Options

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

Options returns a map of options for the section.

func (*Section) SetValueFor

func (s *Section) SetValueFor(option string, value string) string

SetValueFor sets the value for the specified option and returns the old value.

func (*Section) String

func (s *Section) String() string

String returns the text representation of a section with its options.

func (*Section) ValueOf

func (s *Section) ValueOf(option string) string

ValueOf returns the value of specified option.

func (*Section) ValueOfWithoutComments

func (s *Section) ValueOfWithoutComments(option string) string

ValueOf returns the value of specified option without any trailing comments (denoted by ' #')

Jump to

Keyboard shortcuts

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