Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
8 changes: 1 addition & 7 deletions bin/bazel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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


Expand Down
Empty file modified bin/cargo
100644 → 100755
Empty file.
Empty file modified bin/clippy
100644 → 100755
Empty file.
Empty file modified bin/gh
100644 → 100755
Empty file.
Empty file modified bin/go
100644 → 100755
Empty file.
Empty file modified bin/goimports
100644 → 100755
Empty file.
2 changes: 1 addition & 1 deletion bin/goimports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
Empty file modified bin/pyrefly
100644 → 100755
Empty file.
4 changes: 2 additions & 2 deletions bin/ruff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
Empty file modified bin/rustfmt
100644 → 100755
Empty file.
2 changes: 1 addition & 1 deletion bin/rustfmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
Empty file modified bin/staticcheck
100644 → 100755
Empty file.
2 changes: 1 addition & 1 deletion bin/staticcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
13 changes: 2 additions & 11 deletions bin/wrapper_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
1 change: 1 addition & 0 deletions py/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import requests
from cyclopts import App

from py.calculator import evaluate_expression

app = App()
Expand Down
Empty file modified py/testdata/sample_tool
100644 → 100755
Empty file.
46 changes: 21 additions & 25 deletions py/wrappers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -412,33 +417,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__":
Expand Down
17 changes: 8 additions & 9 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "# <bazel-template-setup-start>"
SETUP_END_MARKER = "# <bazel-template-setup-end>"

Expand All @@ -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]:
Expand Down Expand Up @@ -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'
)
Expand Down Expand Up @@ -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 += ';'
Expand Down Expand Up @@ -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:
Expand Down
37 changes: 29 additions & 8 deletions tools/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
)

Expand All @@ -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"],
)

Expand Down
60 changes: 60 additions & 0 deletions tools/run_in_cwd.py
Original file line number Diff line number Diff line change
@@ -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 <tool_rlocationpath> [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()
Loading