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 =
/\$\{([^}]+)\}/
ENV_INTERPOLATION_RE =
/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-(.*?))?\}/
VERSION =
'0.7.0'

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



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/philiprehberger/ini_parser.rb', line 285

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



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/philiprehberger/ini_parser.rb', line 109

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



73
74
75
# File 'lib/philiprehberger/ini_parser.rb', line 73

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



250
251
252
253
254
255
256
257
258
259
260
# File 'lib/philiprehberger/ini_parser.rb', line 250

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



212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/philiprehberger/ini_parser.rb', line 212

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

.has_key?(hash, path) ⇒ Boolean

Check whether a dot-path key exists in a parsed INI hash.

Parameters:

  • hash (Hash)

    parsed configuration

  • path (String)

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

Returns:

  • (Boolean)

    true if the path exists



334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/philiprehberger/ini_parser.rb', line 334

def self.has_key?(hash, path)
  keys = path.to_s.split('.')
  current = hash

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

    current = current[key]
  end

  true
end

.keys(hash, section: nil) ⇒ Array<String>

Return all keys from a parsed INI hash.

When no section is given, returns all keys including dot-path keys for nested sections. When a section is given, returns only the keys within that section.

Parameters:

  • hash (Hash)

    parsed configuration

  • section (String, nil) (defaults to: nil)

    optional section to scope keys to

Returns:

  • (Array<String>)

    list of keys



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/philiprehberger/ini_parser.rb', line 310

def self.keys(hash, section: nil)
  if section
    sub = hash[section]
    return [] unless sub.is_a?(Hash)

    sub.keys
  else
    result = []
    hash.each do |key, value|
      if value.is_a?(Hash)
        value.each_key { |sub_key| result << "#{key}.#{sub_key}" }
      else
        result << key.to_s
      end
    end
    result
  end
end

.load(path, coerce_types: true, interpolate: false, interpolate_env: 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

  • interpolate_env (Boolean) (defaults to: false)

    expand $VAR and $VAR:-default from ENV

  • 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



59
60
61
62
63
64
65
66
67
# File 'lib/philiprehberger/ini_parser.rb', line 59

def self.load(path, coerce_types: true, interpolate: false, interpolate_env: false, includes: false)
  parse(
    File.read(path, encoding: 'utf-8'),
    coerce_types: coerce_types,
    interpolate: interpolate,
    interpolate_env: interpolate_env,
    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



94
95
96
97
98
99
100
101
102
# File 'lib/philiprehberger/ini_parser.rb', line 94

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, interpolate_env: 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

  • interpolate_env (Boolean) (defaults to: false)

    expand $VAR and $VAR:-default from ENV

  • 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



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/philiprehberger/ini_parser.rb', line 30

def self.parse(string, coerce_types: true, interpolate: false, interpolate_env: 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

  if interpolate_env
    interpolate_env_hash(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



82
83
84
# File 'lib/philiprehberger/ini_parser.rb', line 82

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



351
352
353
354
355
356
357
358
359
360
361
# File 'lib/philiprehberger/ini_parser.rb', line 351

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



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

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



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/philiprehberger/ini_parser.rb', line 189

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



266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/philiprehberger/ini_parser.rb', line 266

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



134
135
136
137
138
139
# File 'lib/philiprehberger/ini_parser.rb', line 134

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



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/philiprehberger/ini_parser.rb', line 149

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