Class: Bauk::Gen::Inputs::Templates

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

Constant Summary collapse

Contents =
Bauk::Gen::Contents
TEMPLATE_KEYS =
%i[name dirs extra_dirs].freeze
ATTRIBUTE_VALUE_MAPPINGS =
{
  /^(yes|true)$/ => true,
  /^(no|false|)$/ => false # Empty string is also false
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(generator, config = {}) ⇒ Templates

Returns a new instance of Templates.



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/bauk/gen/inputs/templates.rb', line 24

def initialize(generator, config = {})
  @generator = generator
  config[:inputs] ||= {}
  config[:inputs][:templates] ||= {}
  template_config = config[:inputs][:templates]
  @template_name = template_config[:template_name] || generator.name
  setup_dirs template_config
  invalid_keys = template_config.keys.reject { |key| TEMPLATE_KEYS.include? key }
  unless invalid_keys.empty?
    raise "Invalid keys passed to Bauk::Gen::Inputs::Templates: #{invalid_keys.join ', '}"
  end
end

Instance Method Details

#add_file_to_items(items:, name:, attributes:, full_path:, config: {}) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/bauk/gen/inputs/templates.rb', line 132

def add_file_to_items(items:, name:, attributes:, full_path:, config: {})
  return if attributes.key?(:if) and not check_if(attributes[:if], config)
  merged_config = @generator.config.clone
  merged_config.deep_merge!(config)

  # Substitute any variables in the name
  dst_name = name.clone
  name.scan(/%=([^%]*)%/).flatten.each do |path_item|
    path_value = merged_config.dig(*path_item.split('.').map{|i| i.to_sym})
    raise "Could not file '#{path_item}' config for '#{name}'" unless path_value
    dst_name.sub!("%=#{path_item}%", path_value.to_s)
  end

  log.debug "Adding item: '#{dst_name}'. Attributes: #{attributes}"
  if items[dst_name]
    log.warn "Overwriting #{dst_name} with template: #{full_path}"
  end
  items[dst_name] = {
    name: dst_name,
    attributes: attributes,
    content: if attributes[:erb]
               Contents::ErbContent.new(file: full_path, config: merged_config, attributes: attributes)
             else
               Contents::FileContent.new(file: full_path, config: merged_config, attributes: attributes)
             end
  }
end

#check_if(if_value, extra_if_config = {}) ⇒ Object

Config variable extra complex (extra_if_config) to ensure it does notclash with a key in @generator.config as this causes issues



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/bauk/gen/inputs/templates.rb', line 113

def check_if(if_value, extra_if_config = {})
  # TODO: Use Openstruct to remove this self-binding config issue
  b = binding
  @generator.config.each do |key,value|
    b.local_variable_set(key.to_sym, value)
  end
  extra_if_config.each do |key,value|
    b.local_variable_set(key.to_sym, value)
  end
  if if_value.is_a? String
    if eval(if_value, b)
      return true
    end
  elsif if_value
    return true
  end
  false
end

#default_template_dirsObject



49
50
51
52
53
54
55
# File 'lib/bauk/gen/inputs/templates.rb', line 49

def default_template_dirs
  [
    '.bauk/generator/templates',
    '~/.bauk/generator/templates',
    File.expand_path('../../../../templates', __dir__)
  ]
end

#input_items(items) ⇒ Object



66
67
68
69
70
# File 'lib/bauk/gen/inputs/templates.rb', line 66

def input_items(items)
  @template_dirs.each do |dir|
    input_items_from_dir(items, dir)
  end
end

#input_items_from_dir(items, base_dir, sub_dir = '', dir_attributes = {}) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/bauk/gen/inputs/templates.rb', line 72

def input_items_from_dir(items, base_dir, sub_dir = '', dir_attributes = {})
  dir = "#{base_dir}/#{sub_dir}"
  log.debug "Adding items from dir: #{dir}"
  Dir.entries(dir).reject { |d| %w[. ..].include?(d) || d =~ /\.\.config$/ }.each do |filename|
    path = sub_dir.empty? ? filename.clone : "#{sub_dir}/#{filename}"
    full_path = "#{base_dir}/#{path}"
    name = path.clone.dup
    attributes = dir_attributes.merge(strip_attributes_from_name!(name))
    # Check if there is a config file to read in
    config_file = "#{base_dir}/#{name}..config"
    if File.exist? config_file
      log.debug "Loading in config for #{name} from file: #{config_file}"
      eval File.read(config_file)
    end
    if File.directory? full_path
      next if attributes.key?(:if) and not check_if(attributes[:if])
      input_items_from_dir(items, base_dir, path, attributes)
    else
      if attributes[:foreach]
        foreach = @generator.config.dig(*attributes[:foreach].split(':').map{|i| i.to_sym})
        log.debug "Looping through foreach: #{foreach}"
        if foreach.is_a? Hash
          foreach.each do |key,value|
            add_file_to_items items: items, name: name, attributes: attributes, full_path: full_path, config: {key: key, value: value}
          end
        elsif foreach.is_a? ::Array
          foreach.each do |value|
            add_file_to_items items: items, name: name, attributes: attributes, full_path: full_path, config: {value: value}
          end
        else
          log.debug "Foreach: #{foreach}"
          raise "Cannot itterate though foreach(#{attributes[:foreach]})"
        end
      else
        add_file_to_items items: items, name: name, attributes: attributes, full_path: full_path
      end
    end
  end
end

#sanitise_dirs(dirs) ⇒ Object

This function returns the absolute paths of only the provided dirs that exist



58
59
60
61
62
63
64
# File 'lib/bauk/gen/inputs/templates.rb', line 58

def sanitise_dirs(dirs)
  dirs.map do |dir|
    File.expand_path("#{dir}/#{@template_name}")
  end.select do |dir|
    File.directory? dir
  end
end

#setup_dirs(template_config) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/bauk/gen/inputs/templates.rb', line 37

def setup_dirs(template_config)
  template_dirs = template_config[:dirs] || default_template_dirs
  template_dirs.unshift(*template_config[:extra_dirs]) if template_config.include?(:extra_dirs)
  log.debug "Checking template dirs: #{template_dirs.join(', ')} (#{@template_name})"
  @template_dirs = sanitise_dirs template_dirs
  if @template_dirs.empty?
    log.error "No template directories found for generator: '#{@generator.name}'. Searched dirs: #{template_dirs.join_custom}"
  else
    log.info "Using template dirs: #{@template_dirs}"
  end
end

#strip_attributes_from_name!(name) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/bauk/gen/inputs/templates.rb', line 160

def strip_attributes_from_name!(name)
  return {} unless name =~ /\.\./
  log.debug("strip_attributes_from_name!(#{name})")

  # First strip any attributes from parent folders as those are merged in by default
  # If a folder started with .. then that whole folder should be removed
  name.gsub!(%r{\.\.([^/\.]+\.?)+/}, '/')
  name.gsub!(%r{^/*}, '')
  name.gsub!(%r{//*}, '/')

  parts = name.split('/').last().split('..')
  attr_string = parts.pop
  name.sub!("..#{attr_string}", '')
  log.debug("strip_attributes_from_name!.attr_string = #{attr_string}")

  attributes = {}
  attr_string.split('.').each do |attribute|
    if attribute =~ /=/
      vals = attribute.split('=')
      key = vals.shift.to_sym
      value = vals.join('=')
      ATTRIBUTE_VALUE_MAPPINGS.each do |mapping, val|
        next unless value =~ mapping

        value = val
        break
      end
      attributes[key] = value
    else
      attributes[attribute.to_sym] = true
    end
  end
  attributes
end