Ejemplo n.º 1
0
 def test_validate_package_name_negative(self):
     """Test validate_package_name for negative result."""
     with self.assertRaises(BadParameter):
         validate_package_name("incorrect-name")
Ejemplo n.º 2
0
def scaffold_item(ctx: Context, item_type: str, item_name: str) -> None:
    """
    Add an item scaffolding to the configuration file and agent.

    :param ctx: Context object.
    :param item_type: type of item.
    :param item_name: item name.

    :return: None
    :raises ClickException: if some error occures.
    """
    validate_package_name(item_name)
    author_name = ctx.agent_config.author
    loader = getattr(ctx, f"{item_type}_loader")
    default_config_filename = globals(
    )[f"DEFAULT_{item_type.upper()}_CONFIG_FILE"]

    item_type_plural = item_type + "s"
    existing_ids = getattr(ctx.agent_config, f"{item_type}s")
    existing_ids_only_author_and_name = map(lambda x: (x.author, x.name),
                                            existing_ids)
    # check if we already have an item with the same public id
    if (author_name, item_name) in existing_ids_only_author_and_name:
        raise click.ClickException(
            f"A {item_type} with name '{item_name}' already exists. Aborting..."
        )

    agent_name = ctx.agent_config.agent_name
    click.echo(
        f"Adding {item_type} scaffold '{item_name}' to the agent '{agent_name}'..."
    )

    # create the item folder
    Path(item_type_plural).mkdir(exist_ok=True)
    dest = os.path.join(item_type_plural, item_name)
    if os.path.exists(dest):
        raise click.ClickException(
            f"A {item_type} with this name already exists. Please choose a different name and try again."
        )

    ctx.clean_paths.append(str(dest))
    try:
        # copy the item package into the agent project.
        src = Path(os.path.join(AEA_DIR, item_type_plural, "scaffold"))
        logger.debug(f"Copying {item_type} modules. src={src} dst={dest}")
        shutil.copytree(src, dest)

        # add the item to the configurations.
        logger.debug(
            f"Registering the {item_type} into {DEFAULT_AEA_CONFIG_FILE}")
        new_public_id = PublicId(author_name, item_name, DEFAULT_VERSION)
        existing_ids.add(new_public_id)
        with open_file(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE),
                       "w") as fp:
            ctx.agent_loader.dump(ctx.agent_config, fp)

        # ensure the name in the yaml and the name of the folder are the same
        config_filepath = Path(ctx.cwd, item_type_plural, item_name,
                               default_config_filename)
        with open_file(config_filepath) as fp:
            config = loader.load(fp)
        config.name = item_name
        config.author = author_name
        with open_file(config_filepath, "w") as fp:
            loader.dump(config, fp)

        # update 'PUBLIC_ID' variable with the right public id in connection.py!

        for file_name in ["__init__.py", "connection.py"]:
            file_path = Path(dest) / file_name
            if not file_path.exists():
                continue
            py_file = Path(file_path)
            py_file.write_text(
                re.sub(SCAFFOLD_PUBLIC_ID, str(new_public_id),
                       py_file.read_text()))

        # fingerprint item.
        fingerprint_item(ctx, item_type, new_public_id)

        if ctx.config.get("with_symlinks", False):
            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)

    except ValidationError:
        raise click.ClickException(
            f"Error when validating the {item_type} configuration file.")
    except Exception as e:
        raise click.ClickException(str(e))
Ejemplo n.º 3
0
 def test_validate_package_name_positive(self):
     """Test validate_package_name for positive result."""
     validate_package_name("correct_name")
Ejemplo n.º 4
0
def _scaffold_item(click_context, item_type, item_name):
    """Add an item scaffolding to the configuration file and agent."""
    validate_package_name(item_name)

    ctx = cast(Context, click_context.obj)
    author_name = ctx.agent_config.author
    loader = getattr(ctx, "{}_loader".format(item_type))
    default_config_filename = globals()["DEFAULT_{}_CONFIG_FILE".format(
        item_type.upper())]

    item_type_plural = item_type + "s"
    existing_ids = getattr(ctx.agent_config, "{}s".format(item_type))
    existing_ids_only_author_and_name = map(lambda x: (x.author, x.name),
                                            existing_ids)
    # check if we already have an item with the same public id
    if (author_name, item_name) in existing_ids_only_author_and_name:
        raise click.ClickException(
            "A {} with name '{}' already exists. Aborting...".format(
                item_type, item_name))

    agent_name = ctx.agent_config.agent_name
    click.echo("Adding {} scaffold '{}' to the agent '{}'...".format(
        item_type, item_name, agent_name))

    # create the item folder
    Path(item_type_plural).mkdir(exist_ok=True)
    dest = os.path.join(item_type_plural, item_name)
    if os.path.exists(dest):
        raise click.ClickException(
            "A {} with this name already exists. Please choose a different name and try again."
            .format(item_type))

    ctx.clean_paths.append(str(dest))
    try:
        # copy the item package into the agent project.
        src = Path(os.path.join(AEA_DIR, item_type_plural, "scaffold"))
        logger.debug("Copying {} modules. src={} dst={}".format(
            item_type, src, dest))
        shutil.copytree(src, dest)

        # add the item to the configurations.
        logger.debug("Registering the {} into {}".format(
            item_type, DEFAULT_AEA_CONFIG_FILE))
        existing_ids.add(PublicId(author_name, item_name, DEFAULT_VERSION))
        ctx.agent_loader.dump(
            ctx.agent_config,
            open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))

        # ensure the name in the yaml and the name of the folder are the same
        config_filepath = Path(ctx.cwd, item_type_plural, item_name,
                               default_config_filename)
        config = loader.load(config_filepath.open())
        config.name = item_name
        config.author = author_name
        loader.dump(config, open(config_filepath, "w"))

    except ValidationError:
        raise click.ClickException(
            "Error when validating the {} configuration file.".format(
                item_type))
    except Exception as e:
        raise click.ClickException(str(e))