Class: Pfu::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/pfu/generator.rb

Class Method Summary collapse

Class Method Details

.write(opts) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
# File 'lib/pfu/generator.rb', line 5

def self.write(opts)
  newpath  = "lib/puppet/functions/#{opts[:namespace]}/#{opts[:name]}.rb"
  specpath = "spec/functions/#{opts[:namespace]}_#{opts[:name]}_spec.rb"

  [newpath, specpath].each do |path|
    next unless File.exist?(path)
    $logger.error "Cowardly refusing to overwrite #{path}"
    return
  end

  opts[:fullname] = case opts[:namespace]
  when '', nil
    opts[:name]
  else
    "#{opts[:namespace]}::#{opts[:name]}"
  end

  template = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'function.erb')
  contents = ERB.new(File.read(template), nil, '-').result(binding)

  template = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'function_spec.erb')
  specfile = ERB.new(File.read(template), nil, '-').result(binding)

  $logger.info "Creating #{newpath}"
  $logger.debug "Function contents:\n#{contents}"

  begin
    # syntax check the code before writing it
    # TODO: validate that it actually creates a puppet function
    RubyVM::InstructionSequence.compile(contents)

    FileUtils.mkdir_p("lib/puppet/functions/#{opts[:namespace]}")
    File.write(newpath, contents)

    FileUtils.mkdir_p("spec/functions")
    File.write(specpath, specfile)

    return true
  rescue Exception => e
    $logger.error "Oh crap; the generated function isn't valid Ruby code!"
    $logger.error e.message
    $logger.debug e.backtrace.join("\n")
    return false
  end

end