Skip to content
Open
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
22 changes: 16 additions & 6 deletions src/specify_cli/shared_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,20 @@ def _ensure_safe_shared_destination(
raise ValueError(f"Shared infrastructure destination escapes project root: {label}") from None


def _shared_script_mode(src_path: Path, content: bytes) -> int:
"""Return the mode a shared script is written with.

Packaged scripts are 0644. A POSIX shell script that starts with a shebang
gets an execute bit for each class that can read it (always for the owner),
the rule ``ensure_executable_scripts`` applies, so a refresh that rewrites
it leaves it runnable without a separate chmod pass.
"""
mode = src_path.stat().st_mode & 0o777
if os.name != "nt" and src_path.suffix == ".sh" and content.startswith(b"#!"):
mode |= ((mode & 0o444) >> 2) | 0o100
Comment on lines +329 to +330

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 3f7bdc0: tests/test_shared_infra_script_mode.py calls _shared_script_mode() with explicit source modes (0644 → 0755, 0640 → 0750, 0600 → 0700, 0755 unchanged) and checks the packaged mode is kept for a shebang-less .sh, an empty .sh, .ps1, .py, and for a .sh with os.name set to nt.

Drafted on behalf of @kartsan03 by Claude Code (model: claude-fable-5-2, autonomous); it also wrote the tests and ran them.

return mode


def _write_shared_text(project_path: Path, dest: Path, content: str) -> None:
_write_shared_bytes(project_path, dest, content.encode("utf-8"))

Expand Down Expand Up @@ -636,13 +650,9 @@ def _ensure_or_bucket_dir(directory: Path) -> bool:
content = _resolve_dynamic_command_refs(
content, invoke_separator, invoke_prefix
)
data = content.encode("utf-8")
planned_copies.append(
(
dst_path,
rel,
content.encode("utf-8"),
src_path.stat().st_mode & 0o777,
)
(dst_path, rel, data, _shared_script_mode(src_path, data))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 3f7bdc0: test_failed_switch_restores_shared_script_mode_and_content in test_installed_adapters.py. With the external sample adapter installed, the managed bash scripts are set to 0644, integration switch copilot --script sh refreshes them, and installer.write_records then fails. The failing step asserts the scripts are 0755 at that point; after the rollback the project snapshot equals the one taken before and every script is 0644 again. With shared_infra.py from main the test fails at the 0755 assert.

Drafted on behalf of @kartsan03 by Claude Code (model: claude-fable-5-2, autonomous); it also wrote the tests and ran them.

)

templates_src = shared_templates_source(core_pack=core_pack, repo_root=repo_root)
Expand Down
22 changes: 22 additions & 0 deletions tests/specify_cli/integrations/test_command_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,28 @@ def _project_file_state(project):


class TestIntegrationSwitch:
@pytest.mark.skipif(
os.name == "nt", reason="POSIX execute bits are not meaningful on Windows"
)
@pytest.mark.parametrize(
("target_state", "flags"),
[("new", []), ("installed", []), ("default", ["--force"]), ("default", ["--refresh-shared-infra"])],
)
def test_switch_keeps_shared_scripts_executable(self, tmp_path, target_state, flags):
"""Every switch path refreshes shared scripts; they must stay runnable."""
if target_state == "default":
project = _init_project(tmp_path, "codex")
else:
project = _init_codex_switch_project(tmp_path, target_state)
scripts = sorted((project / ".specify" / "scripts" / "bash").glob("*.sh"))
assert scripts and all(os.access(script, os.X_OK) for script in scripts)

result = _run_in_project(project, ["integration", "switch", "codex", *flags])

assert result.exit_code == 0, result.output
not_executable = [script.name for script in scripts if not os.access(script, os.X_OK)]
assert not not_executable, f"switch left shared scripts non-executable: {not_executable}"

@pytest.mark.parametrize("target_state", ["new", "installed", "default"])
@pytest.mark.parametrize(
"flags", [[], ["--force"], ["--refresh-shared-infra"], ["--force", "--refresh-shared-infra"]],
Expand Down
17 changes: 17 additions & 0 deletions tests/specify_cli/integrations/test_command_uninstall.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,23 @@ def _registered_agents(project, kind, package_id):
return set(registry[kind][package_id]["registered_commands"])

class TestIntegrationUninstall:
@pytest.mark.skipif(
os.name == "nt", reason="POSIX execute bits are not meaningful on Windows"
)
def test_uninstall_default_keeps_fallback_scripts_executable(self, tmp_path):
"""Falling back to another installed integration must keep shared scripts runnable."""
project = _init_project(tmp_path, "claude")
result = _run_in_project(project, ["integration", "install", "codex", "--script", "sh"])
assert result.exit_code == 0, result.output
scripts = sorted((project / ".specify" / "scripts" / "bash").glob("*.sh"))
assert scripts and all(os.access(script, os.X_OK) for script in scripts)

result = _run_in_project(project, ["integration", "uninstall", "claude"])

assert result.exit_code == 0, result.output
not_executable = [script.name for script in scripts if not os.access(script, os.X_OK)]
assert not not_executable, f"uninstall left shared scripts non-executable: {not_executable}"

@pytest.mark.parametrize("command", ["uninstall", "switch"])
def test_unreadable_dispatcher_preserves_other_cleanup(self, tmp_path, monkeypatch, caplog, command):
from specify_cli.events import install_integration_events
Expand Down
48 changes: 48 additions & 0 deletions tests/specify_cli/integrations/test_command_use.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,54 @@
)

class TestIntegrationUse:
@pytest.mark.skipif(
os.name == "nt", reason="POSIX execute bits are not meaningful on Windows"
)
def test_use_keeps_shared_scripts_executable(self, tmp_path):
"""Making an installed integration the default must keep shared scripts runnable."""
project = _init_project(tmp_path, "claude")
result = _run_in_project(project, ["integration", "install", "codex", "--script", "sh"])
assert result.exit_code == 0, result.output
scripts = sorted((project / ".specify" / "scripts" / "bash").glob("*.sh"))
assert scripts and all(os.access(script, os.X_OK) for script in scripts)

result = _run_in_project(project, ["integration", "use", "codex"])

assert result.exit_code == 0, result.output
not_executable = [script.name for script in scripts if not os.access(script, os.X_OK)]
assert not not_executable, f"use left shared scripts non-executable: {not_executable}"

@pytest.mark.skipif(
os.name == "nt", reason="POSIX execute bits are not meaningful on Windows"
)
@pytest.mark.parametrize("linked_scripts_root", [False, True])
def test_use_changes_modes_only_on_scripts_it_writes(self, tmp_path, linked_scripts_root):
"""Execute bits come from the refresh's own writes, never from a scan.

A user's script next to the shared ones keeps its mode, and nothing
behind a symlinked ``.specify/scripts`` (which the refresh skips) is touched.
"""
project = _init_project(tmp_path, "claude")
result = _run_in_project(project, ["integration", "install", "codex", "--script", "sh"])
assert result.exit_code == 0, result.output
scripts_root = project / ".specify" / "scripts"
if linked_scripts_root:
outside = tmp_path / "outside-scripts"
scripts_root.rename(outside)
scripts_root.symlink_to(outside, target_is_directory=True)
user_script = scripts_root.resolve() / "bash" / "local-helper.sh"
user_script.write_bytes(b"#!/usr/bin/env bash\necho local\n")
user_script.chmod(0o644)

result = _run_in_project(project, ["integration", "use", "codex"])

assert result.exit_code == 0, result.output
assert user_script.stat().st_mode & 0o777 == 0o644
if not linked_scripts_root:
shared = sorted((scripts_root / "bash").glob("*.sh"))
not_executable = [s.name for s in shared if s != user_script and not os.access(s, os.X_OK)]
assert not not_executable, f"use left shared scripts non-executable: {not_executable}"

@pytest.mark.parametrize("edited_command", [None, "plan", "tasks"])
def test_use_syncs_manifest_without_blessing_user_edits(
self, tmp_path, tasks_preset_src, edited_command
Expand Down
26 changes: 26 additions & 0 deletions tests/specify_cli/integrations/test_installed_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,32 @@ def fail_commit(*args, **kwargs):
assert snapshot(project) == before


@pytest.mark.skipif(os.name == "nt", reason="POSIX execute bits are not meaningful on Windows")
def test_failed_switch_restores_shared_script_mode_and_content(tmp_path, server, monkeypatch):
"""A refresh that makes a managed script executable is undone with the rest of the switch."""
from specify_cli.integrations import installer

publish(server)
project = catalog_project(tmp_path, server)
install(project)
scripts = sorted((project / ".specify/scripts/bash").glob("*.sh"))
assert scripts
for script in scripts:
script.chmod(0o644)
before = snapshot(project)

def fail_commit(*args, **kwargs):
assert all(stat.S_IMODE(script.stat().st_mode) == 0o755 for script in scripts)
raise OSError("sample package commit failure")

monkeypatch.setattr(installer, "write_records", fail_commit)
result = run(project, ["integration", "switch", "copilot", "--script", "sh"])
assert result.exit_code == 1, result.output
assert "sample package commit failure" in result.output
assert snapshot(project) == before
assert all(stat.S_IMODE(script.stat().st_mode) == 0o644 for script in scripts)


@pytest.mark.parametrize("install_allowed", [False, True])
def test_round4_search_advertises_only_allowed_external_installation(tmp_path, server, install_allowed):
publish(server, code='raise RuntimeError("discovery must not import sample code")')
Expand Down
52 changes: 52 additions & 0 deletions tests/test_shared_infra_script_mode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Unit tests for the mode shared scripts are written with."""

from __future__ import annotations

import os

import pytest

from specify_cli import shared_infra
from specify_cli.shared_infra import _shared_script_mode

SHEBANG = b"#!/usr/bin/env bash\necho hi\n"


def _source(tmp_path, name, mode):
path = tmp_path / name
path.write_bytes(SHEBANG)
path.chmod(mode)
return path


@pytest.mark.skipif(os.name == "nt", reason="POSIX execute bits are not meaningful on Windows")
@pytest.mark.parametrize(
("source_mode", "expected"),
[(0o644, 0o755), (0o640, 0o750), (0o600, 0o700), (0o755, 0o755), (0o200, 0o300)],
)
def test_shell_script_gets_execute_bit_for_each_class_that_reads(tmp_path, source_mode, expected):
source = _source(tmp_path, "setup-plan.sh", source_mode)
assert _shared_script_mode(source, SHEBANG) == expected


@pytest.mark.skipif(os.name == "nt", reason="POSIX execute bits are not meaningful on Windows")
@pytest.mark.parametrize(
("name", "content"),
[
("common.sh", b"echo sourced, no shebang\n"),
("common.sh", b""),
("setup-plan.ps1", SHEBANG),
("setup_plan.py", SHEBANG),
("sh", SHEBANG),
],
)
def test_other_files_keep_the_packaged_mode(tmp_path, name, content):
source = _source(tmp_path, name, 0o644)
assert _shared_script_mode(source, content) == 0o644


def test_windows_keeps_the_packaged_mode(tmp_path, monkeypatch):
source = _source(tmp_path, "setup-plan.sh", 0o644)
packaged = source.stat().st_mode & 0o777
monkeypatch.setattr(shared_infra.os, "name", "nt")
assert _shared_script_mode(source, SHEBANG) == packaged