Class: PDK::Module::Convert

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

Direct Known Subclasses

Update

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(module_dir, options = {}) ⇒ Convert

Returns a new instance of Convert.



12
13
14
15
# File 'lib/pdk/module/convert.rb', line 12

def initialize(module_dir, options = {})
  @module_dir = module_dir
  @options = options
end

Instance Attribute Details

#module_dirObject (readonly)

Returns the value of attribute module_dir.



10
11
12
# File 'lib/pdk/module/convert.rb', line 10

def module_dir
  @module_dir
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/pdk/module/convert.rb', line 10

def options
  @options
end

Class Method Details

.invoke(module_dir, options) ⇒ Object



6
7
8
# File 'lib/pdk/module/convert.rb', line 6

def self.invoke(module_dir, options)
  new(module_dir, options).run
end

Instance Method Details

#add_tests!Object



120
121
122
123
124
125
126
127
128
129
130
# File 'lib/pdk/module/convert.rb', line 120

def add_tests!
  update_manager.clear!
  stage_tests!(update_manager)

  if update_manager.changes?
    update_manager.sync_changes!
    print_summary
  else
    PDK::Report.default_target.puts('No test changes required.')
  end
end

#add_tests?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/pdk/module/convert.rb', line 76

def add_tests?
  options[:'add-tests']
end

#adding_tests?Boolean

Returns:

  • (Boolean)


80
81
82
# File 'lib/pdk/module/convert.rb', line 80

def adding_tests?
  add_tests? && missing_tests?
end

#available_test_generatorsObject



88
89
90
91
92
93
94
95
96
97
# File 'lib/pdk/module/convert.rb', line 88

def available_test_generators
  # Only select generators which can run and have no pre-existing files
  test_generators.select do |gen|
    if gen.can_run?
      gen.template_files.none? { |_, dst_path| PDK::Util::Filesystem.exist?(File.join(gen.context.root_path, dst_path)) }
    else
      false
    end
  end
end

#convert?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/pdk/module/convert.rb', line 17

def convert?
  instance_of?(PDK::Module::Convert)
end

#force?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/pdk/module/convert.rb', line 72

def force?
  options[:force]
end

#full_report(path) ⇒ Object



263
264
265
266
267
268
269
270
# File 'lib/pdk/module/convert.rb', line 263

def full_report(path)
  require 'pdk/report'

  report = ["/* Report generated by PDK at #{Time.now} */"]
  report.concat(update_manager.changes[:modified].map { |_, diff| "\n\n\n#{diff}" })
  PDK::Util::Filesystem.write_file(path, report.join)
  PDK::Report.default_target.puts(format("\nYou can find a report of differences in %{path}.\n\n", path: path))
end

#generate_banner(text, width = 80) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
# File 'lib/pdk/module/convert.rb', line 272

def generate_banner(text, width = 80)
  padding = width - text.length
  banner = ''
  padding_char = '-'

  (padding / 2.0).ceil.times { banner << padding_char }
  banner << text
  (padding / 2.0).floor.times { banner << padding_char }

  banner
end

#missing_tests?Boolean

Returns:

  • (Boolean)


84
85
86
# File 'lib/pdk/module/convert.rb', line 84

def missing_tests?
  !available_test_generators.empty?
end

#noop?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/pdk/module/convert.rb', line 68

def noop?
  options[:noop]
end


255
256
257
258
259
260
261
# File 'lib/pdk/module/convert.rb', line 255

def print_result(banner_text)
  require 'pdk/report'

  PDK::Report.default_target.puts(format("\n%{banner}", banner: generate_banner(banner_text, 40)))
  summary_to_print = summary.filter_map { |k, v| "#{v.length} files #{k}" unless v.empty? }
  PDK::Report.default_target.puts(format("\n%{summary}\n\n", summary: "#{summary_to_print.join(', ')}."))
end


239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/pdk/module/convert.rb', line 239

def print_summary
  require 'pdk/report'

  footer = false

  summary.each_key do |category|
    next if summary[category].empty?

    PDK::Report.default_target.puts(format("\n%{banner}", banner: generate_banner("Files to be #{category}", 40)))
    PDK::Report.default_target.puts(summary[category])
    footer = true
  end

  PDK::Report.default_target.puts(format("\n%{banner}", banner: generate_banner('', 40))) if footer
end

#runObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
# File 'lib/pdk/module/convert.rb', line 21

def run
  stage_changes!

  unless update_manager.changes?
    if adding_tests?
      add_tests!
      print_result 'Convert completed'
    else
      require 'pdk/report'

      PDK::Report.default_target.puts('No changes required.')
    end

    return
  end

  print_summary

  full_report('convert_report.txt') unless update_manager.changes[:modified].empty?

  return if noop?

  unless force?
    require 'pdk/cli/util'

    PDK.logger.info 'Module conversion is a potentially destructive action. ' \
                    'Ensure that you have committed your module to a version control ' \
                    'system or have a backup, and review the changes above before continuing.'
    continue = PDK::CLI::Util.prompt_for_yes('Do you want to continue and make these changes to your module?')
    return unless continue
  end

  # Remove these files straight away as these changes are not something
  # that the user needs to review.
  update_manager.unlink_file('Gemfile.lock')
  update_manager.unlink_file(File.join('.bundle', 'config'))

  update_manager.sync_changes!

  require 'pdk/util/bundler'
  PDK::Util::Bundler.ensure_bundle!

  add_tests! if adding_tests?

  print_result 'Convert completed'
end

#stage_changes!(context = PDK.context) ⇒ 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
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/pdk/module/convert.rb', line 132

def stage_changes!(context = PDK.context)
  require 'pdk/util/filesystem'

   = File.join(module_dir, 'metadata.json')

  PDK::Template.with(template_uri, context) do |template_dir|
     = (, template_dir.)
    if options[:noop] && .nil?
      update_manager.add_file(, '')
    elsif PDK::Util::Filesystem.file?()
      update_manager.modify_file(, .to_json)
    else
      update_manager.add_file(, .to_json)
    end

    # new_metadata == nil when creating a new module but with --noop@
    module_name = .nil? ? 'new-module' : .data['name']
     = .nil? ? {} : .data

    template_dir.render_new_module(module_name, ) do |relative_file_path, file_content, file_status|
      absolute_file_path = File.join(module_dir, relative_file_path)
      case file_status
      when :unmanage
        PDK.logger.debug(format("skipping '%{path}'", path: absolute_file_path))
      when :delete
        update_manager.remove_file(absolute_file_path)
      when :init
        update_manager.add_file(absolute_file_path, file_content) if convert? && !PDK::Util::Filesystem.exist?(absolute_file_path)
      when :manage
        if PDK::Util::Filesystem.exist?(absolute_file_path)
          update_manager.modify_file(absolute_file_path, file_content)
        else
          update_manager.add_file(absolute_file_path, file_content)
        end
      end
    end
  end
rescue ArgumentError => e
  raise PDK::CLI::ExitWithError, e
end

#stage_tests!(manager) ⇒ Object



113
114
115
116
117
118
# File 'lib/pdk/module/convert.rb', line 113

def stage_tests!(manager)
  available_test_generators.each do |gen|
    gen.stage_changes(manager)
  end
  manager
end

#summaryObject



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/pdk/module/convert.rb', line 220

def summary
  summary = {}
  update_manager.changes.each do |category, update_category|
    if update_category.respond_to?(:keys)
      updated_files = update_category.keys
    else
      begin
        updated_files = update_category.map { |file| file[:path] }
      rescue TypeError
        updated_files = update_category.to_a
      end
    end

    summary[category] = updated_files
  end

  summary
end

#template_uriObject



179
180
181
182
183
# File 'lib/pdk/module/convert.rb', line 179

def template_uri
  require 'pdk/util/template_uri'

  @template_uri ||= PDK::Util::TemplateURI.new(options)
end

#test_generators(context = PDK.context) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/pdk/module/convert.rb', line 99

def test_generators(context = PDK.context)
  return @test_generators unless @test_generators.nil?

  require 'pdk/util/puppet_strings'

  test_gens = PDK::Util::PuppetStrings.all_objects.map do |generator, objects|
    (objects || []).map do |obj|
      generator.new(context, obj['name'], spec_only: true)
    end
  end

  @test_generators = test_gens.flatten
end

#update_managerObject



173
174
175
176
177
# File 'lib/pdk/module/convert.rb', line 173

def update_manager
  require 'pdk/module/update_manager'

  @update_manager ||= PDK::Module::UpdateManager.new
end

#update_metadata(metadata_path, template_metadata) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/pdk/module/convert.rb', line 185

def (, )
  require 'pdk/generate/module'
  require 'pdk/util/filesystem'
  require 'pdk/module/metadata'

  if PDK::Util::Filesystem.file?()
    raise PDK::CLI::ExitWithError, format('Unable to update module metadata; %{path} exists but it is not readable.', path: ) unless PDK::Util::Filesystem.readable?()

    begin
       = PDK::Module::Metadata.from_file()
      new_values = PDK::Module::Metadata::DEFAULTS.select do |key, _|
        !.data.key?(key) || .data[key].nil? ||
          (key == 'requirements' && .data[key].empty?)
      end
      .update!(new_values)
    rescue ArgumentError
       = PDK::Generate::Module.(options) unless options[:noop]
    end
  elsif PDK::Util::Filesystem.exist?()
    raise PDK::CLI::ExitWithError, format('Unable to update module metadata; %{path} exists but it is not a file.', path: )
  else
    return if options[:noop]

    project_dir = File.basename(Dir.pwd)
    options[:module_name] = project_dir.split('-', 2).compact[-1]
    options[:prompt] = false
    options[:'skip-interview'] = true if options[:force]

     = PDK::Generate::Module.(options)
  end

  .update!()
  
end