Class: PDK::Module::TemplateDir

Inherits:
Object
  • Object
show all
Defined in:
lib/pdk/module/templatedir.rb

Instance Method Summary collapse

Constructor Details

#initialize(path_or_url, module_metadata = {}) {|self| ... } ⇒ TemplateDir

Initialises the TemplateDir object with the path or URL to the template and the block of code to run to be run while the template is available.

The template directory is only guaranteed to be available on disk within the scope of the block passed to this method.

template or a URL to a git repository. Defaults to an empty Hash. the template available on disk.

the git binary is unavailable. the git clone operation fails.

Examples:

Using a git repository as a template

PDK::Module::TemplateDir.new('https://github.com/puppetlabs/pdk-module-template') do |t|
  t.render do |filename, content|
    File.open(filename, 'w') do |file|
      file.write(content)
    end
  end
end

Parameters:

  • path_or_url (String)

    The path to a directory to use as the

  • module_metadata (Hash) (defaults to: {})

    A Hash containing the module metadata.

Yield Parameters:

Raises:



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/pdk/module/templatedir.rb', line 39

def initialize(path_or_url,  = {})
  if File.directory?(path_or_url)
    @path = path_or_url
  else
    # If path_or_url isn't a directory on disk, we assume that it is
    # a remote git repository.

    # @todo When switching this over to using rugged, cache the cloned
    # template repo in `%AppData%` or `$XDG_CACHE_DIR` and update before
    # use.
    temp_dir = PDK::Util.make_tmpdir_name('pdk-module-template')

    clone_result = PDK::CLI::Exec.git('clone', path_or_url, temp_dir)
    unless clone_result[:exit_code].zero?
      PDK.logger.error clone_result[:stdout]
      PDK.logger.error clone_result[:stderr]
      raise PDK::CLI::FatalError, _("Unable to clone git repository '%{repo}' to '%{dest}'") % { repo: path_or_url, dest: temp_dir }
    end

    @path = PDK::Util.canonical_path(temp_dir)
    @repo = path_or_url
  end

  @moduleroot_dir = File.join(@path, 'moduleroot')
  @object_dir = File.join(@path, 'object_templates')
  validate_module_template!

  @module_metadata = 

  yield self
ensure
  # If we cloned a git repo to get the template, remove the clone once
  # we're done with it.
  if @repo
    FileUtils.remove_dir(@path)
  end
end

Instance Method Details

#metadataHash{String => String}

Retrieve identifying metadata for the template.

For git repositories, this will return the URL to the repository and a reference to the HEAD.

Returns:

  • (Hash{String => String})

    A hash of identifying metadata.



85
86
87
88
89
90
91
92
93
94
# File 'lib/pdk/module/templatedir.rb', line 85

def 
  return {} unless @repo

  ref_result = PDK::CLI::Exec.git('--git-dir', File.join(@path, '.git'), 'describe', '--all', '--long', '--always')
  if ref_result[:exit_code].zero?
    { 'template-url' => @repo, 'template-ref' => ref_result[:stdout].strip }
  else
    {}
  end
end

#object_configHash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Generate a hash of data to be used when rendering object templates.

Read ‘config_defaults.yml` from the root of the template directory (if it exists) build a hash of values from the value of the `:global` key.

‘@configs` instance variable.

Returns:

  • (Hash)

    The data that will be available to the template via the



164
165
166
# File 'lib/pdk/module/templatedir.rb', line 164

def object_config
  config_for(nil)
end

#object_template_for(object_type) ⇒ Hash{Symbol => String}

Searches the template directory for template files that can be used to render files for the specified object type.

‘:defined_type`, `:fact`, etc).

template dir, otherwise ‘nil`. The returned hash can contain two keys, :object contains the path on disk to the template for the object, :spec contains the path on disk to the template for the object’s spec file (if available).

Parameters:

  • object_type (Symbol)

    The object type, e.g. (‘:class`,

Returns:

  • (Hash{Symbol => String})

    if the templates are available in the



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/pdk/module/templatedir.rb', line 141

def object_template_for(object_type)
  object_path = File.join(@object_dir, "#{object_type}.erb")
  spec_path = File.join(@object_dir, "#{object_type}_spec.erb")

  if File.file?(object_path) && File.readable?(object_path)
    result = { object: object_path }
    result[:spec] = spec_path if File.file?(spec_path) && File.readable?(spec_path)
    result
  else
    nil
  end
end

#render {|dest_path, dest_content| ... } ⇒ void

This method returns an undefined value.

Loop through the files in the template, yielding each rendered file to the supplied block.

relative to the root of the module. destination file.

Yield Parameters:

  • dest_path (String)

    The path of the destination file,

  • dest_content (String)

    The rendered content of the

Raises:



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/pdk/module/templatedir.rb', line 109

def render
  files_in_template.each do |template_file|
    PDK.logger.debug(_("Rendering '%{template}'...") % { template: template_file })
    dest_path = template_file.sub(%r{\.erb\Z}, '')

    begin
      dest_content = PDK::TemplateFile.new(File.join(@moduleroot_dir, template_file), configs: config_for(dest_path)).render
    rescue => e
      error_msg = _(
        "Failed to render template '%{template}'\n" \
        '%{exception}: %{message}',
      ) % { template: template_file, exception: e.class, message: e.message }
      raise PDK::CLI::FatalError, error_msg
    end

    yield dest_path, dest_content
  end
end