Class: Kubes::Compiler::Strategy::Erb::YamlError

Inherits:
Object
  • Object
show all
Includes:
Util::SaveFile
Defined in:
lib/kubes/compiler/strategy/erb/yaml_error.rb

Instance Method Summary collapse

Methods included from Util::SaveFile

#save_file

Constructor Details

#initialize(path, rendered_yaml) ⇒ YamlError

Returns a new instance of YamlError.



5
6
7
# File 'lib/kubes/compiler/strategy/erb/yaml_error.rb', line 5

def initialize(path, rendered_yaml)
  @path, @rendered_yaml = path, rendered_yaml
end

Instance Method Details

#destObject



15
16
17
18
# File 'lib/kubes/compiler/strategy/erb/yaml_error.rb', line 15

def dest
  save_file = save_file(@path)
  "#{Kubes.root}/.kubes/output/#{save_file}"
end

#handle_yaml_syntax_error(e, path) ⇒ Object



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
# File 'lib/kubes/compiler/strategy/erb/yaml_error.rb', line 29

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['KUBES_TEST']
    io.string
  else
    puts io.string
    exit 1
  end
end

#showObject



9
10
11
12
13
# File 'lib/kubes/compiler/strategy/erb/yaml_error.rb', line 9

def show
  FileUtils.mkdir_p(File.dirname(dest))
  IO.write(dest, @rendered_yaml)
  show_error(dest)
end

#show_error(path) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/kubes/compiler/strategy/erb/yaml_error.rb', line 20

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