build_cmd.py
1 import click 2 import subprocess 3 import os 4 from pathlib import Path 5 from cli.utils import error_exit 6 7 8 @click.command("build") 9 @click.argument( 10 "plugin_path_arg", 11 type=click.Path(exists=True, file_okay=False, dir_okay=True, resolve_path=True), 12 default=".", 13 metavar="PLUGIN_PATH", 14 ) 15 def build_plugin_cmd(plugin_path_arg: str): 16 """ 17 Builds the SAM plugin in the specified directory (defaults to current directory). 18 This command requires the 'build' package to be installed (pip install build). 19 """ 20 target_path = Path(plugin_path_arg) 21 pyproject_file = target_path / "pyproject.toml" 22 23 if not pyproject_file.is_file(): 24 click.echo( 25 click.style(f"Error: pyproject.toml not found in {target_path}", fg="red") 26 ) 27 click.echo( 28 click.style( 29 "Please ensure you are in the root directory of the plugin or provide the correct path.", 30 fg="yellow", 31 ) 32 ) 33 error_exit() 34 35 click.echo(f"Building plugin in {target_path}...") 36 click.echo( 37 click.style( 38 "Note: This command uses 'python -m build'. Ensure 'build' package is installed ('pip install build').", 39 fg="cyan", 40 ) 41 ) 42 43 original_cwd = Path.cwd() 44 error_exit_msg = None 45 try: 46 os.chdir(target_path) 47 process = subprocess.run( 48 ["python", "-m", "build"], capture_output=True, text=True, check=False 49 ) 50 51 if process.stdout: 52 click.echo("--- Build Output ---") 53 click.echo(process.stdout) 54 click.echo("--- End of Build Output ---") 55 56 if process.stderr: 57 click.echo(click.style("--- Build Errors/Warnings ---", fg="yellow")) 58 click.echo(click.style(process.stderr, fg="yellow")) 59 click.echo(click.style("--- End of Build Errors/Warnings ---", fg="yellow")) 60 61 if process.returncode == 0: 62 dist_path = target_path / "dist" 63 click.echo( 64 click.style( 65 f"Plugin built successfully! Artifacts are in: {dist_path}", 66 fg="green", 67 ) 68 ) 69 if dist_path.exists() and dist_path.is_dir(): 70 click.echo("Generated files:") 71 for item in sorted(dist_path.iterdir()): 72 click.echo(f" - {item.name}") 73 else: 74 error_exit_msg = ( 75 f"Error: 'python -m build' failed with exit code {process.returncode}." 76 ) 77 error_exit_msg += "\nPlease check the build output above for details." 78 79 except FileNotFoundError: 80 error_exit_msg = f"Error: Python executable not found. Ensure Python is installed and in your PATH." 81 except Exception as e: 82 error_exit_msg = f"An unexpected error occurred during the build process: {e}" 83 finally: 84 os.chdir(original_cwd) 85 if error_exit_msg: 86 error_exit(error_exit_msg)