Read and write INI configuration files

In an INI file, properties (or keys) are associated to values thanks to the equals symbol (=). Properties may be grouped into section marked between brackets ([ and ]).

var ini_string = """
; Example INI
key=value1
[section1]
key=value2
[section2]
key=value3
"""

The main class, IniFile, can be created from an INI string and allows easy access to its content.

var ini = new IniFile.from_string(ini_string)

# Check keys presence
assert ini.has_key("key")
assert ini.has_key("section1.key")
assert not ini.has_key("not.found")

# Access values
assert ini["key"] == "value1"
assert ini["section2.key"] == "value3"
assert ini["not.found"] == null

# Access sections
assert ini.sections.length == 2
assert ini.section("section1")["key"] == "value2"

IniFile can also be used to create new INI files from scratch, or edit existing ones through its API.

ini = new IniFile
ini["key"] = "value1"
ini["section1.key"] = "value2"
ini["section2.key"] = "value3"
ini.write_to_file("my_config.ini")

# Load the INI file from disk
ini = new IniFile.from_file("my_config.ini")
assert ini["key"] == "value1"
assert ini["section1.key"] == "value2"
assert ini["section2.key"] == "value3"

"my_config.ini".to_path.delete

Introduced properties

init defaultinit(stop_on_first_error: nullable Bool)

ini :: IniFile :: defaultinit

fun errors: Array[IniError]

ini :: IniFile :: errors

Errors found during parsing
protected fun errors=(errors: Array[IniError])

ini :: IniFile :: errors=

Errors found during parsing
fun flatten: Map[String, String]

ini :: IniFile :: flatten

Flatten self and its subsection in a Map of keys => values
init from_file(file: String, stop_on_first_error: nullable Bool)

ini :: IniFile :: from_file

Create a IniFile from a file content
init from_string(string: String, stop_on_first_error: nullable Bool)

ini :: IniFile :: from_string

Create a IniFile from a string content
fun load_file(file: String): Bool

ini :: IniFile :: load_file

Load a file content as INI
fun load_string(string: String): Bool

ini :: IniFile :: load_string

Read INI content from string
fun section(name: String): nullable IniSection

ini :: IniFile :: section

Get a section by its name
fun sections: Array[IniSection]

ini :: IniFile :: sections

Sections composing this IniFile
protected fun sections=(sections: Array[IniSection])

ini :: IniFile :: sections=

Sections composing this IniFile
fun stop_on_first_error: Bool

ini :: IniFile :: stop_on_first_error

Stop parsing on the first error
fun stop_on_first_error=(stop_on_first_error: nullable Bool)

ini :: IniFile :: stop_on_first_error=

Stop parsing on the first error

Redefined properties

redef type SELF: IniFile

ini $ IniFile :: SELF

Type of this instance, automatically specialized in every class
redef fun [](key: nullable Object): nullable String

ini $ IniFile :: []

Get the value associated with a property (key)
redef fun []=(key: String, value: nullable String)

ini $ IniFile :: []=

Set the value for the property locaated at key
redef fun has_key(key: nullable Object): Bool

ini $ IniFile :: has_key

Is there a property located at key?
redef fun is_empty: Bool

ini $ IniFile :: is_empty

Does this file contains no properties and no sections?
redef fun write_to(stream: Writer)

ini $ IniFile :: write_to

Write self to a stream

All properties

fun !=(other: nullable Object): Bool

core :: Object :: !=

Have self and other different values?
fun ==(other: nullable Object): Bool

core :: Object :: ==

Have self and other the same value?
type CLASS: Class[SELF]

core :: Object :: CLASS

The type of the class of self.
type SELF: Object

core :: Object :: SELF

Type of this instance, automatically specialized in every class
abstract fun [](key: nullable Object): V

core :: MapRead :: []

Get the item at key
abstract fun []=(key: K, value: V)

core :: Map :: []=

Set the value at key.
protected fun accept_json_serializer(v: JsonSerializer)

serialization :: Serializable :: accept_json_serializer

Refinable service to customize the serialization of this class to JSON
protected fun accept_msgpack_attribute_counter(v: AttributeCounter)

serialization :: Serializable :: accept_msgpack_attribute_counter

Hook to customize the behavior of the AttributeCounter
protected fun accept_msgpack_serializer(v: MsgPackSerializer)

serialization :: Serializable :: accept_msgpack_serializer

Hook to customize the serialization of this class to MessagePack
fun add_all(map: MapRead[K, V])

core :: Map :: add_all

Add each (key,value) of map into self.
protected fun add_to_bundle(bundle: NativeBundle, key: JavaString)

serialization :: Serializable :: add_to_bundle

Called by []= to dynamically choose the appropriate method according
protected fun class_factory(name: String): CLASS

core :: Object :: class_factory

Implementation used by get_class to create the specific class.
fun class_name: String

core :: Object :: class_name

The class name of the object.
abstract fun clear

core :: Map :: clear

Remove all items
fun core_serialize_to(serializer: Serializer)

serialization :: Serializable :: core_serialize_to

Actual serialization of self to serializer
init defaultinit(stop_on_first_error: nullable Bool)

ini :: IniFile :: defaultinit

fun errors: Array[IniError]

ini :: IniFile :: errors

Errors found during parsing
protected fun errors=(errors: Array[IniError])

ini :: IniFile :: errors=

Errors found during parsing
fun filter_keys(keys: Collection[nullable Object]): Array[K]

core :: MapRead :: filter_keys

Return all elements of keys that have a value.
fun flatten: Map[String, String]

ini :: IniFile :: flatten

Flatten self and its subsection in a Map of keys => values
init from(coll: Map[K, V])

core :: HashMap :: from

Build a list filled with the items of coll.
init from_deserializer(deserializer: Deserializer)

serialization :: Serializable :: from_deserializer

Create an instance of this class from the deserializer
init from_file(file: String, stop_on_first_error: nullable Bool)

ini :: IniFile :: from_file

Create a IniFile from a file content
init from_string(string: String, stop_on_first_error: nullable Bool)

ini :: IniFile :: from_string

Create a IniFile from a string content
fun get_class: CLASS

core :: Object :: get_class

The meta-object representing the dynamic type of self.
fun get_or_default(key: nullable Object, default: V): V

core :: MapRead :: get_or_default

Get the item at key or return default if not in map
fun get_or_null(key: nullable Object): nullable V

core :: MapRead :: get_or_null

Get the item at key or null if key is not in the map.
fun has_key(key: nullable Object): Bool

core :: MapRead :: has_key

Is there an item associated with key?
fun hash: Int

core :: Object :: hash

The hash code of the object.
init init

core :: Object :: init

fun inspect: String

core :: Object :: inspect

Developer readable representation of self.
protected fun inspect_head: String

core :: Object :: inspect_head

Return "CLASSNAME:#OBJECTID".
abstract fun is_empty: Bool

core :: MapRead :: is_empty

Is there no item in the collection?
intern fun is_same_instance(other: nullable Object): Bool

core :: Object :: is_same_instance

Return true if self and other are the same instance (i.e. same identity).
fun is_same_serialized(other: nullable Object): Bool

core :: Object :: is_same_serialized

Is self the same as other in a serialization context?
intern fun is_same_type(other: Object): Bool

core :: Object :: is_same_type

Return true if self and other have the same dynamic type.
abstract fun iterator: MapIterator[K, V]

core :: MapRead :: iterator

Get a new iterator on the map.
abstract fun join(sep: String, couple_sep: String): String

core :: Map :: join

Concatenate couples of key value.
abstract fun keys: Collection[K]

core :: MapRead :: keys

Return the point of view of self on the keys only.
protected fun keys=(keys: RemovableCollection[K])

core :: HashMap :: keys=

fun keys_sorted_by_values(comparator: Comparator): Array[K]

core :: MapRead :: keys_sorted_by_values

Return an array of all keys sorted with their values using comparator.
abstract fun length: Int

core :: MapRead :: length

Number of items in the collection.
fun load_file(file: String): Bool

ini :: IniFile :: load_file

Load a file content as INI
fun load_string(string: String): Bool

ini :: IniFile :: load_string

Read INI content from string
fun lookup_all_values(pe: POSetElement[K]): Set[V]

core :: MapRead :: lookup_all_values

Search all the values in pe.greaters.
fun lookup_values(pe: POSetElement[K]): Set[V]

core :: MapRead :: lookup_values

Combine the values in pe.greaters from the most smaller elements that have a value.
protected fun msgpack_extra_array_items: Int

serialization :: Serializable :: msgpack_extra_array_items

Hook to request a larger than usual metadata array
init new: Map[K, V]

core :: Map :: new

Get a HashMap[K, V] as default implementation
fun not_empty: Bool

core :: MapRead :: not_empty

Alias for not is_empty.
intern fun object_id: Int

core :: Object :: object_id

An internal hash code for the object based on its identity.
fun output

core :: Object :: output

Display self on stdout (debug only).
intern fun output_class_name

core :: Object :: output_class_name

Display class name on stdout (debug only).
protected fun provide_default_value(key: nullable Object): V

core :: MapRead :: provide_default_value

Called by the underling implementation of [] to provide a default value when a key has no value
fun recover_with(map: MapRead[K, V])

core :: Map :: recover_with

Alias for add_all
fun section(name: String): nullable IniSection

ini :: IniFile :: section

Get a section by its name
fun sections: Array[IniSection]

ini :: IniFile :: sections

Sections composing this IniFile
protected fun sections=(sections: Array[IniSection])

ini :: IniFile :: sections=

Sections composing this IniFile
fun serialization_hash: Int

core :: Object :: serialization_hash

Hash value use for serialization
fun serialize_msgpack(plain: nullable Bool): Bytes

serialization :: Serializable :: serialize_msgpack

Serialize self to MessagePack bytes
fun serialize_to(serializer: Serializer)

serialization :: Serializable :: serialize_to

Serialize self to serializer
fun serialize_to_json(plain: nullable Bool, pretty: nullable Bool): String

serialization :: Serializable :: serialize_to_json

Serialize self to JSON
fun stop_on_first_error: Bool

ini :: IniFile :: stop_on_first_error

Stop parsing on the first error
fun stop_on_first_error=(stop_on_first_error: nullable Bool)

ini :: IniFile :: stop_on_first_error=

Stop parsing on the first error
intern fun sys: Sys

core :: Object :: sys

Return the global sys object, the only instance of the Sys class.
fun to_json: String

serialization :: Serializable :: to_json

Serialize self to plain JSON
abstract fun to_jvalue(env: JniEnv): JValue

core :: Object :: to_jvalue

fun to_map_comparator(comparator: Comparator): MapComparator[K, V]

core :: MapRead :: to_map_comparator

A comparator that compares things with their values in self.
fun to_pretty_json: String

serialization :: Serializable :: to_pretty_json

Serialize self to plain pretty JSON
fun to_s: String

core :: Object :: to_s

User readable representation of self.
abstract fun values: Collection[V]

core :: MapRead :: values

Return the point of view of self on the values only.
protected fun values=(values: RemovableCollection[V])

core :: HashMap :: values=

fun values_sorted_by_key(comparator: Comparator): Array[V]

core :: MapRead :: values_sorted_by_key

Return an array of all values sorted with their keys using comparator.
abstract fun write_to(stream: Writer)

core :: Writable :: write_to

Write itself to a stream
fun write_to_bytes: Bytes

core :: Writable :: write_to_bytes

Like write_to but return a new Bytes (may be quite large)
fun write_to_file(filepath: String)

core :: Writable :: write_to_file

Like write_to but take care of creating the file
fun write_to_string: String

core :: Writable :: write_to_string

Like write_to but return a new String (may be quite large).
package_diagram ini::IniFile IniFile core::Writable Writable ini::IniFile->core::Writable core::HashMap HashMap ini::IniFile->core::HashMap core::Object Object core::Writable->core::Object core::Map Map core::HashMap->core::Map ...core::Object ... ...core::Object->core::Object ...core::Map ... ...core::Map->core::Map

Ancestors

interface Map[K: nullable Object, V: nullable Object]

core :: Map

Maps are associative collections: key -> item.
interface MapRead[K: nullable Object, V: nullable Object]

core :: MapRead

MapRead are abstract associative collections: key -> item.
interface Object

core :: Object

The root of the class hierarchy.
interface Serializable

serialization :: Serializable

Instances of this class can be passed to Serializer::serialize

Parents

class HashMap[K: nullable Object, V: nullable Object]

core :: HashMap

A Map implemented with a hash table.
interface Writable

core :: Writable

Things that can be efficienlty written to a Writer

Class definitions

ini $ IniFile
# Read and write INI configuration files
#
# In an INI file, properties (or keys) are associated to values thanks to the
# equals symbol (`=`).
# Properties may be grouped into section marked between brackets (`[` and `]`).
#
# ~~~
# var ini_string = """
# ; Example INI
# key=value1
# [section1]
# key=value2
# [section2]
# key=value3
# """
# ~~~
#
# The main class, `IniFile`, can be created from an INI string and allows easy
# access to its content.
#
# ~~~
# # Read INI from string
# var ini = new IniFile.from_string(ini_string)
#
# # Check keys presence
# assert ini.has_key("key")
# assert ini.has_key("section1.key")
# assert not ini.has_key("not.found")
#
# # Access values
# assert ini["key"] == "value1"
# assert ini["section2.key"] == "value3"
# assert ini["not.found"] == null
#
# # Access sections
# assert ini.sections.length == 2
# assert ini.section("section1")["key"] == "value2"
# ~~~
#
# `IniFile` can also be used to create new INI files from scratch, or edit
# existing ones through its API.
#
# ~~~
# # Create a new INI file and write it to disk
# ini = new IniFile
# ini["key"] = "value1"
# ini["section1.key"] = "value2"
# ini["section2.key"] = "value3"
# ini.write_to_file("my_config.ini")
#
# # Load the INI file from disk
# ini = new IniFile.from_file("my_config.ini")
# assert ini["key"] == "value1"
# assert ini["section1.key"] == "value2"
# assert ini["section2.key"] == "value3"
#
# "my_config.ini".to_path.delete
# ~~~
class IniFile
	super Writable
	super HashMap[String, nullable String]

	# Create a IniFile from a `string` content
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# key1=value1
	# [section1]
	# key2=value2
	# """)
	# assert ini["key1"] == "value1"
	# assert ini["section1.key2"] == "value2"
	# ~~~
	#
	# See also `stop_on_first_error` and `errors`.
	init from_string(string: String, stop_on_first_error: nullable Bool) do
		init stop_on_first_error or else false
		load_string(string)
	end

	# Create a IniFile from a `file` content
	#
	# ~~~
	# """
	# key1=value1
	# [section1]
	# key2=value2
	# """.write_to_file("my_config.ini")
	#
	# var ini = new IniFile.from_file("my_config.ini")
	# assert ini["key1"] == "value1"
	# assert ini["section1.key2"] == "value2"
	#
	# "my_config.ini".to_path.delete
	# ~~~
	#
	# See also `stop_on_first_error` and `errors`.
	init from_file(file: String, stop_on_first_error: nullable Bool) do
		init stop_on_first_error or else false
		load_file(file)
	end

	# Sections composing this IniFile
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# [section1]
	# key1=value1
	# [ section 2 ]
	# key2=value2
	# """)
	# assert ini.sections.length == 2
	# assert ini.sections.first.name == "section1"
	# assert ini.sections.last.name == "section 2"
	# ~~~
	var sections = new Array[IniSection]

	# Get a section by its `name`
	#
	# Returns `null` if the section is not found.
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# [section1]
	# key1=value1
	# [section2]
	# key2=value2
	# """)
	# assert ini.section("section1") isa IniSection
	# assert ini.section("section2").name == "section2"
	# assert ini.section("not.found") == null
	# ~~~
	fun section(name: String): nullable IniSection do
		for section in sections do
			if section.name == name then return section
		end
		return null
	end

	# Does this file contains no properties and no sections?
	#
	# ~~~
	# var ini = new IniFile.from_string("")
	# assert ini.is_empty
	#
	# ini = new IniFile.from_string("""
	# key=value
	# """)
	# assert not ini.is_empty
	#
	# ini = new IniFile.from_string("""
	# [section]
	# """)
	# assert not ini.is_empty
	# ~~~
	redef fun is_empty do return super and sections.is_empty

	# Is there a property located at `key`?
	#
	# Returns `true` if the `key` is not found of if its associated value is `null`.
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# key=value1
	# [section1]
	# key=value2
	# [section2]
	# key=value3
	# """)
	# assert ini.has_key("key")
	# assert ini.has_key("section1.key")
	# assert ini.has_key("section2.key")
	# assert not ini.has_key("section1")
	# assert not ini.has_key("not.found")
	# ~~~
	redef fun has_key(key) do return self[key] != null

	# Get the value associated with a property (`key`)
	#
	# Returns `null` if the key is not found.
	# Section properties can be accessed with the `.` notation.
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# key=value1
	# [section1]
	# key=value2
	# [section2]
	# key=value3
	# """)
	# assert ini["key"] == "value1"
	# assert ini["section1.key"] == "value2"
	# assert ini["section2.key"] == "value3"
	# assert ini["section1"] == null
	# assert ini["not.found"] == null
	# ~~~
	redef fun [](key) do
		if key == null then return null
		key = key.to_s.trim

		# Look in root
		var node = node_at(key)
		if node != null then return node.value

		# Look in sections
		for section in sections do
			# Matched if the section name is a prefix of the key
			if not key.has_prefix(section.name) then continue
			var skey = key.substring(section.name.length + 1, key.length)
			if section.has_key(skey) then return section[skey]
		end
		return null
	end

	# Set the `value` for the property locaated at `key`
	#
	# ~~~
	# var ini = new IniFile
	# ini["key"] = "value1"
	# ini["section1.key"] = "value2"
	# ini["section2.key"] = "value3"
	#
	# assert ini["key"] == "value1"
	# assert ini["section1.key"] == "value2"
	# assert ini["section2.key"] == "value3"
	# assert ini.section("section1").name == "section1"
	# assert ini.section("section2")["key"] == "value3"
	# ~~~
	redef fun []=(key, value) do
		if value == null then return
		var parts = key.split_once_on(".")

		# No dot notation, store value in root
		if parts.length == 1 then
			super(key.trim, value.trim)
			return
		end

		# First part matches a section, store value in it
		var section = self.section(parts.first.trim)
		if section != null then
			section[parts.last.trim] = value.trim
			return
		end

		# No section matched, create a new one and store value in it
		section = new IniSection(parts.first.trim)
		section[parts.last.trim] = value.trim
		sections.add section
	end

	# Flatten `self` and its subsection in a `Map` of keys => values
	#
	# Properties from section are prefixed with their section names with the
	# dot (`.`) notation.
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# key=value1
	# [section]
	# key=value2
	# """)
	# assert ini.flatten.join(", ", ": ") == "key: value1, section.key: value2"
	# ~~~
	fun flatten: Map[String, String] do
		var map = new HashMap[String, String]
		for key, value in self do
			if value == null then continue
			map[key] = value
		end
		for section in sections do
			for key, value in section do
				if value == null then continue
				map["{section.name}.{key}"] = value
			end
		end
		return map
	end

	# Write `self` to a `stream`
	#
	# Key with `null` values are ignored.
	# The empty string can be used to represent an empty value.
	#
	# ~~~
	# var ini = new IniFile
	# ini["key"] = "value1"
	# ini["key2"] = null
	# ini["key3"] = ""
	# ini["section1.key"] = "value2"
	# ini["section1.key2"] = null
	# ini["section2.key"] = "value3"
	#
	# var stream = new StringWriter
	# ini.write_to(stream)
	#
	# assert stream.to_s == """
	# key=value1
	# key3=
	# [section1]
	# key=value2
	# [section2]
	# key=value3
	# """
	# ~~~
	redef fun write_to(stream) do
		for key, value in self do
			if value == null then continue
			stream.write "{key}={value}\n"
		end
		for section in sections do
			stream.write "[{section.name}]\n"
			for key, value in section do
				if value == null then continue
				stream.write "{key}={value}\n"
			end
		end
	end

	# Read INI content from `string`
	#
	# ~~~
	# var ini = new IniFile
	# ini.load_string("""
	# section1.key1=value1
	# section1.key2=value2
	# [section2]
	# key=value3
	# """)
	# assert ini["section1.key1"] == "value1"
	# assert ini["section1.key2"] == "value2"
	# assert ini["section2.key"] == "value3"
	# ~~~
	#
	# Returns `true` if the parsing finished correctly.
	#
	# See also `stop_on_first_error` and `errors`.
	fun load_string(string: String): Bool do
		var stream = new StringReader(string)
		var last_section = null
		var was_error = false
		var i = 0
		while not stream.eof do
			i += 1
			var line = stream.read_line.trim
			if line.is_empty then
				continue
			else if line.has_prefix(";") then
				continue
			else if line.has_prefix("#") then
				continue
			else if line.has_prefix("[") then
				var section = new IniSection(line.substring(1, line.length - 2).trim)
				sections.add section
				last_section = section
				continue
			else
				var parts = line.split_once_on("=")
				if parts.length != 2 then
					# FIXME silent skip?
					# we definitely need exceptions...
					was_error = true
					errors.add new IniError("Unexpected string `{line}` at line {i}.")
					if stop_on_first_error then return was_error
					continue
				end
				var key = parts[0].trim
				var value = parts[1].trim

				if last_section != null then
					last_section[key] = value
				else
					self[key] = value
				end
			end
		end
		stream.close
		return was_error
	end

	# Load a `file` content as INI
	#
	# New properties will be appended to the `self`, existing properties will be
	# overwrote by the values contained in `file`.
	#
	# ~~~
	# var ini = new IniFile
	# ini["key1"] = "value1"
	# ini["key2"] = "value2"
	#
	# """
	# key2=changed
	# key3=added
	# """.write_to_file("load_config.ini")
	#
	# ini.load_file("load_config.ini")
	# assert ini["key1"] == "value1"
	# assert ini["key2"] == "changed"
	# assert ini["key3"] == "added"
	#
	# "load_config.ini".to_path.delete
	# ~~~
	#
	# The process fails silently if the file does not exist.
	#
	# ~~~
	# ini = new IniFile
	# ini.load_file("ini_not_found.ini")
	# assert ini.is_empty
	# ~~~
	#
	# Returns `true` if the parsing finished correctly.
	#
	# See also `stop_on_first_error` and `errors`.
	fun load_file(file: String): Bool do return load_string(file.to_path.read_all)

	# Stop parsing on the first error
	#
	# By default, `load_string` will skip unparsable properties so the string can
	# be loaded.
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# key1=value1
	# key2
	# key3=value3
	# """)
    #
	# assert ini.length == 2
	# assert ini["key1"] == "value1"
	# assert ini["key2"] == null
	# assert ini["key3"] == "value3"
	# ~~~
	#
	# Set `stop_on_first_error` to `true` to force the parsing to stop.
	#
	# ~~~
	# ini = new IniFile
	# ini.stop_on_first_error = true
	# ini.load_string("""
	# key1=value1
	# key2
	# key3=value3
	# """)
    #
	# assert ini.length == 1
	# assert ini["key1"] == "value1"
	# assert ini["key2"] == null
	# assert ini["key3"] == null
	# ~~~
	#
	# See also `errors`.
	var stop_on_first_error = false is optional, writable

	# Errors found during parsing
	#
	# Wathever the value of `stop_on_first_error`, errors from parsing a string
	# or a file are logged into `errors`.
	#
	# ~~~
	# var ini = new IniFile.from_string("""
	# key1=value1
	# key2
	# key3=value3
	# """)
    #
	# assert ini.errors.length == 1
	# assert ini.errors.first.message == "Unexpected string `key2` at line 2."
	# ~~~
	#
	# `errors` is not cleared between two parsing:
	#
	# ~~~
	# ini.load_string("""
	# key4
	# key5=value5
	# """)
    #
	# assert ini.errors.length == 2
	# assert ini.errors.last.message == "Unexpected string `key4` at line 1."
	# ~~~
	#
	# See also `stop_on_first_error`.
	var errors = new Array[IniError]
end
lib/ini/ini.nit:21,1--505,3