Module: Lono::Template::Util

Included in:
Dsl::Builder, Erb
Defined in:
lib/lono/template/util.rb

Instance Method Summary collapse

Instance Method Details

#ensure_parent_dir(path) ⇒ Object



3
4
5
6
# File 'lib/lono/template/util.rb', line 3

def ensure_parent_dir(path)
  dir = File.dirname(path)
  FileUtils.mkdir_p(dir) unless File.exist?(dir)
end

#handle_yaml_syntax_error(e, path) ⇒ Object



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
# File 'lib/lono/template/util.rb', line 17

def handle_yaml_syntax_error(e, path)
  io = StringIO.new
  io.puts "Invalid yaml.  Output written to debugging: #{path}".color(:red)
  io.puts "ERROR: #{e.message}".color(:red)

  # Grab line info.  Example error:
  #   ERROR: (<unknown>): could not find expected ':' while scanning a simple key at line 2 column 1
  md = e.message.match(/at line (\d+) column (\d+)/)
  line = md[1].to_i

  lines = IO.read(path).split("\n")
  context = 5 # lines of context
  top, bottom = [line-context-1, 0].max, line+context-1
  spacing = lines.size.to_s.size
  lines[top..bottom].each_with_index do |line_content, index|
    line_number = top+index+1
    if line_number == line
      io.printf("%#{spacing}d %s\n".color(:red), line_number, line_content)
    else
      io.printf("%#{spacing}d %s\n", line_number, line_content)
    end
  end

  if ENV['TEST']
    io.string
  else
    puts io.string
    exit 1
  end
end

#validate_yaml(path) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/lono/template/util.rb', line 8

def validate_yaml(path)
  text = IO.read(path)
  begin
    YAML.load(text)
  rescue Psych::SyntaxError => e
    handle_yaml_syntax_error(e, path)
  end
end