From bb8772c58c5d143064c5d7332720e04021fce539 Mon Sep 17 00:00:00 2001 From: jdicorpo Date: Tue, 17 Nov 2026 13:39:24 -0800 Subject: [PATCH 1/4] Add double_wide CLI support and scope cf status to linked project - Sync dw_openframe_user_project template in cf setup and cf repo update - Harden double_wide macros and wrapper with LibreLane 3 via project flake - cf status shows only the linked platform project's SFTP rows - Bump cf-cli to 2.7.3 Co-authored-by: Cursor --- README.md | 7 ++- chipfoundry_cli/__init__.py | 2 +- chipfoundry_cli/librelane_run.py | 4 +- chipfoundry_cli/main.py | 92 ++++++++++++++++++++------------ chipfoundry_cli/utils.py | 25 +++++++-- pyproject.toml | 2 +- tests/test_double_wide.py | 70 ++++++++++++++++++++++++ 7 files changed, 158 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 176089c..078d219 100644 --- a/README.md +++ b/README.md @@ -118,10 +118,15 @@ Double-wide projects (`type: double_wide`, detected from `gds/double_wide_openframe_project_wrapper.gds`) use the same commands as openframe projects, with these differences: +- Start from the user-project template + ([chipfoundry/dw_openframe_user_project](https://github.com/chipfoundry/dw_openframe_user_project)). + `cf repo update` syncs that template's `.cf/repo.json` file list. - `cf setup` clones the double-wide harness ([chipfoundry/double_wide_openframe](https://github.com/chipfoundry/double_wide_openframe)) into `caravel/` instead of caravel-lite, and skips the management core wrapper. The harness ref comes from `harness_refs.double_wide` in `versions.json` (default `main`). +- `cf harden` runs LibreLane 3 (the project's `flake.nix`) for each macro and + for `double_wide_openframe_project_wrapper`. Harden the macro first, then the wrapper. - `cf precheck` passes `caravel/` to cf-precheck as the golden root, since the precheck image only ships the standard caravel. - `cf verify` runs caravel-cocotb in OpenFrame mode. The harness supplies the @@ -778,7 +783,7 @@ cf repo update [OPTIONS] **Options:** - `--project-root`: Specify project directory (defaults to current directory) - `--repo-owner`: GitHub repository owner (default: chipfoundry) -- `--repo-name`: GitHub repository name (default: caravel_user_project) +- `--repo-name`: GitHub repository name (default: `dw_openframe_user_project` for double-wide projects, otherwise `caravel_user_project`) - `--branch`: Branch name containing the repo.json file (default: main) - `--dry-run`: Preview changes without updating files diff --git a/chipfoundry_cli/__init__.py b/chipfoundry_cli/__init__.py index 9dfd181..be7fecc 100644 --- a/chipfoundry_cli/__init__.py +++ b/chipfoundry_cli/__init__.py @@ -1,2 +1,2 @@ """ChipFoundry CLI package: Automate project submission to SFTP.""" -__version__ = "2.7.2" \ No newline at end of file +__version__ = "2.7.3" \ No newline at end of file diff --git a/chipfoundry_cli/librelane_run.py b/chipfoundry_cli/librelane_run.py index 0ec1ce3..6962281 100644 --- a/chipfoundry_cli/librelane_run.py +++ b/chipfoundry_cli/librelane_run.py @@ -232,7 +232,7 @@ def double_wide_flake_dir(project_root: Path) -> Optional[Path]: """The double_wide project's own flake.nix dir, pinning LibreLane 3. double_wide ships its own flake (not cf-cli's `chipfoundry/openlane-2` - flake used by every other project type) because the flat wrapper needs + flake used by every other project type) so macros and the wrapper use LibreLane 3's native PDN-to-pad routing. Returns None if the project doesn't have one (e.g. it predates this, or a user deleted it). """ @@ -268,7 +268,7 @@ def build_double_wide_librelane_command( open_in_openroad: bool = False, open_in_klayout: bool = False, ) -> Tuple[List[str], Dict[str, str]]: - """Build the `nix develop` command that runs LibreLane 3 on a flat double_wide wrapper. + """Build the `nix develop` command that runs LibreLane 3 on a double_wide macro or wrapper. No `--manual-pdk`/`--pdk-root`/`--pdk` flags: LibreLane 3's default (Ciel-managed) PDK resolution auto-fetches the pinned PDK commit into diff --git a/chipfoundry_cli/main.py b/chipfoundry_cli/main.py index f23acc6..246dcb9 100644 --- a/chipfoundry_cli/main.py +++ b/chipfoundry_cli/main.py @@ -19,7 +19,7 @@ GPIO_MODES, GPIO_MODE_DESCRIPTIONS, GPIO_HEX_TO_MODE, detect_github_repo_url, get_head_commit_sha, PROJECT_TYPES, HARNESS_REPOS, is_padframe_only, harness_ref, - read_project_type, DOUBLE_WIDE_LIBRELANE_REV, + read_project_type, user_project_repo, DOUBLE_WIDE_LIBRELANE_REV, ) from chipfoundry_cli import librelane_run import os @@ -2708,6 +2708,16 @@ def status(sftp_host, sftp_username, sftp_key, json_output, show_all): except Exception: pass + linked_name = _linked_platform_project_name(os.getcwd(), config) + if linked_name is None: + console.print( + "[dim]Not linked to a platform project. Run [bold]cf link[/bold] " + "to show this project's SFTP status.[/dim]" + ) + return + # Only this project's archive runs; other projects on the account are not shown. + archived_projects = [a for a in archived_projects if a[0] == linked_name] + # Create main status table table = Table(title=f"SFTP Status for {sftp_username}") table.add_column("Project Name", style="cyan", no_wrap=True) @@ -2743,24 +2753,16 @@ def status(sftp_host, sftp_username, sftp_key, json_output, show_all): has_output = "Yes" if latest_tapeout[0] in results else "No" table.add_row(latest_tapeout[0], has_input, has_output, formatted_time) else: - # No tapeout runs yet, show active projects with their status - all_projects = set(projects) | set(results) - for proj in sorted(all_projects): - has_input = "Yes" if proj in projects else "No" - has_output = "Yes" if proj in results else "No" - last_tapeout = "No tapeout yet" - table.add_row(proj, has_input, has_output, last_tapeout) - - if table.row_count > 0: - console.print(table) - else: - console.print("[yellow]No projects or results found on SFTP server.[/yellow]") - + # No tapeout run for this project yet: show its input/output state only + has_input = "Yes" if linked_name in projects else "No" + has_output = "Yes" if linked_name in results else "No" + table.add_row(linked_name, has_input, has_output, "No tapeout yet") + + console.print(table) + # Add informative message about tapeout status - if not archived_projects and all_projects: - console.print("\n[cyan]Note: No tapeout runs have started yet. Your projects are waiting in the queue.[/cyan]") - elif not archived_projects and not all_projects: - console.print("\n[cyan]Note: No projects found and no tapeout runs have started yet.[/cyan]") + if not archived_projects: + console.print(f"\n[cyan]Note: No tapeout runs for {linked_name} have started yet.[/cyan]") finally: if transport: sftp.close() @@ -3124,7 +3126,7 @@ def confirm(project_root, sftp_host, sftp_username, sftp_key, project_name): @main.command('setup') @click.option('--project-root', required=False, type=click.Path(exists=True, file_okay=False), help='Path to the project directory (defaults to current directory).') @click.option('--repo-owner', default='chipfoundry', help='GitHub repository owner (default: chipfoundry)') -@click.option('--repo-name', default='caravel_user_project', help='GitHub repository name (default: caravel_user_project)') +@click.option('--repo-name', default=None, help='GitHub repository name (default: the project-type template, otherwise caravel_user_project)') @click.option('--branch', default='main', help='Branch name (default: main)') @click.option('--pdk', default='sky130A', type=click.Choice(['sky130A', 'sky130B']), help='PDK variant (default: sky130A)') @click.option('--caravel-lite/--no-caravel-lite', default=True, help='Install caravel-lite (default) or full caravel') @@ -3169,6 +3171,8 @@ def setup(project_root, repo_owner, repo_name, branch, pdk, caravel_lite, padframe_only = is_padframe_only(project_type) harness_repo = HARNESS_REPOS.get(project_type) + if repo_name is None: + repo_name = user_project_repo(project_type) had_errors = False @@ -4003,13 +4007,14 @@ def _harden_double_wide( dry_run: bool, list_from_steps: bool, ): - """Harden a `double_wide` macro with LibreLane 3 (native PDN-to-pad routing). + """Harden a `double_wide` macro or wrapper with LibreLane 3. double_wide bypasses the OpenLane-2/Docker-venv path used by every other - project type: its upstream template ships its own `flake.nix` pinning - LibreLane 3, whose native PDN generator (`PDN_ENABLE_PINS`) reaches the - padframe-aligned power pins directly, so no bridging "connection" macro - or cf-cli-managed OpenLane install is needed. + project type. The user-project template ships its own `flake.nix` pinning + LibreLane 3. Macros are hardened on their own, then placed in the wrapper + through a MACROS entry. The wrapper PDN reaches padframe-aligned power + pins directly (`PDN_ENABLE_PINS`) and stitches each macro with + `PDN_MACRO_CONNECTIONS`, so no bridging "connection" macro is needed. """ gui_mode_count = int(open_in_openroad) + int(open_in_klayout) @@ -4220,10 +4225,10 @@ def harden( ): """Harden a macro using LibreLane (OpenLane 2). - For `double_wide` projects, hardens the single flat wrapper design with - LibreLane 3 instead (using the project's own pinned flake.nix), since its - native PDN generator routes directly to the padframe-aligned power pins. - Every other project type is unaffected and keeps using OpenLane 2. + For `double_wide` projects, hardens the named macro or the wrapper with + LibreLane 3 (the project's own pinned flake.nix). The wrapper PDN routes + directly to the padframe-aligned power pins. Every other project type + keeps using OpenLane 2. Examples: cf harden user_proj_example @@ -4363,10 +4368,10 @@ def harden( console.print(f"[yellow]Expected one of: config.json, config.yaml, config.tcl[/yellow]") sys.exit(1) - # `double_wide` is hardened as one flat design with LibreLane 3's native - # PDN-to-pad routing, using the project's own pinned flake.nix instead of - # cf-cli's OpenLane-2 Nix/Docker install. Every other project type falls - # through to the existing OpenLane 2 (CI2511) flow below, unaffected. + # `double_wide` macros and the wrapper are hardened with LibreLane 3, + # using the project's own pinned flake.nix instead of cf-cli's OpenLane-2 + # Nix/Docker install. Every other project type falls through to the + # existing OpenLane 2 (CI2511) flow below. if read_project_type(project_root_path) == "double_wide": _harden_double_wide( macro=macro, @@ -4753,7 +4758,7 @@ def repo_group(): @repo_group.command('update') @click.option('--project-root', required=False, type=click.Path(exists=True, file_okay=False), help='Path to the local ChipFoundry project directory (defaults to current directory if .cf/project.json exists).') @click.option('--repo-owner', default='chipfoundry', help='GitHub repository owner (default: chipfoundry)') -@click.option('--repo-name', default='caravel_user_project', help='GitHub repository name (default: caravel_user_project)') +@click.option('--repo-name', default=None, help='GitHub repository name (default: the project-type template, otherwise caravel_user_project)') @click.option('--branch', default='main', help='Branch name containing the repo.json file (default: main)') @click.option('--dry-run', is_flag=True, help='Preview changes without updating files') def repo_update(project_root, repo_owner, repo_name, branch, dry_run): @@ -4764,7 +4769,10 @@ def repo_update(project_root, repo_owner, repo_name, branch, dry_run): project_root = cwd_root if not project_root: project_root = os.getcwd() - + + if repo_name is None: + repo_name = user_project_repo(read_project_type(Path(project_root))) + console.print(f"[bold cyan]Updating repository files from {repo_owner}/{repo_name}@{branch}[/bold cyan]") try: @@ -5828,6 +5836,22 @@ def _load_project_platform_id(project_root: str): return data.get('project', {}).get('platform_project_id') +def _linked_platform_project_name(project_root: str, config: dict) -> Optional[str]: + """Platform name of the linked project, or None when not linked/logged in. + + SFTP folders are named after the platform project (same name `cf pull` + resolves), so this is the key for filtering SFTP status rows. + """ + platform_id = _load_project_platform_id(project_root) + if not platform_id or not config.get('api_key'): + return None + project = _api_get(f"/projects/{platform_id}") + name = project.get('name') + if not name: + raise click.ClickException(f"Platform project {platform_id} has no name.") + return name + + def _find_remote_results_dir_by_uuid(sftp, platform_id: str) -> Optional[str]: """Scan outgoing/results/*/config/project.json for a directory whose embedded platform_project_id matches `platform_id`. Returns the bare directory name diff --git a/chipfoundry_cli/utils.py b/chipfoundry_cli/utils.py index 8eb77a9..402f519 100644 --- a/chipfoundry_cli/utils.py +++ b/chipfoundry_cli/utils.py @@ -42,11 +42,19 @@ } DEFAULT_HARNESS_REF = "main" -# `double_wide` is hardened as one flat design (no separate macros), and its -# upstream template ships its own flake.nix pinning LibreLane 3: the native -# PDN generator reaches the padframe-aligned power pins directly, so no -# bridging "connection" macro is needed. Every other project type keeps using -# `openlane_version` (LibreLane/OpenLane 2, fetched from cf-cli's versions.json). +# User-project templates `cf repo update` syncs from. Types omitted here keep +# the historical caravel_user_project default. +USER_PROJECT_REPOS: Dict[str, str] = { + "double_wide": "dw_openframe_user_project", +} +DEFAULT_USER_PROJECT_REPO = "caravel_user_project" + +# `double_wide` hardens each macro and the wrapper with LibreLane 3. The +# upstream template (dw_openframe_user_project) ships its own flake.nix: the +# native PDN generator reaches the padframe-aligned power pins directly +# (PDN_ENABLE_PINS) and stitches macro power through PDN_MACRO_CONNECTIONS, +# so no bridging "connection" macro is needed. Every other project type keeps +# using `openlane_version` (LibreLane/OpenLane 2, fetched from cf-cli's versions.json). # Pin the exact commit (not the `3.1.0.dev2` tag) so `nix` resolves it from the # local store/cache without an unauthenticated GitHub API call that can 403. DOUBLE_WIDE_LIBRELANE_REPO = "github:librelane/librelane" @@ -89,6 +97,13 @@ def harness_ref(project_type: str, versions: Optional[dict] = None) -> str: refs = (versions or {}).get("harness_refs") or {} return refs.get(project_type) or DEFAULT_HARNESS_REF + +def user_project_repo(project_type: str) -> str: + """GitHub repo name `cf repo update` syncs for ``project_type``.""" + if project_type in USER_PROJECT_REPOS: + return USER_PROJECT_REPOS[project_type] + return DEFAULT_USER_PROJECT_REPO + USER_DEFINES_REL = "verilog/rtl/user_defines.v" CF_PROJECT_JSON_REL = ".cf/project.json" diff --git a/pyproject.toml b/pyproject.toml index f27aec2..c7d1769 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "chipfoundry-cli" -version = "2.7.2" +version = "2.7.3" description = "CLI tool to automate ChipFoundry project submission to SFTP server" authors = ["ChipFoundry "] readme = "README.md" diff --git a/tests/test_double_wide.py b/tests/test_double_wide.py index 549c7ed..62ffed8 100644 --- a/tests/test_double_wide.py +++ b/tests/test_double_wide.py @@ -16,9 +16,11 @@ GDS_TYPE_MAP, HARNESS_REPOS, PROJECT_TYPES, + USER_PROJECT_REPOS, collect_project_files, harness_ref, is_padframe_only, + user_project_repo, ) WRAPPER = "double_wide_openframe_project_wrapper" @@ -71,6 +73,12 @@ def test_harness_ref_from_versions(self): versions = {"harness_refs": {"double_wide": "DW2026.1"}} assert harness_ref("double_wide", versions) == "DW2026.1" + def test_user_project_repo(self): + assert USER_PROJECT_REPOS["double_wide"] == "dw_openframe_user_project" + assert user_project_repo("double_wide") == "dw_openframe_user_project" + assert user_project_repo("digital") == "caravel_user_project" + assert user_project_repo("openframe") == "caravel_user_project" + def test_collect_without_user_defines(self, tmp_path: Path): (tmp_path / "gds").mkdir() (tmp_path / "gds" / f"{WRAPPER}.gds.gz").write_bytes(b"gz") @@ -86,6 +94,50 @@ def test_collect_rejects_mixed_types(self, tmp_path: Path): collect_project_files(str(tmp_path)) +class TestRepoUpdate: + def test_repo_update_uses_double_wide_template(self, tmp_path: Path, monkeypatch): + _write_project_json(tmp_path) + seen = {} + + def fake_fetch(owner, name, path, branch): + seen["repo"] = (owner, name, path, branch) + return json.dumps({"changes": ["verilog/rtl/double_wide_openframe_project_wrapper.v"]}) + + monkeypatch.setattr("chipfoundry_cli.utils.fetch_github_file", fake_fetch) + result = CliRunner().invoke( + main, ["repo", "update", "--project-root", str(tmp_path), "--dry-run"] + ) + assert result.exit_code == 0, result.output + assert seen["repo"] == ( + "chipfoundry", + "dw_openframe_user_project", + ".cf/repo.json", + "main", + ) + assert "chipfoundry/dw_openframe_user_project@main" in result.output + + def test_repo_update_honors_explicit_repo_name(self, tmp_path: Path, monkeypatch): + _write_project_json(tmp_path) + seen = {} + + def fake_fetch(owner, name, path, branch): + seen["name"] = name + return json.dumps({"changes": []}) + + monkeypatch.setattr("chipfoundry_cli.utils.fetch_github_file", fake_fetch) + result = CliRunner().invoke( + main, + [ + "repo", "update", + "--project-root", str(tmp_path), + "--repo-name", "caravel_user_project", + "--dry-run", + ], + ) + assert result.exit_code == 0, result.output + assert seen["name"] == "caravel_user_project" + + class TestPushAndRemoteDetection: def test_push_candidates_skip_user_defines(self, tmp_path: Path): (tmp_path / "gds").mkdir() @@ -339,3 +391,21 @@ def test_verify_runs_in_openframe_mode(self, dw_project: Path): assert result.exit_code == 0, result.output assert "GPIO configuration not found" not in result.output assert "-t counter -sim RTL --openframe" in result.output.replace("\n", "") + + +class TestLinkedPlatformProjectName: + def test_returns_none_when_not_linked(self, tmp_path: Path, monkeypatch): + monkeypatch.setattr(cf_main, "_load_project_platform_id", lambda _root: None) + assert cf_main._linked_platform_project_name(str(tmp_path), {"api_key": "k"}) is None + + def test_returns_none_when_logged_out(self, tmp_path: Path, monkeypatch): + monkeypatch.setattr(cf_main, "_load_project_platform_id", lambda _root: "pid") + assert cf_main._linked_platform_project_name(str(tmp_path), {}) is None + + def test_returns_platform_name(self, tmp_path: Path, monkeypatch): + monkeypatch.setattr(cf_main, "_load_project_platform_id", lambda _root: "pid") + monkeypatch.setattr(cf_main, "_api_get", lambda path: {"name": "dw-openframe-test"}) + assert ( + cf_main._linked_platform_project_name(str(tmp_path), {"api_key": "k"}) + == "dw-openframe-test" + ) From 6b1a6f156f4e12f16f0319e20afc4582f110c39b Mon Sep 17 00:00:00 2001 From: jdicorpo Date: Tue, 17 Nov 2026 14:47:21 -0800 Subject: [PATCH 2/4] fix(confirm): update existing SFTP project dir instead of creating a case variant cf push can land files under the local folder name (e.g. af-r2) while project.json carries the platform name (AF-R2). cf confirm previously wrote project.json to incoming/projects/, creating a second directory that held only project.json. The shuttle importer then picked the json-only copy and failed with 'Wrapper file not found'. Confirm now resolves the existing directory by platform_project_id (preferring the one with the wrapper GDS), then by case-insensitive name, and only creates a new directory when neither exists. Json-only duplicate directories for the same project are removed after the Final project.json is uploaded. Bump version to 2.7.3. Co-authored-by: Cursor --- chipfoundry_cli/__init__.py | 2 +- chipfoundry_cli/main.py | 196 +++++++++++++++++++++++++++++++++- pyproject.toml | 2 +- tests/test_confirm_command.py | 155 ++++++++++++++++++++++++++- 4 files changed, 351 insertions(+), 4 deletions(-) diff --git a/chipfoundry_cli/__init__.py b/chipfoundry_cli/__init__.py index 9dfd181..be7fecc 100644 --- a/chipfoundry_cli/__init__.py +++ b/chipfoundry_cli/__init__.py @@ -1,2 +1,2 @@ """ChipFoundry CLI package: Automate project submission to SFTP.""" -__version__ = "2.7.2" \ No newline at end of file +__version__ = "2.7.3" \ No newline at end of file diff --git a/chipfoundry_cli/main.py b/chipfoundry_cli/main.py index f23acc6..51b5116 100644 --- a/chipfoundry_cli/main.py +++ b/chipfoundry_cli/main.py @@ -22,7 +22,9 @@ read_project_type, DOUBLE_WIDE_LIBRELANE_REV, ) from chipfoundry_cli import librelane_run +import errno import os +import stat from pathlib import Path from rich.console import Console from rich.panel import Panel @@ -2988,6 +2990,175 @@ def submit(project_root): except SystemExit: raise click.Abort() +_PROJECT_JSON_RELS = (".cf/project.json", "project.json") + + +def _sftp_path_missing(exc: BaseException) -> bool: + if isinstance(exc, FileNotFoundError): + return True + return getattr(exc, "errno", None) == errno.ENOENT + + +def _sftp_walk_files(sftp, path: str, prefix: str = ""): + """Yield file paths relative to ``path``.""" + try: + entries = sftp.listdir_attr(path) + except OSError as exc: + if _sftp_path_missing(exc): + return + raise + for attr in entries: + name = attr.filename + rel = f"{prefix}/{name}" if prefix else name + remote = f"{path}/{name}" + if attr.st_mode is not None and stat.S_ISDIR(attr.st_mode): + yield from _sftp_walk_files(sftp, remote, rel) + else: + yield rel + + +def _read_remote_json(sftp, path: str): + try: + with sftp.open(path, "r") as handle: + raw = handle.read() + except OSError as exc: + if _sftp_path_missing(exc): + return None + raise + if isinstance(raw, bytes): + raw = raw.decode("utf-8") + return json.loads(raw) + + +def _sftp_remove_tree(sftp, path: str) -> None: + for attr in sftp.listdir_attr(path): + remote = f"{path}/{attr.filename}" + if attr.st_mode is not None and stat.S_ISDIR(attr.st_mode): + _sftp_remove_tree(sftp, remote) + else: + sftp.remove(remote) + sftp.rmdir(path) + + +def list_incoming_confirm_candidates(sftp) -> List[dict]: + """Describe each directory under incoming/projects/. + + Each candidate has name, platform_project_id, has_wrapper, and files. + """ + root = "incoming/projects" + try: + entries = sftp.listdir_attr(root) + except OSError as exc: + if _sftp_path_missing(exc): + return [] + raise + + wrapper_rels = {f"gds/{name}" for name in GDS_TYPE_MAP} + candidates = [] + for attr in entries: + if attr.st_mode is not None and not stat.S_ISDIR(attr.st_mode): + continue + name = attr.filename + project_dir = f"{root}/{name}" + files = tuple(_sftp_walk_files(sftp, project_dir)) + platform_id = None + for rel in _PROJECT_JSON_RELS: + if rel not in files: + continue + data = _read_remote_json(sftp, f"{project_dir}/{rel}") + if not isinstance(data, dict): + break + platform_id = str( + ((data.get("project") or {}).get("platform_project_id") or "") + ).strip() or None + break + candidates.append({ + "name": name, + "platform_project_id": platform_id, + "has_wrapper": any(rel in wrapper_rels for rel in files), + "files": files, + }) + return candidates + + +def _is_project_json_only(files) -> bool: + if not files: + return False + return set(files) <= set(_PROJECT_JSON_RELS) + + +def resolve_confirm_sftp_dirname( + requested_name: str, + candidates: List[dict], + platform_project_id: Optional[str] = None, +) -> str: + """Choose the incoming/projects directory cf confirm should update. + + Push may have landed under the local folder name (``af-r2``) while + project.json names the project ``AF-R2``. Confirm must update the + directory that already holds this project's files instead of creating + a second directory that differs only by case. + """ + requested = (requested_name or "").strip() + if not requested: + raise ValueError("project name is required") + + def prefer(matches: List[dict]) -> str: + ranked = sorted( + matches, + key=lambda candidate: ( + 0 if candidate.get("has_wrapper") else 1, + 0 if candidate["name"] == requested else 1, + candidate["name"].casefold(), + ), + ) + return ranked[0]["name"] + + target = (platform_project_id or "").strip() + if target: + id_matches = [ + candidate for candidate in candidates + if (candidate.get("platform_project_id") or "") == target + ] + if id_matches: + return prefer(id_matches) + + folded = requested.casefold() + name_matches = [] + for candidate in candidates: + if candidate["name"].casefold() != folded: + continue + existing_id = (candidate.get("platform_project_id") or "").strip() + if target and existing_id and existing_id != target: + continue + name_matches.append(candidate) + if name_matches: + return prefer(name_matches) + return requested + + +def confirm_duplicate_stub_dirs( + chosen_name: str, + requested_name: str, + candidates: List[dict], + platform_project_id: Optional[str] = None, +) -> List[str]: + """Return json-only directories that duplicate the directory confirm updates.""" + target = (platform_project_id or "").strip() + folds = {chosen_name.casefold(), (requested_name or "").casefold()} + stubs = [] + for candidate in candidates: + if candidate["name"] == chosen_name: + continue + if not _is_project_json_only(candidate.get("files") or ()): + continue + same_id = bool(target) and (candidate.get("platform_project_id") or "") == target + same_name = candidate["name"].casefold() in folds + if same_id or same_name: + stubs.append(candidate["name"]) + return stubs + + @main.command('confirm') @click.option('--project-root', required=False, type=click.Path(exists=True, file_okay=False), help='Path to the local ChipFoundry project directory (defaults to current directory if .cf/project.json exists).') @click.option('--sftp-host', default=DEFAULT_SFTP_HOST, show_default=True, help='SFTP server hostname.') @@ -3080,7 +3251,20 @@ def confirm(project_root, sftp_host, sftp_username, sftp_key, project_name): username=sftp_username, key_path=key_path ) - # Ensure the project directory exists before uploading + platform_project_id = str( + (project_data.get("project") or {}).get("platform_project_id") or "" + ).strip() or None + candidates = list_incoming_confirm_candidates(sftp) + requested_name = final_project_name + final_project_name = resolve_confirm_sftp_dirname( + requested_name, + candidates, + platform_project_id, + ) + if final_project_name != requested_name: + console.print( + f"[yellow]Updating existing upload at incoming/projects/{final_project_name}[/yellow]" + ) sftp_project_dir = f"incoming/projects/{final_project_name}" sftp_ensure_dirs(sftp, sftp_project_dir) except Exception as e: @@ -3098,6 +3282,16 @@ def confirm(project_root, sftp_host, sftp_username, sftp_key, project_name): ) console.print(f"[green]✓ Confirmed project submission: {final_project_name}[/green]") console.print(f"[green]✓ Uploaded project.json to {remote_path}[/green]") + for stub_name in confirm_duplicate_stub_dirs( + final_project_name, + requested_name, + candidates, + platform_project_id, + ): + _sftp_remove_tree(sftp, f"incoming/projects/{stub_name}") + console.print( + f"[yellow]Removed duplicate directory incoming/projects/{stub_name}[/yellow]" + ) except Exception as e: console.print(f"[red]Upload failed: {e}[/red]") diff --git a/pyproject.toml b/pyproject.toml index f27aec2..c7d1769 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "chipfoundry-cli" -version = "2.7.2" +version = "2.7.3" description = "CLI tool to automate ChipFoundry project submission to SFTP server" authors = ["ChipFoundry "] readme = "README.md" diff --git a/tests/test_confirm_command.py b/tests/test_confirm_command.py index ff33162..c7901bb 100644 --- a/tests/test_confirm_command.py +++ b/tests/test_confirm_command.py @@ -1,9 +1,43 @@ """ Unit tests for cf confirm command. """ +import io +import json +import stat + import pytest from click.testing import CliRunner -from chipfoundry_cli.main import main +from chipfoundry_cli.main import ( + confirm_duplicate_stub_dirs, + list_incoming_confirm_candidates, + main, + resolve_confirm_sftp_dirname, +) + + +class _Attr: + def __init__(self, filename, is_dir): + self.filename = filename + self.st_mode = stat.S_IFDIR | 0o755 if is_dir else stat.S_IFREG | 0o644 + + +class _FakeSFTP: + def __init__(self, tree): + self.tree = tree + + def listdir_attr(self, path): + node = self.tree.get(path) + if node is None: + raise FileNotFoundError(path) + if not isinstance(node, dict): + raise NotADirectoryError(path) + return [_Attr(name, isinstance(child, dict)) for name, child in node.items()] + + def open(self, path, mode="r"): + node = self.tree.get(path) + if not isinstance(node, str): + raise FileNotFoundError(path) + return io.StringIO(node) class TestConfirmCommand: @@ -37,5 +71,124 @@ def test_confirm_with_all_options(self): assert result.exit_code != 0 +PID = "af56147b-1994-49e6-a68e-79f9f3c3f081" + + +def test_confirm_updates_the_directory_that_has_the_wrapper(): + candidates = [ + { + "name": "AF-R2", + "platform_project_id": PID, + "has_wrapper": False, + "files": (".cf/project.json",), + }, + { + "name": "af-r2", + "platform_project_id": PID, + "has_wrapper": True, + "files": (".cf/project.json", "gds/openframe_project_wrapper.gds"), + }, + ] + + assert resolve_confirm_sftp_dirname("AF-R2", candidates, PID) == "af-r2" + + +def test_confirm_uses_the_project_name_when_nothing_is_uploaded_yet(): + assert resolve_confirm_sftp_dirname("AF-R2", [], PID) == "AF-R2" + + +def test_confirm_keeps_an_exact_directory_that_already_has_the_wrapper(): + candidates = [ + { + "name": "AF-R2", + "platform_project_id": PID, + "has_wrapper": True, + "files": (".cf/project.json", "gds/openframe_project_wrapper.gds"), + } + ] + + assert resolve_confirm_sftp_dirname("AF-R2", candidates, PID) == "AF-R2" + + +def test_confirm_matches_a_case_variant_by_directory_name(): + candidates = [ + { + "name": "af-a2", + "platform_project_id": None, + "has_wrapper": True, + "files": ("gds/openframe_project_wrapper.gds",), + } + ] + + assert resolve_confirm_sftp_dirname("AF-A2", candidates, PID) == "af-a2" + + +def test_confirm_does_not_reuse_a_different_project_with_the_same_spelling(): + candidates = [ + { + "name": "af-r2", + "platform_project_id": "someone-else", + "has_wrapper": True, + "files": ("gds/openframe_project_wrapper.gds",), + } + ] + + assert resolve_confirm_sftp_dirname("AF-R2", candidates, PID) == "AF-R2" + + +def test_confirm_stub_dirs_are_json_only_duplicates(): + candidates = [ + { + "name": "AF-R2", + "platform_project_id": PID, + "has_wrapper": False, + "files": (".cf/project.json",), + }, + { + "name": "af-r2", + "platform_project_id": PID, + "has_wrapper": True, + "files": (".cf/project.json", "gds/openframe_project_wrapper.gds"), + }, + { + "name": "notes", + "platform_project_id": PID, + "has_wrapper": False, + "files": (".cf/project.json", "README.md"), + }, + ] + + assert confirm_duplicate_stub_dirs("af-r2", "AF-R2", candidates, PID) == ["AF-R2"] + + +def test_list_incoming_confirm_candidates_reads_project_json_and_wrapper(): + project_json = json.dumps({"project": {"platform_project_id": PID, "name": "AF-R2"}}) + sftp = _FakeSFTP({ + "incoming/projects": { + "af-r2": {}, + "AF-R2": {}, + }, + "incoming/projects/af-r2": { + ".cf": {}, + "gds": {}, + }, + "incoming/projects/af-r2/.cf": {"project.json": project_json}, + "incoming/projects/af-r2/.cf/project.json": project_json, + "incoming/projects/af-r2/gds": {"openframe_project_wrapper.gds": "gds-bytes"}, + "incoming/projects/af-r2/gds/openframe_project_wrapper.gds": "gds-bytes", + "incoming/projects/AF-R2": {".cf": {}}, + "incoming/projects/AF-R2/.cf": {"project.json": project_json}, + "incoming/projects/AF-R2/.cf/project.json": project_json, + }) + + candidates = list_incoming_confirm_candidates(sftp) + by_name = {candidate["name"]: candidate for candidate in candidates} + + assert by_name["af-r2"]["has_wrapper"] is True + assert by_name["af-r2"]["platform_project_id"] == PID + assert by_name["AF-R2"]["has_wrapper"] is False + assert resolve_confirm_sftp_dirname("AF-R2", candidates, PID) == "af-r2" + + if __name__ == '__main__': pytest.main([__file__, '-v']) From 4671b7f01ddafa50792ebe6da504521ef76af1ac Mon Sep 17 00:00:00 2001 From: jdicorpo Date: Tue, 17 Nov 2026 14:49:30 -0800 Subject: [PATCH 3/4] ci: pin Linux unit test runner to ubuntu-22.04 ubuntu-latest now resolves to Ubuntu 26.04, which has no Python 3.8 in the setup-python toolcache, so the 3.8 job fails before running tests. Co-authored-by: Cursor --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 196fc69..587585a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,7 +11,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest, macos-latest] + os: [ubuntu-22.04, macos-latest] python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] steps: From 09ebb50d1bce959e63437c199655c350ddb50a81 Mon Sep 17 00:00:00 2001 From: jdicorpo Date: Tue, 17 Nov 2026 15:02:38 -0800 Subject: [PATCH 4/4] test: print precheck dry run on one line in CI Co-authored-by: Cursor --- tests/test_double_wide.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_double_wide.py b/tests/test_double_wide.py index 62ffed8..3aa5a9b 100644 --- a/tests/test_double_wide.py +++ b/tests/test_double_wide.py @@ -243,13 +243,16 @@ def test_precheck_local_source(self, dw_project: Path, tmp_path_factory, monkeyp (src / "pyproject.toml").write_text("[project]\nname = 'cf-precheck'\n") monkeypatch.setenv("CF_PRECHECK_SOURCE", str(src)) monkeypatch.setattr(cf_main.shutil, "which", lambda name: f"/usr/bin/{name}") + # CI has no TTY, so Rich wraps at 80 columns and a break can eat the + # space in "install -q". Print the dry run on one line. + monkeypatch.setattr(cf_main.console, "width", 10000) result = CliRunner().invoke( main, ["precheck", "--project-root", str(dw_project), "--dry-run"] ) assert result.exit_code == 0, result.output out = result.output.replace("\n", "") assert f"-v {src.resolve()}:{src.resolve()}:ro" in out - assert f"pip3 install -q --root-user-action=ignore /tmp/cf-precheck-src" in out + assert "pip3 install -q --root-user-action=ignore /tmp/cf-precheck-src" in out assert "--upgrade -q --root-user-action=ignore cf-precheck" not in out def test_precheck_rejects_bad_local_source(self, dw_project: Path, tmp_path, monkeypatch):