Class: Bauk::Gen::Configs::Files

Inherits:
Base
  • Object
show all
Includes:
Utils::Log
Defined in:
lib/bauk/gen/configs/files.rb

Instance Method Summary collapse

Methods inherited from Base

#add_config!, #symbolize

Constructor Details

#initialize(map = {}) ⇒ Files

Returns a new instance of Files.



14
15
16
17
18
19
20
21
# File 'lib/bauk/gen/configs/files.rb', line 14

def initialize(map = {})
  super map
  @files = map[:files] || default_files
  @files << map[:extra_files] if map[:extra_files]
  log.debug "Searching for the following files: #{@files.join ', '}"
  sanitise_files
  log.debug "Files used for config: #{YAML.dump @files}"
end

Instance Method Details

#default_filesObject



23
24
25
26
27
28
# File 'lib/bauk/gen/configs/files.rb', line 23

def default_files
  [
    '.bauk/generator/config.yaml',
    '~/.bauk/generator/config.yaml'
  ]
end

#generate_configObject

TODO: get working with custom base key Method that collects config from config files



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/bauk/gen/configs/files.rb', line 53

def generate_config
  conf = {}
  log.warn 'No config files found' if @files.empty?
  @files.each do |file_data|
    file = file_data[:path]
    if Dir.exist?(file)
      log.debug "Adding config from dir: #{file}"
      Find.find(file) do |path|
        next if Dir.exist?(path)
        base_keys = path.sub(/\.[a-z]*$/, '').sub(%r{^#{file}/*}, '').gsub('/', '.').split('.').map(&:to_sym)
        log.debug("Adding nested config file '#{path}' as #{base_keys.join("->")}")
        nested_config = conf
        base_keys.each do |key|
          nested_config[key] ||= {}
          nested_config = nested_config[key]
        end
        nested_config.deep_merge!(symbolize(YAML.load_file(path)))
      end
    else
      log.debug "Adding config from file: #{file}"
      conf.deep_merge!(symbolize((YAML.load_file(file))))
    end
  end
  conf
end

#sanitise_filesObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/bauk/gen/configs/files.rb', line 30

def sanitise_files
  files_map = {}
  @files = @files.select do |file|
    path = file.is_a?(Hash) ? file[:path] : file
    File.exist?(path) or Dir.exist?(path)
  end.map do |file|
    if file.is_a?(Hash)
      file[:path] = File.expand_path file[:path]
      file
    else
      {
        path: File.expand_path(file)
      }
    end
  end
  @files.each do |file|
    log.warn("Config file included twice: '#{file}'") if files_map[file[:path]]
    files_map[file[:path]] = {}
  end
end