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
28 changes: 22 additions & 6 deletions src/specify_cli/shared_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,26 @@ 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
and no execute bit yet gets one 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. A script that
already has an execute bit keeps its mode.
"""
mode = src_path.stat().st_mode & 0o777
if (
os.name != "nt"
and src_path.suffix == ".sh"
and content.startswith(b"#!")
and not mode & 0o111
):
mode |= ((mode & 0o444) >> 2) | 0o100
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 +656,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))
Comment thread
mnriem marked this conversation as resolved.
Resolved
)

templates_src = shared_templates_source(core_pack=core_pack, repo_root=repo_root)
Expand Down
26 changes: 26 additions & 0 deletions tests/specify_cli/integrations/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Shared fixtures for mirrored integration command tests."""

import shutil

import pytest

from tests.specify_cli.integrations._helpers import _copy_project_template, _init_project
Expand Down Expand Up @@ -37,3 +39,27 @@ def tasks_preset_src(tmp_path):
- {type: command, name: speckit.tasks, file: commands/speckit.tasks.md}
""")
return preset


@pytest.fixture
def packaged_scripts_0644(tmp_path_factory, monkeypatch):
"""Serve the shared scripts from a copy with every file at 0644.

That is how the wheel ships them, so the execute-bit tests fail without the
fix whatever modes the checkout running the tests has.
"""
from specify_cli import shared_infra

real_source = shared_infra.shared_scripts_source
copy = tmp_path_factory.mktemp("packaged-scripts") / "scripts"

def source(*, core_pack, repo_root):
if not copy.exists():
shutil.copytree(real_source(core_pack=core_pack, repo_root=repo_root), copy)
for path in copy.rglob("*"):
if path.is_file():
path.chmod(0o644)
return copy

monkeypatch.setattr(shared_infra, "shared_scripts_source", source)
return copy
24 changes: 24 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,30 @@ 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, packaged_scripts_0644
):
"""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
19 changes: 19 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,25 @@ 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, packaged_scripts_0644
):
"""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
50 changes: 50 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,56 @@
)

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, packaged_scripts_0644):
"""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, packaged_scripts_0644
):
"""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
28 changes: 28 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,34 @@ 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, packaged_scripts_0644
):
"""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(script.stat().st_mode & stat.S_IXUSR 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
59 changes: 59 additions & 0 deletions tests/test_shared_infra_script_mode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""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), (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("source_mode", [0o755, 0o744, 0o754, 0o700, 0o710])
def test_already_executable_script_keeps_its_mode(tmp_path, source_mode):
source = _source(tmp_path, "setup-plan.sh", source_mode)
assert _shared_script_mode(source, SHEBANG) == source_mode


@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
Loading