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.9.0'
Class Method Summary collapse
-
.delete(hash, path) ⇒ Object?
Delete a value by dot-separated path.
-
.diff(a, b) ⇒ Hash
Compare two parsed INI hashes and return a diff.
-
.dump(hash) ⇒ String
Serialize a Hash to an INI string.
-
.filter(hash, section:) ⇒ Hash
Filter a parsed INI hash to only the named section(s).
-
.flatten(hash) ⇒ Hash{String => Object}
Flatten a nested INI hash to dot-separated keys.
-
.get(hash, path, default: nil) ⇒ Object
Retrieve a value from a parsed hash using a dot-separated path.
-
.has_key?(hash, path) ⇒ Boolean
Check whether a dot-path key exists in a parsed INI hash.
-
.has_section?(hash, name) ⇒ Boolean
Whether a parsed INI hash contains the given section.
-
.keys(hash, section: nil) ⇒ Array<String>
Return all keys from a parsed INI hash.
-
.load(path, coerce_types: true, interpolate: false, interpolate_env: false, includes: false) ⇒ Hash
Parse an INI file into a Hash.
-
.merge(base, override) ⇒ Hash
Deep merge two INI configurations.
-
.parse(string, coerce_types: true, interpolate: false, interpolate_env: false, includes: false) ⇒ Hash
Parse an INI string into a Hash.
-
.save(hash, path) ⇒ void
Write a Hash to an INI file.
-
.sections(string_or_path) ⇒ Array<String>
Extract section names from INI content without fully parsing values.
-
.set(hash, path, value) ⇒ Object
Set a value in a parsed hash using a dot-separated path.
-
.to_env(hash) ⇒ String
Convert a parsed INI hash to flat KEY=VALUE environment format.
-
.unflatten(hash) ⇒ Hash
Convert a flat dot-separated hash back to nested sections.
-
.valid?(string) ⇒ Boolean
Check whether an INI string is syntactically valid.
-
.validate(string) ⇒ Array<Hash{Symbol => Object}>
Validate an INI string and return detailed errors.
Class Method Details
.delete(hash, path) ⇒ Object?
Delete a value by dot-separated path.
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/philiprehberger/ini_parser.rb', line 321 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.
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/philiprehberger/ini_parser.rb', line 145 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.
73 74 75 |
# File 'lib/philiprehberger/ini_parser.rb', line 73 def self.dump(hash) Serializer.new.serialize(hash) end |
.filter(hash, section:) ⇒ Hash
Filter a parsed INI hash to only the named section(s).
Returns a new hash containing only the entries whose keys match the given section name(s). The input hash is not mutated. Unknown sections are silently ignored and yield an empty hash.
114 115 116 117 118 119 120 121 |
# File 'lib/philiprehberger/ini_parser.rb', line 114 def self.filter(hash, section:) raise ArgumentError, 'hash must be a Hash' unless hash.is_a?(Hash) sections = Array(section).map(&:to_s) hash.each_with_object({}) do |(k, v), acc| acc[k] = v if sections.include?(k.to_s) end end |
.flatten(hash) ⇒ Hash{String => Object}
Flatten a nested INI hash to dot-separated keys.
286 287 288 289 290 291 292 293 294 295 296 |
# File 'lib/philiprehberger/ini_parser.rb', line 286 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.
248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/philiprehberger/ini_parser.rb', line 248 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.
370 371 372 373 374 375 376 377 378 379 380 381 |
# File 'lib/philiprehberger/ini_parser.rb', line 370 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 |
.has_section?(hash, name) ⇒ Boolean
Whether a parsed INI hash contains the given section.
A section is a top-level key whose value is a Hash. Returns ‘false` if the key exists but maps to a scalar (i.e. is a global key, not a section). String/symbol-equivalent names are matched after `to_s`.
133 134 135 136 137 138 |
# File 'lib/philiprehberger/ini_parser.rb', line 133 def self.has_section?(hash, name) raise ArgumentError, 'hash must be a Hash' unless hash.is_a?(Hash) target = name.to_s hash.any? { |k, v| k.to_s == target && v.is_a?(Hash) } 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.
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
# File 'lib/philiprehberger/ini_parser.rb', line 346 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.
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.
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.
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.
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.
387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/philiprehberger/ini_parser.rb', line 387 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.
269 270 271 272 273 274 275 276 277 278 279 280 |
# File 'lib/philiprehberger/ini_parser.rb', line 269 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.
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/philiprehberger/ini_parser.rb', line 225 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.
302 303 304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/philiprehberger/ini_parser.rb', line 302 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.
170 171 172 173 174 175 |
# File 'lib/philiprehberger/ini_parser.rb', line 170 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.
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
# File 'lib/philiprehberger/ini_parser.rb', line 185 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 |