diff --git a/lib/sync.py b/lib/sync.py index 1df83ff..3cf1ef5 100644 --- a/lib/sync.py +++ b/lib/sync.py @@ -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) @@ -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: diff --git a/tests/fixtures/smoke/fake_cli.py b/tests/fixtures/smoke/fake_cli.py index 9e3b91d..0eb1588 100644 --- a/tests/fixtures/smoke/fake_cli.py +++ b/tests/fixtures/smoke/fake_cli.py @@ -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 .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") diff --git a/tests/harness.py b/tests/harness.py index 577947c..fe9b75a 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -2,7 +2,9 @@ import json import os import shutil +import stat import subprocess +import sys import tempfile import unittest @@ -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 @@ -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 @@ -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) @@ -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 @@ -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 diff --git a/tests/test_cleanup.py b/tests/test_cleanup.py index e2dfdd0..3360a0e 100644 --- a/tests/test_cleanup.py +++ b/tests/test_cleanup.py @@ -2,7 +2,7 @@ import os import unittest -from tests.harness import SyncSandbox +from tests.harness import SyncSandbox, requires_symlinks MARKER = ".managed-by-devflow" @@ -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 @@ -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 @@ -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") @@ -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 diff --git a/tests/test_followups.py b/tests/test_followups.py index ea54ffb..93da1ba 100644 --- a/tests/test_followups.py +++ b/tests/test_followups.py @@ -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 = "" @@ -52,16 +52,16 @@ def __init__(self, home_is_repo_parent): self.home = tmp if home_is_repo_parent else os.path.realpath(self.sb.home) def run(self, *args): - env = os.environ.copy() - env["HOME"] = self.home + env = set_home(os.environ.copy(), self.home) # Keep the ignore file at today's default whatever the runner's environment (#37 # resolves XDG_CONFIG_HOME and core.excludesFile; not under test here). env.pop("XDG_CONFIG_HOME", None) for k in list(env): if k.startswith("GIT_CONFIG"): del env[k] - return subprocess.run([os.path.join(self.repo, "sync.sh")] + list(args), - cwd=self.repo, env=env, capture_output=True, text=True) + return subprocess.run(script_argv(os.path.join(self.repo, "sync.sh")) + list(args), + cwd=self.repo, env=env, capture_output=True, text=True, + encoding="utf-8") def path(self, tilde): return os.path.join(self.home, tilde[2:]) @@ -253,6 +253,7 @@ def test_manifest_vendor_dirs_ignored_as_directories(self): self.assertTrue(self.ignored(d)) # characterization: a symlink under a real `vendor/` folder is already covered by `vendor/` + @requires_symlinks def test_manifest_vendor_dirs_ignored_as_symlinks(self): dirs = self.vendor_dirs() self.assertTrue(dirs) @@ -261,6 +262,7 @@ def test_manifest_vendor_dirs_ignored_as_symlinks(self): self.make_link(d) self.assertTrue(self.ignored(d)) + @requires_symlinks def test_root_vendor_symlink_ignored(self): self.make_link("vendor") self.assertTrue(self.ignored("vendor")) diff --git a/tests/test_neutral_paths.py b/tests/test_neutral_paths.py index 7b4d28a..d71351a 100644 --- a/tests/test_neutral_paths.py +++ b/tests/test_neutral_paths.py @@ -15,7 +15,7 @@ def read(path): - with open(path) as f: + with open(path, encoding="utf-8") as f: return f.read() diff --git a/tests/test_smoke_driver.py b/tests/test_smoke_driver.py index eecddf9..fd8af4d 100644 --- a/tests/test_smoke_driver.py +++ b/tests/test_smoke_driver.py @@ -25,6 +25,8 @@ import unittest import uuid +from tests.harness import install_python_command + HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) SMOKE = os.path.join(ROOT, "smoke") @@ -63,9 +65,7 @@ def setUp(self): self.bin = os.path.join(self.tmp, "bin") os.makedirs(self.bin) for name in ("claude", "agent", "codex", "gh"): - dest = os.path.join(self.bin, name) - shutil.copy(FAKE, dest) - os.chmod(dest, 0o755) + install_python_command(FAKE, self.bin, name) self.logs = os.path.join(self.tmp, "logs") # not created: the driver creates it self.repo = os.path.join(self.tmp, "repo") os.makedirs(self.repo) @@ -681,7 +681,8 @@ def test_prints_setup_answers(self): def _fixture_tests(self): self.init_ok() self.assertTrue(os.path.isdir(self.target), "precondition: no repo dir") - return subprocess.run(["python3", "-m", "unittest"], cwd=self.target, env=self.env(), + # sys.executable, not "python3": Windows' python.org installs have no python3 command. + return subprocess.run([sys.executable, "-m", "unittest"], cwd=self.target, env=self.env(), capture_output=True, text=True, timeout=120) def test_fixture_tests_pass(self): @@ -696,7 +697,7 @@ def test_fixture_has_tests(self): def _existing_target(self): os.makedirs(self.target) - with open(os.path.join(self.target, "keep.txt"), "w") as f: + with open(os.path.join(self.target, "keep.txt"), "w", newline="") as f: f.write("mine\n") def test_existing_dir_exits_1(self): diff --git a/tests/test_uninstall.py b/tests/test_uninstall.py index e0570f4..c41a84a 100644 --- a/tests/test_uninstall.py +++ b/tests/test_uninstall.py @@ -7,7 +7,7 @@ import stat import unittest -from tests.harness import SyncSandbox +from tests.harness import SyncSandbox, ignores_permissions, requires_posix_permissions, requires_symlinks MARKER = ".managed-by-devflow" @@ -50,6 +50,8 @@ def install(self, providers="claude,codex"): 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) @@ -106,6 +108,7 @@ def test_unmanaged_folder_survives(self): self.assertEqual(r.returncode, 0, r.stdout + r.stderr) self.assertEqual(_read(f), "mine\n") + @requires_symlinks def test_symlinked_skill_folder_survives(self): sb = self.sb self.install() @@ -120,6 +123,7 @@ def test_symlinked_skill_folder_survives(self): self.assertTrue(os.path.isfile(os.path.join(target, "SKILL.md"))) self.assertTrue(os.path.isfile(os.path.join(target, MARKER))) + @requires_symlinks def test_link_inside_managed_skill_not_followed(self): sb = self.sb self.install() @@ -132,6 +136,7 @@ def test_link_inside_managed_skill_not_followed(self): self.assertFalse(os.path.lexists(skill)) self.assertEqual(_read(data), "keep\n") + @requires_symlinks def test_symlinked_skills_root_cleared_link_kept(self): sb = self.sb real = os.path.join(sb.tmp, "dotfiles", "skills") @@ -145,6 +150,7 @@ def test_symlinked_skills_root_cleared_link_kept(self): self.assertTrue(os.path.islink(sb.home_path("~/.claude/skills"))) self.assertEqual(sb.managed_skills("~/.claude/skills"), set()) + @requires_symlinks def test_shared_folder_processed_once(self): sb = self.sb os.makedirs(sb.home_path("~/.claude/skills")) @@ -177,7 +183,7 @@ def test_works_without_vendor(self): self.assertFalse(os.path.exists(os.path.join(sb.repo, "vendor"))) self.assertNotIn("cloning", r.stdout) - @unittest.skipIf(os.geteuid() == 0, "root ignores read-only folders") + @requires_posix_permissions def test_failed_removal_reported_exit_1(self): sb = self.sb self.install() @@ -267,6 +273,7 @@ def test_incomplete_markers_left_untouched_and_counted(self): self.assertIn("1 item(s) left for you to remove by hand (see the SKIP lines above)", r.stdout) + @requires_symlinks def test_shared_instructions_file_handled_once(self): sb = self.sb self.install("claude") @@ -280,6 +287,7 @@ def test_shared_instructions_file_handled_once(self): r.stdout) self.assertNotIn("item(s) left", r.stdout) + @requires_symlinks def test_symlinked_instructions_file_stays_a_link(self): sb = self.sb self.install("claude") diff --git a/tests/test_uninstall_failures.py b/tests/test_uninstall_failures.py index baa44a6..e829dca 100644 --- a/tests/test_uninstall_failures.py +++ b/tests/test_uninstall_failures.py @@ -9,7 +9,7 @@ import stat import unittest -from tests.harness import SyncSandbox +from tests.harness import SyncSandbox, requires_posix_permissions MARKER = ".managed-by-devflow" SKIP_UNMANAGED = "SKIP (exists, not managed by devflow)" @@ -21,7 +21,7 @@ def _write(path, text=""): f.write(text) -@unittest.skipIf(os.geteuid() == 0, "root ignores read-only folders") +@requires_posix_permissions class FailedRemovalKeepsMarkerTest(unittest.TestCase): def setUp(self): self.sb = SyncSandbox() diff --git a/tests/test_vendor_repair.py b/tests/test_vendor_repair.py index 38c1651..f881022 100644 --- a/tests/test_vendor_repair.py +++ b/tests/test_vendor_repair.py @@ -7,14 +7,14 @@ import stat import unittest -from tests.harness import SyncSandbox +from tests.harness import SyncSandbox, ignores_permissions from tests.test_line_endings import _files_with_cr, _local_autocrlf class FailedVendorRepairRetriesTest(unittest.TestCase): def setUp(self): - if hasattr(os, "geteuid") and os.geteuid() == 0: - raise unittest.SkipTest("root ignores folder permissions, so the reset can't be made to fail") + if ignores_permissions(): + raise unittest.SkipTest("root and Windows ignore folder permissions, so the reset can't be made to fail") self.sb = SyncSandbox(own_vendors=True) self.addCleanup(self.sb.close) self.sb.set_global_git_config("core.autocrlf", "true")