Skip to content

Commit 4b14bf5

Browse files
Better autoformat (#26)
* autoformat multiple files at once * add newline at end of file
1 parent b00b1c7 commit 4b14bf5

File tree

2 files changed

+32
-17
lines changed

2 files changed

+32
-17
lines changed

latticejson/cli.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import click
22
import json
33
from pathlib import Path
4+
import itertools
45

56
from .validate import validate_file
67
from .io import convert as _convert
@@ -10,7 +11,7 @@
1011

1112

1213
FORMATS = "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):
5455
def 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))

latticejson/format.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22

33

44
class CompactJSONEncoder(json.JSONEncoder):
5-
"""A JSON Encoder which only indents the first two level."""
5+
"""A JSON Encoder which only indents the first two levels."""
66

77
def encode(self, obj, level=0):
8-
if isinstance(obj, (list, tuple)):
9-
return f"[{', '.join(json.dumps(el) for el in obj)}]"
10-
elif isinstance(obj, dict) and level < 2:
11-
indent = (level + 1) * self.indent * " "
12-
items = ",\n".join(
13-
f"{indent}{json.dumps(key)}: {self.encode(value, level=level+1)}"
8+
if isinstance(obj, dict) and level < 2:
9+
items_indent = (level + 1) * self.indent * " "
10+
items_string = ",\n".join(
11+
f"{items_indent}{json.dumps(key)}: {self.encode(value, level=level+1)}"
1412
for key, value in obj.items()
1513
)
16-
return f"{{\n{items}\n{level * self.indent * ' '}}}"
14+
dict_indent = level * self.indent * " "
15+
newline = "\n" if level == 0 else ""
16+
return f"{{\n{items_string}\n{dict_indent}}}{newline}"
1717
else:
1818
return json.dumps(obj)

0 commit comments

Comments
 (0)