11import click
22import json
33from pathlib import Path
4+ import itertools
45
56from .validate import validate_file
67from .io import convert as _convert
1011
1112
1213FORMATS = "json" , "lte"
13- print_latticejson = lambda obj : print ( json .dumps (obj , cls = CompactJSONEncoder , indent = 4 ) )
14+ dump_latticejson = lambda obj : json .dumps (obj , cls = CompactJSONEncoder , indent = 4 )
1415
1516
1617@click .group ()
@@ -39,7 +40,7 @@ def convert(file, from_, to):
3940 if from_ is None :
4041 from_ = path .suffix [1 :]
4142
42- print (_convert (path .read_text (), from_ , to ))
43+ click . echo (_convert (path .read_text (), from_ , to ))
4344
4445
4546@main .command ()
@@ -54,15 +55,29 @@ def validate(file):
5455def parse_elegant (file ):
5556 """Parse elegant file but do not convert to LatticeJSON."""
5657 text = Path (file ).read_text ()
57- print ( json . dumps ( _parse_elegant (text ), cls = CompactJSONEncoder , indent = 4 ))
58+ click . echo ( dump_latticejson ( _parse_elegant (text )))
5859
5960
6061@main .command ()
61- @click .argument ("file" , type = click .Path (exists = True ))
62- def autoformat (file ):
62+ @click .argument ("files" , nargs = - 1 , type = click .Path (exists = True ))
63+ @click .option (
64+ "--dry-run" ,
65+ "-d" ,
66+ is_flag = True ,
67+ help = "Don't write the files back, just output the formatted files." ,
68+ )
69+ def autoformat (files , dry_run ):
6370 """Format a LatticeJSON file."""
64- latticejson = json .loads (Path (file ).read_text ())
65- print (json .dumps (latticejson , cls = CompactJSONEncoder , indent = 4 ))
71+ for path in itertools .chain .from_iterable (
72+ path .rglob ("*.json" ) if path .is_dir () else (path ,) for path in map (Path , files )
73+ ):
74+ latticejson = json .loads (path .read_text ())
75+ formatted = dump_latticejson (latticejson )
76+ click .secho (f"reformatted { path } " , bold = True )
77+ if dry_run :
78+ click .echo (formatted )
79+ else :
80+ path .write_text (formatted )
6681
6782
6883@main .command ()
@@ -74,5 +89,5 @@ def migrate(file, from_, to):
7489 text = Path (file ).read_text ()
7590 initial_version = from_ .split ("." )
7691 final_version = to .split ("." )
77- res = _migrate (json .loads (text ), initial_version , final_version )
78- print ( json . dumps ( res , cls = CompactJSONEncoder , indent = 4 ))
92+ latticejson = _migrate (json .loads (text ), initial_version , final_version )
93+ click . echo ( dump_latticejson ( latticejson ))
0 commit comments