Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
Split cli command code
Louis Choquelfb15c89e0ee6
diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.pyindex d7461c13f..e5234f56b 100644--- a/pipelex/cli/_cli.py+++ b/pipelex/cli/_cli.py@@ -1,57 +1,11 @@-import asyncio-import os-import shutil-from pathlib import Path-from typing import Annotated, Optional+from typing import Optionalimport typerfrom click import Command, Contextfrom typer.core import TyperGroupfrom typing_extensions import override-from pipelex import log, pretty_print-from pipelex.exceptions import PipelexCLIError, PipelexConfigError-from pipelex.hub import get_pipe_provider, get_pipeline_tracker, get_required_pipe-from pipelex.libraries.library_config import LibraryConfig-from pipelex.pipe_works.pipe_dry import dry_run_all_pipes, dry_run_single_pipe-from pipelex.pipelex import Pipelex-from pipelex.tools.config.manager import config_manager-from pipelex.tools.migrate.migrate_v0_1_0_to_v0_2_0 import TomlMigrator, migrate_concept_syntax---def is_pipelex_libraries_folder(folder_path: str) -> bool:- """Check if the given folder path contains a valid pipelex libraries structure.-- A valid pipelex libraries folder should contain the following subdirectories:- - pipelines- - llm_deck- - llm_integrations- - plugins- - templates-- Args:- folder_path: Path to the folder to check-- Returns:- True if the folder contains all required subdirectories, False otherwise- """- if not os.path.exists(folder_path) or not os.path.isdir(folder_path):- return False-- required_subdirs = [- "pipelines",- "llm_deck",- "llm_integrations",- "plugins",- "templates",- ]-- for subdir in required_subdirs:- subdir_path = os.path.join(folder_path, subdir)- if not os.path.exists(subdir_path) or not os.path.isdir(subdir_path):- return False-- return True+from pipelex.cli.commands import init_app, migrate_app, show_app, validate_appclass PipelexCLI(TyperGroup):@@ -65,6 +19,11 @@ class PipelexCLI(TyperGroup):return cmd+def main() -> None:+ """Entry point for the pipelex CLI."""+ app()++app = typer.Typer(add_completion=False,no_args_is_help=True,@@ -73,253 +32,7 @@ app = typer.Typer()[email protected]("init-libraries")-def init_libraries(- directory: Annotated[- str,- typer.Argument(help="Directory where to create the pipelex_libraries folder"),- ] = ".",- overwrite: Annotated[- bool,- typer.Option(- "--overwrite",- "-o",- help="Warning: If set, existing files will be overwritten.",- ),- ] = False,-) -> None:- """Initialize pipelex libraries in a pipelex_libraries folder in the specified directory.-- If overwrite is False, only create files that don't exist yet.- If overwrite is True, all files will be overwritten even if they exist.- """- try:- # Always create a pipelex_libraries folder in the specified directory- target_path = os.path.join(directory, "pipelex_libraries")-- # Create the target directory if it doesn't exist- os.makedirs(directory, exist_ok=True)-- # Create a LibraryConfig instance with the target path- library_config = LibraryConfig(config_folder_path=target_path)- library_config.export_libraries(overwrite=overwrite)-- if overwrite:- typer.echo(f"✅ Successfully initialized pipelex libraries at '{target_path}' (all files overwritten)")- else:- typer.echo(f"✅ Successfully initialized pipelex libraries at '{target_path}' (only created non-existing files)")- except Exception as exc:- raise PipelexCLIError(f"Failed to initialize libraries at '{directory}': {exc}")--[email protected]("init-config")-def init_config(- reset: Annotated[- bool,- typer.Option("--reset", "-r", help="Warning: If set, existing files will be overwritten."),- ] = False,-) -> None:- """Initialize pipelex configuration in the current directory."""- pipelex_template_path = os.path.join(config_manager.pipelex_root_dir, "pipelex_template.toml")- target_config_path = os.path.join(config_manager.local_root_dir, "pipelex.toml")-- if os.path.exists(target_config_path) and not reset:- typer.echo("Warning: pipelex.toml already exists. Use --reset to force creation.")- return-- try:- shutil.copy2(pipelex_template_path, target_config_path)- typer.echo(f"Created pipelex.toml at {target_config_path}")- except Exception as exc:- raise PipelexCLIError(f"Failed to create pipelex.toml: {exc}")---def validate(- relative_config_folder_path: Annotated[- str,- typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path"),- ] = "./pipelex_libraries",-) -> None:- """Run the setup sequence."""- # Check if pipelex libraries folder exists- if not is_pipelex_libraries_folder(relative_config_folder_path):- typer.echo(f"❌ No pipelex libraries folder found at '{relative_config_folder_path}'")- typer.echo("To create a pipelex libraries folder, run: pipelex init-libraries")- raise typer.Exit(1)-- pipelex_instance = Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)- pipelex_instance.validate_libraries()- asyncio.run(dry_run_all_pipes())- log.info("Setup sequence passed OK, config and pipelines are validated.")---def dry_run_pipe(- pipe_code: Annotated[str, typer.Argument(help="The pipe code to dry run")],- relative_config_folder_path: Annotated[- str,- typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path"),- ] = "./pipelex_libraries",-) -> None:- """Dry run a single pipe."""- # Check if pipelex libraries folder exists- if not is_pipelex_libraries_folder(relative_config_folder_path):- typer.echo(f"❌ No pipelex libraries folder found at '{relative_config_folder_path}'")- typer.echo("To create a pipelex libraries folder, run: pipelex init-libraries")- raise typer.Exit(1)-- try:- # Initialize Pipelex- pipelex_instance = Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)- pipelex_instance.validate_libraries()-- # Run the single pipe dry run- asyncio.run(dry_run_single_pipe(pipe_code))- get_pipeline_tracker().output_flowchart()-- except Exception as exc:- typer.echo(f"❌ Error running dry run for pipe '{pipe_code}': {exc}")- raise typer.Exit(1)---def show_config() -> None:- """Show the pipelex configuration."""- try:- final_config = config_manager.load_config()- pretty_print(- final_config,- title=f"Pipelex configuration for project: {config_manager.get_project_name()}",- )- except Exception as exc:- raise PipelexConfigError(f"Error loading configuration: {exc}")---def list_pipes(- relative_config_folder_path: Annotated[- str,- typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path"),- ] = "pipelex_libraries",-) -> None:- """List all available pipes."""- Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)-- try:- get_pipe_provider().pretty_list_pipes()-- except Exception as exc:- raise PipelexCLIError(f"Failed to list pipes: {exc}")--[email protected]("show-pipe")-def show_pipe(- pipe_code: Annotated[- str,- typer.Argument(help="Pipeline code to show definition for"),- ],- relative_config_folder_path: Annotated[- str,- typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path"),- ] = "./pipelex_libraries",-) -> None:- """Show pipe from the pipe library."""- Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)- pipe = get_required_pipe(pipe_code=pipe_code)- pretty_print(pipe, title=f"Pipe '{pipe_code}'")--[email protected]("migrate")-def migrate(- relative_config_folder_path: Annotated[- str,- typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path"),- ] = "./pipelex_libraries",- dry_run: Annotated[- bool,- typer.Option("--dry-run", help="Preview changes without applying them"),- ] = False,- backups: Annotated[- bool,- typer.Option("--backups/--no-backups", help="Create backup files before migration"),- ] = True,-) -> None:- """Migrate TOML files to new syntax (Concept = -> definition = and PipeClassName = -> type/definition)."""- config_path = Path(relative_config_folder_path)-- # Check if it's a pipelex libraries folder structure or just a directory with TOML files- if is_pipelex_libraries_folder(relative_config_folder_path):- pipelines_dir = config_path / "pipelines"- else:- # Assume it's a directory containing TOML files directly- pipelines_dir = config_path-- if not pipelines_dir.exists():- typer.echo(f"❌ Directory not found at '{pipelines_dir}'")- raise typer.Exit(1)-- try:- # Use the migration module (now handles both concepts and pipes)- result = migrate_concept_syntax(- directory=pipelines_dir,- create_backups=backups and not dry_run, # Create backups if enabled and not dry-run- dry_run=dry_run,- )-- # Handle any errors that occurred- for error in result.errors:- typer.echo(f"❌ {error}")-- if result.errors and not result.files_modified:- typer.echo("❌ Migration failed due to errors")- raise typer.Exit(1)-- typer.echo(f"Found {result.files_processed} TOML file(s) to check")-- if result.files_modified == 0:- typer.echo("✅ All TOML files are already using the new syntax")- return-- if dry_run:- # Show detailed preview for dry run- migrator = TomlMigrator()- for file_path in result.modified_files:- try:- with open(file_path, "r", encoding="utf-8") as f:- content = f.read()-- changes = migrator.get_migration_preview(content)- typer.echo(f"\n📄 {file_path.relative_to(pipelines_dir)}:")- for change in changes:- typer.echo(f" Line {change['line_number']}: {change['old_line']} → {change['new_line']}")- except Exception as e:- typer.echo(f"❌ Error reading {file_path}: {e}")-- typer.echo(f"\n📋 Summary: Found {result.total_changes} change(s) in {result.files_modified} file(s)")- typer.echo(" Run without --dry-run to apply these changes")- else:- # Show migration results- create_backups = backups and not dry_run- for file_path in result.modified_files:- typer.echo(f"✅ Migrated {file_path.relative_to(pipelines_dir)}")- if create_backups:- backup_path = file_path.with_suffix(".toml.backup")- typer.echo(f" Backup saved to {backup_path.name}")-- typer.echo(f"\n✅ Migration completed: {result.total_changes} change(s) applied to {result.files_modified} file(s)")- if create_backups:- typer.echo(" Backup files created with .backup extension")- typer.echo(" Run 'pipelex validate' to verify the migration")-- except FileNotFoundError as e:- typer.echo(f"❌ {e}")- raise typer.Exit(1)- except Exception as e:- typer.echo(f"❌ Migration failed: {e}")- raise typer.Exit(1)---def main() -> None:- """Entry point for the pipelex CLI."""- app()+app.add_typer(init_app, name="init", help="Initialization commands")+app.add_typer(validate_app, name="validate", help="Validation and dry-run commands")+app.add_typer(show_app, name="show", help="Show and list commands")+app.add_typer(migrate_app, name="migrate", help="Migration commands")diff --git a/pipelex/cli/commands/__init__.py b/pipelex/cli/commands/__init__.pynew file mode 100644index 000000000..19b9cd5a6--- /dev/null+++ b/pipelex/cli/commands/__init__.py@@ -0,0 +1,11 @@+"""Command groups for Pipelex CLI.++This package organizes CLI commands into logical modules.+"""++from .init_cmd import init_app+from .migrate_cmd import migrate_app+from .show_cmd import show_app+from .validate_cmd import validate_app++__all__ = ["init_app", "migrate_app", "show_app", "validate_app"]diff --git a/pipelex/cli/commands/common.py b/pipelex/cli/commands/common.pynew file mode 100644index 000000000..f4c948780--- /dev/null+++ b/pipelex/cli/commands/common.py@@ -0,0 +1,25 @@+from __future__ import annotations++import os+from typing import Final++REQUIRED_PIPELEX_SUBDIRS: Final[list[str]] = [+ "pipelines",+ "llm_deck",+ "llm_integrations",+ "plugins",+ "templates",+]+++def is_pipelex_libraries_folder(folder_path: str) -> bool:+ """Check if the given folder path contains a valid pipelex libraries structure."""+ if not os.path.exists(folder_path) or not os.path.isdir(folder_path):+ return False++ for subdir in REQUIRED_PIPELEX_SUBDIRS:+ subdir_path = os.path.join(folder_path, subdir)+ if not os.path.exists(subdir_path) or not os.path.isdir(subdir_path):+ return False++ return Truediff --git a/pipelex/cli/commands/init_cmd.py b/pipelex/cli/commands/init_cmd.pynew file mode 100644index 000000000..bb64fe69e--- /dev/null+++ b/pipelex/cli/commands/init_cmd.py@@ -0,0 +1,63 @@+from __future__ import annotations++import os+import shutil+from typing import Annotated++import typer++from pipelex.exceptions import PipelexCLIError+from pipelex.libraries.library_config import LibraryConfig+from pipelex.tools.config.manager import config_manager+++def do_init_libraries(directory: str = ".", overwrite: bool = False) -> None:+ """Initialize pipelex libraries in a pipelex_libraries folder in the specified directory."""+ try:+ target_path = os.path.join(directory, "pipelex_libraries")+ os.makedirs(directory, exist_ok=True)++ library_config = LibraryConfig(config_folder_path=target_path)+ library_config.export_libraries(overwrite=overwrite)++ if overwrite:+ typer.echo(f"✅ Successfully initialized pipelex libraries at '{target_path}' (all files overwritten)")+ else:+ typer.echo(f"✅ Successfully initialized pipelex libraries at '{target_path}' (only created non-existing files)")+ except Exception as exc:+ raise PipelexCLIError(f"Failed to initialize libraries at '{directory}': {exc}")+++def do_init_config(reset: bool = False) -> None:+ """Initialize pipelex configuration in the current directory."""+ pipelex_template_path = os.path.join(config_manager.pipelex_root_dir, "pipelex_template.toml")+ target_config_path = os.path.join(config_manager.local_root_dir, "pipelex.toml")++ if os.path.exists(target_config_path) and not reset:+ typer.echo("Warning: pipelex.toml already exists. Use --reset to force creation.")+ return++ try:+ shutil.copy2(pipelex_template_path, target_config_path)+ typer.echo(f"Created pipelex.toml at {target_config_path}")+ except Exception as exc:+ raise PipelexCLIError(f"Failed to create pipelex.toml: {exc}")+++# Typer group for init commands+init_app = typer.Typer(help="Initialization commands")+++@init_app.command("libraries")+def init_libraries_cmd(+ directory: Annotated[str, typer.Argument(help="Directory where to create the pipelex_libraries folder")] = ".",+ overwrite: Annotated[bool, typer.Option("--overwrite", "-o", help="Warning: If set, existing files will be overwritten.")] = False,+) -> None:+ do_init_libraries(directory=directory, overwrite=overwrite)+++@init_app.command("config")+def init_config_cmd(+ reset: Annotated[bool, typer.Option("--reset", "-r", help="Warning: If set, existing files will be overwritten.")] = False,+) -> None:+ do_init_config(reset=reset)diff --git a/pipelex/cli/commands/migrate_cmd.py b/pipelex/cli/commands/migrate_cmd.pynew file mode 100644index 000000000..1ddbf42c5--- /dev/null+++ b/pipelex/cli/commands/migrate_cmd.py@@ -0,0 +1,98 @@+from __future__ import annotations++from pathlib import Path+from typing import Annotated++import typer++from pipelex.tools.migrate.migrate_v0_1_0_to_v0_2_0 import TomlMigrator, migrate_concept_syntax++from .common import is_pipelex_libraries_folder+++def do_migrate(+ relative_config_folder_path: str = "./pipelex_libraries",+ dry_run: bool = False,+ backups: bool = True,+) -> None:+ """Migrate TOML files to new syntax (Concept = -> definition = and PipeClassName = -> type/definition)."""+ config_path = Path(relative_config_folder_path)++ if is_pipelex_libraries_folder(relative_config_folder_path):+ pipelines_dir = config_path / "pipelines"+ else:+ pipelines_dir = config_path++ if not pipelines_dir.exists():+ typer.echo(f"❌ Directory not found at '{pipelines_dir}'")+ raise typer.Exit(1)++ try:+ result = migrate_concept_syntax(+ directory=pipelines_dir,+ create_backups=backups and not dry_run,+ dry_run=dry_run,+ )++ for error in result.errors:+ typer.echo(f"❌ {error}")++ if result.errors and not result.files_modified:+ typer.echo("❌ Migration failed due to errors")+ raise typer.Exit(1)++ typer.echo(f"Found {result.files_processed} TOML file(s) to check")++ if result.files_modified == 0:+ typer.echo("✅ All TOML files are already using the new syntax")+ return++ if dry_run:+ migrator = TomlMigrator()+ for file_path in result.modified_files:+ try:+ with open(file_path, "r", encoding="utf-8") as f:+ content = f.read()++ changes = migrator.get_migration_preview(content)+ typer.echo(f"\n📄 {file_path.relative_to(pipelines_dir)}:")+ for change in changes:+ typer.echo(f" Line {change['line_number']}: {change['old_line']} → {change['new_line']}")+ except Exception as exc:+ typer.echo(f"❌ Error reading {file_path}: {exc}")++ typer.echo(f"\n📋 Summary: Found {result.total_changes} change(s) in {result.files_modified} file(s)")+ typer.echo(" Run without --dry-run to apply these changes")+ else:+ create_backups = backups and not dry_run+ for file_path in result.modified_files:+ typer.echo(f"✅ Migrated {file_path.relative_to(pipelines_dir)}")+ if create_backups:+ backup_path = file_path.with_suffix(".toml.backup")+ typer.echo(f" Backup saved to {backup_path.name}")++ typer.echo(f"\n✅ Migration completed: {result.total_changes} change(s) applied to {result.files_modified} file(s)")+ if create_backups:+ typer.echo(" Backup files created with .backup extension")+ typer.echo(" Run 'pipelex validate' to verify the migration")+ except FileNotFoundError as exc:+ typer.echo(f"❌ {exc}")+ raise typer.Exit(1)+ except Exception as exc:+ typer.echo(f"❌ Migration failed: {exc}")+ raise typer.Exit(1)+++# Typer group for migration commands+migrate_app = typer.Typer(help="Migration commands")+++@migrate_app.command("run")+def migrate_cmd(+ relative_config_folder_path: Annotated[+ str, typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path")+ ] = "./pipelex_libraries",+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Preview changes without applying them")] = False,+ backups: Annotated[bool, typer.Option("--backups/--no-backups", help="Create backup files before migration")] = True,+) -> None:+ do_migrate(relative_config_folder_path=relative_config_folder_path, dry_run=dry_run, backups=backups)diff --git a/pipelex/cli/commands/show_cmd.py b/pipelex/cli/commands/show_cmd.pynew file mode 100644index 000000000..0c3f5c2c3--- /dev/null+++ b/pipelex/cli/commands/show_cmd.py@@ -0,0 +1,68 @@+from __future__ import annotations++from typing import Annotated++import typer++from pipelex import pretty_print+from pipelex.exceptions import PipelexCLIError, PipelexConfigError+from pipelex.hub import get_pipe_provider, get_required_pipe+from pipelex.pipelex import Pipelex+from pipelex.tools.config.manager import config_manager+++def do_show_config() -> None:+ """Show the pipelex configuration."""+ try:+ final_config = config_manager.load_config()+ pretty_print(+ final_config,+ title=f"Pipelex configuration for project: {config_manager.get_project_name()}",+ )+ except Exception as exc:+ raise PipelexConfigError(f"Error loading configuration: {exc}")+++def do_list_pipes(relative_config_folder_path: str = "pipelex_libraries") -> None:+ """List all available pipes."""+ Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)++ try:+ get_pipe_provider().pretty_list_pipes()+ except Exception as exc:+ raise PipelexCLIError(f"Failed to list pipes: {exc}")+++def do_show_pipe(pipe_code: str, relative_config_folder_path: str = "./pipelex_libraries") -> None:+ """Show a single pipe definition from the library."""+ Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)+ pipe = get_required_pipe(pipe_code=pipe_code)+ pretty_print(pipe, title=f"Pipe '{pipe_code}'")+++# Typer group for show commands+show_app = typer.Typer(help="Show and list commands")+++@show_app.command("config")+def show_config_cmd() -> None:+ do_show_config()+++@show_app.command("pipes")+def list_pipes_cmd(+ relative_config_folder_path: Annotated[+ str, typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path")+ ] = "pipelex_libraries",+) -> None:+ do_list_pipes(relative_config_folder_path=relative_config_folder_path)+++@show_app.command("pipe")+def show_pipe_cmd(+ pipe_code: Annotated[str, typer.Argument(help="Pipeline code to show definition for")],+ relative_config_folder_path: Annotated[+ str, typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path")+ ] = "./pipelex_libraries",+) -> None:+ do_show_pipe(pipe_code=pipe_code, relative_config_folder_path=relative_config_folder_path)diff --git a/pipelex/cli/commands/validate_cmd.py b/pipelex/cli/commands/validate_cmd.pynew file mode 100644index 000000000..31b1a41ba--- /dev/null+++ b/pipelex/cli/commands/validate_cmd.py@@ -0,0 +1,66 @@+from __future__ import annotations++import asyncio+from typing import Annotated++import typer++from pipelex import log+from pipelex.hub import get_pipeline_tracker+from pipelex.pipe_works.pipe_dry import dry_run_all_pipes, dry_run_single_pipe+from pipelex.pipelex import Pipelex++from .common import is_pipelex_libraries_folder+++def do_validate(relative_config_folder_path: str = "./pipelex_libraries") -> None:+ """Validate libraries and dry-run all pipes."""+ if not is_pipelex_libraries_folder(relative_config_folder_path):+ typer.echo(f"❌ No pipelex libraries folder found at '{relative_config_folder_path}'")+ typer.echo("To create a pipelex libraries folder, run: pipelex init-libraries")+ raise typer.Exit(1)++ pipelex_instance = Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)+ pipelex_instance.validate_libraries()+ asyncio.run(dry_run_all_pipes())+ log.info("Setup sequence passed OK, config and pipelines are validated.")+++def do_dry_run_pipe(pipe_code: str, relative_config_folder_path: str = "./pipelex_libraries") -> None:+ """Dry run a single pipe."""+ if not is_pipelex_libraries_folder(relative_config_folder_path):+ typer.echo(f"❌ No pipelex libraries folder found at '{relative_config_folder_path}'")+ typer.echo("To create a pipelex libraries folder, run: pipelex init-libraries")+ raise typer.Exit(1)++ try:+ pipelex_instance = Pipelex.make(relative_config_folder_path=relative_config_folder_path, from_file=False)+ pipelex_instance.validate_libraries()+ asyncio.run(dry_run_single_pipe(pipe_code))+ get_pipeline_tracker().output_flowchart()+ except Exception as exc:+ typer.echo(f"❌ Error running dry run for pipe '{pipe_code}': {exc}")+ raise typer.Exit(1)+++# Typer group for validation commands+validate_app = typer.Typer(help="Validation and dry-run commands")+++@validate_app.command("all")+def validate_all_cmd(+ relative_config_folder_path: Annotated[+ str, typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path")+ ] = "./pipelex_libraries",+) -> None:+ do_validate(relative_config_folder_path=relative_config_folder_path)+++@validate_app.command("pipe")+def dry_run_pipe_cmd(+ pipe_code: Annotated[str, typer.Argument(help="The pipe code to dry run")],+ relative_config_folder_path: Annotated[+ str, typer.Option("--config-folder-path", "-c", help="Relative path to the config folder path")+ ] = "./pipelex_libraries",+) -> None:+ do_dry_run_pipe(pipe_code=pipe_code, relative_config_folder_path=relative_config_folder_path)