Beispiel #1
0
def load(
    project_path: Union[Path, str, None] = None,
    name: Optional[str] = None,
    raise_if_loaded: bool = True,
) -> "Project":
    """Loads a project and instantiates various related objects.

    Args:
        project_path: Path of the project to load. If None, will attempt to
                      locate a project using check_for_project()
        name: Name to assign to the project. If None, the name is generated
              from the name of the project folder

    Returns a Project object.
    """
    # checks
    if project_path is None:
        project_path = check_for_project(".")
        if project_path is not None and project_path != Path(".").absolute():
            warnings.warn(
                f"Loaded project has a root folder of '{project_path}' "
                "which is different from the current working directory",
                BrownieEnvironmentWarning,
            )
    else:
        project_path = Path(project_path)
        if project_path.resolve() != check_for_project(project_path):
            packages_path = _get_data_folder().joinpath("packages")
            if not project_path.is_absolute() and packages_path.joinpath(
                    project_path).exists():
                project_path = packages_path.joinpath(project_path)
            else:
                project_path = None

    if project_path is None:
        raise ProjectNotFound("Could not find Brownie project")

    project_path = Path(project_path).resolve()
    if name is None:
        name = project_path.name
        if not name.lower().endswith("project"):
            name += " project"
        if not name[0].isalpha():
            raise BadProjectName(
                "Project must start with an alphabetic character")
        name = "".join(i for i in name.title() if i.isalnum())

    for loaded_project in _loaded_projects:
        if loaded_project._name == name:
            if raise_if_loaded:
                raise ProjectAlreadyLoaded(
                    "There is already a project loaded with this name")
            return loaded_project

    # paths
    _create_folders(project_path)
    _add_to_sys_path(project_path)

    # load sources and build
    return Project(name, project_path)
Beispiel #2
0
def load(project_path: Union[Path, str, None] = None,
         name: Optional[str] = None) -> "Project":
    """Loads a project and instantiates various related objects.

    Args:
        project_path: Path of the project to load. If None, will attempt to
                      locate a project using check_for_project()
        name: Name to assign to the project. If None, the name is generated
              from the name of the project folder

    Returns a Project object.
    """
    # checks
    if project_path is None:
        project_path = check_for_project(".")
    if not project_path or not _get_project_config_path(Path(project_path)):
        raise ProjectNotFound("Could not find Brownie project")

    project_path = Path(project_path).resolve()
    if name is None:
        name = project_path.name
        if not name.lower().endswith("project"):
            name += " project"
        name = "".join(i for i in name.title() if i.isalpha())
    if next((True for i in _loaded_projects if i._name == name), False):
        raise ProjectAlreadyLoaded(
            "There is already a project loaded with this name")

    # paths
    _create_folders(project_path)
    _add_to_sys_path(project_path)

    # load sources and build
    return Project(name, project_path)
Beispiel #3
0
    def load(self) -> None:
        """Compiles the project contracts, creates ContractContainer objects and
        populates the namespace."""
        if self._active:
            raise ProjectAlreadyLoaded("Project is already active")

        self._compiler_config = _load_project_compiler_config(self._path)

        # compile updated sources, update build
        changed = self._get_changed_contracts()
        self._compile(changed, self._compiler_config, False)
        self._create_containers()
        self._load_deployments()

        # add project to namespaces, apply import blackmagic
        name = self._name
        self.__all__ = list(self._containers)
        sys.modules[f"brownie.project.{name}"] = self  # type: ignore
        sys.modules["brownie.project"].__dict__[name] = self
        sys.modules["brownie.project"].__all__.append(name)  # type: ignore
        sys.modules["brownie.project"].__console_dir__.append(
            name)  # type: ignore
        self._namespaces = [
            sys.modules["__main__"].__dict__,
            sys.modules["brownie.project"].__dict__,
        ]
        self._active = True
        _loaded_projects.append(self)
Beispiel #4
0
    def load(self):
        '''Compiles the project contracts, creates ContractContainer objects and
        populates the namespace.'''
        if self._active:
            raise ProjectAlreadyLoaded("Project is already active")

        self._compiler_config = load_project_compiler_config(
            self._project_path, "solc")
        solc_version = self._compiler_config['version']
        if solc_version:
            self._compiler_config['version'] = compiler.set_solc_version(
                solc_version)

        # compile updated sources, update build
        changed = self._get_changed_contracts()
        self._compiler_config['version'] = solc_version
        self._compile(changed, self._compiler_config, False)
        self._create_containers()

        # add project to namespaces, apply import blackmagic
        name = self._name
        self.__all__ = list(self._containers)
        sys.modules[f'brownie.project.{name}'] = self
        sys.modules['brownie.project'].__dict__[name] = self
        sys.modules['brownie.project'].__all__.append(name)
        sys.modules['brownie.project'].__console_dir__.append(name)
        self._namespaces = [
            sys.modules['__main__'].__dict__,
            sys.modules['brownie.project'].__dict__
        ]
        self._active = True
        _loaded_projects.append(self)
Beispiel #5
0
    def load(self) -> None:
        """Compiles the project contracts, creates ContractContainer objects and
        populates the namespace."""
        if self._active:
            raise ProjectAlreadyLoaded("Project is already active")

        contract_sources = _load_sources(self._path, "contracts", False)
        interface_sources = _load_sources(self._path, "interfaces", True)
        self._sources = Sources(contract_sources, interface_sources)
        self._build = Build(self._sources)

        contract_list = self._sources.get_contract_list()
        for path in list(self._path.glob("build/contracts/*.json")):
            try:
                with path.open() as fp:
                    build_json = json.load(fp)
            except json.JSONDecodeError:
                build_json = {}
            if not set(BUILD_KEYS).issubset(
                    build_json) or path.stem not in contract_list:
                path.unlink()
                continue
            if isinstance(build_json["allSourcePaths"], list):
                # this handles the format change in v1.7.0, it can be removed in a future release
                path.unlink()
                test_path = self._path.joinpath("build/tests.json")
                if test_path.exists():
                    test_path.unlink()
                continue
            self._build._add(build_json)

        self._compiler_config = _load_project_compiler_config(self._path)

        # compile updated sources, update build
        changed = self._get_changed_contracts()
        self._compile(changed, self._compiler_config, False)
        self._save_interface_hashes()
        self._create_containers()
        self._load_deployments()

        # add project to namespaces, apply import blackmagic
        name = self._name
        self.__all__ = list(self._containers)
        sys.modules[f"brownie.project.{name}"] = self  # type: ignore
        sys.modules["brownie.project"].__dict__[name] = self
        sys.modules["brownie.project"].__all__.append(name)  # type: ignore
        sys.modules["brownie.project"].__console_dir__.append(
            name)  # type: ignore
        self._namespaces = [
            sys.modules["__main__"].__dict__,
            sys.modules["brownie.project"].__dict__,
        ]
        self._active = True
        _loaded_projects.append(self)
Beispiel #6
0
def _new_checks(project_path, ignore_subfolder):
    if CONFIG['folders']['project']:
        raise ProjectAlreadyLoaded("Project has already been loaded")
    project_path = Path(project_path).resolve()
    if CONFIG['folders']['brownie'] in str(project_path):
        raise SystemError(
            "Cannot make a new project inside the main brownie installation folder."
        )
    if not ignore_subfolder:
        check = check_for_project(project_path)
        if check and check != project_path:
            raise SystemError(
                "Cannot make a new project in a subfolder of an existing project."
            )
    return project_path
Beispiel #7
0
def load(project_path=None):
    '''Loads a project and instantiates various related objects.

    Args:
        project_path: Path of the project to load. If None, will attempt to
                      locate a project using check_for_project()

    Returns a list of ContractContainer objects.
    '''
    # checks
    if CONFIG['folders']['project']:
        raise ProjectAlreadyLoaded(
            f"Project already loaded at {CONFIG['folders']['project']}")
    if project_path is None:
        project_path = check_for_project('.')
    if not project_path or not Path(project_path).joinpath(
            "brownie-config.json").exists():
        raise ProjectNotFound("Could not find Brownie project")

    # paths
    project_path = Path(project_path).resolve()
    _create_folders(project_path)
    _add_to_sys_path(project_path)

    # load config
    load_project_config(project_path)
    CONFIG['solc']['version'] = compiler.set_solc_version(
        CONFIG['solc']['version'])

    # load sources and build
    sources.load(project_path)
    build.load(project_path)

    # compare build, erase as needed
    changed_paths = _get_changed_contracts()

    # compile sources, update build
    build_json = sources.compile_paths(changed_paths,
                                       optimize=CONFIG['solc']['optimize'],
                                       runs=CONFIG['solc']['runs'],
                                       minify=CONFIG['solc']['minify_source'])
    for data in build_json.values():
        build.add(data)

    # create objects, add to namespace
    return _create_objects()
Beispiel #8
0
def load(project_path: Union[Path, str, None] = None,
         name: Optional[str] = None) -> "Project":
    """Loads a project and instantiates various related objects.

    Args:
        project_path: Path of the project to load. If None, will attempt to
                      locate a project using check_for_project()
        name: Name to assign to the project. If None, the name is generated
              from the name of the project folder

    Returns a Project object.
    """
    # checks
    if project_path is None:
        project_path = check_for_project(".")
        if project_path is not None and project_path != Path(".").absolute():
            warnings.warn(
                f"Loaded project has a root folder of '{project_path}' "
                "which is different from the current working directory",
                BrownieEnvironmentWarning,
            )

    elif Path(project_path).resolve() != check_for_project(project_path):
        project_path = None
    if project_path is None:
        raise ProjectNotFound("Could not find Brownie project")

    project_path = Path(project_path).resolve()
    if name is None:
        name = project_path.name
        if not name.lower().endswith("project"):
            name += " project"
        name = "".join(i for i in name.title() if i.isalpha())
    if next((True for i in _loaded_projects if i._name == name), False):
        raise ProjectAlreadyLoaded(
            "There is already a project loaded with this name")

    # paths
    _create_folders(project_path)
    _add_to_sys_path(project_path)

    # load sources and build
    return Project(name, project_path)
Beispiel #9
0
    def load(self, raise_if_loaded: bool = True) -> None:
        """Compiles the project contracts, creates ContractContainer objects and
        populates the namespace."""
        if self._active:
            if raise_if_loaded:
                raise ProjectAlreadyLoaded("Project is already active")
            return None

        contract_sources = _load_sources(self._path,
                                         self._structure["contracts"], False)
        interface_sources = _load_sources(self._path,
                                          self._structure["interfaces"], True)
        self._sources = Sources(contract_sources, interface_sources)
        self._build = Build(self._sources)

        contract_list = self._sources.get_contract_list()
        for path in list(self._build_path.glob("contracts/*.json")):
            try:
                with path.open() as fp:
                    build_json = json.load(fp)
            except json.JSONDecodeError:
                build_json = {}
            if not set(BUILD_KEYS).issubset(
                    build_json) or path.stem not in contract_list:
                path.unlink()
                continue
            if isinstance(build_json["allSourcePaths"], list):
                # this handles the format change in v1.7.0, it can be removed in a future release
                path.unlink()
                test_path = self._build_path.joinpath("tests.json")
                if test_path.exists():
                    test_path.unlink()
                continue
            if not self._path.joinpath(build_json["sourcePath"]).exists():
                path.unlink()
                continue
            self._build._add_contract(build_json)

        interface_hashes = {}
        interface_list = self._sources.get_interface_list()
        for path in list(self._build_path.glob("interfaces/*.json")):
            try:
                with path.open() as fp:
                    build_json = json.load(fp)
            except json.JSONDecodeError:
                build_json = {}
            if not set(INTERFACE_KEYS).issubset(
                    build_json) or path.stem not in interface_list:
                path.unlink()
                continue
            self._build._add_interface(build_json)
            interface_hashes[path.stem] = build_json["sha1"]

        self._compiler_config = expand_posix_vars(
            _load_project_compiler_config(self._path), self._envvars)

        # compile updated sources, update build
        changed = self._get_changed_contracts(interface_hashes)
        self._compile(changed, self._compiler_config, False)
        self._compile_interfaces(interface_hashes)
        self._load_dependency_artifacts()

        self._create_containers()
        self._load_deployments()

        # add project to namespaces, apply import blackmagic
        name = self._name
        self.__all__ = list(self._containers) + ["interface"]
        sys.modules[f"brownie.project.{name}"] = self  # type: ignore
        sys.modules["brownie.project"].__dict__[name] = self
        sys.modules["brownie.project"].__all__.append(name)  # type: ignore
        sys.modules["brownie.project"].__console_dir__.append(
            name)  # type: ignore
        self._namespaces = [
            sys.modules["__main__"].__dict__,
            sys.modules["brownie.project"].__dict__,
        ]

        # register project for revert and reset
        _revert_register(self)

        self._active = True
        _loaded_projects.append(self)