Module: Philiprehberger::IniParser

Defined in:
lib/philiprehberger/ini_parser.rb,
lib/philiprehberger/ini_parser/parser.rb,
lib/philiprehberger/ini_parser/version.rb,
lib/philiprehberger/ini_parser/serializer.rb

Defined Under Namespace

Classes: Error, ParseError, Parser, Serializer

Constant Summary collapse

SECTION_RE =
/\A\s*\[([^\]]+)\]\s*\z/
INTERPOLATION_RE =
/\$\{([^}]+)\}/
VERSION =
'0.5.1'

Class Method Summary collapse

Class Method Details

.delete(hash, path) ⇒ Object?

Delete a value by dot-separated path.

Parameters:

  • hash (Hash)

    parsed configuration (mutated in place)

  • path (String)

    dot-separated key path (e.g. “database.host”)

Returns:

  • (Object, nil)

    the deleted value, or nil if the path did not exist



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/philiprehberger/ini_parser.rb', line 271

def self.delete(hash, path)
  keys = path.to_s.split('.')
  last = keys.pop
  current = hash

  keys.each do |key|
    return nil unless current.is_a?(Hash) && current.key?(key)

    current = current[key]
  end

  return nil unless current.is_a?(Hash)

  current.delete(last)
end

.diff(a, b) ⇒ Hash

Compare two parsed INI hashes and return a diff.

Parameters:

  • a (Hash)

    first configuration (from parse)

  • b (Hash)

    second configuration (from parse)

Returns:

  • (Hash)

    diff with :added, :removed, and :changed keys



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/philiprehberger/ini_parser.rb', line 95

def self.diff(a, b)
  result = { added: {}, removed: {}, changed: {} }

  all_keys = (a.keys + b.keys).uniq

  all_keys.each do |key|
    in_a = a.key?(key)
    in_b = b.key?(key)

    if in_a && in_b
      diff_key(key, a[key], b[key], result)
    elsif in_b
      add_to_result(result[:added], key, b[key])
    else
      add_to_result(result[:removed], key, a[key])
    end
  end

  result
end

.dump(hash) ⇒ String

Serialize a Hash to an INI string.

Parameters:

  • hash (Hash)

    configuration data

Returns:

  • (String)

    INI formatted string



59
60
61
# File 'lib/philiprehberger/ini_parser.rb', line 59

def self.dump(hash)
  Serializer.new.serialize(hash)
end

.flatten(hash) ⇒ Hash{String => Object}

Flatten a nested INI hash to dot-separated keys.

Parameters:

  • hash (Hash)

    parsed configuration

Returns:

  • (Hash{String => Object})

    flat hash with dot-separated keys



236
237
238
239
240
241
242
243
244
245
246
# File 'lib/philiprehberger/ini_parser.rb', line 236

def self.flatten(hash)
  result = {}
  hash.each do |key, value|
    if value.is_a?(Hash)
      value.each { |sub_key, sub_val| result["#{key}.#{sub_key}"] = sub_val }
    else
      result[key.to_s] = value
    end
  end
  result
end

.get(hash, path, default: nil) ⇒ Object

Retrieve a value from a parsed hash using a dot-separated path.

Parameters:

  • hash (Hash)

    parsed configuration

  • path (String)

    dot-separated key path (e.g. “database.host”)

  • default (Object) (defaults to: nil)

    value to return if the path does not exist

Returns:

  • (Object)

    the value at the path, or the default



198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/philiprehberger/ini_parser.rb', line 198

def self.get(hash, path, default: nil)
  keys = path.to_s.split('.')
  current = hash

  keys.each do |key|
    return default unless current.is_a?(Hash) && current.key?(key)

    current = current[key]
  end

  current
end

.load(path, coerce_types: true, interpolate: false, includes: false) ⇒ Hash

Parse an INI file into a Hash.

Parameters:

  • path (String)

    path to an INI file

  • coerce_types (Boolean) (defaults to: true)

    coerce booleans, integers, and floats

  • interpolate (Boolean) (defaults to: false)

    expand $VAR references after parsing

  • includes (Boolean) (defaults to: false)

    process @include directives

Returns:

  • (Hash)

    parsed configuration

Raises:

  • (ParseError)

    if the file contains invalid lines

  • (Errno::ENOENT)

    if the file does not exist

  • (Error)

    if circular includes are detected



51
52
53
# File 'lib/philiprehberger/ini_parser.rb', line 51

def self.load(path, coerce_types: true, interpolate: false, includes: false)
  parse(File.read(path, encoding: 'utf-8'), coerce_types: coerce_types, interpolate: interpolate, includes: includes)
end

.merge(base, override) ⇒ Hash

Deep merge two INI configurations.

Section-aware: when both hashes contain the same section key, the section contents are merged rather than replaced.

Parameters:

  • base (Hash)

    base configuration

  • override (Hash)

    overriding configuration

Returns:

  • (Hash)

    merged result



80
81
82
83
84
85
86
87
88
# File 'lib/philiprehberger/ini_parser.rb', line 80

def self.merge(base, override)
  base.merge(override) do |_key, old_val, new_val|
    if old_val.is_a?(Hash) && new_val.is_a?(Hash)
      old_val.merge(new_val)
    else
      new_val
    end
  end
end

.parse(string, coerce_types: true, interpolate: false, includes: false) ⇒ Hash

Parse an INI string into a Hash.

Top-level keys become global entries. Sections become nested Hashes.

Parameters:

  • string (String)

    INI content

  • coerce_types (Boolean) (defaults to: true)

    coerce booleans, integers, and floats

  • interpolate (Boolean) (defaults to: false)

    expand $VAR references after parsing

  • includes (Boolean) (defaults to: false)

    process @include directives

Returns:

  • (Hash)

    parsed configuration

Raises:

  • (ParseError)

    if the input contains invalid lines

  • (Error)

    if circular includes are detected



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/philiprehberger/ini_parser.rb', line 27

def self.parse(string, coerce_types: true, interpolate: false, includes: false)
  if includes
    string = process_includes(string, [])
  end

  result = Parser.new.parse(string, coerce_types: coerce_types)

  if interpolate
    interpolate_hash(result, result)
  end

  result
end

.save(hash, path) ⇒ void

This method returns an undefined value.

Write a Hash to an INI file.

Parameters:

  • hash (Hash)

    configuration data

  • path (String)

    output file path



68
69
70
# File 'lib/philiprehberger/ini_parser.rb', line 68

def self.save(hash, path)
  File.write(path, dump(hash), encoding: 'utf-8')
end

.sections(string_or_path) ⇒ Array<String>

Extract section names from INI content without fully parsing values.

Parameters:

  • string_or_path (String)

    INI content string or file path

Returns:

  • (Array<String>)

    section names



291
292
293
294
295
296
297
298
299
300
301
# File 'lib/philiprehberger/ini_parser.rb', line 291

def self.sections(string_or_path)
  content = File.exist?(string_or_path) ? File.read(string_or_path, encoding: 'utf-8') : string_or_path
  names = []

  content.each_line do |line|
    match = SECTION_RE.match(line.strip)
    names << match[1].strip if match
  end

  names
end

.set(hash, path, value) ⇒ Object

Set a value in a parsed hash using a dot-separated path.

Creates intermediate section hashes as needed.

Parameters:

  • hash (Hash)

    parsed configuration (mutated in place)

  • path (String)

    dot-separated key path (e.g. “database.host”)

  • value (Object)

    the value to set

Returns:

  • (Object)

    the value that was set



219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/philiprehberger/ini_parser.rb', line 219

def self.set(hash, path, value)
  keys = path.to_s.split('.')
  last = keys.pop
  current = hash

  keys.each do |key|
    current[key] = {} unless current[key].is_a?(Hash)
    current = current[key]
  end

  current[last] = value
end

.to_env(hash) ⇒ String

Convert a parsed INI hash to flat KEY=VALUE environment format.

Section keys become SECTION_KEY=value (uppercased with underscore separator). Global keys are simply uppercased.

Parameters:

  • hash (Hash)

    parsed configuration

Returns:

  • (String)

    environment variable format



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/philiprehberger/ini_parser.rb', line 175

def self.to_env(hash)
  lines = []

  hash.each do |key, value|
    if value.is_a?(Hash)
      value.each do |sub_key, sub_val|
        env_key = "#{key}_#{sub_key}".upcase
        lines << "#{env_key}=#{sub_val}"
      end
    else
      lines << "#{key.upcase}=#{value}"
    end
  end

  lines.join("\n")
end

.unflatten(hash) ⇒ Hash

Convert a flat dot-separated hash back to nested sections.

Parameters:

  • hash (Hash{String => Object})

    flat hash with dot-separated keys

Returns:

  • (Hash)

    nested configuration hash



252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/philiprehberger/ini_parser.rb', line 252

def self.unflatten(hash)
  result = {}
  hash.each do |key, value|
    parts = key.to_s.split('.', 2)
    if parts.length == 2
      result[parts[0]] ||= {}
      result[parts[0]][parts[1]] = value
    else
      result[parts[0]] = value
    end
  end
  result
end

.valid?(string) ⇒ Boolean

Check whether an INI string is syntactically valid.

Parameters:

  • string (String)

    INI content

Returns:

  • (Boolean)

    true if the content parses without errors



120
121
122
123
124
125
# File 'lib/philiprehberger/ini_parser.rb', line 120

def self.valid?(string)
  parse(string)
  true
rescue ParseError
  false
end

.validate(string) ⇒ Array<Hash{Symbol => Object}>

Validate an INI string and return detailed errors.

Returns an array of hashes, each with :line and :message keys, describing syntax errors found in the input. Returns an empty array if the content is valid.

Parameters:

  • string (String)

    INI content

Returns:

  • (Array<Hash{Symbol => Object}>)

    validation errors



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/philiprehberger/ini_parser.rb', line 135

def self.validate(string)
  errors = []
  line_number = 0
  in_continuation = false

  string.each_line do |raw_line|
    line_number += 1
    line = raw_line.strip

    if in_continuation
      in_continuation = line.end_with?('\\')
      next
    end

    next if line.empty?
    next if line.match?(/\A\s*[;#]/)

    if line.match?(/\A\[([^\]]+)\]\z/)
      next
    end

    if line.match?(/\A([^=]+)=(.*)?\z/)
      raw_value = (line.split('=', 2)[1] || '').strip
      in_continuation = raw_value.match?(/\\\s*\z/)
      next
    end

    errors << { line: line_number, message: "invalid line: #{raw_line.chomp}" }
  end

  errors
end