Class: Lono::Yamler::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/lono/yamler/validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Validator

Returns a new instance of Validator.



3
4
5
# File 'lib/lono/yamler/validator.rb', line 3

def initialize(path)
  @path = path
end

Instance Method Details

#handle_yaml_syntax_error(e, path) ⇒ Object



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
# File 'lib/lono/yamler/validator.rb', line 20

def handle_yaml_syntax_error(e, path)
  io = StringIO.new
  io.puts "Invalid yaml. Output written for 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['LONO_TEST']
    io.string
  else
    puts io.string
    exit 1
  end
end

#validate!Object



7
8
9
# File 'lib/lono/yamler/validator.rb', line 7

def validate!
  validate_yaml(@path)
end

#validate_yaml(path) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/lono/yamler/validator.rb', line 11

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