33This script recursively converts hcl2 files to json
44
55Usage:
6- hcl2tojson PATH OUT_PATH
6+ hcl2tojson [-s] PATH [ OUT_PATH]
77
88Options:
9+ -s Skip un-parsable files
910 PATH The path to convert
1011 OUT_PATH The path to write files to
1112"""
1213import json
14+ import sys
1315import os
1416
1517from docopt import docopt
1618
1719from hcl2 import load
1820from hcl2 .parser import hcl2
1921from hcl2 .version import __version__
22+ from lark import UnexpectedToken
2023
2124if __name__ == '__main__' :
2225 arguments = docopt (__doc__ , version = __version__ )
26+ skip = arguments ["-s" ]
2327 in_path = arguments ["PATH" ]
2428 out_path = arguments ["OUT_PATH" ]
2529 if os .path .isfile (in_path ):
26- with open (in_path , 'r' ) as in_file , open (out_path , 'w' ) as out_file :
27- print (in_path )
30+ with open (in_path , 'r' ) as in_file :
31+ out_file = sys .stdout if out_path is None else open (out_path , 'w' )
32+ print (in_path , file = sys .stderr , flush = True )
2833 json .dump (hcl2 .parse (in_file .read ()), out_file )
34+ if out_path is None :
35+ out_file .write ('\n ' )
36+ out_file .close ()
2937 elif os .path .isdir (in_path ):
3038 processed_files = set ()
39+ if out_path is None :
40+ raise RuntimeError ("Positional OUT_PATH parameter shouldn't be empty" )
41+ if not os .path .exists (out_path ):
42+ os .mkdir (out_path )
3143 for current_dir , dirs , files in os .walk (in_path ):
3244 dir_prefix = os .path .commonpath ([in_path , current_dir ])
33- relative_current_dir = current_dir .replace (dir_prefix , '' )
34- current_out_path = os .path .join (out_path , relative_current_dir )
45+ relative_current_dir = os .path .relpath (current_dir , dir_prefix )
46+ current_out_path = os .path .normpath (os .path .join (out_path , relative_current_dir ))
47+ if not os .path .exists (current_out_path ):
48+ os .mkdir (current_out_path )
3549 for file_name in files :
3650 in_file_path = os .path .join (current_dir , file_name )
3751 out_file_path = os .path .join (current_out_path , file_name )
@@ -44,8 +58,15 @@ if __name__ == '__main__':
4458 processed_files .add (in_file_path )
4559 processed_files .add (out_file_path )
4660
47- with open (in_file_path , 'r' ) as in_file , open (out_file_path , 'w' ) as out_file :
48- print (in_file_path )
49- json .dump (load (in_file ), out_file )
61+ with open (in_file_path , 'r' ) as in_file :
62+ print (in_file_path , file = sys .stderr , flush = True )
63+ try :
64+ parsed_data = load (in_file )
65+ except UnexpectedToken :
66+ if skip :
67+ continue
68+ raise
69+ with open (out_file_path , 'w' ) as out_file :
70+ json .dump (parsed_data , out_file )
5071 else :
5172 raise RuntimeError ('Invalid Path %s' , in_path )
0 commit comments