virtuald / pyhcl

HCL is a configuration language. pyhcl is a python parser for it.
Mozilla Public License 2.0
335 stars 60 forks source link

pyhcl throws a ValueError when parsing the empty string #54

Closed alexwlchan closed 4 years ago

alexwlchan commented 5 years ago

If you try to parse an empty string (or in my case, an empty file), you get an error. Here’s a minimal example:

import hcl

print(hcl.loads(""))

This is the error it throws:

Traceback (most recent call last):
  File "r.py", line 3, in <module>
    print(hcl.loads(""))
  File "/Users/alexwlchan/.virtualenvs/tempenv-7c5b148003b76/lib/python3.6/site-packages/hcl/api.py", line 65, in loads
    if isHcl(s):
  File "/Users/alexwlchan/.virtualenvs/tempenv-7c5b148003b76/lib/python3.6/site-packages/hcl/api.py", line 42, in isHcl
    raise ValueError("No HCL object could be decoded")
ValueError: No HCL object could be decoded

I think this could be returned as {} and not throw an exception. I haven’t checked what the Golang parser does here.

Package versions:

$ pip freeze
ply==3.11
pyhcl==0.3.12
bgehman commented 5 years ago

JSON

>>> import json
>>> print(json.loads(""))
Traceback (most recent call last):
...
"/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

YAML

>>> import yaml
>>> print(yaml.safe_load(""))
None

An Exception, or None seems to be most appropriate. Definitely not {} though (in my opinion).

alexwlchan commented 5 years ago

The empty string isn’t a valid JSON object, but I think it might be valid HCL.

If I create an empty main.tf file in a directory and run terraform plan (which is how I usually interact with HCL), it runs fine. That’s how I uncovered this – one of my Terraform modules has an empty file which Terraform is happy to work with, but pyhcl didn't like.

robeden commented 4 years ago

Fixed in PR #68