Class: PDK::Generate::PuppetObject

Inherits:
Object
  • Object
show all
Defined in:
lib/pdk/generate/puppet_object.rb

Direct Known Subclasses

DefinedType, Provider, PuppetClass, Task, Transport

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(module_dir, object_name, options) ⇒ PuppetObject

Initialises the PDK::Generate::PuppetObject object.

In general, this object should never be instantiated directly. Instead, one of the subclasses should be used e.g. PDK::Generate::Klass.

New subclasses generally only need to inherit this class, set the OBJECT_TYPE constant and implement the #template_data, #target_object_path and #target_spec_path methods.

Parameters:

  • module_dir (String)

    The path to the module directory that the will contain the object.

  • object_name (String)

    The name of the object.

  • options (Hash{Symbol => Object})


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/pdk/generate/puppet_object.rb', line 32

def initialize(module_dir, object_name, options)
  @module_dir = module_dir
  @options = options
  @object_name = object_name

  if [:class, :defined_type].include?(object_type) # rubocop:disable Style/GuardClause
    object_name_parts = object_name.split('::')

    @object_name = if object_name_parts.first == module_name
                     object_name
                   else
                     [module_name, object_name].join('::')
                   end
  end
end

Instance Attribute Details

#module_dirObject (readonly)

Returns the value of attribute module_dir.



13
14
15
# File 'lib/pdk/generate/puppet_object.rb', line 13

def module_dir
  @module_dir
end

#object_nameObject (readonly)

Returns the value of attribute object_name.



14
15
16
# File 'lib/pdk/generate/puppet_object.rb', line 14

def object_name
  @object_name
end

#optionsObject (readonly)

Returns the value of attribute options.



15
16
17
# File 'lib/pdk/generate/puppet_object.rb', line 15

def options
  @options
end

Class Method Details

.class_name_from_object_name(object_name) ⇒ Object

transform a object name into a ruby class name



327
328
329
# File 'lib/pdk/generate/puppet_object.rb', line 327

def self.class_name_from_object_name(object_name)
  object_name.to_s.split('_').map(&:capitalize).join
end

.puppet_strings_typeString

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.

Retrieves the type of the object being generated as represented in the JSON output of puppet-strings.

Returns:

  • (String)

    the type of the object being generated or nil if there is no mapping.



113
114
115
116
117
# File 'lib/pdk/generate/puppet_object.rb', line 113

def self.puppet_strings_type
  return nil unless const_defined?(:PUPPET_STRINGS_TYPE)

  self::PUPPET_STRINGS_TYPE
end

Instance Method Details

#check_preconditionsObject

Check preconditions of this template group. By default this only makes sure that the target files do not already exist. Override this (and call super) to add your own preconditions.

Raises:



143
144
145
146
147
148
149
150
151
152
# File 'lib/pdk/generate/puppet_object.rb', line 143

def check_preconditions
  targets.each do |target_file|
    next unless File.exist?(target_file)

    raise PDK::CLI::ExitWithError, _("Unable to generate %{object_type}; '%{file}' already exists.") % {
      file:        target_file,
      object_type: spec_only? ? 'unit test' : object_type,
    }
  end
end

#module_metadataPDK::Module::Metadata

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.

Parses the metadata.json file for the module.

Returns:

Raises:

  • (PDK::CLI::FatalError)

    if the metadata.json file does not exist, can not be read, or contains invalid metadata.



318
319
320
321
322
323
324
# File 'lib/pdk/generate/puppet_object.rb', line 318

def 
  @module_metadata ||= begin
    PDK::Module::Metadata.from_file(File.join(module_dir, 'metadata.json'))
  rescue ArgumentError => e
    raise PDK::CLI::FatalError, _("'%{dir}' does not contain valid Puppet module metadata: %{msg}") % { dir: module_dir, msg: e.message }
  end
end

#module_nameString

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.

Retrieves the name of the module (without the forge username) from the module metadata.

Returns:

  • (String)

    The name of the module.

Raises:

  • (PDK::CLI::FatalError)

    if the metadata.json file does not exist, can not be read, or contains invalid metadata.



306
307
308
# File 'lib/pdk/generate/puppet_object.rb', line 306

def module_name
  @module_name ||= .data['name'].rpartition('-').last
end

#object_typeSymbol

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.

Retrieves the type of the object being generated, e.g. :class, :defined_type, etc. This is specified in the subclass’ OBJECT_TYPE constant.

Returns:

  • (Symbol)

    the type of the object being generated.



102
103
104
# File 'lib/pdk/generate/puppet_object.rb', line 102

def object_type
  self.class::OBJECT_TYPE
end

#render_file(dest_path, template_path, data) ⇒ void

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.

This method returns an undefined value.

Render a file using the provided template and write it to disk.

Parameters:

  • dest_path (String)

    The path that the rendered file should be written to. Any necessary directories will be automatically created.

  • template_path (String)

    The path on disk to the file containing the template.

  • data (Hash{Object => Object})

    The data to be provided to the template when rendering.

Raises:



193
194
195
196
197
# File 'lib/pdk/generate/puppet_object.rb', line 193

def render_file(dest_path, template_path, data)
  write_file(dest_path) do
    PDK::TemplateFile.new(template_path, data).render
  end
end

#runObject

Check that the templates can be rendered. Find an appropriate template and create the target files from the template. This is the main entry point for the class.

Raises:



162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/pdk/generate/puppet_object.rb', line 162

def run
  check_preconditions

  with_templates do |template_path, config_hash|
    data = template_data.merge(configs: config_hash)

    render_file(target_object_path, template_path[:object], data) unless spec_only?
    render_file(target_type_path, template_path[:type], data) if template_path[:type]
    render_file(target_device_path, template_path[:device], data) if template_path[:device]
    render_file(target_spec_path, template_path[:spec], data) if template_path[:spec]
    render_file(target_type_spec_path, template_path[:type_spec], data) if template_path[:type_spec]
  end
end

#spec_only?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/pdk/generate/puppet_object.rb', line 48

def spec_only?
  @options[:spec_only]
end

#target_device_pathObject

This method is abstract.

Subclass and implement #target_device_path. Implementations of this method should return a String containing the destination path of the device class being generated.



91
92
93
# File 'lib/pdk/generate/puppet_object.rb', line 91

def target_device_path
  nil
end

#target_object_pathObject

This method is abstract.

Subclass and implement #target_object_path. Implementations of this method should return a String containing the destination path of the object being generated.

Raises:

  • (NotImplementedError)


62
63
64
# File 'lib/pdk/generate/puppet_object.rb', line 62

def target_object_path
  raise NotImplementedError
end

#target_spec_pathObject

This method is abstract.

Subclass and implement #target_spec_path. Implementations of this method should return a String containing the destination path of the tests for the object being generated.

Raises:

  • (NotImplementedError)


77
78
79
# File 'lib/pdk/generate/puppet_object.rb', line 77

def target_spec_path
  raise NotImplementedError
end

#target_type_pathString

This method is abstract.

Subclass and implement #target_type_path. Implementations of this method should return a String containing the destination path of the additional object file being generated.

Returns nil if there is no additional object file

Returns:

  • (String)

    returns nil if there is no additional object file



70
71
72
# File 'lib/pdk/generate/puppet_object.rb', line 70

def target_type_path
  nil
end

#target_type_spec_pathObject

This method is abstract.

Subclass and implement #target_type_spec_path. Implementations of this method should return a String containing the destination path of the tests for the object being generated.



84
85
86
# File 'lib/pdk/generate/puppet_object.rb', line 84

def target_type_spec_path
  nil
end

#targetsObject

Returns an array of possible target path strings.



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/pdk/generate/puppet_object.rb', line 120

def targets
  targets = [
    target_spec_path,
    target_type_spec_path,
  ]

  unless spec_only?
    targets += [
      target_object_path,
      target_type_path,
      target_device_path,
    ]
  end

  targets.compact
end

#template_dataObject

This method is abstract.

Subclass and implement #template_data to provide data to the templates during rendering. Implementations of this method should return a Hash{Symbol => Object}.

Raises:

  • (NotImplementedError)


55
56
57
# File 'lib/pdk/generate/puppet_object.rb', line 55

def template_data
  raise NotImplementedError
end

#templatesArray<Hash{Symbol => Object}>

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.

Provides the possible template directory locations in the order in which they should be searched for a valid template.

If a template-url has been specified on in the options hash (e.g. from a CLI parameter), then this template directory will be checked first and we do not fall back to the next possible template directory.

If we have not been provided a specific template directory to use, we try the template specified in the module metadata (as set during PDK::Generate::Module) and fall back to the default template if necessary.

Returns:

  • (Array<Hash{Symbol => Object}>)

    an array of hashes. Each hash contains 3 keys: :type contains a String that describes the template directory, :url contains a String with the URL to the template directory, and :allow_fallback contains a Boolean that specifies if the lookup process should proceed to the next template directory if the template file is not in this template directory.



295
296
297
# File 'lib/pdk/generate/puppet_object.rb', line 295

def templates
  @templates ||= PDK::Util::TemplateURI.templates(@options)
end

#with_templates {|template_paths, config_hash| ... } ⇒ Object

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.

Search the possible template directories in order of preference to find a template that can be used to render a new object of the specified type.

Yield Parameters:

  • template_paths (Hash{Symbol => String})

    :object contains the path on disk to the template file for the object, :spec contains the path on disk to the template file for the tests for the object (if it exists).

  • config_hash (Hash{Object => Object})

    the contents of the :global key in the config_defaults.yml file.

Raises:



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/pdk/generate/puppet_object.rb', line 249

def with_templates
  templates.each do |template|
    if template[:uri].nil?
      PDK.logger.debug(_('No %{dir_type} template found; trying next template directory.') % { dir_type: template[:type] })
      next
    end

    PDK::Module::TemplateDir.new(PDK::Util::TemplateURI.new(template[:uri])) do |template_dir|
      template_paths = template_dir.object_template_for(object_type)

      if template_paths
        config_hash = template_dir.object_config
        yield template_paths, config_hash
        # TODO: refactor to a search-and-execute form instead
        return # work is done # rubocop:disable Lint/NonLocalExitFromIterator
      elsif template[:allow_fallback]
        PDK.logger.debug(_('Unable to find a %{type} template in %{url}; trying next template directory.') % { type: object_type, url: template[:uri] })
      else
        raise PDK::CLI::FatalError, _('Unable to find the %{type} template in %{url}.') % { type: object_type, url: template[:uri] }
      end
    end
  end
rescue ArgumentError => e
  raise PDK::CLI::ExitWithError, e
end

#write_file(dest_path) ⇒ void

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.

This method returns an undefined value.

Write the result of the block to disk.

Parameters:

  • dest_path (String)

    The path that the rendered file should be written to. Any necessary directories will be automatically created.

  • &block (String)

    The content to be written

Raises:



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/pdk/generate/puppet_object.rb', line 213

def write_file(dest_path)
  PDK.logger.info(_("Creating '%{file}' from template.") % { file: dest_path })

  file_content = yield

  begin
    FileUtils.mkdir_p(File.dirname(dest_path))
  rescue SystemCallError => e
    raise PDK::CLI::FatalError, _("Unable to create directory '%{path}': %{message}") % {
      path:    File.dirname(dest_path),
      message: e.message,
    }
  end

  PDK::Util::Filesystem.write_file(dest_path, file_content)
rescue SystemCallError => e
  raise PDK::CLI::FatalError, _("Unable to write to file '%{path}': %{message}") % {
    path:    dest_path,
    message: e.message,
  }
end