Ejemplo n.º 1
0
def check_for_project(path: Union[Path, str] = ".") -> Optional[Path]:
    """Checks for a Brownie project."""
    path = Path(path).resolve()
    for folder in [path] + list(path.parents):

        structure_config = _load_project_structure_config(folder)
        contracts = folder.joinpath(structure_config["contracts"])
        interfaces = folder.joinpath(structure_config["interfaces"])
        scripts = folder.joinpath(structure_config["scripts"])
        tests = folder.joinpath(structure_config["tests"])

        if next(
            (i for i in contracts.glob("**/*") if i.suffix in (".vy", ".sol")),
                None):
            return folder
        if next((i for i in interfaces.glob("**/*")
                 if i.suffix in (".json", ".vy", ".sol")), None):
            return folder
        if next((i for i in scripts.glob("**/*") if i.suffix in (".py")),
                None):
            return folder
        if contracts.is_dir() and tests.is_dir():
            return folder

    return None
Ejemplo n.º 2
0
def _create_folders(project_path: Path) -> None:
    structure = _load_project_structure_config(project_path)
    for path in structure.values():
        project_path.joinpath(path).mkdir(exist_ok=True)
    build_path = project_path.joinpath(structure["build"])
    for path in BUILD_FOLDERS:
        build_path.joinpath(path).mkdir(exist_ok=True)
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
    def __init__(self, name: str, project_path: Path) -> None:
        self._path: Path = project_path
        self._structure = _load_project_structure_config(project_path)
        self._build_path: Path = project_path.joinpath(self._structure["build"])

        self._name = name
        self._active = False
        self.load()
Ejemplo n.º 5
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()
Ejemplo n.º 6
0
    def __init__(self, name: str, project_path: Path) -> None:
        self._path: Path = project_path
        self._envvars = _load_project_envvars(project_path)
        self._structure = expand_posix_vars(
            _load_project_structure_config(project_path), self._envvars)
        self._build_path: Path = project_path.joinpath(
            self._structure["build"])

        self._name = name
        self._active = False
        self.load()
Ejemplo n.º 7
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)

    project.load()
    print(f"Project has been compiled. Build artifacts saved at {contract_artifact_path}")
Ejemplo n.º 8
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}"
    )
Ejemplo n.º 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)