88import sys
99from typing import Any , List , Optional , Tuple
1010
11+ from hcl2 .version import __version__
12+
1113from hcl2 .query ._base import NodeView
12- from hcl2 .utils import SerializationOptions
1314from hcl2 .query .body import DocumentView
1415from hcl2 .query .introspect import build_schema , describe_results
1516from hcl2 .query .path import QuerySyntaxError
1617from hcl2 .query .pipeline import classify_stage , execute_pipeline , split_pipeline
1718from hcl2 .query .resolver import resolve_path
1819from hcl2 .query .safe_eval import (
19- UnsafeExpressionError ,
2020 _SAFE_CALLABLE_NAMES ,
21+ UnsafeExpressionError ,
2122 safe_eval ,
2223)
23- from hcl2 .version import __version__
24+ from hcl2 .utils import SerializationOptions
25+
2426from .helpers import _expand_file_args # noqa: F401 — re-exported for tests
2527
2628# ---------------------------------------------------------------------------
@@ -171,9 +173,7 @@ def _collect_files(path: str) -> List[str]:
171173def _error (msg : str , use_json : bool , ** extra ) -> str :
172174 """Format an error message."""
173175 if use_json :
174- return json .dumps (
175- {"error" : extra .get ("error_type" , "error" ), "message" : msg , ** extra }
176- )
176+ return json .dumps ({"error" : extra .get ("error_type" , "error" ), "message" : msg , ** extra })
177177 return f"Error: { msg } "
178178
179179
@@ -347,17 +347,12 @@ def format_result(self, result: Any) -> str:
347347 def format_list (self , items : list ) -> str :
348348 """Format a list result (e.g. from hybrid mode returning a list)."""
349349 if self .output_json :
350- converted = [
351- _convert_for_json (item , options = self .serialization_options )
352- for item in items
353- ]
350+ converted = [_convert_for_json (item , options = self .serialization_options ) for item in items ]
354351 return json .dumps (converted , indent = self .json_indent , default = str )
355352 parts = []
356353 for item in items :
357354 if isinstance (item , NodeView ):
358- parts .append (
359- item .to_hcl () if not self .output_value else str (item .to_dict ())
360- )
355+ parts .append (item .to_hcl () if not self .output_value else str (item .to_dict ()))
361356 else :
362357 parts .append (str (item ))
363358 if not self .output_value :
@@ -367,10 +362,7 @@ def format_list(self, items: list) -> str:
367362 def format_output (self , results : List [Any ]) -> str :
368363 """Format results for final output."""
369364 if self .output_json and len (results ) > 1 :
370- items = [
371- _convert_for_json (item , options = self .serialization_options )
372- for item in results
373- ]
365+ items = [_convert_for_json (item , options = self .serialization_options ) for item in results ]
374366 return json .dumps (items , indent = self .json_indent , default = str )
375367 return "\n " .join (self .format_result (r ) for r in results )
376368
@@ -427,9 +419,7 @@ def emit(self, results: List[Any], file_path: str) -> None:
427419
428420 # JSON + multi — accumulate for merged output
429421 if self .config .output_json and self .multi :
430- self ._accumulator .extend (
431- _convert_results (results , file_path , self .multi , self .config )
432- )
422+ self ._accumulator .extend (_convert_results (results , file_path , self .multi , self .config ))
433423 return
434424
435425 # Single-file output (with_location or default)
@@ -458,12 +448,8 @@ def flush(self) -> None:
458448 """Sort and emit accumulated JSON results."""
459449 if not self ._accumulator :
460450 return
461- self ._accumulator .sort (
462- key = lambda x : x .get ("__file__" , "" ) if isinstance (x , dict ) else ""
463- )
464- print (
465- json .dumps (self ._accumulator , indent = self .config .json_indent , default = str )
466- )
451+ self ._accumulator .sort (key = lambda x : x .get ("__file__" , "" ) if isinstance (x , dict ) else "" )
452+ print (json .dumps (self ._accumulator , indent = self .config .json_indent , default = str ))
467453 self ._accumulator .clear ()
468454
469455
@@ -543,9 +529,7 @@ def _process_file(args_tuple):
543529 return (file_path , EXIT_SUCCESS , converted , None )
544530
545531
546- def _run_diff (
547- file1 : str , file2 : str , use_json : bool , json_indent : Optional [int ]
548- ) -> int :
532+ def _run_diff (file1 : str , file2 : str , use_json : bool , json_indent : Optional [int ]) -> int :
549533 """Run structural diff between two HCL files.
550534
551535 Returns an exit code: 0 if files are identical, 1 if they differ.
@@ -554,9 +538,7 @@ def _run_diff(
554538 import hcl2
555539 from hcl2 .query .diff import diff_dicts , format_diff_json , format_diff_text
556540
557- opts = SerializationOptions (
558- with_comments = False , with_meta = False , explicit_blocks = True
559- )
541+ opts = SerializationOptions (with_comments = False , with_meta = False , explicit_blocks = True )
560542 for path in (file1 , file2 ):
561543 if path == "-" :
562544 continue
@@ -630,9 +612,7 @@ def _build_parser() -> argparse.ArgumentParser:
630612
631613 output_group = parser .add_mutually_exclusive_group ()
632614 output_group .add_argument ("--json" , action = "store_true" , help = "Output as JSON" )
633- output_group .add_argument (
634- "--value" , action = "store_true" , help = "Output raw value only"
635- )
615+ output_group .add_argument ("--value" , action = "store_true" , help = "Output raw value only" )
636616 output_group .add_argument (
637617 "--raw" ,
638618 action = "store_true" ,
@@ -796,9 +776,7 @@ def _execute_and_emit(
796776 output_config : OutputConfig ,
797777) -> int :
798778 """Execute queries across files and emit results. Returns an exit code."""
799- file_paths = [
800- fp for fa in _expand_file_args (args .FILE ) for fp in _collect_files (fa )
801- ]
779+ file_paths = [fp for fa in _expand_file_args (args .FILE ) for fp in _collect_files (fa )]
802780 any_results = False
803781 worst_exit = EXIT_SUCCESS
804782 multi = len (file_paths ) > 1
@@ -816,14 +794,9 @@ def _execute_and_emit(
816794 with OutputSink (output_config , multi ) as sink :
817795 if use_parallel :
818796 n_workers = args .jobs or min (os .cpu_count () or 1 , len (file_paths ))
819- worker_args = [
820- (fp , query , False , args .QUERY , multi , output_config )
821- for fp in file_paths
822- ]
797+ worker_args = [(fp , query , False , args .QUERY , multi , output_config ) for fp in file_paths ]
823798 with multiprocessing .Pool (n_workers ) as pool :
824- for fp , exit_code , converted , error_msg in pool .imap_unordered (
825- _process_file , worker_args
826- ):
799+ for fp , exit_code , converted , error_msg in pool .imap_unordered (_process_file , worker_args ):
827800 if error_msg :
828801 etype = _EXIT_TO_ERROR_TYPE .get (exit_code , "error" )
829802 print (
@@ -838,9 +811,7 @@ def _execute_and_emit(
838811 sink .emit_converted (converted )
839812 else :
840813 for file_path in file_paths :
841- results , exit_code = _run_query_on_file (
842- file_path , query , args .eval , use_json , args .QUERY
843- )
814+ results , exit_code = _run_query_on_file (file_path , query , args .eval , use_json , args .QUERY )
844815 if results is None :
845816 worst_exit = max (worst_exit , exit_code )
846817 continue
0 commit comments