class Bauk::Gen::Inputs::Templates

Constants

ATTRIBUTE_VALUE_MAPPINGS
Contents
TEMPLATE_KEYS

Public Class Methods

new(generator, config = {}) click to toggle source
# 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

Public Instance Methods

add_file_to_items(items:, name:, attributes:, full_path:, config: {}) click to toggle source
# 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 = {}) click to toggle source

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

# 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_dirs() click to toggle source
# 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) click to toggle source
# 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 = {}) click to toggle source
# 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) click to toggle source

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

# 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) click to toggle source
# 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) click to toggle source
# 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