Esempio n. 1
0
    def can_eject(self) -> bool:
        """Ask to the user if packages can be ejected if needed."""
        to_upgrade = set(self.item_to_new_version.keys())
        order = find_topological_order(self.adjacency_list)
        for package_id in order:
            if package_id in self.item_to_new_version:
                # if dependency is going to be upgraded,
                # no need to do anything
                continue

            depends_on = self.adjacency_list[package_id]
            dependencies_to_upgrade = depends_on.intersection(to_upgrade)
            if len(dependencies_to_upgrade) == 0:
                # if dependencies of the package are not going to be upgraded,
                # no need to worry about its ejection.
                continue  # pragma: nocover

            # if we are here, it means we need to eject the package.
            answer = self._prompt(package_id, dependencies_to_upgrade)
            should_eject = answer
            if not should_eject:
                return False
            click.echo(f"Package '{package_id}' scheduled for ejection.")
            self.to_eject.append(package_id)
        return True
Esempio n. 2
0
    def test_chain(self, chain_length):
        """Test the function with a chain."""
        adj_list: Dict[int, Set[int]] = {}
        for i in range(chain_length - 1):
            adj_list[i] = {i + 1}
        adj_list[chain_length - 1] = set()

        order = find_topological_order(adj_list)
        assert order == list(range(chain_length))
Esempio n. 3
0
 def test_two_nodes_clique(self):
     """Test the function with a clique of two nodes."""
     with pytest.raises(ValueError, match="Graph has at least one cycle."):
         find_topological_order({0: {1, 0}, 1: {0, 1}})
Esempio n. 4
0
 def test_two_nodes_with_cycle(self):
     """Test the function with two nodes and a cycle between them."""
     with pytest.raises(ValueError, match="Graph has at least one cycle."):
         find_topological_order({0: {1}, 1: {0}})
Esempio n. 5
0
 def test_two_nodes_no_cycle(self):
     """Test the function with two nodes, but no cycles."""
     order = find_topological_order({0: {1}})
     assert order == [0, 1]
Esempio n. 6
0
 def test_two_nodes_no_edges(self):
     """Test the function with two nodes, but no edges."""
     order = find_topological_order({0: set(), 1: set()})
     assert order == [0, 1]
Esempio n. 7
0
 def test_one_node_with_cycle(self):
     """Test the function with only one node and a loop."""
     with pytest.raises(ValueError, match="Graph has at least one cycle."):
         find_topological_order({0: {0}})
Esempio n. 8
0
 def test_one_node(self):
     """Test the function with only one node."""
     order = find_topological_order({0: set()})
     assert order == [0]
Esempio n. 9
0
 def test_empty_graph(self):
     """Test the function with empty input."""
     order = find_topological_order({})
     assert order == []
Esempio n. 10
0
def _eject_item(
    ctx: Context,
    item_type: str,
    public_id: PublicId,
    quiet: bool = True,
    with_symlinks: bool = False,
) -> None:
    """
    Eject item from installed (vendor) to custom folder.

    :param ctx: context object.
    :param item_type: item type.
    :param public_id: item public ID.
    :param quiet: if false, the function will ask the user in case of recursive eject.

    :return: None
    :raises: ClickException if item is absent at source path or present at destenation path.
    """
    # we know cli_author is set because of the above checks.
    cli_author: str = cast(str, ctx.config.get("cli_author"))
    item_type_plural = item_type + "s"
    if not is_item_present(
            ctx.cwd,
            ctx.agent_config,
            item_type,
            public_id,
            is_vendor=True,
            with_version=True,
    ):  # pragma: no cover
        raise click.ClickException(
            f"{item_type.title()} {public_id} not found in agent's vendor items."
        )
    src = get_package_path(ctx.cwd, item_type, public_id)
    dst = get_package_path(ctx.cwd, item_type, public_id, is_vendor=False)
    if is_item_present(ctx.cwd,
                       ctx.agent_config,
                       item_type,
                       public_id,
                       is_vendor=False):  # pragma: no cover
        raise click.ClickException(
            f"{item_type.title()} {public_id} is already a non-vendor package."
        )
    configuration = load_item_config(item_type, Path(src))

    if public_id.package_version.is_latest:
        # get 'concrete' public id, in case it is 'latest'
        component_prefix = ComponentType(
            item_type), public_id.author, public_id.name
        component_id = get_latest_component_id_from_prefix(
            ctx.agent_config, component_prefix)
        # component id is necessarily found, due to the checks above.
        public_id = cast(ComponentId, component_id).public_id

    package_id = PackageId(PackageType(item_type), public_id)

    click.echo(
        f"Ejecting item {package_id.package_type.value} {str(package_id.public_id)}"
    )

    # first, eject all the vendor packages that depend on this
    item_remover = ItemRemoveHelper(ctx, ignore_non_vendor=True)
    reverse_dependencies = (
        item_remover.get_agent_dependencies_with_reverse_dependencies())
    reverse_reachable_dependencies = reachable_nodes(reverse_dependencies,
                                                     {package_id})
    # the reversed topological order of a graph
    # is the topological order of the reverse graph.
    eject_order = list(
        reversed(find_topological_order(reverse_reachable_dependencies)))
    eject_order.remove(package_id)
    if len(eject_order) > 0 and not quiet:
        click.echo(
            f"The following vendor packages will be ejected: {eject_order}")
        answer = click.confirm("Do you want to proceed?")
        if not answer:
            click.echo("Aborted.")
            return

    for dependency_package_id in eject_order:
        # 'dependency_package_id' depends on 'package_id',
        # so we need to eject it first
        _eject_item(
            ctx,
            dependency_package_id.package_type.value,
            dependency_package_id.public_id,
            quiet=True,
        )

    # copy the vendor package into the non-vendor packages
    ctx.clean_paths.append(dst)
    copy_package_directory(Path(src), dst)

    new_public_id = PublicId(cli_author, public_id.name, DEFAULT_VERSION)
    current_version = Version(aea.__version__)
    new_aea_range = (
        configuration.aea_version
        if configuration.aea_version_specifiers.contains(current_version) else
        compute_specifier_from_version(current_version))
    update_item_config(
        item_type,
        Path(dst),
        author=new_public_id.author,
        version=new_public_id.version,
        aea_version=new_aea_range,
    )
    update_item_public_id_in_init(item_type, Path(dst), new_public_id)
    shutil.rmtree(src)

    # update references in all the other packages
    component_type = ComponentType(item_type_plural[:-1])
    old_component_id = ComponentId(component_type, public_id)
    new_component_id = ComponentId(component_type, new_public_id)
    update_references(ctx, {old_component_id: new_component_id})

    # need to reload agent configuration with the updated references
    try_to_load_agent_config(ctx)

    # replace import statements in all the non-vendor packages
    replace_all_import_statements(Path(ctx.cwd), ComponentType(item_type),
                                  public_id, new_public_id)

    # fingerprint all (non-vendor) packages
    fingerprint_all(ctx)

    if with_symlinks:
        click.echo(
            "Adding symlinks from vendor to non-vendor and packages to vendor folders."
        )
        create_symlink_vendor_to_local(ctx, item_type, new_public_id)
        create_symlink_packages_to_vendor(ctx)

    click.echo(
        f"Successfully ejected {item_type} {public_id} to {dst} as {new_public_id}."
    )