Class: Pfu::Parser

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

Class Method Summary collapse

Class Method Details

.parse(path) ⇒ Object



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
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/pfu/parser.rb', line 38

def self.parse(path)
  return unless File.extname(path) == '.rb'
  source = File.read(path)
  lines  = source.split("\n")

  begin
    funcname, opts, lineno = eval(source)
    
    raise 'Invalid function definition' unless (funcname and opts and lineno)
  rescue => e
    $logger.error "The function in #{path} doesn't load properly!"
    $logger.error e.message
    return nil
  end

  stripcount = case source
  when /module\s+Puppet::Parser::Functions/
    2
  when /Puppet::Parser::Functions(.|::)newfunction/
    1
  end

  block = lines[(lineno-1)..-1].join("\n")
  block.gsub!(/\A.*\|\*?\w+\|/, '')                            # remove block arg string ("|args|")
  block.gsub!(/((end|})\s*){#{stripcount}}(^#.*|\s*)*\z/, '')  # remove closing block keywords and trailing comments

  heredoc = source.match(/<<-['"]?(\w+)['"]?/)
  if heredoc
    block.gsub!(/\A.*#{heredoc[1]}/m, '')
  end

  header = lines[0...(lines.index { |l| l =~ /Puppet::Parser::Functions/ })].join("\n")
  args   = lines[lineno-1].match(/\|\s*\*?(\w+)\s*\|/)[1]

  opts[:doc]            = opts[:doc].gsub("\n", "\n#") unless opts[:doc].nil?
  opts[:name]           = funcname.to_sym
  opts[:header]         = header
  opts[:args]           = args
  opts[:implementation] = block

  opts
end