This repository has been archived on 2026-10-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
imagelab_v3_extension/cli.py
T

211 lines
5.9 KiB
Python

"""
CLI commands for the external-api workflow schema system.
"""
import argparse
from pathlib import Path
from typing import List, Optional
import yaml
# Support both relative and absolute imports
try:
from .schema_generator import (
generate_workflow_schema,
validate_workflow_schema,
)
except ImportError:
from schema_generator import (
generate_workflow_schema,
validate_workflow_schema,
)
def get_workflows_dir() -> Path:
"""Get the workflows directory."""
return Path(__file__).parent / "workflows"
def find_workflow_files(workflows_dir: Path) -> List[Path]:
"""Find all workflow .py files (excluding __init__.py and base files)."""
workflow_files = []
for py_file in workflows_dir.glob("*.py"):
if py_file.name.startswith("_"):
continue
if py_file.name == "base.py":
continue
workflow_files.append(py_file)
return sorted(workflow_files)
def cmd_generate(args: argparse.Namespace) -> int:
"""Generate YAML schema(s) from workflow files."""
workflows_dir = get_workflows_dir()
if args.all:
# Generate for all workflows
workflow_files = find_workflow_files(workflows_dir)
if not workflow_files:
print("No workflow files found.")
return 1
for wf_path in workflow_files:
try:
schema = generate_workflow_schema(wf_path, dry_run=args.dry_run)
action = "Would generate" if args.dry_run else "Generated"
yaml_path = wf_path.with_suffix(".yaml")
print(f"{action}: {yaml_path.name}")
if args.dry_run:
print(yaml.dump(schema, default_flow_style=False, sort_keys=False))
print("-" * 40)
except Exception as e:
print(f"Error processing {wf_path.name}: {e}")
return 0
elif args.workflow:
# Generate for single workflow
workflow_path = workflows_dir / f"{args.workflow}.py"
if not workflow_path.exists():
print(f"Workflow not found: {workflow_path}")
return 1
try:
schema = generate_workflow_schema(workflow_path, dry_run=args.dry_run)
yaml_path = workflow_path.with_suffix(".yaml")
if args.dry_run:
print(f"Would generate: {yaml_path.name}")
print(yaml.dump(schema, default_flow_style=False, sort_keys=False))
else:
print(f"Generated: {yaml_path.name}")
return 0
except Exception as e:
print(f"Error: {e}")
return 1
else:
print("Must specify --all or a workflow name")
return 1
def cmd_validate(args: argparse.Namespace) -> int:
"""Validate YAML schema(s) against workflow files."""
workflows_dir = get_workflows_dir()
all_valid = True
if args.all:
workflow_files = find_workflow_files(workflows_dir)
elif args.workflow:
workflow_path = workflows_dir / f"{args.workflow}.py"
if not workflow_path.exists():
print(f"Workflow not found: {workflow_path}")
return 1
workflow_files = [workflow_path]
else:
print("Must specify --all or a workflow name")
return 1
for wf_path in workflow_files:
errors = validate_workflow_schema(wf_path)
if errors:
all_valid = False
print(f"❌ {wf_path.name}:")
for error in errors:
print(f" - {error}")
else:
print(f"✓ {wf_path.name}")
return 0 if all_valid else 1
def cmd_list(args: argparse.Namespace) -> int:
"""List all workflows and their YAML status."""
workflows_dir = get_workflows_dir()
workflow_files = find_workflow_files(workflows_dir)
if not workflow_files:
print("No workflow files found.")
return 1
print(f"Workflows in {workflows_dir}:\n")
for wf_path in workflow_files:
yaml_path = wf_path.with_suffix(".yaml")
has_yaml = yaml_path.exists()
status = "✓ YAML" if has_yaml else "✗ no YAML"
print(f" {wf_path.stem:30} [{status}]")
return 0
def main(argv: Optional[List[str]] = None) -> int:
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
prog="external-api",
description="External API workflow schema management"
)
subparsers = parser.add_subparsers(dest="command", help="Commands")
# generate command
gen_parser = subparsers.add_parser(
"generate",
help="Generate YAML schema from workflow file"
)
gen_parser.add_argument(
"workflow",
nargs="?",
help="Workflow name (without .py extension)"
)
gen_parser.add_argument(
"--all",
action="store_true",
help="Generate schemas for all workflows"
)
gen_parser.add_argument(
"--dry-run",
action="store_true",
help="Preview generated schema without writing"
)
gen_parser.set_defaults(func=cmd_generate)
# validate command
val_parser = subparsers.add_parser(
"validate",
help="Validate YAML schema matches workflow"
)
val_parser.add_argument(
"workflow",
nargs="?",
help="Workflow name (without .py extension)"
)
val_parser.add_argument(
"--all",
action="store_true",
help="Validate all workflows"
)
val_parser.set_defaults(func=cmd_validate)
# list command
list_parser = subparsers.add_parser(
"list",
help="List all workflows"
)
list_parser.set_defaults(func=cmd_list)
args = parser.parse_args(argv)
if args.command is None:
parser.print_help()
return 0
return args.func(args)
if __name__ == "__main__":
import sys
sys.exit(main())