ini

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2021 License: BSD-3-Clause Imports: 14 Imported by: 7

Documentation

Overview

Package ini implement reading and writing INI text format as defined by Git configuration file syntax.

Features

* Reading and writing on the same file should not change the content of file (including comment).

* Template friendly, through Val(), Vals(), and Subs().

Unsupported features

Git "include" and "includeIf" directives.

In Git specification, an empty variable is equal to boolean true. This cause inconsistency between empty string and boolean true.

Syntax

The '#' and ';' characters begin comments to the end of line.

Blank lines are ignored.

Section

A section begins with the name of the section in square brackets.

A section continues until the next section begins.

Section name are case-insensitive.

Variable name must start with an alphabetic character, no whitespace before name or after '['.

Section name only allow alphanumeric characters, `-` and `.`.

Section can be further divided into subsections.

Section headers cannot span multiple lines.

You can have `[section]` if you have `[section "subsection"]`, but you don’t need to.

All the other lines (and the remainder of the line after the section header) are recognized as setting variables, in the form `name = value`.

Subsection

To begin a subsection put its name in double quotes, separated by space from the section name, in the section header, for example

[section "subsection"]

Subsection name are case sensitive and can contain any characters except newline and the null byte.

Subsection name can include doublequote `"` and backslash by escaping them as `\"` and `\\`, respectively.

Other backslashes preceding other characters are dropped when reading subsection name; for example, `\t` is read as `t` and `\0` is read as `0`.

Variable

Variable name must start with an alphabetic character.

Variable must belong to some section, which means that there must be a section header before the first setting of a variable.

Variable name are case-insensitive.

Variable name allow only alphanumeric characters and `-`. This ini library add extension to allow dot ('.') and underscore ('_') characters on variable name.

Value

Value can be empty or not set. (EXT) Variable name without value is a short-hand to set the value to the empty string value, for example

[section]
	thisisempty # equal to thisisempty=

Internal whitespaces within the value are retained verbatim. Leading and trailing whitespaces on value without double quote will be discarded.

key = multiple strings     # equal to "multiple strings"
key = " multiple strings " # equal to " multiple strings "

Value can be continued to the next line by ending it with a backslash '\' character, the backquote and the end-of-line are stripped.

key = multiple \           # equal to "multiple string"
strings

Value can contain inline comment, for example

key = value # this is inline comment

Comment characters, '#' and ';', inside double quoted value will be read as content of value, not as comment,

key = "value # with hash"

Inside value enclosed double quotes, the following escape sequences are recognized: `\"` for doublequote, `\\` for backslash, `\n` for newline character (NL), `\t` for horizontal tabulation (HT, TAB) and `\b` for backspace (BS).

Other char escape sequences (including octal escape sequences) are invalid.

Marshaling

The container to be passed when marshaling must be struct type. Each exported field in the struct with "ini" tags will be marshaled based on the section, subsection, and key in the tag.

If the field type is slice of primitive, for example "[]int", it will be marshaled into multiple key with the same name.

If the field type is struct, it will marshaled as new section and/or subsection based on tag on the struct field

If the field type is slice of struct, it will marshaled as multiple section-subsection with the same tags.

Map type is supported as long as the key is string, otherwise it will be ignored. The map key will be marshaled as key.

Other standard type that supported is time.Time, which will be rendered with the time format defined in "layout" tag.

Example,

type U struct {
	Int `ini:"::int"`
}

type T struct {
	String      string         `ini:"single::string"
	Time        time.Time      `ini:"single::time" layout:"2006-01-02"`
	SliceString []string       `ini:"slice::string"
	Struct      U              `ini:"single:struct"
	SliceStruct []U            `ini:"slice:struct"
	Map         map[string]int `ini:"map::"
}

will be marshaled into

[single]
string = <value of T.String>
time = <value of T.Time with layout "YYYY-MM-DD">

[slice]
string = <value of T.SliceStruct[0]>
...
string = <value of T.SliceStruct[n]>

[single "struct"]
int = <value of T.U.Int>

[slice "struct"]
int = <value of T.SliceStruct[0].Int

[slice "struct"]
int = <value of T.SliceStruct[n].Int

[map]
<T.Map.Key[0]> = <T.Map.Value[0]>
...
<T.Map.Key[n]> = <T.Map.Value[n]>

Unmarshaling

The syntax and rules for unmarshaling is equal to the marshaling.

References

https://git-scm.com/docs/git-config#_configuration_file

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsValueBoolTrue

func IsValueBoolTrue(v string) bool

IsValueBoolTrue will return true if variable contains boolean value for true. The following conditions is boolean true for value: "" (empty string), "true", "yes", "ya", "t", "1" (all of string is case insensitive).

func Marshal added in v0.10.1

func Marshal(v interface{}) (b []byte, err error)

Marshal encode the struct of v into stream of ini formatted string.

To encode a struct, each exported fields must have tagged with "ini" key; untagged field will not be exported.

Each exported field in the struct must have at least one tag: a section where the field's name (the key) and field's value will be saved. An optional subsection can be defined by adding a string separated by colon ":" after section's name. An optional key's name also can be defined by adding string after subsection name. If key's name is not defined it would be default to lowercase string of field's name.

An array or slice will be encoded as multiple keys.

One exception to above rule is map type. A map's key will override the key defined in tag.

Example
ptrString := "b"
ptrInt := int(2)
ptrTime := time.Date(2021, 2, 28, 18, 44, 1, 0, time.UTC)

type U struct {
	String string `ini:"::string"`
	Int    int    `ini:"::int"`
}

t := struct {
	String      string            `ini:"section::string"`
	Int         int               `ini:"section::int"`
	Bool        bool              `ini:"section::bool"`
	Duration    time.Duration     `ini:"section::duration"`
	Time        time.Time         `ini:"section::time" layout:"2006-01-02 15:04:05"`
	Struct      U                 `ini:"section:struct"`
	SliceString []string          `ini:"section:slice:string"`
	SliceInt    []int             `ini:"section:slice:int"`
	SliceUint   []uint            `ini:"section:slice:uint"`
	SliceBool   []bool            `ini:"section:slice:bool"`
	SliceStruct []U               `ini:"slice:OfStruct"`
	MapString   map[string]string `ini:"map:string"`
	MapInt      map[string]int    `ini:"map:int"`
	PtrString   *string           `ini:"section:pointer:string"`
	PtrInt      *int              `ini:"section:pointer:int"`
	PtrTime     *time.Time        `ini:"section:pointer:time" layout:"2006-01-02 15:04:05"`
	PtrStruct   *U                `ini:"pointer:struct"`
}{
	String:   "a",
	Int:      1,
	Bool:     true,
	Duration: time.Minute,
	Time:     time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC),
	Struct: U{
		String: "b",
		Int:    2,
	},
	SliceString: []string{"c", "d"},
	SliceInt:    []int{2, 3},
	SliceUint:   []uint{4, 5},
	SliceBool:   []bool{true, false},
	SliceStruct: []U{{
		String: "U.string 1",
		Int:    1,
	}, {
		String: "U.string 2",
		Int:    2,
	}},
	MapString: map[string]string{
		"k": "v",
	},
	MapInt: map[string]int{
		"keyInt": 6,
	},
	PtrString: &ptrString,
	PtrInt:    &ptrInt,
	PtrTime:   &ptrTime,
	PtrStruct: &U{
		String: "PtrStruct.String",
		Int:    3,
	},
}

iniText, err := Marshal(&t)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("%s\n", iniText)
Output:

[section]
string = a
int = 1
bool = true
duration = 1m0s
time = 2006-01-02 15:04:05

[section "struct"]
string = b
int = 2

[section "slice"]
string = c
string = d
int = 2
int = 3
uint = 4
uint = 5
bool = true
bool = false

[slice "OfStruct"]
string = U.string 1
int = 1

[slice "OfStruct"]
string = U.string 2
int = 2

[map "string"]
k = v

[map "int"]
keyint = 6

[section "pointer"]
string = b
int = 2
time = 2021-02-28 18:44:01

[pointer "struct"]
string = PtrStruct.String
int = 3

func Unmarshal added in v0.10.1

func Unmarshal(b []byte, v interface{}) (err error)

Unmarshal parse the INI stream from slice of byte and store its value into struct of `v`. All the properties and specifications of field's tag follow the Marshal function.

Example
iniText := `
[section]
string = a
int = 1
bool = true
duration = 1s
time = 2006-01-02 15:04:05

[section "slice"]
string = c
string = d
int = 2
int = 3
bool = true
bool = false
uint = 4
uint = 5

[slice "OfStruct"]
string = U.string 1
int = 1

[slice "OfStruct"]
string = U.string 2
int = 2

[map "string"]
k = v

[map "int"]
k = 6

[section "pointer"]
string = b
int = 2
`

type U struct {
	String string `ini:"::string"`
	Int    int    `ini:"::int"`
}

t := struct {
	String      string            `ini:"section::string"`
	Int         int               `ini:"section::int"`
	Bool        bool              `ini:"section::bool"`
	Duration    time.Duration     `ini:"section::duration"`
	Time        time.Time         `ini:"section::time" layout:"2006-01-02 15:04:05"`
	SliceString []string          `ini:"section:slice:string"`
	SliceInt    []int             `ini:"section:slice:int"`
	SliceUint   []uint            `ini:"section:slice:uint"`
	SliceBool   []bool            `ini:"section:slice:bool"`
	SliceStruct []U               `ini:"slice:OfStruct"`
	MapString   map[string]string `ini:"map:string"`
	MapInt      map[string]int    `ini:"map:int"`
	PtrString   *string           `ini:"section:pointer:string"`
	PtrInt      *int              `ini:"section:pointer:int"`
}{}

err := Unmarshal([]byte(iniText), &t)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("String: %v\n", t.String)
fmt.Printf("Int: %v\n", t.Int)
fmt.Printf("Bool: %v\n", t.Bool)
fmt.Printf("Duration: %v\n", t.Duration)
fmt.Printf("Time: %v\n", t.Time)
fmt.Printf("SliceString: %v\n", t.SliceString)
fmt.Printf("SliceInt: %v\n", t.SliceInt)
fmt.Printf("SliceUint: %v\n", t.SliceUint)
fmt.Printf("SliceBool: %v\n", t.SliceBool)
fmt.Printf("SliceStruct: %v\n", t.SliceStruct)
fmt.Printf("MapString: %v\n", t.MapString)
fmt.Printf("MapInt: %v\n", t.MapInt)
fmt.Printf("PtrString: %v\n", *t.PtrString)
fmt.Printf("PtrInt: %v\n", *t.PtrInt)
Output:

String: a
Int: 1
Bool: true
Duration: 1s
Time: 2006-01-02 15:04:05 +0000 UTC
SliceString: [c d]
SliceInt: [2 3]
SliceUint: [4 5]
SliceBool: [true false]
SliceStruct: [{U.string 1 1} {U.string 2 2}]
MapString: map[k:v]
MapInt: map[k:6]
PtrString: b
PtrInt: 2

Types

type Ini

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

Ini contains the parsed file.

func Open

func Open(filename string) (in *Ini, err error)

Open and parse INI formatted file.

On fail it will return incomplete instance of Ini with an error.

func Parse

func Parse(text []byte) (in *Ini, err error)

Parse INI format from text.

func (*Ini) Add added in v0.7.0

func (in *Ini) Add(secName, subName, key, value string) bool

Add the new key and value to the last item in section and/or subsection.

If section or subsection is not exist it will create a new one. If section or key is empty, or value already exist it will not modify the INI object.

It will return true if new variable is added, otherwise it will return false.

Example
ini := new(Ini)

ini.Add("", "", "k1", "v1")
ini.Add("s1", "", "", "v2")

ini.Add("s1", "", "k1", "")
ini.Add("s1", "", "k1", "v1")
ini.Add("s1", "", "k1", "v2")
ini.Add("s1", "", "k1", "v1")

ini.Add("s1", "sub", "k1", "v1")
ini.Add("s1", "sub", "k1", "v1")

ini.Add("s2", "sub", "k1", "v1")

err := ini.Write(os.Stdout)
if err != nil {
	log.Fatal(err)
}
Output:

[s1]
k1 =
k1 = v1
k1 = v2

[s1 "sub"]
k1 = v1

[s2 "sub"]
k1 = v1

func (*Ini) AsMap added in v0.7.0

func (in *Ini) AsMap(sectionName, subName string) (out map[string][]string)

AsMap return the INI contents as mapping of (section-name ":" subsection-name ":" variable-name) as key and the variable's values as slice of string.

If section name is not empty, only the keys will be listed in the map.

Example
input := []byte(`
[section]
key=value1
key2=

[section "sub"]
key=value1
key2=

[section]
key=value2
key2=false

[section "sub"]
key=value2
key=value3
`)

inis, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

iniMap := inis.AsMap("", "")

for k, v := range iniMap {
	fmt.Println(k, "=", v)
}

iniMap = inis.AsMap("section", "sub")

fmt.Println()
for k, v := range iniMap {
	fmt.Println(k, "=", v)
}
Output:

section::key = [value1 value2]
section::key2 = [ false]
section:sub:key = [value1 value2 value3]
section:sub:key2 = []

key = [value1 value2 value3]
key2 = []

func (*Ini) Get

func (in *Ini) Get(secName, subName, key, def string) (val string, ok bool)

Get the last key on section and/or subsection.

If key found it will return its value and true; otherwise it will return default value in def and false.

func (*Ini) GetBool

func (in *Ini) GetBool(secName, subName, key string, def bool) bool

GetBool return key's value as boolean. If no key found it will return default value.

func (*Ini) Gets added in v0.7.0

func (in *Ini) Gets(secName, subName, key string) (out []string)

Gets key's values as slice of string in the same section and subsection.

Example
input := []byte(`
[section]
key=value1

[section "sub"]
key=value2

[section]
key=value3

[section "sub"]
key=value4
key=value2
`)

inis, _ := Parse(input)

fmt.Println(inis.Gets("section", "", "key"))
fmt.Println(inis.Gets("section", "sub", "key"))
Output:

[value1 value3]
[value2 value4 value2]

func (*Ini) GetsUniq added in v0.10.1

func (in *Ini) GetsUniq(secName, subName, key string, caseSensitive bool) (out []string)

GetsUniq key's values as slice of string in the same section and subsection.

Example
input := []byte(`
[section]
key=value1

[section "sub"]
key=value2

[section]
key=value3

[section "sub"]
key=value4
key=value2
`)

inis, _ := Parse(input)

fmt.Println(inis.GetsUniq("section", "", "key", true))
fmt.Println(inis.GetsUniq("section", "sub", "key", true))
Output:

[value1 value3]
[value2 value4]

func (*Ini) Prune added in v0.7.0

func (in *Ini) Prune()

Prune remove all empty lines, comments, and merge all section and subsection with the same name into one group.

Example
input := []byte(`
[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

; here is comment on section
[section]
key=value2
key2=false

[section "sub"]
key=value2
key=value1
`)

in, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

in.Prune()

err = in.Write(os.Stdout)
if err != nil {
	log.Fatal(err)
}
Output:

[section]
key = value1
key2 = true
key = value2
key2 = false

[section "sub"]
key = value2
key = value1

func (*Ini) Rebase added in v0.7.0

func (in *Ini) Rebase(other *Ini)

Rebase merge the other INI sections into this INI sections.

Example
input := []byte(`
		[section]
		key=value1
		key2=

		[section "sub"]
		key=value1
`)

other := []byte(`
		[section]
		key=value2
		key2=false

		[section "sub"]
		key=value2
		key=value1
`)

in, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

in2, err := Parse(other)
if err != nil {
	log.Fatal(err)
}

in.Prune()
in2.Prune()

in.Rebase(in2)

err = in.Write(os.Stdout)
if err != nil {
	log.Fatal(err)
}
Output:

[section]
key = value1
key2 = true
key = value2
key2 = false

[section "sub"]
key = value2
key = value1

func (*Ini) Save

func (in *Ini) Save(filename string) (err error)

Save the current parsed Ini into file `filename`. It will overwrite the destination file if it's exist.

func (*Ini) Section added in v0.7.0

func (in *Ini) Section(secName, subName string) (sec *Section)

Section given section and/or subsection name, return the Section object that match with it. If section name is empty, it will return nil. If ini contains duplicate section (or subsection) it will merge all of its variables into one section.

Example
input := []byte(`
[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

[section] ; here is comment on section
key=value2
key2=false

[section "sub"]
key=value2
key=value1
`)

ini, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

sec := ini.Section("section", "")
for _, v := range sec.vars {
	fmt.Printf("%s=%s\n", v.key, v.value)
}
Output:

key=value1
key2=
key=value2
key2=false

func (*Ini) Set added in v0.7.0

func (in *Ini) Set(secName, subName, key, value string) bool

Set the last variable's value in section-subsection that match with the key. If section or subsection is not found, the new section-subsection will be created. If key not found, the new key-value variable will be added to the section.

It will return true if new key added or updated; otherwise it will return false.

Example
input := []byte(`
[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

[section] ; here is comment on section
key=value2
key2=false

[section "sub"]
key=value2
key=value1
`)

ini, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

ini.Set("", "sub", "key", "value3")
ini.Set("sectionnotexist", "sub", "key", "value3")
ini.Set("section", "sub", "key", "value3")
ini.Set("section", "", "key", "value4")
ini.Set("section", "", "keynotexist", "value4")

err = ini.Write(os.Stdout)
if err != nil {
	log.Fatal(err)
}
Output:

[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

[section] ; here is comment on section
key=value4
key2=false

keynotexist = value4

[section "sub"]
key=value2
key=value3

[sectionnotexist "sub"]
key = value3

func (*Ini) Subs added in v0.7.0

func (in *Ini) Subs(secName string) (subs []*Section)

Subs return all non empty subsections (and its variable) that have the same section name.

This function is shortcut to be used in templating.

Example
input := []byte(`
[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

[section] ; here is comment on section
key=value2
key2=false

[section "sub"]
key=value2
key=value1
`)

ini, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

subs := ini.Subs("section")

for _, sub := range subs {
	fmt.Println(sub.SubName(), sub.Vals("key"))
}
Output:

sub [value2 value1]

func (*Ini) Unmarshal added in v0.16.0

func (in *Ini) Unmarshal(v interface{}) (err error)

Unmarshal store the value from configuration, based on `ini` tag, into a struct pointed by interface `v`.

func (*Ini) Unset added in v0.7.0

func (in *Ini) Unset(secName, subName, key string) bool

Unset remove the last variable's in section and/or subsection that match with the key. If key found it will return true, otherwise it will return false.

Example
input := []byte(`
[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

; here is comment on section
[section]
key=value2
key2=false

[section "sub"]
key=value2
key=value1
`)

ini, err := Parse(input)
if err != nil {
	log.Fatal(err)
}

ini.Unset("", "sub", "keynotexist")
ini.Unset("sectionnotexist", "sub", "keynotexist")
ini.Unset("section", "sub", "keynotexist")
ini.Unset("section", "sub", "key")
ini.Unset("section", "", "keynotexist")
ini.Unset("section", "", "key")

err = ini.Write(os.Stdout)
if err != nil {
	log.Fatal(err)
}
Output:

[section]
key=value1 # comment
key2= ; another comment

[section "sub"]
key=value1

; here is comment on section
[section]
key2=false

[section "sub"]
key=value2

func (*Ini) UnsetAll added in v0.16.0

func (in *Ini) UnsetAll(secName, subName, key string)

UnsetAll remove all variables in section and/or subsection that match with the key. If key found it will return true, otherwise it will return false.

func (*Ini) Val added in v0.7.0

func (in *Ini) Val(keyPath string) (val string)

Val return the last variable value using a string as combination of section, subsection, and key with ":" as separator. If key not found, it will return empty string.

For example, to get the value of key "k" in section "s" and subsection "sub", call

V("s:sub:k")

This function is shortcut to be used in templating.

Example
input := `
[section]
key=value1
key2=

[section "sub"]
key=value1

[section]
key=value2
key2=false

[section "sub"]
key=value2
key=value3
`

ini, err := Parse([]byte(input))
if err != nil {
	log.Fatal(err)
}

fmt.Println(ini.Val("section:sub:key"))
fmt.Println(ini.Val("section:sub:key2"))
fmt.Println(ini.Val("section::key"))
fmt.Println(ini.Val("section:key"))
Output:

value3

value2

func (*Ini) Vals added in v0.7.0

func (in *Ini) Vals(keyPath string) (vals []string)

Vals return all values as slice of string. The keyPath is combination of section, subsection, and key using colon ":" as separator. If key not found, it will return an empty slice.

For example, to get all values of key "k" in section "s" and subsection "sub", call

Vals("s:sub:k")

This function is shortcut to be used in templating.

Example
ini, err := Parse([]byte(testInput))
if err != nil {
	log.Fatal(err)
}

fmt.Println(ini.Vals("section:key"))
fmt.Println(ini.Vals("section::key"))
fmt.Println(ini.Vals("section:sub:key2"))
fmt.Println(ini.Vals("section:sub:key"))
Output:

[]
[value1 value2]
[]
[value1 value2 value2 value3]

func (*Ini) ValsUniq added in v0.10.1

func (in *Ini) ValsUniq(keyPath string, caseSensitive bool) (vals []string)

ValsUniq return all values as slice of string without any duplication.

Example
ini, err := Parse([]byte(testInput))
if err != nil {
	log.Fatal(err)
}

fmt.Println(ini.ValsUniq("section:key", true))
fmt.Println(ini.ValsUniq("section::key", true))
fmt.Println(ini.ValsUniq("section:sub:key2", true))
fmt.Println(ini.ValsUniq("section:sub:key", true))
Output:

[]
[value1 value2]
[]
[value1 value2 value3]

func (*Ini) Vars added in v0.7.0

func (in *Ini) Vars(sectionPath string) (vars map[string]string)

Vars return all variables in section and/or subsection as map of string. If there is a duplicate in key's name, only the last key value that will be store on map value.

This method is a shortcut that can be used in templating.

Example
ini, err := Parse([]byte(testInput))
if err != nil {
	log.Fatal(err)
}

for k, v := range ini.Vars("section:") {
	fmt.Println(k, "=", v)
}

fmt.Println()
for k, v := range ini.Vars("section:sub") {
	fmt.Println(k, "=", v)
}
Output:

section::key = value2
section::key2 = false

key = value3

func (*Ini) Write

func (in *Ini) Write(w io.Writer) (err error)

Write the current parsed Ini into writer `w`.

type Section

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

Section represent section header in INI file format and their variables.

Remember that section's name is case insensitive.

func (*Section) Name

func (sec *Section) Name() string

Name return the section's name.

func (*Section) String

func (sec *Section) String() string

String return formatted INI section header.

func (*Section) SubName added in v0.7.0

func (sec *Section) SubName() string

SubName return subsection's name.

func (*Section) Val added in v0.7.0

func (sec *Section) Val(key string) string

Val return the last defined variable key in section.

func (*Section) Vals added in v0.7.0

func (sec *Section) Vals(key string) []string

Vals return all variables in section as slice of string.

Jump to

Keyboard shortcuts

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