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
20 changes: 18 additions & 2 deletions lib/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,12 +335,25 @@ def cleanup(man, tilde_dir, install_ids, dry, failures):
# --------------------------------------------------------------------- global config
def tilde(path):
"""`~/...` for a path under HOME (or `~` itself), the path unchanged otherwise."""
if os.name == "nt":
return _tilde_windows(path)
home = os.path.expanduser("~").rstrip(os.sep)
if home and (path == home or path.startswith(home + os.sep)):
return "~" + path[len(home):]
return path


def _tilde_windows(path):
"""Windows: paths arrive with either separator (expanduser keeps the `/` in `~/.config`, git
prints `C:/...`) and any case, so compare normalized; name the rest with `/`, as on POSIX."""
home = os.path.normpath(os.path.expanduser("~")).rstrip("\\")
norm = os.path.normpath(path)
h, p = os.path.normcase(home), os.path.normcase(norm)
if home and (p == h or p.startswith(h + "\\")):
return "~" + norm[len(home):].replace("\\", "/")
return path


def clone_path():
"""This clone's root as the section header and ignore comment name it."""
return tilde(ROOT)
Expand Down Expand Up @@ -433,10 +446,13 @@ def remove_instructions(tilde_path, dry):
if bounds is None:
return None
a, b = bounds
nl = "\r\n" if "\r\n" in cur else "\n" # keep a CRLF file's own line endings
if not cur[b:].strip():
new = cur[:a].rstrip("\n") + "\n" if cur[:a].strip() else ""
new = cur[:a].rstrip("\r\n") + nl if cur[:a].strip() else ""
else:
if cur[b:b + 1] == "\n":
if cur.startswith("\r\n", b):
b += 2
elif cur[b:b + 1] == "\n":
b += 1
new = cur[:a] + cur[b:]
if not dry:
Expand Down
2 changes: 2 additions & 0 deletions tests/fixtures/smoke/fake_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ def session_id(args):

def main():
prog = os.path.basename(sys.argv[0])
if prog.lower().endswith(".exe"): # Windows: the test wraps this file as <prog>.exe
prog = prog[:-4]
args = sys.argv[1:]
with open(os.environ["FAKE_RECORD"], "a") as f:
f.write(json.dumps({"prog": prog, "argv": args, "cwd": os.getcwd()}) + "\n")
Expand Down
144 changes: 139 additions & 5 deletions tests/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import json
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import unittest

Expand All @@ -11,6 +13,134 @@
_DIRS = ("lib", "owned", "patches", "global")
_FILES = ("manifest.json", "vendor.lock", "sync.sh")

IS_WINDOWS = os.name == "nt"


# --- platform support --------------------------------------------------------------------
# The suite runs on Linux, macOS and Windows (from Git Bash, as the README says). Windows
# differs in four ways the tests meet: creating symlinks needs Developer Mode or admin, a
# script can't be executed directly (only .exe/.com), chmod can't make a folder read-only,
# and git leaves its object files read-only, so a plain rmtree fails on a clone.

def _probe_symlinks():
d = tempfile.mkdtemp(prefix="devflow-symlink-probe-")
try:
os.symlink(d, os.path.join(d, "link"), target_is_directory=True)
return True
except (OSError, NotImplementedError):
return False
finally:
shutil.rmtree(d, ignore_errors=True)


CAN_SYMLINK = _probe_symlinks()

requires_symlinks = unittest.skipUnless(
CAN_SYMLINK, "needs symlinks (on Windows: turn on Developer Mode, or run as admin)")


def ignores_permissions():
"""True where a read-only folder can still be written to: root, and Windows, where
chmod only toggles a file's read-only flag and has no effect on folders."""
return IS_WINDOWS or (hasattr(os, "geteuid") and os.geteuid() == 0)


requires_posix_permissions = unittest.skipIf(
ignores_permissions(), "needs read-only folders (POSIX, not root)")


def set_home(env, home):
"""Point `~` at `home` in the environment dict `env`, for every process a sync starts.
Python on Windows resolves ~ from USERPROFILE and never reads HOME, so setting HOME alone
would let sync.py write to the runner's real profile while the test looks in `home`."""
env["HOME"] = home
if IS_WINDOWS:
env["USERPROFILE"] = home
env.pop("HOMEDRIVE", None)
env.pop("HOMEPATH", None)
return env


def link_dir(target, link):
"""Make `link` point at the folder `target`: a symlink, or on Windows without symlink
rights a directory junction, which needs no privilege and which rmtree never follows."""
if CAN_SYMLINK:
os.symlink(target, link, target_is_directory=True)
elif IS_WINDOWS:
import _winapi
_winapi.CreateJunction(os.path.abspath(target), os.path.abspath(link))
else:
raise unittest.SkipTest("cannot create symlinks here")


def rmtree(path):
"""shutil.rmtree that also removes read-only files (git objects on Windows)."""
def onerror(func, p, _exc):
os.chmod(p, stat.S_IWRITE)
func(p)
if not os.path.lexists(path):
return
if sys.version_info >= (3, 12):
shutil.rmtree(path, onexc=onerror)
else:
shutil.rmtree(path, onerror=onerror)


def _git_bash():
"""Git for Windows' bash: the bash next to the git on PATH, so a WSL `bash.exe` in
System32 is never picked up. Falls back to whatever `bash` is on PATH."""
git = shutil.which("git")
if git:
d = os.path.dirname(os.path.realpath(git))
for _ in range(4):
for cand in (os.path.join(d, "bin", "bash.exe"),
os.path.join(d, "usr", "bin", "bash.exe")):
if os.path.isfile(cand):
return cand
d = os.path.dirname(d)
return shutil.which("bash") or "bash"


def script_argv(path):
"""argv that runs the shell script at `path`: the script itself on POSIX, through Git
Bash on Windows, which can't execute a script directly."""
return [_git_bash(), path] if IS_WINDOWS else [path]


def install_python_command(script, bin_dir, name):
"""Make the Python file `script` runnable as the command `name` from `bin_dir`.

POSIX: a copy named `name`, made executable (the script has a shebang). Windows:
`name.exe`, the console launcher pip uses for its own commands with the script zipped
behind it, so argv (newlines included) reaches the script intact and sys.argv[0] ends
in `name.exe`."""
if not IS_WINDOWS:
dest = os.path.join(bin_dir, name)
shutil.copy(script, dest)
os.chmod(dest, 0o755)
return dest
import io
import platform
import zipfile
try:
from pip._vendor.distlib import scripts as _distlib_scripts
except ImportError:
raise unittest.SkipTest("needs pip's console launcher to fake a command on Windows")
arch = "t64-arm.exe" if platform.machine().lower() in ("arm64", "aarch64") else (
"t64.exe" if sys.maxsize > 2 ** 32 else "t32.exe")
with open(os.path.join(os.path.dirname(_distlib_scripts.__file__), arch), "rb") as f:
launcher = f.read()
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
with open(script, encoding="utf-8") as f:
z.writestr("__main__.py", f.read())
exe = sys.executable
shebang = ('#!"%s"\r\n' % exe if " " in exe else "#!%s\r\n" % exe).encode("utf-8")
dest = os.path.join(bin_dir, name + ".exe")
with open(dest, "wb") as f:
f.write(launcher + shebang + buf.getvalue())
return dest


def check_vendors(root):
"""Skip unless every vendor clone exists at its locked commit: the sandbox links the
Expand Down Expand Up @@ -57,7 +187,7 @@ def __init__(self, own_vendors=False):
if own_vendors:
self._own_vendors()
else:
os.symlink(os.path.join(REAL_ROOT, "vendor"), os.path.join(self.repo, "vendor"))
link_dir(os.path.join(REAL_ROOT, "vendor"), os.path.join(self.repo, "vendor"))
except Exception:
self.close()
raise
Expand All @@ -77,7 +207,7 @@ def _env(self, env=None):
e = {k: v for k, v in os.environ.items()
if k != "XDG_CONFIG_HOME" and not k.startswith("GIT_CONFIG")}
e["GIT_CONFIG_NOSYSTEM"] = "1"
e["HOME"] = self.home
set_home(e, self.home)
for k, v in (env or {}).items():
if v is None:
e.pop(k, None)
Expand All @@ -89,8 +219,9 @@ def run(self, *args, env=None):
"""Run sync.sh isolated from the runner's git and XDG settings; `env` overrides on top
(a None value deletes the key)."""
return subprocess.run(
[os.path.join(self.repo, "sync.sh")] + list(args),
cwd=self.repo, env=self._env(env), capture_output=True, text=True)
script_argv(os.path.join(self.repo, "sync.sh")) + list(args),
cwd=self.repo, env=self._env(env), capture_output=True, text=True,
encoding="utf-8") # sync.py runs with -X utf8; Windows' default would be cp1252

def git(self, *args, cwd=None, check=True):
"""Run git with the same isolated environment as `run` (the sandbox HOME's
Expand Down Expand Up @@ -146,7 +277,10 @@ def manifest_skill_names(self):
return {s["name"] for s in json.load(f)["skills"]}

def close(self):
shutil.rmtree(self.tmp, ignore_errors=True)
try:
rmtree(self.tmp)
except OSError:
shutil.rmtree(self.tmp, ignore_errors=True)

def __enter__(self):
return self
Expand Down
6 changes: 5 additions & 1 deletion tests/test_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import unittest

from tests.harness import SyncSandbox
from tests.harness import SyncSandbox, requires_symlinks

MARKER = ".managed-by-devflow"

Expand Down Expand Up @@ -82,6 +82,7 @@ def test_dry_run_deselect_writes_nothing(self):
self.assertEqual(sb.managed_skills("~/.agents/skills"), sb.manifest_skill_names())
self.assertIn("would remove tdd (provider not selected)", r.stdout)

@requires_symlinks
def test_symlinked_agents_folder_to_claude_is_not_cleaned(self):
# Review Focus 1: cleanup folder resolving to an install folder is skipped and reported
sb = self.sb
Expand All @@ -95,6 +96,7 @@ def test_symlinked_agents_folder_to_claude_is_not_cleaned(self):
self.assertIn("SKIP (same folder as an install folder)", r.stdout)
self.assertTrue(os.path.islink(sb.home_path("~/.agents/skills")))

@requires_symlinks
def test_symlinked_skill_folder_is_never_followed(self):
# Review Focus 2: a symlinked skill folder is never followed or deleted
sb = self.sb
Expand All @@ -110,6 +112,7 @@ def test_symlinked_skill_folder_is_never_followed(self):
self.assertTrue(os.path.islink(sb.home_path(d + "/ext")), d)
self.assertTrue(os.path.exists(os.path.join(ext, "SKILL.md")))

@requires_symlinks
def test_case_mismatched_symlink_to_claude_is_not_cleaned(self):
sb = self.sb
probe = os.path.join(sb.home, "CaseProbe")
Expand Down Expand Up @@ -238,6 +241,7 @@ def setUp(self):
self.sb = SyncSandbox()
self.addCleanup(self.sb.close)

@requires_symlinks
def test_unselected_link_to_selected_instructions_file_is_skipped(self):
# F1: an unselected provider's instructions file that is the selected one's file is never stripped
sb = self.sb
Expand Down
12 changes: 8 additions & 4 deletions tests/test_followups.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from unittest import mock

from tests import harness
from tests.harness import SyncSandbox
from tests.harness import SyncSandbox, ignores_permissions, requires_symlinks

START = "<!-- devflow:start"
MARKER = ".managed-by-devflow"
Expand All @@ -33,6 +33,8 @@ def setUp(self):

def lock(self, skill_dir):
# a read-only subfolder with a file in it: rmtree cannot unlink the file
if ignores_permissions():
self.skipTest("needs read-only folders (POSIX, not root)")
locked = os.path.join(skill_dir, "locked")
_write(os.path.join(locked, "f"), "x\n")
os.chmod(locked, stat.S_IRUSR | stat.S_IXUSR)
Expand Down Expand Up @@ -74,11 +76,12 @@ def test_instructions_file_replaced_not_rewritten(self):
md = sb.home_path("~/.claude/CLAUDE.md")
_write(md, "# mine\n")
os.chmod(md, 0o640)
mode = stat.S_IMODE(os.stat(md).st_mode) # 0o640 on POSIX; Windows keeps only read-only
ino = os.stat(md).st_ino
r = sb.run()
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertNotEqual(os.stat(md).st_ino, ino)
self.assertEqual(stat.S_IMODE(os.stat(md).st_mode), 0o640)
self.assertEqual(stat.S_IMODE(os.stat(md).st_mode), mode)
self.assertEqual(sorted(os.listdir(sb.home_path("~/.claude"))), ["CLAUDE.md", "skills"])

def test_removed_section_file_replaced_not_rewritten(self):
Expand All @@ -91,6 +94,7 @@ def test_removed_section_file_replaced_not_rewritten(self):
self.assertNotEqual(os.stat(agents).st_ino, ino)
self.assertEqual(os.listdir(sb.home_path("~/.codex")), ["AGENTS.md"])

@requires_symlinks
def test_symlinked_instructions_file_stays_a_link(self):
sb = self.sb
target = os.path.join(sb.home, "dotfiles", "CLAUDE.md")
Expand Down Expand Up @@ -229,7 +233,7 @@ def git(self, *args, cwd):

def fake_root(self, lock_sha):
root = tempfile.mkdtemp(prefix="devflow-drift-")
self.addCleanup(shutil.rmtree, root, True)
self.addCleanup(harness.rmtree, root)
clone = os.path.join(root, "vendor", "v")
os.makedirs(clone)
self.git("init", "-q", cwd=clone)
Expand Down Expand Up @@ -259,7 +263,7 @@ def test_matching_clone_passes(self):

def test_missing_clone_skips(self):
root, clone, _ = self.fake_root(None)
shutil.rmtree(clone)
harness.rmtree(clone) # git leaves read-only objects on Windows
with self.assertRaises(unittest.SkipTest):
harness.check_vendors(root)

Expand Down
10 changes: 6 additions & 4 deletions tests/test_git_ignore_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import unittest

from tests.harness import REAL_ROOT, SyncSandbox
from tests.harness import REAL_ROOT, SyncSandbox, ignores_permissions, requires_symlinks


def read(path):
Expand All @@ -27,7 +27,8 @@ def expected_lines():


def core_block(value):
return "[core]\n\texcludesFile = %s\n" % value
# git config treats `\` as an escape, so a Windows path's backslashes must be doubled
return "[core]\n\texcludesFile = %s\n" % value.replace("\\", "\\\\")


class IgnoreTargetTest(unittest.TestCase):
Expand Down Expand Up @@ -159,8 +160,8 @@ def gitconfig(self, value):
write(os.path.join(self.home, ".gitconfig"), core_block(value))

def locked_setup(self, *args):
if os.geteuid() == 0:
self.skipTest("root ignores directory permissions")
if ignores_permissions():
self.skipTest("needs read-only folders (POSIX, not root)")
locked = os.path.join(self.tmp, "locked")
os.makedirs(locked)
os.chmod(locked, 0o500)
Expand All @@ -171,6 +172,7 @@ def locked_setup(self, *args):
def ignore_lines(self, r):
return [l for l in r.stdout.splitlines() if "git ignore" in l]

@requires_symlinks
def test_symlinked_target_stays_a_link(self):
# Characterization: may already pass after Task 1.
real = os.path.join(self.home, "dotfiles", "ignore")
Expand Down
Loading
Loading