Class: HclVariables::Parser
- Inherits:
-
Object
- Object
- HclVariables::Parser
- Defined in:
- lib/hcl_variables/parser.rb
Constant Summary collapse
- COMMENT_REGEX =
/^(^|\s)#/i
Instance Method Summary collapse
-
#code ⇒ Object
The parser being used cannot handle unquoted literal type values and comments.
- #empty? ⇒ Boolean
- #fix_quotes(raw) ⇒ Object
-
#initialize(raw) ⇒ Parser
constructor
A new instance of Parser.
- #load ⇒ Object
- #quote_line(l) ⇒ Object
- #remove_comments(raw) ⇒ Object
Constructor Details
#initialize(raw) ⇒ Parser
Returns a new instance of Parser.
5 6 7 |
# File 'lib/hcl_variables/parser.rb', line 5 def initialize(raw) @raw = raw end |
Instance Method Details
#code ⇒ Object
The parser being used cannot handle unquoted literal type values and comments. Hacking it and updating the raw code as a workaround. May have to fix the parser or write a new parser.
17 18 19 20 |
# File 'lib/hcl_variables/parser.rb', line 17 def code return @code if @code @code = fix_quotes(@raw) end |
#empty? ⇒ Boolean
22 23 24 25 26 27 |
# File 'lib/hcl_variables/parser.rb', line 22 def empty? text = remove_comments(code) lines = text.split("\n") lines.reject! { |l| l.strip.empty? } lines.empty? end |
#fix_quotes(raw) ⇒ Object
39 40 41 42 43 44 45 |
# File 'lib/hcl_variables/parser.rb', line 39 def fix_quotes(raw) lines = raw.split("\n") lines.map! do |l| quote_line(l) end lines.join("\n") end |
#load ⇒ Object
9 10 11 12 |
# File 'lib/hcl_variables/parser.rb', line 9 def load return {} if empty? # Rhcl parser cannot handle empty file Rhcl.parse(code) end |
#quote_line(l) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/hcl_variables/parser.rb', line 47 def quote_line(l) return "# " if l =~ COMMENT_REGEX # return empty comment so parser wont try to parse it return l unless l =~ /type\s*=/ # just check for type return l if l =~ /type\s*=\s*['"]([a-zA-Z0-9()]+)["']/ # check quotes in the type value # Reaching here means there is probably a type value without quotes # Try to capture unquoted value so we can add quotes md = l.match(/type\s*=\s*([a-zA-Z0-9()]+)/) if md value = md[1] %Q|type = "#{value}"| else # Example: type = "list(object({ l # unable to capture quotes, passthrough as fallback end end |
#remove_comments(raw) ⇒ Object
30 31 32 33 34 35 36 37 |
# File 'lib/hcl_variables/parser.rb', line 30 def remove_comments(raw) lines = raw.split("\n") # filter out commented lines lines.reject! { |l| l =~ COMMENT_REGEX } # filter out empty lines lines.reject! { |l| l.strip.empty? } lines.join("\n") end |