From 9949c5115798d5231c007f592dbb4d8ea8d7b2e8 Mon Sep 17 00:00:00 2001 From: Justin Wei Date: Mon, 16 Nov 2026 02:17:25 -0600 Subject: [PATCH 1/2] Fix Windows setup, wrapper working directory, and per-repo bin path --- .bazelrc | 10 ++----- .github/workflows/ci.yml | 2 +- README.md | 9 ++++-- bin/bazel.py | 8 +----- bin/goimports.py | 2 +- bin/ruff.py | 4 +-- bin/rustfmt.py | 2 +- bin/staticcheck.py | 2 +- bin/wrapper_utils.py | 13 ++------- py/main.py | 1 + py/wrappers_test.py | 41 +++++++++++---------------- setup.py | 17 ++++++------ tools/BUILD.bazel | 37 +++++++++++++++++++------ tools/run_in_cwd.py | 60 ++++++++++++++++++++++++++++++++++++++++ 14 files changed, 131 insertions(+), 77 deletions(-) create mode 100644 tools/run_in_cwd.py diff --git a/.bazelrc b/.bazelrc index f10cdab..0175683 100644 --- a/.bazelrc +++ b/.bazelrc @@ -16,16 +16,10 @@ build:windows --action_env=SYSTEMROOT build:windows --action_env=TEMP build:windows --action_env=TMP -# Symlink-based runfiles require Windows Developer Mode. -# We disable them by default to ensure portability; Bazel will use a -# manifest file instead. -build:windows --enable_runfiles=no +# Windows requires Developer Mode enabled for symlink-based runfiles and tooling. +build:windows --enable_runfiles build:windows --nolegacy_external_runfiles -# Force rules_python to use the 'script' bootstrap instead of the new 'venv' -# bootstrap on Windows, as the latter requires symlink privileges (WinError 1314). -build:windows --@rules_python//python/config_settings:bootstrap_impl=script - # Link Rust targets on Windows using the bundled rust-lld linker from the # hermetic x86_64-pc-windows-gnu toolchain instead of the C++ toolchain wrapper. build:windows --@rules_rust//rust/settings:toolchain_linker_preference=rust diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5da92cb..3a97104 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: - name: Add wrappers and tools to PATH run: | echo "${{ github.workspace }}/bin" >> $GITHUB_PATH - echo "$HOME/.local/bin" >> $GITHUB_PATH + echo "$HOME/.local/justhecuke/bazel-template/bin" >> $GITHUB_PATH - name: Set up Bazel uses: bazel-contrib/setup-bazel@0.19.0 diff --git a/README.md b/README.md index 759d411..7eed27a 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,11 @@ This repository uses a completely hermetic Bazel setup. You should **not** insta To bootstrap this environment, we use `mise` to automatically manage your `PATH`. +### 0. Prerequisites (Windows) +Enable **Windows Developer Mode** (*Settings → System → For developers → Developer Mode*), which is required for symlink-based Bazel runfiles and tooling. + ### 1. Provision System Dependencies -Run the initial setup script to download the required global bootstrappers (`bazelisk` and `mise`). We recommend using the `--add-to-path` flag to update your system PATH, and the `--configure-shell` flag to automatically inject activation into your shell profile. +Run the initial setup script to download the required global bootstrappers (`bazelisk`, `mise`, and `prek`). We recommend using the `--add-to-path` flag to update your system PATH, and the `--configure-shell` flag to automatically inject activation into your shell profile. **On Windows (PowerShell):** ```powershell @@ -19,14 +22,14 @@ python setup.py --add-to-path --configure-shell $PROFILE ```bash python setup.py --configure-shell ~/.bashrc # or ~/.zshrc ``` -*Note: On Windows, binaries are installed to `C:\dev\bin` (this can be automatically added to your Windows User `PATH` via the `--add-to-path` flag). On Mac/Linux, they are installed to `~/.local/bin`.* +*Note: On Windows, binaries are installed to `%LOCALAPPDATA%\justhecuke\bazel-template\bin` (this can be automatically added to your Windows User `PATH` via the `--add-to-path` flag). On Mac/Linux, they are installed to `~/.local/justhecuke/bazel-template/bin`.* ### 2. Restart Your IDE Completely `setup.py` modifies your Windows User `PATH` in the registry. This change **will not be visible** to any terminal that was already open, including "new terminal" tabs inside your IDE — those inherit the IDE process's environment, which was frozen at launch time. **You must completely close and reopen your IDE** (or open a fresh terminal outside the IDE, e.g. Windows Terminal / PowerShell directly) for the new `PATH` to take effect. -> **Tip:** You can verify the path is correct by running `where.exe mise` in a fresh terminal. It should print `C:\dev\bin\mise.exe`. If it prints a path containing spaces (like `C:\Users\...`), you have a stale terminal and need to restart your IDE. +> **Tip:** You can verify the path is correct by running `where.exe bazelisk` in a fresh terminal. It should print `%LOCALAPPDATA%\justhecuke\bazel-template\bin\bazelisk.exe`. ### 3. Trust the Project Open a new terminal in the root of the project and trust the `.mise.toml` configuration: diff --git a/bin/bazel.py b/bin/bazel.py index ea6d789..0b49978 100644 --- a/bin/bazel.py +++ b/bin/bazel.py @@ -21,8 +21,7 @@ def _bootstrap_venv(venv_dir: Path) -> None: """Ensure an isolated Python venv exists for Bazel bootstrap.""" if not venv_dir.is_dir(): print("Bootstrapping isolated Python venv...") - python_exe = "python3" if shutil.which("python3") else "python" - subprocess.run([python_exe, "-m", "venv", str(venv_dir)], check=True) + subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True) def _setup_windows_bash(env: dict[str, str]) -> None: @@ -57,11 +56,6 @@ def _get_bazel_cmd(env: dict[str, str]) -> tuple[str, list[str]]: if env.get("CI") == "true" and "--config=ci" not in sys.argv: cmd.insert(2, "--config=ci") - # On Windows, enable runfiles by default as many Python-based tools (like Gazelle) depend on them. - if sys.platform == "win32" and len(sys.argv) > 1 and sys.argv[1] in ["run", "test", "build"]: - if "--enable_runfiles" not in sys.argv: - cmd.insert(2, "--enable_runfiles") - return bazel_exe, cmd diff --git a/bin/goimports.py b/bin/goimports.py index 4933a75..eba2fd8 100644 --- a/bin/goimports.py +++ b/bin/goimports.py @@ -20,7 +20,7 @@ def main() -> None: # Use the local alias defined in //tools:BUILD.bazel - run_bazel_target("//tools:goimports", extra_args=sys.argv[1:], resolve_paths=True) + run_bazel_target("//tools:goimports", extra_args=sys.argv[1:]) if __name__ == "__main__": diff --git a/bin/ruff.py b/bin/ruff.py index 95a3090..cb9dfcc 100644 --- a/bin/ruff.py +++ b/bin/ruff.py @@ -32,8 +32,8 @@ def main() -> None: else: args.insert(0, f"--config={pyproject_toml.resolve()}") - # Use the local alias defined in //tools:BUILD.bazel - run_bazel_target("//tools:ruff", extra_args=args) + # Use the CLI wrapper target defined in //tools:BUILD.bazel + run_bazel_target("//tools:ruff_cli", extra_args=args) if __name__ == "__main__": diff --git a/bin/rustfmt.py b/bin/rustfmt.py index b04392e..38f6109 100644 --- a/bin/rustfmt.py +++ b/bin/rustfmt.py @@ -20,7 +20,7 @@ def main() -> None: # Use the local alias defined in //tools:BUILD.bazel - run_bazel_target("//tools:rustfmt", extra_args=sys.argv[1:], resolve_paths=True) + run_bazel_target("//tools:rustfmt", extra_args=sys.argv[1:]) if __name__ == "__main__": diff --git a/bin/staticcheck.py b/bin/staticcheck.py index 3a9801a..71c3c12 100644 --- a/bin/staticcheck.py +++ b/bin/staticcheck.py @@ -25,7 +25,7 @@ def main() -> None: if not args: args = ["./..."] - run_bazel_target("//tools:staticcheck", extra_args=args, resolve_paths=False) + run_bazel_target("//tools:staticcheck", extra_args=args) if __name__ == "__main__": diff --git a/bin/wrapper_utils.py b/bin/wrapper_utils.py index 2a8a5c5..e74e56b 100644 --- a/bin/wrapper_utils.py +++ b/bin/wrapper_utils.py @@ -22,17 +22,13 @@ def run_bazel_target( target: str, extra_args: list[str] | None = None, - resolve_paths: bool = True, command: str = "run", ) -> None: """Run a Bazel target via the local bazel.py wrapper. Args: target: The Bazel target or target pattern (e.g. //tools:ruff or //...). - extra_args: Additional arguments forwarded after `--` to the target. - resolve_paths: If True, any file arguments following a `--` separator - are resolved to absolute paths. This is needed for tools like ruff - that are invoked by prek with workspace-relative file paths. + extra_args: Additional arguments forwarded verbatim to the target. command: Bazel command to invoke ('run' or 'build'). Defaults to 'run'. """ bin_dir = pathlib.Path(__file__).parent @@ -41,12 +37,7 @@ def run_bazel_target( if command == "run": cmd = [sys.executable, bazel_py, "run", target, "--"] if extra_args: - if resolve_paths and "--" in extra_args: - sep_idx = extra_args.index("--") - cmd.extend(extra_args[: sep_idx + 1]) - cmd.extend(str(pathlib.Path(f).resolve()) for f in extra_args[sep_idx + 1 :]) - else: - cmd.extend(extra_args) + cmd.extend(extra_args) else: cmd = [sys.executable, bazel_py, command] if extra_args: diff --git a/py/main.py b/py/main.py index 227b1db..5348d12 100644 --- a/py/main.py +++ b/py/main.py @@ -2,6 +2,7 @@ import requests from cyclopts import App + from py.calculator import evaluate_expression app = App() diff --git a/py/wrappers_test.py b/py/wrappers_test.py index 53c18ea..2583115 100644 --- a/py/wrappers_test.py +++ b/py/wrappers_test.py @@ -412,33 +412,24 @@ def test_script_location_resolution(self) -> None: class WrapperUtilsLogicTest(unittest.TestCase): """Unit tests verifying wrapper_utils.py argument handling.""" - def test_path_resolution_after_double_dash(self) -> None: - """run_bazel_target logic must resolve file paths after '--' to absolute paths.""" - extra_args = ["-lint", "fix", "--", "BUILD.bazel", "MODULE.bazel"] - resolve_paths = True - - cmd: list[str] = ["python", "bazel.py", "run", "//tools:buildifier", "--"] - if extra_args: - if resolve_paths and "--" in extra_args: - sep_idx = extra_args.index("--") - cmd.extend(extra_args[: sep_idx + 1]) - cmd.extend(str(Path(f).resolve()) for f in extra_args[sep_idx + 1 :]) - else: - cmd.extend(extra_args) - - self.assertEqual(cmd[5], "-lint") - self.assertEqual(cmd[6], "fix") - self.assertEqual(cmd[7], "--") - # Ensure arguments following '--' became absolute paths - self.assertTrue(Path(cmd[8]).is_absolute(), f"Expected absolute path: {cmd[8]}") - self.assertTrue(Path(cmd[9]).is_absolute(), f"Expected absolute path: {cmd[9]}") - - def test_no_double_dash_leaves_args_untouched(self) -> None: - """When '--' is not present in extra_args, arguments must be preserved as-is.""" - extra_args = ["version"] + def test_no_resolve_paths_argument(self) -> None: + """run_bazel_target must not rewrite arguments as paths.""" + wrapper_utils_py = get_bin_dir() / "wrapper_utils.py" + content = wrapper_utils_py.read_text(encoding="utf-8") + self.assertNotIn( + "resolve_paths", + content, + "wrapper_utils.py must not rewrite arguments via resolve_paths; tools run in BUILD_WORKING_DIRECTORY.", + ) + + def test_arguments_forwarded_verbatim(self) -> None: + """Arguments including '--' and non-file args (like Go's 'unsafe') must be preserved verbatim.""" + extra_args = ["list", "-f", "{{.Dir}}", "--", "unsafe"] cmd: list[str] = ["python", "bazel.py", "run", "@rules_go//go", "--"] cmd.extend(extra_args) - self.assertEqual(cmd, ["python", "bazel.py", "run", "@rules_go//go", "--", "version"]) + self.assertEqual( + cmd, ["python", "bazel.py", "run", "@rules_go//go", "--", "list", "-f", "{{.Dir}}", "--", "unsafe"] + ) if __name__ == "__main__": diff --git a/setup.py b/setup.py index cf523f2..68a9d16 100644 --- a/setup.py +++ b/setup.py @@ -42,10 +42,6 @@ "prek-aarch64-unknown-linux-gnu.tar.gz": "0112ffa44a0aaa869aa9da45393b7a4d7c30c24abd6e540bac0494db24844c79", } -# On Windows, install to C:\dev\bin — a conventional, space-free developer tools directory. -# This avoids a known bug in `mise activate pwsh` that breaks when the path contains spaces -# (common for Windows user profiles like C:\Users\John Doe\...). -WINDOWS_LOCAL_BIN = r"C:\dev\bin" SETUP_START_MARKER = "# " SETUP_END_MARKER = "# " @@ -55,8 +51,9 @@ def get_local_bin(os_name: str | None = None) -> Path: if os_name is None: os_name, _, _ = get_platform_info() if os_name == "windows": - return Path(WINDOWS_LOCAL_BIN) - return Path.home() / ".local" / "bin" + local_app_data = Path(os.environ.get("LOCALAPPDATA") or (Path.home() / "AppData" / "Local")) + return local_app_data / "justhecuke" / "bazel-template" / "bin" + return Path.home() / ".local" / "justhecuke" / "bazel-template" / "bin" def get_platform_info() -> tuple[str, str, str]: @@ -322,7 +319,8 @@ def configure_shell_profile(profile_path: str, local_bin: str) -> bool: local_bin_path = Path(local_bin) if shell_type == "pwsh": - mise_exe = str(local_bin_path / "mise.exe").replace("\\", "\\\\") + local_mise = local_bin_path / "mise.exe" + mise_exe = str(local_mise) if local_mise.exists() else (shutil.which("mise") or str(local_mise)) activation_block = ( f'{SETUP_START_MARKER}\n& "{mise_exe}" activate pwsh | Out-String | Invoke-Expression\n{SETUP_END_MARKER}\n' ) @@ -369,7 +367,8 @@ def ensure_windows_path(*paths: Path) -> bool: if ($currentPath -eq $null) {{ $currentPath = '' }} - if (-not $currentPath.Contains('{path_str}')) {{ + $entries = $currentPath -split ';' | Where-Object {{ $_ -ne '' }} + if ($entries -notcontains '{path_str}') {{ $newPath = $currentPath if ($newPath -and -not $newPath.EndsWith(';')) {{ $newPath += ';' @@ -425,7 +424,7 @@ def main() -> None: print("\n[ok] Setup complete!") if os_name != "windows": - print("Ensure ~/.local/bin (and ~/.local/share/mise/bin if using mise) is in your PATH.") + print(f"Ensure {local_bin_str} (and ~/.local/share/mise/bin if using mise) is in your PATH.") needs_restart = path_modified or profile_modified if needs_restart: diff --git a/tools/BUILD.bazel b/tools/BUILD.bazel index 6651568..cedb81a 100644 --- a/tools/BUILD.bazel +++ b/tools/BUILD.bazel @@ -6,15 +6,30 @@ alias( visibility = ["//visibility:public"], ) -alias( +py_binary( + name = "ruff_cli", + srcs = ["run_in_cwd.py"], + args = ["$(rlocationpath @ruff//:ruff)"], + data = ["@ruff"], + main = "run_in_cwd.py", + visibility = ["//visibility:public"], +) + +py_binary( name = "buildifier", - actual = "@buildifier_prebuilt//:buildifier", + srcs = ["run_in_cwd.py"], + args = ["$(rlocationpath @buildifier_prebuilt//:buildifier)"], + data = ["@buildifier_prebuilt//:buildifier"], + main = "run_in_cwd.py", visibility = ["//visibility:public"], ) -alias( +py_binary( name = "buildozer", - actual = "@buildifier_prebuilt//:buildozer", + srcs = ["run_in_cwd.py"], + args = ["$(rlocationpath @buildifier_prebuilt//:buildozer)"], + data = ["@buildifier_prebuilt//:buildozer"], + main = "run_in_cwd.py", visibility = ["//visibility:public"], ) @@ -27,15 +42,21 @@ py_binary( deps = ["@pip//pyrefly"], ) -alias( +py_binary( name = "goimports", - actual = "@org_golang_x_tools//cmd/goimports:goimports", + srcs = ["run_in_cwd.py"], + args = ["$(rlocationpath @org_golang_x_tools//cmd/goimports:goimports)"], + data = ["@org_golang_x_tools//cmd/goimports"], + main = "run_in_cwd.py", visibility = ["//visibility:public"], ) -alias( +py_binary( name = "staticcheck", - actual = "@co_honnef_go_tools//cmd/staticcheck:staticcheck", + srcs = ["run_in_cwd.py"], + args = ["$(rlocationpath @co_honnef_go_tools//cmd/staticcheck:staticcheck)"], + data = ["@co_honnef_go_tools//cmd/staticcheck"], + main = "run_in_cwd.py", visibility = ["//visibility:public"], ) diff --git a/tools/run_in_cwd.py b/tools/run_in_cwd.py new file mode 100644 index 0000000..b2ce059 --- /dev/null +++ b/tools/run_in_cwd.py @@ -0,0 +1,60 @@ +"""Run a bundled Bazel tool binary in the user's original working directory.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +EXPECTED_MANIFEST_PARTS = 2 +MIN_ARGV_LEN = 2 + + +def _resolve_runfile(rlocation_path: str) -> Path: + """Resolve a Bazel rlocationpath via RUNFILES_MANIFEST_FILE or RUNFILES_DIR.""" + normalized = rlocation_path.replace("\\", "/") + + manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE") + if manifest_file: + manifest_path = Path(manifest_file) + if manifest_path.is_file(): + for line in manifest_path.read_text(encoding="utf-8").splitlines(): + parts = line.split(" ", 1) + if len(parts) == EXPECTED_MANIFEST_PARTS and parts[0] == normalized: + return Path(parts[1]) + + runfiles_dir = os.environ.get("RUNFILES_DIR") + if runfiles_dir: + candidate = Path(runfiles_dir) / normalized + if candidate.exists(): + return candidate + + # Fallback: relative to this script's runfiles root + fallback = Path(__file__).resolve().parent.parent / normalized + if fallback.exists(): + return fallback + + raise FileNotFoundError(f"Could not locate runfile: {rlocation_path}") + + +def main() -> None: + if len(sys.argv) < MIN_ARGV_LEN: + print("Usage: run_in_cwd.py [args...]", file=sys.stderr) + sys.exit(1) + + tool_path = _resolve_runfile(sys.argv[1]) + tool_args = sys.argv[2:] + + working_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") + if working_dir: + os.chdir(working_dir) + + if sys.platform != "win32": + os.execv(str(tool_path), [str(tool_path), *tool_args]) + else: + sys.exit(subprocess.run([str(tool_path), *tool_args], check=False).returncode) + + +if __name__ == "__main__": + main() From 3374d4675a9aad0c75fcd9cb6bfaabd5618f863a Mon Sep 17 00:00:00 2001 From: Justin Wei Date: Mon, 16 Nov 2026 02:43:22 -0600 Subject: [PATCH 2/2] Fix executable permissions on POSIX launchers in bin/ --- bin/cargo | 0 bin/clippy | 0 bin/gh | 0 bin/go | 0 bin/goimports | 0 bin/pyrefly | 0 bin/rustfmt | 0 bin/staticcheck | 0 py/testdata/sample_tool | 0 py/wrappers_test.py | 5 +++++ 10 files changed, 5 insertions(+) mode change 100644 => 100755 bin/cargo mode change 100644 => 100755 bin/clippy mode change 100644 => 100755 bin/gh mode change 100644 => 100755 bin/go mode change 100644 => 100755 bin/goimports mode change 100644 => 100755 bin/pyrefly mode change 100644 => 100755 bin/rustfmt mode change 100644 => 100755 bin/staticcheck mode change 100644 => 100755 py/testdata/sample_tool diff --git a/bin/cargo b/bin/cargo old mode 100644 new mode 100755 diff --git a/bin/clippy b/bin/clippy old mode 100644 new mode 100755 diff --git a/bin/gh b/bin/gh old mode 100644 new mode 100755 diff --git a/bin/go b/bin/go old mode 100644 new mode 100755 diff --git a/bin/goimports b/bin/goimports old mode 100644 new mode 100755 diff --git a/bin/pyrefly b/bin/pyrefly old mode 100644 new mode 100755 diff --git a/bin/rustfmt b/bin/rustfmt old mode 100644 new mode 100755 diff --git a/bin/staticcheck b/bin/staticcheck old mode 100644 new mode 100755 diff --git a/py/testdata/sample_tool b/py/testdata/sample_tool old mode 100644 new mode 100755 diff --git a/py/wrappers_test.py b/py/wrappers_test.py index 2583115..c725f91 100644 --- a/py/wrappers_test.py +++ b/py/wrappers_test.py @@ -217,6 +217,11 @@ def test_wrapper_triplet_integrity(self) -> None: posix_launcher.exists(), f"Missing POSIX launcher for {tool}: expected {posix_launcher}", ) + if sys.platform != "win32": + self.assertTrue( + os.access(posix_launcher, os.X_OK), + f"POSIX launcher for {tool} must be executable (+x): {posix_launcher}", + ) posix_content = posix_launcher.read_text(encoding="utf-8").strip() self.assertTrue( posix_content.startswith("#!/usr/bin/env bash"),