#!/usr/bin/env python3 import click import json import pprint with open('data.json', 'r') as DATA_JSON: data=DATA_JSON.read() try: dsp_data = json.loads(data) except ValueError as e: click.echo("Error: %s"% e) @click.group() def cli(): pass @cli.command() def verify(): """verify your data.json""" try: dsp_data = json.loads(data) except ValueError as e: click.echo("Error: %s"% e) else: click.echo("Your data seems to be good.") @cli.command() @click.argument('item') def tree(item): """ Show the requirement tree of an item. Pass the item down lowercase, space replaced with a "_" underscore and MKII and mk3. Example: $dsp_calc tree sorter_mk3 """ click.echo(json.dumps(get_required(item), indent=4)) def get_required(item_name): """Function that returns the entire requirements of an item""" dsp_data_combined = get_combined_data(dsp_data) required_items = {} item = dsp_data_combined[item_name] if "requires" not in item and "recipes" not in item: return {} if item.get("recipes"): required_items["recipes"] = {} for i in item["recipes"]: for req_name, amount in i["requires"].items(): sub_req = get_required(req_name) required_items["recipes"][req_name] = {**dsp_data_combined[req_name], "amount": amount, "requires": sub_req } return required_items for req_name, amount in item["requires"].items(): sub_req = get_required(req_name) required_items[req_name] = {**dsp_data_combined[req_name], "amount": amount, "requires": sub_req} return required_items def get_combined_data(data): combined = data["components"] combined.update(data["buildings"]) return combined def get_item(item): if dsp_data["components"].get(item): return dsp_data["components"].get(item) elif dsp_data["buildings"].get(item): return dsp_data["buildings"].get(item) else: click.echo("Item %s not found!" % item) if __name__ == '__main__': cli()