Skip to content
40 changes: 36 additions & 4 deletions lkml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def parse_args(args: Sequence) -> argparse.Namespace:
)
)
parser.add_argument(
"file", type=argparse.FileType("r"), help="path to the LookML file to parse"
"file", type=argparse.FileType("r+"), help="path to the LookML file to parse"
)
parser.add_argument(
"-v",
Expand All @@ -96,6 +96,27 @@ def parse_args(args: Sequence) -> argparse.Namespace:
help="increase logging verbosity to debug",
)

group = parser.add_mutually_exclusive_group()
group.add_argument(
"--json",
action="store_true",
default=True,
help="return a JSON string (default)",
)
group.add_argument(
"--lookml",
action="store_true",
default=False,
help="return a LookML string",
)
group.add_argument(
"-f",
"--format",
action="store_true",
default=False,
help="parse and write back to the LookML file",
)

return parser.parse_args(args)


Expand All @@ -117,7 +138,18 @@ def cli():
logging.getLogger().setLevel(args.log_level)

result: dict = load(args.file)
args.file.close()

json_string = json.dumps(result, indent=2)
print(json_string)
try:
if args.format:
args.file.seek(0)
dump(result, args.file)
args.file.truncate()
elif args.lookml:
lookml_string = dump(result)
print(lookml_string)
elif args.json:
json_string = json.dumps(result, indent=2)
print(json_string)

finally:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FileType objects dont work with context managers, this makes sure the file is closed even if they cannot be parsed.

args.file.close()