Resolve sketch argument to examples directory path. Handles various input formats and performs disambiguation when needed. Args: sketch_arg: Sketch name, relative path, or full path project_dir: Project root directory Returns: Resolved path relative to project
(sketch_arg: str, project_dir: Path)
| 21 | |
| 22 | |
| 23 | def resolve_sketch_path(sketch_arg: str, project_dir: Path) -> str: |
| 24 | """Resolve sketch argument to examples directory path. |
| 25 | |
| 26 | Handles various input formats and performs disambiguation when needed. |
| 27 | |
| 28 | Args: |
| 29 | sketch_arg: Sketch name, relative path, or full path |
| 30 | project_dir: Project root directory |
| 31 | |
| 32 | Returns: |
| 33 | Resolved path relative to project root (e.g., 'examples/RX') |
| 34 | |
| 35 | Raises: |
| 36 | SystemExit: If sketch cannot be found or is ambiguous |
| 37 | """ |
| 38 | # Handle full paths |
| 39 | sketch_path = Path(sketch_arg) |
| 40 | if sketch_path.is_absolute(): |
| 41 | # Convert absolute path to relative from project root |
| 42 | try: |
| 43 | relative_path = sketch_path.relative_to(project_dir) |
| 44 | # If it's a .ino file, get the parent directory |
| 45 | if relative_path.suffix == ".ino": |
| 46 | relative_path = relative_path.parent |
| 47 | return str(relative_path).replace("\\", "/") |
| 48 | except ValueError: |
| 49 | print(f"❌ Error: Sketch path is outside project directory: {sketch_arg}") |
| 50 | print(f" Project directory: {project_dir}") |
| 51 | sys.exit(1) |
| 52 | |
| 53 | # Handle relative paths or sketch names |
| 54 | sketch_str = str(sketch_path).replace("\\", "/") |
| 55 | |
| 56 | # Strip .ino extension if present |
| 57 | if sketch_str.endswith(".ino"): |
| 58 | sketch_str = str(Path(sketch_str).parent).replace("\\", "/") |
| 59 | |
| 60 | # If already starts with 'examples/', use as-is |
| 61 | if sketch_str.startswith("examples/"): |
| 62 | candidate = project_dir / sketch_str |
| 63 | if candidate.is_dir(): |
| 64 | return sketch_str |
| 65 | print(f"❌ Error: Sketch directory not found: {sketch_str}") |
| 66 | print(f" Expected directory: {candidate}") |
| 67 | sys.exit(1) |
| 68 | |
| 69 | # Search for sketch in examples directory |
| 70 | examples_dir = project_dir / "examples" |
| 71 | if not examples_dir.exists(): |
| 72 | print(f"❌ Error: examples directory not found: {examples_dir}") |
| 73 | sys.exit(1) |
| 74 | |
| 75 | # Find all matching directories |
| 76 | sketch_name = sketch_str.split("/")[-1] # Get the sketch name |
| 77 | matches = list(examples_dir.rglob(f"*/{sketch_name}")) + list( |
| 78 | examples_dir.glob(sketch_name) |
| 79 | ) |
| 80 |