Module: Bolt::Util

Defined in:
lib/bolt/util.rb

Class Method Summary collapse

Class Method Details

.deep_merge(hash1, hash2) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/bolt/util.rb', line 35

def deep_merge(hash1, hash2)
  recursive_merge = proc do |_key, h1, h2|
    if h1.is_a?(Hash) && h2.is_a?(Hash)
      h1.merge(h2, &recursive_merge)
    else
      h2
    end
  end
  hash1.merge(hash2, &recursive_merge)
end

.read_config_file(path, default_paths = nil, file_name = 'file') ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/bolt/util.rb', line 5

def read_config_file(path, default_paths = nil, file_name = 'file')
  logger = Logging.logger[self]
  path_passed = path
  if path.nil? && default_paths
    found_default = default_paths.select { |p| File.exist?(p) }
    if found_default.size > 1
      logger.warn "Found #{file_name}s at #{found_default.join(', ')}, using the first"
    end
    # Use first found, fall back to first default and try to load even if it didn't exist
    path = found_default.first || default_paths.first
  end

  path = File.expand_path(path)
  # safe_load doesn't work with psych in ruby 2.0
  # The user controls the configfile so this isn't a problem
  # rubocop:disable YAMLLoad
  File.open(path, "r:UTF-8") { |f| YAML.load(f.read) }
rescue Errno::ENOENT
  if path_passed
    raise Bolt::CLIError, "Could not read #{file_name} file: #{path}"
  end
# In older releases of psych SyntaxError is not a subclass of Exception
rescue Psych::SyntaxError
  raise Bolt::CLIError, "Could not parse #{file_name} file: #{path}"
rescue Psych::Exception
  raise Bolt::CLIError, "Could not parse #{file_name} file: #{path}"
rescue IOError, SystemCallError
  raise Bolt::CLIError, "Could not read #{file_name} file: #{path}"
end

.symbolize_keys(hash) ⇒ Object



46
47
48
49
50
51
# File 'lib/bolt/util.rb', line 46

def symbolize_keys(hash)
  hash.each_with_object({}) do |(k, v), acc|
    k = k.to_sym
    acc[k] = v.is_a?(Hash) ? symbolize_keys(v) : v
  end
end