diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f6cb1b..bde521c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,3 +71,42 @@ jobs: run: python3 -m unittest env: DEVFLOW_REQUIRE_VENDORS: "1" + + windows-install: + # A fresh install under Git Bash with Git for Windows' default line endings. + # The unit suite doesn't run here yet (#51). + runs-on: windows-latest + steps: + - name: Force the default Windows line-ending setting + run: git config --global core.autocrlf true + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 # provides python, not python3 + with: + python-version: "3.x" + - name: Dry run + run: ./sync.sh --dry-run + - name: Sync + run: ./sync.sh + - name: Every manifest skill is installed and managed + run: | + python - <<'PY' + import json, os, sys + man = json.load(open("manifest.json", encoding="utf-8")) + root = os.path.expanduser("~/.claude/skills") + missing = [s["name"] for s in man["skills"] + if not os.path.isfile(os.path.join(root, s["name"], man["marker"]))] + if missing: + sys.exit("not installed with a %s marker in %s: %s" % (man["marker"], root, ", ".join(missing))) + print("%d managed skills in %s" % (len(man["skills"]), root)) + PY + - name: Re-sync and dry run report no change + # Every status that changes something (or would) starts its line with one of these words. + run: | + for args in "" "--dry-run"; do + out=$(./sync.sh $args) + echo "$out" + if grep -E '^[[:space:]]*(installed|updated|removed|added|would|FAIL|WARN|SKIP)([[:space:]]|$)' <<<"$out"; then + echo "::error::./sync.sh $args reported a change after a full sync" + exit 1 + fi + done diff --git a/README.md b/README.md index 28aa912..2d3db24 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ Use it as is, or fork it to choose your own skills: edit `manifest.json`, then r **Prerequisites:** Python 3.9+, git, the GitHub CLI `gh` signed in (`gh auth login`), and one supported provider (see [Providers](#providers)). GitHub is the only tracker the workflows support. +**Windows:** run everything from Git Bash, with Python 3.9+ from python.org or the Microsoft Store. + ```bash git clone https://github.com/maceorichards/devflow.git cd devflow @@ -17,6 +19,8 @@ cd devflow The dry run clones the upstream skill repos into `vendor/` at the locked commits and shows what would change, writing nothing outside the clone. The second command builds and installs for Claude Code; to pick other providers, run `./sync.sh providers ` instead. Then, in each project, run `/setup-devflow-skills` once (see [Workflows](#workflows)). +If you cloned on Windows before the line-ending fix, bash rejects `sync.sh`. Repair the clone once: commit or stash your changes, then run `git rm -rq --cached . && git reset -q --hard`, or clone again. `devflow.local.json` and `vendor/` are git-ignored and aren't affected. + What the sync edits outside the clone: - Each selected provider's skills folder (e.g. `~/.claude/skills`): only folders it marks with `.managed-by-devflow`. A folder of the same name without the marker is skipped. - The devflow section of each provider's instructions file (e.g. `~/.claude/CLAUDE.md`), between `devflow` markers. The rest of the file is left alone. diff --git a/lib/sync.py b/lib/sync.py index 65dcf4d..62c9b82 100644 --- a/lib/sync.py +++ b/lib/sync.py @@ -30,19 +30,26 @@ MD_END = "" -def sh(args, cwd=None, check=True): - r = subprocess.run(args, cwd=cwd, capture_output=True, text=True) +def sh(args, cwd=None, check=True, input=None): + """Run a command; its stdout and stderr come back as UTF-8 text. `input` (text) goes to + stdin as UTF-8 bytes, because a text-mode stdin turns LF into CRLF on Windows.""" + if input is None: + r = subprocess.run(args, cwd=cwd, capture_output=True, text=True, encoding="utf-8") + else: + r = subprocess.run(args, cwd=cwd, input=input.encode("utf-8"), capture_output=True) + r.stdout, r.stderr = (b.decode("utf-8", "replace").replace("\r\n", "\n") + for b in (r.stdout, r.stderr)) if check and r.returncode != 0: raise RuntimeError(f"{' '.join(args)} failed:\n{r.stdout}{r.stderr}") return r def load(): - with open(MANIFEST) as f: + with open(MANIFEST, encoding="utf-8") as f: man = json.load(f) lock = {} if os.path.exists(LOCK): - with open(LOCK) as f: + with open(LOCK, encoding="utf-8") as f: lock = json.load(f) return man, lock @@ -55,7 +62,18 @@ def ensure_vendor(man, src, sha=None): d = vendor_dir(man, src) if not os.path.isdir(os.path.join(d, ".git")): print(f"cloning {src} …") - sh(["git", "clone", "-q", man["vendors"][src]["url"], d]) + # -c on clone checks out LF and records core.autocrlf=false in the clone's config. + sh(["git", "clone", "-q", "-c", "core.autocrlf=false", man["vendors"][src]["url"], d]) + elif sh(["git", "config", "--get", "core.autocrlf"], cwd=d, check=False).stdout.strip() == "true": + # A clone checked out with CRLF (Windows' default): make it LF once. Vendor clones + # are never edited, so dropping the index and resetting loses nothing. The setting is + # persisted only after the reset succeeds: if it fails (a locked file), the trigger + # still reads true and the next sync retries (on an index the failed reset left empty, + # hence --ignore-unmatch). + sh(["git", "-c", "core.autocrlf=false", "rm", "-q", "--cached", "-r", "--ignore-unmatch", "."], + cwd=d) + sh(["git", "-c", "core.autocrlf=false", "reset", "-q", "--hard"], cwd=d) + sh(["git", "config", "--local", "core.autocrlf", "false"], cwd=d) if sha: cur = sh(["git", "rev-parse", "HEAD"], cwd=d).stdout.strip() if cur != sha: @@ -76,7 +94,7 @@ def write_atomic(path, text, newline=None): mode = 0o666 & ~umask fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=f".{os.path.basename(path)}.") try: - with os.fdopen(fd, "w", newline=newline) as f: + with os.fdopen(fd, "w", encoding="utf-8", newline=newline) as f: f.write(text) os.chmod(tmp, mode) os.replace(tmp, path) @@ -88,7 +106,7 @@ def write_atomic(path, text, newline=None): # --------------------------------------------------------------------- frontmatter def set_frontmatter(path, skill): - with open(path) as f: + with open(path, encoding="utf-8") as f: txt = f.read() m = re.match(r"---\n(.*?)\n---\n", txt, re.S) if not m: @@ -104,7 +122,7 @@ def set_frontmatter(path, skill): if skill["tier"] == "slash": out.append("disable-model-invocation: true") new = "---\n" + "\n".join(out) + "\n---\n" + txt[m.end():] - with open(path, "w") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(new) @@ -113,7 +131,7 @@ def set_codex_policy(stage, skill): path = os.path.join(stage, "agents", "openai.yaml") lines = [] if os.path.exists(path): - with open(path) as f: + with open(path, encoding="utf-8") as f: lines = f.read().split("\n") # drop any top-level policy: block (that line and its indented children) kept, skipping = [], False @@ -133,11 +151,20 @@ def set_codex_policy(stage, skill): os.remove(path) return os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(text + "\n") # --------------------------------------------------------------------- build +def apply_patch(rel, cwd): + """`git apply` the patch at ROOT/rel in cwd. The patch is read as UTF-8 with CRLF turned + into LF, and core.autocrlf is off, so neither the checkout nor git config adds a CR.""" + with open(os.path.join(ROOT, rel), encoding="utf-8", newline="") as f: + text = f.read().replace("\r\n", "\n") + return sh(["git", "-c", "core.autocrlf=false", "apply", "--whitespace=nowarn", "-p1"], + cwd=cwd, check=False, input=text) + + def build_skill(man, skill, stage_root): """Return (staged_dir, error_or_None).""" stage = os.path.join(stage_root, skill["name"]) @@ -149,8 +176,7 @@ def build_skill(man, skill, stage_root): return stage, f"source missing: {src}" shutil.copytree(src, stage) if skill.get("patch"): - patch = os.path.join(ROOT, skill["patch"]) - r = sh(["git", "apply", "--whitespace=nowarn", "-p1", patch], cwd=stage, check=False) + r = apply_patch(skill["patch"], stage) if r.returncode != 0: return stage, f"patch failed: {skill['patch']}\n{r.stderr.strip()}" # Text rewrites on every .md and .yaml file, after the patch: the vendor's prefix is @@ -165,13 +191,13 @@ def build_skill(man, skill, stage_root): for fn in files: if fn.endswith((".md", ".yaml")): p = os.path.join(dp, fn) - with open(p) as f: + with open(p, encoding="utf-8") as f: t = f.read() new = t for old, rep in subs: new = new.replace(old, rep) if new != t: - with open(p, "w") as f: + with open(p, "w", encoding="utf-8", newline="\n") as f: f.write(new) set_frontmatter(os.path.join(stage, "SKILL.md"), skill) set_codex_policy(stage, skill) @@ -200,7 +226,7 @@ def install(man, skill, stage, lock, dry, dest_root): if dry: return f"would {action}" os.makedirs(dest_root, exist_ok=True) - with open(os.path.join(stage, marker), "w") as f: + with open(os.path.join(stage, marker), "w", encoding="utf-8", newline="\n") as f: src = skill["source"] f.write(json.dumps({"source": src, "path": skill["path"], "commit": lock.get(src, "owned"), "tier": skill["tier"]}) + "\n") @@ -288,7 +314,7 @@ def git_ignore_target(): try: r = subprocess.run(["git", "config", "--global", "--includes", "--type=path", "--get", "core.excludesFile"], - capture_output=True, text=True) + capture_output=True, text=True, encoding="utf-8") except OSError as e: raise ValueError(f"could not read core.excludesFile ({e})") if r.returncode not in (0, 1): @@ -325,12 +351,12 @@ def unreadable_skip(tilde_path): def sync_instructions(tilde_path, dry): path = os.path.expanduser(tilde_path) - with open(os.path.join(ROOT, "global", "claude-md-section.md")) as f: + with open(os.path.join(ROOT, "global", "claude-md-section.md"), encoding="utf-8") as f: section = f.read().replace("{{clone}}", clone_path()).strip() + "\n" cur = "" if os.path.exists(path): try: - with open(path, newline="") as f: + with open(path, encoding="utf-8", newline="") as f: cur = f.read() except (UnicodeDecodeError, OSError): return unreadable_skip(tilde_path) @@ -356,7 +382,7 @@ def remove_instructions(tilde_path, dry): if not os.path.isfile(path): return None try: - with open(path, newline="") as f: + with open(path, encoding="utf-8", newline="") as f: cur = f.read() except (UnicodeDecodeError, OSError): return unreadable_skip(tilde_path) @@ -379,7 +405,7 @@ def remove_instructions(tilde_path, dry): def sync_git_ignore(dry): - with open(os.path.join(ROOT, "global", "git-ignore-lines")) as f: + with open(os.path.join(ROOT, "global", "git-ignore-lines"), encoding="utf-8") as f: want = [l.strip() for l in f if l.strip() and not l.startswith("#")] manual = "add these lines yourself: " + ", ".join(want) try: @@ -390,7 +416,7 @@ def sync_git_ignore(dry): missing = want # nothing is known to be present until the file has been read action = "read" try: - cur = open(target).read() if os.path.exists(target) else "" + cur = open(target, encoding="utf-8").read() if os.path.exists(target) else "" have = {l.strip() for l in cur.splitlines()} missing = [l for l in want if l not in have] if not missing: @@ -398,7 +424,7 @@ def sync_git_ignore(dry): if not dry: action = "write" os.makedirs(os.path.dirname(target), exist_ok=True) - with open(target, "a") as f: + with open(target, "a", encoding="utf-8") as f: if cur and not cur.endswith("\n"): f.write("\n") if "# devflow" not in cur: @@ -429,7 +455,7 @@ def selected_providers(man): if not os.path.exists(LOCAL): return ["claude"] try: - with open(LOCAL) as f: + with open(LOCAL, encoding="utf-8") as f: names = json.load(f)["providers"] except (OSError, ValueError, KeyError, TypeError): names = None @@ -567,7 +593,7 @@ def update(man, lock): def save_lock(lock): - with open(LOCK, "w") as f: + with open(LOCK, "w", encoding="utf-8", newline="\n") as f: json.dump(lock, f, indent=2) f.write("\n") @@ -591,17 +617,17 @@ def edit(man, lock, name): shutil.copytree(src, os.path.join(work, "a")) shutil.copytree(src, os.path.join(work, "b")) if skill.get("patch") and os.path.exists(os.path.join(ROOT, skill["patch"])): - sh(["git", "apply", "--whitespace=nowarn", "-p1", os.path.join(ROOT, skill["patch"])], - cwd=os.path.join(work, "b"), check=False) + apply_patch(skill["patch"], os.path.join(work, "b")) print(f"Edit {work}/b (upstream + current patch), then run: sync.sh save {name}") def save(man, name): skill = find_skill(man, name) work = os.path.join(ROOT, ".patch-work", name) - r = subprocess.run(["diff", "-ruN", "a", "b"], cwd=work, capture_output=True, text=True) + r = subprocess.run(["diff", "-ruN", "a", "b"], cwd=work, capture_output=True, text=True, + encoding="utf-8") patch_rel = skill.get("patch") or f"patches/{name}.patch" - with open(os.path.join(ROOT, patch_rel), "w") as f: + with open(os.path.join(ROOT, patch_rel), "w", encoding="utf-8", newline="\n") as f: f.write(r.stdout) if not skill.get("patch"): print(f"Add \"patch\": \"{patch_rel}\" to {name} in manifest.json") diff --git a/smoke/drive.py b/smoke/drive.py index 4c49645..e4d2d24 100644 --- a/smoke/drive.py +++ b/smoke/drive.py @@ -64,24 +64,25 @@ class Fail(Exception): def run(argv, cwd): """(exit code, stdout, stderr) of argv, with no shell and no stdin.""" try: - r = subprocess.run(argv, cwd=cwd, stdin=subprocess.DEVNULL, capture_output=True, text=True) + r = subprocess.run(argv, cwd=cwd, stdin=subprocess.DEVNULL, capture_output=True, text=True, + encoding="utf-8") except OSError as e: return 127, "", f"{argv[0]}: {e}\n" return r.returncode, r.stdout, r.stderr def write(path, text): - with open(path, "w") as f: + with open(path, "w", encoding="utf-8") as f: f.write(text) def read(path): - with open(path) as f: + with open(path, encoding="utf-8") as f: return f.read() def load_agent(name): - with open(AGENTS) as f: + with open(AGENTS, encoding="utf-8") as f: table = json.load(f) if name not in table: raise Fail(f"unknown agent {name!r}; agents.json has {', '.join(sorted(table))}") diff --git a/sync.sh b/sync.sh index 08f25b9..367c417 100755 --- a/sync.sh +++ b/sync.sh @@ -1,4 +1,17 @@ #!/usr/bin/env bash # devflow: rebuild and install managed skills. See README.md. set -euo pipefail -exec python3 -I "$(cd "$(dirname "$0")" && pwd)/lib/sync.py" "$@" +here="$(cd "$(dirname "$0")" && pwd)" + +# Interpreter probe: the first candidate that runs and is Python 3.9+ wins. A missing command, +# the Windows Store shim (exits non-zero) or an older Python fails the check and is skipped. +check='import sys; sys.exit(0 if tuple(sys.version_info[:2]) >= (3, 9) else 1)' +for candidate in python3 python "py -3"; do + # $candidate is unquoted on purpose: "py -3" is a command plus its argument. + if $candidate -I -c "$check" >/dev/null 2>&1; then + exec $candidate -I -X utf8 "$here/lib/sync.py" "$@" + fi +done + +echo "devflow needs Python 3.9+; tried: python3, python, py -3" >&2 +exit 1 diff --git a/tests/harness.py b/tests/harness.py index 0e80eb4..577947c 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -37,7 +37,11 @@ def check_vendors(root): class SyncSandbox: - def __init__(self): + def __init__(self, own_vendors=False): + """own_vendors=False (default): the sandbox links the real `vendor/`. + own_vendors=True: the sandbox gets an empty `vendor/` of its own and a manifest whose + vendor urls are the real local clones (no network), so a sync clones them into the + sandbox, or the test pre-clones them with `clone_vendors()`.""" check_vendors(REAL_ROOT) self.tmp = tempfile.mkdtemp(prefix="devflow-sandbox-") self.repo = os.path.join(self.tmp, "repo") @@ -50,15 +54,26 @@ def __init__(self): shutil.copytree(os.path.join(REAL_ROOT, d), os.path.join(self.repo, d), ignore=ignore) for f in _FILES: shutil.copy2(os.path.join(REAL_ROOT, f), os.path.join(self.repo, f)) - os.symlink(os.path.join(REAL_ROOT, "vendor"), os.path.join(self.repo, "vendor")) + if own_vendors: + self._own_vendors() + else: + os.symlink(os.path.join(REAL_ROOT, "vendor"), os.path.join(self.repo, "vendor")) except Exception: self.close() raise self.local_file = os.path.join(self.repo, "devflow.local.json") - 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).""" + def _own_vendors(self): + path = os.path.join(self.repo, "manifest.json") + with open(path, encoding="utf-8") as f: + man = json.load(f) + for v in man["vendors"].values(): + v["url"] = os.path.join(REAL_ROOT, v["dir"]) + with open(path, "w", encoding="utf-8") as f: + json.dump(man, f, indent=2) + os.makedirs(os.path.join(self.repo, "vendor")) + + 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" @@ -68,9 +83,45 @@ def run(self, *args, env=None): e.pop(k, None) else: e[k] = v + return e + + 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=e, capture_output=True, text=True) + cwd=self.repo, env=self._env(env), capture_output=True, text=True) + + def git(self, *args, cwd=None, check=True): + """Run git with the same isolated environment as `run` (the sandbox HOME's + `.gitconfig` is the global config).""" + return subprocess.run(["git"] + list(args), cwd=cwd or self.repo, env=self._env(), + capture_output=True, text=True, check=check) + + def set_global_git_config(self, key, value): + """Set `key` in the sandbox HOME's global git config.""" + self.git("config", "--global", key, value) + + def vendor_dirs(self): + """{source: absolute path of the sandbox's clone of that vendor}.""" + with open(os.path.join(self.repo, "manifest.json"), encoding="utf-8") as f: + vendors = json.load(f)["vendors"] + return {src: os.path.join(self.repo, v["dir"]) for src, v in vendors.items()} + + def clone_vendors(self, git_config=None): + """own_vendors only: clone every vendor from its manifest url at its vendor.lock commit, + under the sandbox's git config plus `git_config` ({key: value}, passed as `git -c`).""" + with open(os.path.join(self.repo, "manifest.json"), encoding="utf-8") as f: + vendors = json.load(f)["vendors"] + with open(os.path.join(self.repo, "vendor.lock"), encoding="utf-8") as f: + lock = json.load(f) + opts = [] + for k, v in (git_config or {}).items(): + opts += ["-c", f"{k}={v}"] + for src, v in vendors.items(): + d = os.path.join(self.repo, v["dir"]) + self.git(*opts, "clone", "-q", "--no-checkout", v["url"], d) + self.git(*opts, "checkout", "-q", lock[src], cwd=d) def home_path(self, tilde_path): if tilde_path == "~": diff --git a/tests/test_docs.py b/tests/test_docs.py index 4b02273..ecacd08 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -271,3 +271,95 @@ def test_runs_sync_dry_run(self): def test_runs_unittest(self): self.assertIn("python3 -m unittest", self.ci()) + + +class WindowsQuickstartTest(unittest.TestCase): + """#56 (#52 user stories 18-19): the Quickstart tells Windows users what to run and how to repair.""" + + REPAIR = "git rm -rq --cached . && git reset -q --hard" + + def quickstart(self): + return ReadmeFirstRunTest.quickstart(self) + + def test_quickstart_mentions_git_bash(self): + self.assertIn("Git Bash", self.quickstart()) + + def test_quickstart_windows_line_names_git_bash_and_python_3_9(self): + paras = paragraphs(self.quickstart()) + self.assertTrue( + any("Windows" in p and "Git Bash" in p and "Python 3.9" in p for p in paras), + "no paragraph or list item has Windows with Git Bash and Python 3.9") + + def test_quickstart_gives_one_time_repair_command(self): + self.assertIn(self.REPAIR, self.quickstart()) + + def test_repair_command_comes_with_commit_or_stash_warning(self): + paras = [p.lower() for p in paragraphs(self.quickstart()) if self.REPAIR in p] + self.assertTrue( + any("commit" in p and "stash" in p for p in paras), + "the paragraph with the repair command doesn't say to commit or stash first") + + +def strip_comments(text): + """Drop YAML/shell '#' comments so prose in comments can't satisfy or break a check.""" + return re.sub(r"(?m)(^|\s)#.*$", r"\1", text) + + +class WindowsCiJobTest(unittest.TestCase): + """#56 (#52 user stories 22-24): a windows-latest job proves a fresh install under Git Bash.""" + + def windows_job(self): + """The text of the job whose runs-on is windows-latest: its job key line up to the next job key.""" + ci = read(os.path.join(".github", "workflows", "ci.yml")) + jobs = ci.split("\njobs:\n", 1)[1] if "\njobs:\n" in ci else "" + blocks = re.split(r"(?m)^(?= [\w-]+\s*:\s*$)", jobs) + found = [b for b in blocks if re.search(r"(?m)^\s+runs-on\s*:\s*windows-latest\s*$", b)] + if not found: + self.fail("no job with runs-on: windows-latest") + return found[0] + + def test_has_windows_latest_job(self): + self.assertRegex(self.windows_job(), r"(?m)^ [\w-]+\s*:\s*$") + + def test_windows_job_forces_autocrlf_true(self): + self.assertRegex(strip_comments(self.windows_job()), + r"git config --global core\.autocrlf true") + + def test_windows_job_forces_autocrlf_before_checkout(self): + job = strip_comments(self.windows_job()) + m = re.search(r"git config --global core\.autocrlf true", job) + autocrlf = m.start() if m else -1 + checkout = job.find("actions/checkout") + self.assertTrue(0 <= autocrlf < checkout, + "git config --global core.autocrlf true must come before actions/checkout") + + def test_windows_job_uses_setup_python(self): + self.assertIn("actions/setup-python", strip_comments(self.windows_job())) + + def test_windows_job_runs_dry_run(self): + self.assertIn("./sync.sh --dry-run", strip_comments(self.windows_job())) + + def test_windows_job_runs_bare_sync(self): + self.assertRegex(strip_comments(self.windows_job()), + r"(?m)^\s*(?:-\s*)?(?:run\s*:\s*)?\./sync\.sh\s*$") + + def test_windows_job_checks_managed_marker_with_python(self): + # `python -` (stdin/heredoc), `python <<` or `python -c`, not python3 (#52 user story 23) + self.assertRegex(strip_comments(self.windows_job()), + r"(?m)(? Apps > " + "Advanced app settings > App execution aliases.") + +_LOG = r'''_log() { + f=$(mktemp "$LOGDIR/call.XXXXXX") + printf '%s\0' "$@" > "$f" +} +''' + +# Store-shim-like: complains and fails for any invocation. 9009 is cmd.exe's "not found" +# status (#48); POSIX truncates it to 49, which is non-zero and, importantly, not 1. +_BROKEN = r'''#!/bin/sh +LOGDIR='{logdir}' +{log}_log '{name}' broken "$@" +echo "{msg}" >&2 +exit 9009 +''' + +# Working: log, then exec the real interpreter. The py flavour drops a leading -3. +_WORKING = r'''#!/bin/sh +LOGDIR='{logdir}' +{log}_log '{name}' working "$@" +{drop3}exec '{real}' "$@" +''' +_DROP3 = 'if [ "${1:-}" = "-3" ]; then shift; fi\n' + +# Old (3.8): `-c ` runs in the real interpreter with sys.version_info replaced by a +# 5-field namedtuple (3, 8, 18, 'final', 0); --version/-V prints 3.8.18; anything else is +# logged and exits 0 without running anything. +_OLD_WRAPPER = ( + 'import collections, sys\n' + 'VI = collections.namedtuple("version_info", "major minor micro releaselevel serial")\n' + 'sys.version_info = VI(3, 8, 18, "final", 0)\n' + 'code = sys.argv[1]\n' + 'sys.argv = ["-c"]\n' + 'exec(compile(code, "", "exec"), {"__name__": "__main__"})\n' +) # double quotes only: it is embedded in a single-quoted shell string +_OLD = r'''#!/bin/sh +LOGDIR='{logdir}' +{log}_log '{name}' old "$@" +{drop3}for a in "$@"; do + case "$a" in --version|-V) echo "Python 3.8.18"; exit 0;; esac +done +prev= +for a in "$@"; do + if [ "$prev" = "-c" ]; then exec '{real}' -c '{wrapper}' "$a"; fi + prev=$a +done +exit 0 +''' + +NAMES = {"python3": "python3", "python": "python", "py": "py"} + + +class InterpreterProbeTest(unittest.TestCase): + def setUp(self): + self.sb = SyncSandbox() + self.addCleanup(self.sb.close) + self.bin = tempfile.mkdtemp(prefix="devflow-fakepy-") + self.addCleanup(shutil.rmtree, self.bin, True) + self.logdir = os.path.join(self.bin, "log") + os.makedirs(self.logdir) + + # --- fakes --------------------------------------------------------------------------- + + def _fake(self, name, kind): + drop3 = _DROP3 if name == "py" else "" + fmt = dict(logdir=self.logdir, log=_LOG, name=name, real=REAL_PYTHON, drop3=drop3) + if kind == "broken": + text = _BROKEN.format(msg=STORE_MESSAGE, **fmt) + elif kind == "working": + text = _WORKING.format(**fmt) + elif kind == "old": + text = _OLD.format(wrapper=_OLD_WRAPPER, **fmt) + else: + raise ValueError(kind) + path = os.path.join(self.bin, name) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + def _run(self, python3, python, py): + self._fake("python3", python3) + self._fake("python", python) + self._fake("py", py) + path = self.bin + os.pathsep + os.environ.get("PATH", "") + return self.sb.run("--dry-run", env={"PATH": path}) + + def _calls(self): + calls = [] + for n in sorted(os.listdir(self.logdir)): + with open(os.path.join(self.logdir, n), "rb") as f: + fields = f.read().decode("utf-8").split("\0")[:-1] + calls.append((fields[0], fields[1], fields[2:])) + return calls + + def _sync_calls(self): + """(name, argv) of every fake call whose argv holds the sync script lib/sync.py.""" + return [(name, argv) for name, _kind, argv in self._calls() + if any(a.replace("\\", "/").endswith("lib/sync.py") for a in argv)] + + def _ran_by(self): + return [name for name, _argv in self._sync_calls()] + + def _missing_from_message(self, stderr): + # Substring/word checks, since wording may vary (#52, user stories 4 and 5). + needles = {"3.9": r"3\.9", "python3": r"\bpython3\b", "python": r"\bpython\b", + "py -3": r"\bpy -3\b"} + return [k for k, rx in needles.items() if not re.search(rx, stderr)] + + # --- order and fall-through (#52, user stories 1, 3, 6; ticket #55 criterion 1) ------- + + def test_working_python3_runs_the_sync(self): + # characterization: today's behaviour (#52, user story 6) + r = self._run(python3="working", python="broken", py="broken") + self.assertEqual((r.returncode, self._ran_by()), (0, ["python3"]), r.stderr) + + def test_store_shim_python3_falls_through_to_python(self): + # #52, user story 1 (#48) + r = self._run(python3="broken", python="working", py="broken") + self.assertEqual((r.returncode, self._ran_by()), (0, ["python"]), r.stderr) + + def test_launcher_only_runs_the_sync_with_py(self): + # #52, user story 3 + r = self._run(python3="broken", python="broken", py="working") + self.assertEqual((r.returncode, self._ran_by()), (0, ["py"]), r.stderr) + + def test_launcher_is_invoked_as_py_dash_3(self): + # #52, user story 3: the candidate is `py -3`, so its argv begins with -3 + self._run(python3="broken", python="broken", py="working") + firsts = [argv[0] if argv else None for _n, argv in self._sync_calls()] + self.assertEqual(firsts, ["-3"]) + + # --- flags (#52 Implementation Decisions: run with -I -X utf8, script, user args) ----- + + def test_sync_runs_isolated_and_utf8_with_user_args_after_script(self): + self._run(python3="working", python="broken", py="broken") + calls = self._sync_calls() + self.assertEqual(len(calls), 1, calls) + argv = calls[0][1] + i = next(k for k, a in enumerate(argv) if a.replace("\\", "/").endswith("lib/sync.py")) + before, after = argv[:i], argv[i + 1:] + utf8 = any(before[k] == "-X" and before[k + 1] == "utf8" for k in range(len(before) - 1)) + self.assertEqual({"-I before script": "-I" in before, + "-X utf8 before script": utf8, + "args after script": after}, + {"-I before script": True, + "-X utf8 before script": True, + "args after script": ["--dry-run"]}) + + # --- version floor (#52, user story 4; ticket #55 criterion 1) ------------------------ + + def test_old_python3_is_skipped_for_working_python(self): + r = self._run(python3="old", python="working", py="broken") + self.assertEqual((r.returncode, self._ran_by()), (0, ["python"]), r.stderr) + + # --- no qualifying interpreter (#52, user stories 4 and 5; ticket #55 criterion 2) ---- + + def test_only_old_interpreters_exits_1(self): + r = self._run(python3="old", python="old", py="broken") + self.assertEqual(r.returncode, 1, r.stderr) + + def test_only_old_interpreters_message_names_floor_and_every_candidate(self): + r = self._run(python3="old", python="old", py="broken") + self.assertEqual(self._missing_from_message(r.stderr), [], r.stderr) + + def test_only_old_interpreters_never_run_the_sync(self): + self._run(python3="old", python="old", py="broken") + self.assertEqual(self._ran_by(), []) + + def test_no_usable_interpreter_exits_1(self): + r = self._run(python3="broken", python="broken", py="broken") + self.assertEqual(r.returncode, 1, r.stderr) + + def test_no_usable_interpreter_message_names_floor_and_every_candidate(self): + r = self._run(python3="broken", python="broken", py="broken") + self.assertEqual(self._missing_from_message(r.stderr), [], r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_line_endings.py b/tests/test_line_endings.py new file mode 100644 index 0000000..9deeb37 --- /dev/null +++ b/tests/test_line_endings.py @@ -0,0 +1,263 @@ +"""Acceptance tests for #54 (#52 user stories 11-15, 17): line endings independent of the +user's git config. Black-box, through ./sync.sh in a SyncSandbox. `core.autocrlf=true` converts +LF to CRLF on checkout on every OS, so the Windows defect (#50) reproduces on Linux and macOS.""" +import glob +import os +import re +import unittest + +from tests.harness import REAL_ROOT, SyncSandbox + +CLAUDE_SKILLS = "~/.claude/skills" +# The CI fresh-install job's "no change" check: every status that changes something starts +# its line with one of these words. +CHANGE_LINE = re.compile(r"^\s*(installed|updated|removed|added|would|FAIL|WARN|SKIP)(\s|$)") + + +def _to_crlf(path): + with open(path, "rb") as f: + data = f.read() + data = data.replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + with open(path, "wb") as f: + f.write(data) + + +def _patch_paths(sb): + return sorted(glob.glob(os.path.join(sb.repo, "patches", "*.patch"))) + + +def _tracked_files(sb, clone): + out = sb.git("ls-files", "-z", cwd=clone).stdout + paths = [os.path.join(clone, p) for p in out.split("\0") if p] + return [p for p in paths if os.path.isfile(p) and not os.path.islink(p)] + + +def _files_with_cr(sb, clone): + """Tracked text files containing a CR. Binary files (a NUL byte, git's own heuristic) are + skipped: line endings don't apply to them, and e.g. every PNG's signature holds a CR.""" + bad = [] + for p in _tracked_files(sb, clone): + with open(p, "rb") as f: + data = f.read() + if b"\r" in data and b"\0" not in data: + bad.append(os.path.relpath(p, clone)) + return bad + + +def _tree(root): + """{relative path: bytes} of every file under root ({} if root doesn't exist).""" + out = {} + for dp, _, files in os.walk(root): + for fn in files: + p = os.path.join(dp, fn) + with open(p, "rb") as f: + out[os.path.relpath(p, root)] = f.read() + return out + + +def _local_autocrlf(sb, clone): + r = sb.git("config", "--local", "--get", "core.autocrlf", cwd=clone, check=False) + return r.stdout.strip() if r.returncode == 0 else None + + +def _change_lines(stdout): + return [l for l in stdout.splitlines() if CHANGE_LINE.match(l)] + + +class _Base(unittest.TestCase): + def sandbox(self, **kw): + sb = SyncSandbox(**kw) + self.addCleanup(sb.close) + return sb + + def assert_every_skill_installed(self, sb, r): + out = r.stdout + r.stderr + self.assertEqual(r.returncode, 0, out) + self.assertEqual([l for l in r.stdout.splitlines() if l.lstrip().startswith("FAIL")], [], out) + self.assertEqual(sb.managed_skills(CLAUDE_SKILLS), sb.manifest_skill_names(), out) + + def assert_no_change(self, r): + self.assertEqual(_change_lines(r.stdout), [], r.stdout + r.stderr) + + +class CrlfPatchesTest(_Base): + """#52 user stories 11 and 14: a clone whose patches/*.patch are CRLF still syncs.""" + + def setUp(self): + self.sb = self.sandbox() + for p in _patch_paths(self.sb): + _to_crlf(p) + + def test_crlf_patches_install_every_skill(self): + self.assert_every_skill_installed(self.sb, self.sb.run()) + + def test_crlf_patches_resync_reports_no_change(self): + self.sb.run() + self.assert_no_change(self.sb.run()) + + +class CrlfVendorClonesTest(_Base): + """#52 user story 12: vendor clones checked out under core.autocrlf=true are repaired once.""" + + def setUp(self): + self.sb = self.sandbox(own_vendors=True) + self.sb.set_global_git_config("core.autocrlf", "true") + self.sb.clone_vendors() + # Precondition: without a CRLF file in mattpocock-skills (no upstream eol rule) the + # cases below prove nothing. + matt = self.sb.vendor_dirs()["matt"] + self.assertNotEqual(_files_with_cr(self.sb, matt), [], + "pre-cloned mattpocock-skills has no CRLF file under core.autocrlf=true") + + def test_crlf_vendor_clones_install_every_skill(self): + # characterization: passes today, because git apply honours the effective + # core.autocrlf=true and normalises the CRLF vendor files before matching the patch. + self.assert_every_skill_installed(self.sb, self.sb.run()) + + def test_crlf_vendor_clones_are_lf_after_sync(self): + self.sb.run() + bad = {src: _files_with_cr(self.sb, d) for src, d in self.sb.vendor_dirs().items()} + self.assertEqual({src: f for src, f in bad.items() if f}, {}) + + def test_crlf_vendor_clones_get_local_autocrlf_false(self): + self.sb.run() + got = {src: _local_autocrlf(self.sb, d) for src, d in self.sb.vendor_dirs().items()} + self.assertEqual(got, {src: "false" for src in got}) + + def test_crlf_vendor_clones_installed_skills_are_lf(self): + # #52 user story 9: installed skill files are LF, byte-for-byte as on macOS. + sb = self.sb + r = sb.run() + root = sb.home_path(CLAUDE_SKILLS) + bad = [os.path.join(n, p) for n in sorted(sb.managed_skills(CLAUDE_SKILLS)) + for p, data in _tree(os.path.join(root, n)).items() if b"\r" in data] + self.assertEqual(bad, [], r.stdout + r.stderr) + + def test_crlf_vendor_clones_resync_reports_no_change(self): + # characterization: passes today (nothing changes the clones between the two syncs). + self.sb.run() + self.assert_no_change(self.sb.run()) + + +class MissingVendorClonesTest(_Base): + """#52 user story 11: a vendor clone the sync creates is LF even under global autocrlf=true.""" + + def setUp(self): + self.sb = self.sandbox(own_vendors=True) + self.sb.set_global_git_config("core.autocrlf", "true") + + def test_new_clones_install_every_skill(self): + # characterization: passes today for the same reason as the pre-cloned case. + self.assert_every_skill_installed(self.sb, self.sb.run()) + + def test_new_clones_are_lf(self): + self.sb.run() + bad = {src: _files_with_cr(self.sb, d) for src, d in self.sb.vendor_dirs().items()} + self.assertEqual({src: f for src, f in bad.items() if f}, {}) + + def test_new_clones_record_local_autocrlf_false(self): + self.sb.run() + got = {src: _local_autocrlf(self.sb, d) for src, d in self.sb.vendor_dirs().items()} + self.assertEqual(got, {src: "false" for src in got}) + + +class AutocrlfNotTrueTest(_Base): + """#52 user story 13: when the effective core.autocrlf isn't true, the repair never runs. + Characterization: today's sync never touches an existing clone at its locked commit.""" + + def pre_cloned(self, global_autocrlf): + sb = self.sandbox(own_vendors=True) + if global_autocrlf is not None: + sb.set_global_git_config("core.autocrlf", global_autocrlf) + sb.clone_vendors() + return sb + + def mtimes(self, sb): + return {p: os.stat(p).st_mtime_ns + for d in sb.vendor_dirs().values() for p in _tracked_files(sb, d)} + + def assert_no_local_key(self, global_autocrlf): + sb = self.pre_cloned(global_autocrlf) + r = sb.run() + got = {src: _local_autocrlf(sb, d) for src, d in sb.vendor_dirs().items()} + self.assertEqual(got, {src: None for src in got}, r.stdout + r.stderr) + + def assert_files_untouched(self, global_autocrlf): + sb = self.pre_cloned(global_autocrlf) + before = self.mtimes(sb) + r = sb.run() + self.assertEqual(self.mtimes(sb), before, r.stdout + r.stderr) + + def test_autocrlf_input_adds_no_local_key(self): + self.assert_no_local_key("input") + + def test_autocrlf_input_leaves_tracked_files_untouched(self): + self.assert_files_untouched("input") + + def test_autocrlf_unset_adds_no_local_key(self): + self.assert_no_local_key(None) + + def test_autocrlf_unset_leaves_tracked_files_untouched(self): + self.assert_files_untouched(None) + + +class EditCrlfPatchTest(_Base): + """#52 user story 15: `sync.sh edit` applies a CRLF patch the same way the build does.""" + + def test_edit_applies_crlf_patch(self): + sb = self.sandbox() + _to_crlf(os.path.join(sb.repo, "patches", "grilling.patch")) + r = sb.run("edit", "grilling") + work = os.path.join(sb.repo, ".patch-work", "grilling") + # A missing a/ or b/ reads as an empty tree, so a crashed edit fails here too. + self.assertNotEqual(_tree(os.path.join(work, "a")), _tree(os.path.join(work, "b")), + "b/ equals a/: the patch was not applied\n" + r.stdout + r.stderr) + + +class FailingPatchTest(_Base): + """#54 criterion 5: a patch that genuinely doesn't apply is still reported, naming the file. + Characterization: today's sync already prints this FAIL line and exits non-zero.""" + + PATCH = "patches/grilling.patch" + + def setUp(self): + self.sb = self.sandbox() + path = os.path.join(self.sb.repo, self.PATCH) + with open(path, encoding="utf-8", newline="") as f: + lines = f.read().split("\n") + in_hunk = False + for i, line in enumerate(lines): + if line.startswith("@@"): + in_hunk = True + elif in_hunk and line.startswith(" ") and line.strip(): + lines[i] = " devflow-test: this context line matches nothing upstream" + break + else: + self.fail(f"no context line to corrupt in {self.PATCH}") + with open(path, "w", encoding="utf-8", newline="") as f: + f.write("\n".join(lines)) + self.r = self.sb.run() + + def test_unappliable_patch_fail_line_names_patch_file(self): + fails = [l for l in self.r.stdout.splitlines() + if l.lstrip().startswith("FAIL") and self.PATCH in l] + self.assertNotEqual(fails, [], self.r.stdout + self.r.stderr) + + def test_unappliable_patch_exits_non_zero(self): + self.assertNotEqual(self.r.returncode, 0, self.r.stdout + self.r.stderr) + + +class GitattributesTest(unittest.TestCase): + """#54 criterion 1 (#52 user story 17): the repo declares LF for its text files.""" + + def test_repo_gitattributes_declares_lf(self): + path = os.path.join(REAL_ROOT, ".gitattributes") + lines = [] + if os.path.exists(path): + with open(path, encoding="utf-8") as f: + lines = [l.strip() for l in f.read().splitlines()] + self.assertIn("* text=auto eol=lf", lines) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_text_encoding.py b/tests/test_text_encoding.py new file mode 100644 index 0000000..7abe860 --- /dev/null +++ b/tests/test_text_encoding.py @@ -0,0 +1,158 @@ +"""Acceptance tests for #53 (part of #52): every text read and write in the sync library and +the smoke driver names its encoding. + +On Windows the locale encoding is cp1252, so text I/O without an explicit encoding reads, +writes or decodes non-ASCII skill text wrongly (#49; #52 user stories 7 and 20). UTF-8 is +already the default on Linux and macOS, so the defect can't be observed there by running the +code. The guard below is a static check by design (#52 user story 21): it parses each source +file's AST and lists every text-mode call that doesn't pass encoding="utf-8". +""" +import ast +import os +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +_UTF8 = {"utf-8", "utf8"} + + +def _keyword(call, name): + for kw in call.keywords: + if kw.arg == name: + return kw + return None + + +def _mode_is_text(call): + """The mode is the 2nd positional arg or mode=. Absent, or a str constant without "b", + is text. A mode that isn't a str constant can't be proven binary, so it counts as text.""" + mode = call.args[1] if len(call.args) > 1 else None + kw = _keyword(call, "mode") + if kw is not None: + mode = kw.value + if mode is None: + return True + if isinstance(mode, ast.Constant) and isinstance(mode.value, str): + return "b" not in mode.value + return True + + +def _is_text_flag(kw): + # text=False / text=None is bytes mode; anything else (True, or a value that isn't a + # constant) may be text, so it must name an encoding. + if kw is None: + return False + return not (isinstance(kw.value, ast.Constant) and kw.value.value in (False, None)) + + +def _call_kind(call): + """'open', 'fdopen' or 'subprocess' for the calls the guard covers, else None.""" + f = call.func + if isinstance(f, ast.Name) and f.id == "open": + return "open" + if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name): + if f.value.id == "os" and f.attr == "fdopen": + return "fdopen" + if f.value.id == "subprocess": + return "subprocess" + return None + + +def _is_text_call(call, kind): + if kind in ("open", "fdopen"): + return _mode_is_text(call) + return (_is_text_flag(_keyword(call, "text")) + or _is_text_flag(_keyword(call, "universal_newlines"))) + + +def _encoding_ok(call): + """True when encoding= is present and isn't a str constant other than utf-8/utf8. + encoding=None means the locale encoding, so it counts as missing.""" + kw = _keyword(call, "encoding") + if kw is None: + return False + v = kw.value + if isinstance(v, ast.Constant): + return isinstance(v.value, str) and v.value.lower() in _UTF8 + return True + + +def find_violations(source, filename=""): + """List of 'file:line: call text' for each text-mode open()/os.fdopen()/subprocess call + without encoding="utf-8".""" + tree = ast.parse(source, filename) + out = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + kind = _call_kind(node) + if kind is None: + continue + has_enc = _keyword(node, "encoding") is not None + if not has_enc and not _is_text_call(node, kind): + continue + if _encoding_ok(node): + continue + text = ast.get_source_segment(source, node) or ast.dump(node) + out.append((node.lineno, f"{filename}:{node.lineno}: {' '.join(text.split())}")) + return [msg for _, msg in sorted(out)] + + +def violations_in(rel): + with open(os.path.join(ROOT, rel), encoding="utf-8") as f: + return find_violations(f.read(), rel) + + +class SourceEncodingTest(unittest.TestCase): + # #52 Implementation Decisions, encoding policy; ticket #53 criteria 1 and 5; + # #52 user story 21. + def assertNoViolations(self, rel): + found = violations_in(rel) + self.assertEqual(found, [], "text I/O without encoding=\"utf-8\":\n" + "\n".join(found)) + + def test_sync_library_names_utf8_for_every_text_io_call(self): + # #52 user stories 7 and 8: the sync reads, writes and decodes as UTF-8 + self.assertNoViolations("lib/sync.py") + + def test_smoke_driver_names_utf8_for_every_text_io_call(self): + # #52 user story 20: the smoke driver decodes agent output and its files as UTF-8 + self.assertNoViolations("smoke/drive.py") + + +class GuardSelfTest(unittest.TestCase): + """Tests of the guard itself (test code, so these pass as soon as the guard exists). + Cases come from the violation rules for #53.""" + + def assertFlagged(self, src): + self.assertEqual(len(find_violations(src)), 1, src) + + def assertNotFlagged(self, src): + self.assertEqual(find_violations(src), [], src) + + def test_bare_text_open_is_flagged(self): + self.assertFlagged("open(p)\n") + + def test_binary_open_is_not_flagged(self): + self.assertNotFlagged('open(p, "rb")\n') + + def test_text_open_with_utf8_is_not_flagged(self): + self.assertNotFlagged('open(p, "w", encoding="utf-8")\n') + + def test_text_fdopen_without_encoding_is_flagged(self): + self.assertFlagged('os.fdopen(fd, "w", newline=x)\n') + + def test_text_subprocess_without_encoding_is_flagged(self): + self.assertFlagged("subprocess.run(a, text=True)\n") + + def test_text_subprocess_with_utf8_is_not_flagged(self): + self.assertNotFlagged('subprocess.run(a, text=True, encoding="utf-8")\n') + + def test_bytes_subprocess_is_not_flagged(self): + self.assertNotFlagged("subprocess.run(a)\n") + + def test_open_with_non_utf8_encoding_is_flagged(self): + self.assertFlagged('open(p, encoding="latin-1")\n') + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vendor_repair.py b/tests/test_vendor_repair.py new file mode 100644 index 0000000..38c1651 --- /dev/null +++ b/tests/test_vendor_repair.py @@ -0,0 +1,59 @@ +"""Regression test for the #52 final review: the one-time CRLF repair of a vendor clone must +survive a failed reset. If `git reset --hard` fails (on Windows, a file locked by antivirus or +an editor), the clone's local core.autocrlf must not yet read false, so the next sync retries +the repair. Black-box, through ./sync.sh in a SyncSandbox; the reset is made to fail by making +a folder of the clone read-only, so git can't replace the CRLF file inside it.""" +import os +import stat +import unittest + +from tests.harness import SyncSandbox +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") + self.sb = SyncSandbox(own_vendors=True) + self.addCleanup(self.sb.close) + self.sb.set_global_git_config("core.autocrlf", "true") + self.sb.clone_vendors() + self.clone = self.sb.vendor_dirs()["matt"] + crlf = _files_with_cr(self.sb, self.clone) + self.assertNotEqual(crlf, [], "pre-cloned mattpocock-skills has no CRLF file under core.autocrlf=true") + self.crlf_files = [os.path.join(self.clone, f) for f in crlf] + self.locked = os.path.dirname(self.crlf_files[0]) + self.assertNotEqual(os.path.realpath(self.locked), os.path.realpath(self.clone)) + self.mode = stat.S_IMODE(os.stat(self.locked).st_mode) + os.chmod(self.locked, 0o555) + self.addCleanup(self.unlock) + + def unlock(self): + os.chmod(self.locked, self.mode) + + def test_failed_reset_leaves_local_autocrlf_unset_to_false(self): + r = self.sb.run() + self.assertNotEqual(r.returncode, 0, "the reset was expected to fail:\n" + r.stdout + r.stderr) + self.assertNotEqual(_local_autocrlf(self.sb, self.clone), "false", r.stdout + r.stderr) + + def test_next_sync_completes_the_repair(self): + self.sb.run() + self.unlock() + r = self.sb.run() + out = r.stdout + r.stderr + self.assertEqual(r.returncode, 0, out) + self.assertEqual(_local_autocrlf(self.sb, self.clone), "false", out) + # Read the files directly: a clone left with an empty index lists no tracked files. + still_crlf = [] + for p in self.crlf_files: + with open(p, "rb") as f: + if b"\r" in f.read(): + still_crlf.append(os.path.relpath(p, self.clone)) + self.assertEqual(still_crlf, [], out) + status = self.sb.git("status", "--porcelain", cwd=self.clone).stdout + self.assertEqual(status, "", out) + + +if __name__ == "__main__": + unittest.main()