Пример #1
0
def main():

    print(f"Brownie v{__version__} - Python development framework for Ethereum\n")

    if len(sys.argv) < 2 or sys.argv[1].startswith("-"):
        # this call triggers a SystemExit
        docopt(__doc__, ["brownie", "-h"])

    cmd = sys.argv[1]
    cmd_list = [i.stem for i in Path(__file__).parent.glob("[!_]*.py")]
    if cmd not in cmd_list:
        distances = sorted([(i, levenshtein_norm(cmd, i)) for i in cmd_list], key=lambda k: k[1])
        if distances[0][1] <= 0.2:
            sys.exit(f"Invalid command. Did you mean 'brownie {distances[0][0]}'?")
        sys.exit("Invalid command. Try 'brownie --help' for available commands.")

    CONFIG.argv["cli"] = cmd
    sys.modules["brownie"].a = network.accounts
    sys.modules["brownie"].__all__.append("a")

    try:
        importlib.import_module(f"brownie._cli.{cmd}").main()
    except ProjectNotFound:
        notify("ERROR", "Brownie environment has not been initiated for this folder.")
        print("Type 'brownie init' to create the file structure.")
    except Exception as e:
        print(color.format_tb(e))
Пример #2
0
def main():
    args = docopt(__doc__)

    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound

    # ensure imports are possible from anywhere in the project
    project.main._add_to_sys_path(project_path)

    if args["<path>"] is None:
        structure_config = _load_project_structure_config(project_path)
        args["<path>"] = project_path.joinpath(
            structure_config["tests"]).as_posix()

    pytest_args = [args["<path>"]]
    for opt, value in [(i, args[i]) for i in sorted(args)
                       if i.startswith("-") and args[i]]:
        if value is True:
            pytest_args.append(opt)
        elif isinstance(value, str):
            pytest_args.extend([opt, value])

    return_code = pytest.main(pytest_args, ["pytest-brownie"])

    if return_code:
        # only exit with non-zero status to make testing easier
        sys.exit(return_code)
Пример #3
0
def main():
    args = docopt(__doc__, more_magic=True)
    _update_argv_from_docopt(args)

    active_project = None
    if project.check_for_project():
        active_project = project.load()
        active_project.load_config()
        print(f"{active_project._name} is the active project.")

    network.connect(CONFIG.argv["network"])

    path, _ = _get_path(args["<filename>"])
    path_str = path.absolute().as_posix()

    try:
        return_value, frame = run(
            args["<filename>"],
            method_name=args["<function>"] or "main",
            args=args["<arg>"],
            _include_frame=True,
        )
        exit_code = 0
    except Exception as e:
        print(color.format_tb(e))
        frame = next(
            (i.frame for i in inspect.trace()[::-1]
             if Path(i.filename).as_posix() == path_str),
            None,
        )
        if frame is None:
            # exception was an internal brownie issue - do not open the console
            sys.exit(1)
        exit_code = 1
        return_value = None

    try:
        if args["--interactive"]:
            # filter internal objects from the namespace prior to opening the console
            globals_dict = {
                k: v
                for k, v in frame.f_globals.items() if not k.startswith("__")
            }
            extra_locals = {
                "_": return_value,
                **globals_dict,
                **frame.f_locals
            }
            shell = Console(active_project, extra_locals)
            shell.interact(
                banner="\nInteractive mode enabled. Use quit() to close.",
                exitmsg="")
    finally:
        # the console terminates from a SystemExit - make sure we still deliver the final gas report
        if CONFIG.argv["gas"]:
            print("\n======= Gas profile =======")
            for line in _build_gas_profile_output():
                print(line)

        sys.exit(exit_code)
Пример #4
0
def main():
    """The main entry point of the MythX plugin for Brownie."""

    args = docopt(__doc__)
    _update_argv_from_docopt(args)

    if CONFIG.argv["mode"] not in ANALYSIS_MODES:
        raise ValidationError(
            "Invalid analysis mode: Must be one of [{}]".format(
                ", ".join(ANALYSIS_MODES)))

    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound

    build = project.load()._build
    submission = SubmissionPipeline(build)

    print("Preparing project data for submission to MythX...")
    submission.prepare_requests()

    print("Sending analysis requests to MythX...")
    submission.send_requests()

    # exit if user wants an async analysis run
    if CONFIG.argv["async"]:
        print(
            "\nAll contracts were submitted successfully. Check the dashboard at "
            "https://dashboard.mythx.io/ for the progress and results of your analyses"
        )
        return

    print("\nWaiting for results...")

    submission.wait_for_jobs()
    submission.generate_stdout_report()
    submission.generate_highlighting_report()

    # erase previous report
    report_path = project_path.joinpath(
        _load_project_structure_config(project_path)["reports"])

    report_path = report_path.joinpath("security.json")
    if report_path.exists():
        report_path.unlink()

    print_console_report(submission.stdout_report)

    # Write report to Brownie directory
    with report_path.open("w+") as fp:
        json.dump(submission.highlight_report, fp, indent=2, sort_keys=True)

    # Launch GUI if user requested it
    if CONFIG.argv["gui"]:
        print("Launching the Brownie GUI")
        gui = importlib.import_module("brownie._gui").Gui
        gui().mainloop()
Пример #5
0
def main():
    args = docopt(__doc__)
    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound
    build_path = project_path.joinpath("build/contracts")
    if args["--all"]:
        shutil.rmtree(build_path, ignore_errors=True)
    project.load(project_path)
    print(f"Brownie project has been compiled at {build_path}")
Пример #6
0
def main():
    args = docopt(__doc__)
    try:
        fn = getattr(sys.modules[__name__], f"_{args['<command>']}")
    except AttributeError:
        print("Invalid command. Try brownie networks --help")
        return
    try:
        fn(*args["<arguments>"])
    except TypeError:
        print(f"Invalid arguments for command '{args['<command>']}'. Try brownie networks --help")
        return
Пример #7
0
def main():
    args = docopt(__doc__)
    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound
    contract_artifact_path = project_path.joinpath("build/contracts")
    interface_artifact_path = project_path.joinpath("build/interfaces")
    if args["--all"]:
        shutil.rmtree(contract_artifact_path, ignore_errors=True)
        shutil.rmtree(interface_artifact_path, ignore_errors=True)
    project.load(project_path)
    print(
        f"Project has been compiled. Build artifacts saved at {contract_artifact_path}"
    )
Пример #8
0
def main():
    args = docopt(__doc__)
    _get_data_folder().joinpath("accounts").mkdir(exist_ok=True)
    try:
        fn = getattr(sys.modules[__name__], f"_{args['<command>']}")
    except AttributeError:
        print("Invalid command. Try brownie accounts --help")
        return
    try:
        fn(*args["<arguments>"])
    except TypeError:
        print(
            f"Invalid arguments for command '{args['<command>']}'. Try brownie ethpm --help"
        )
        return
Пример #9
0
def main():
    if "-h" in sys.argv or "--help" in sys.argv:
        # display the help screen and exit
        docopt(__doc__)

    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound

    # ensure imports are possible from anywhere in the project
    project.main._add_to_sys_path(project_path)

    pytest_args = sys.argv[sys.argv.index("test") + 1:]
    if not pytest_args or pytest_args[0].startswith("-"):
        structure_config = _load_project_structure_config(project_path)
        pytest_args.insert(
            0,
            project_path.joinpath(structure_config["tests"]).as_posix())

    return_code = pytest.main(pytest_args, ["pytest-brownie"])

    if return_code:
        # only exit with non-zero status to make testing easier
        sys.exit(return_code)
Пример #10
0
def main():
    args = docopt(__doc__)
    _update_argv_from_docopt(args)

    if project.check_for_project():
        active_project = project.load()
        active_project.load_config()
        print(f"{active_project._name} is the active project.")
    else:
        active_project = None
        print("No project was loaded.")

    network.connect(CONFIG.argv["network"])

    shell = Console(active_project)
    shell.interact(banner="Brownie environment is ready.", exitmsg="")
Пример #11
0
def main():
    args = docopt(__doc__)
    _update_argv_from_docopt(args)

    if project.check_for_project():
        active_project = project.load()
        active_project.load_config()
        print(f"{active_project._name} is the active project.")
    else:
        raise ProjectNotFound

    network.connect(ARGV["network"])

    run(args["<filename>"], method_name=args["<function>"] or "main")
    if ARGV["gas"]:
        _print_gas_profile()
Пример #12
0
def main():
    args = docopt(__doc__)
    _update_argv_from_docopt(args)

    if project.check_for_project():
        active_project = project.load()
        active_project.load_config()
        print(f"{active_project._name} is the active project.")
    else:
        raise ProjectNotFound

    network.connect(CONFIG.argv["network"])

    path, _ = _get_path(args["<filename>"])
    path_str = path.absolute().as_posix()

    try:
        run(args["<filename>"], method_name=args["<function>"] or "main")
    except Exception as e:
        print(color.format_tb(e))

        if args["--interactive"]:
            frame = next(
                (i.frame for i in inspect.trace()[::-1]
                 if Path(i.filename).as_posix() == path_str),
                None,
            )
            if frame is not None:
                globals_dict = {
                    k: v
                    for k, v in frame.f_globals.items()
                    if not k.startswith("__")
                }

                shell = Console(active_project, {
                    **globals_dict,
                    **frame.f_locals
                })
                shell.interact(
                    banner="\nInteractive mode enabled. Use quit() to close.",
                    exitmsg="")
        sys.exit(1)

    if CONFIG.argv["gas"]:
        print("\n======= Gas profile =======")
        for line in _build_gas_profile_output():
            print(line)
Пример #13
0
def main():
    args = docopt(__doc__)

    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound

    if args["<path>"] is None:
        args["<path>"] = project_path.joinpath("tests").as_posix()

    pytest_args = [args["<path>"]]
    for opt, value in [(i, args[i]) for i in sorted(args) if i.startswith("-") and args[i]]:
        if value is True:
            pytest_args.append(opt)
        elif isinstance(value, str):
            pytest_args.extend([opt, value])

    pytest.main(pytest_args, ["pytest-brownie"])
Пример #14
0
def main():
    args = docopt(__doc__)
    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound

    build_path = project_path.joinpath(
        _load_project_structure_config(project_path)["build"])

    contract_artifact_path = build_path.joinpath("contracts")
    interface_artifact_path = build_path.joinpath("interfaces")

    if args["--all"]:
        shutil.rmtree(contract_artifact_path, ignore_errors=True)
        shutil.rmtree(interface_artifact_path, ignore_errors=True)
    elif args["<contract>"]:
        for name in args["<contract>"]:
            path = contract_artifact_path.joinpath(f"{name}.json")
            if path.exists():
                path.unlink()

    proj = project.load()

    if args["--size"]:
        print("============ Deployment Bytecode Sizes ============")
        codesize = []
        for contract in proj:
            bytecode = contract._build["deployedBytecode"]
            if bytecode:
                codesize.append((contract._name, len(bytecode) // 2))
        indent = max(len(i[0]) for i in codesize)
        for name, size in sorted(codesize, key=lambda k: k[1], reverse=True):
            pct = size / 24577
            pct_color = color(
                next((i[1] for i in CODESIZE_COLORS if pct >= i[0]), ""))
            print(
                f"  {name:<{indent}}  -  {size:>6,}B  ({pct_color}{pct:.2%}{color})"
            )
        print()

    print(
        f"Project has been compiled. Build artifacts saved at {contract_artifact_path}"
    )
Пример #15
0
def main():
    args = docopt(__doc__)
    try:
        fn = getattr(sys.modules[__name__], f"_{args['<command>']}")
    except AttributeError:
        print("Invalid command. Try brownie ethpm --help")
        return
    project_path = check_for_project(".")
    if project_path is None:
        raise ProjectNotFound
    if not project_path.joinpath("ethpm-config.yaml").exists():
        shutil.copy(
            BROWNIE_FOLDER.joinpath("data/ethpm-config.yaml"),
            project_path.joinpath("ethpm-config.yaml"),
        )
    try:
        fn(project_path, *args["<arguments>"])
    except TypeError:
        print(
            f"Invalid arguments for command '{args['<command>']}'. Try brownie ethpm --help"
        )
        return
Пример #16
0
def main():
    args = docopt(__doc__)
    path = project.from_brownie_mix(args["<mix>"], args["<path>"],
                                    args["--force"])
    notify("SUCCESS",
           f"Brownie mix '{args['<mix>']}' has been initiated at {path}")
Пример #17
0
def main():
    args = docopt(__doc__)
    path = project.new(args["<path>"] or ".", args["--force"])
    notify("SUCCESS", f"Brownie environment has been initiated at {path}")
Пример #18
0
def main():
    docopt(__doc__)
    project.load()
    print("Loading Brownie GUI...")
    Gui().mainloop()
    print("GUI was terminated.")
Пример #19
0
def main():
    args = docopt(__doc__)
    path = project.new(args["<path>"] or ".", args["--force"], args["--force"])
    notify("SUCCESS", f"A new Brownie project has been initialized at {path}")