Skip to content
Closed
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
6 changes: 5 additions & 1 deletion src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ def redirect_request(self, *_args, **_kwargs):


def _open(request: urllib.request.Request):
return urllib.request.build_opener(_NoRedirect).open(request, timeout=30)
try:
return urllib.request.build_opener(_NoRedirect).open(request, timeout=30)
except ValueError:
# The HTTP client can include the Authorization value in a header error.
raise MergifyError("Mergify API request has an invalid URL or header") from None


def api_get(repo: str, suffix: str) -> object | None:
Expand Down
37 changes: 18 additions & 19 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
from __future__ import annotations

import errno
import fcntl
import os
import re
import stat
import subprocess
import sys
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from pathlib import Path
from select import select
from uuid import uuid4

from loopzero._proc import build_env, run

GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK")
_ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir")
EXCLUDES = (".worktrees/", ".loopzero/")
EXCLUDES = (b".worktrees/", b".loopzero/")
_BASE_LINE = re.compile(r"^Base:\s*([0-9a-fA-F]{7,40})\s*$", re.MULTILINE)
_TASK_TEMPLATE = """# {title}

Expand Down Expand Up @@ -113,21 +113,20 @@ def _ensure_excludes(repo_root: Path) -> None:
if not info.is_relative_to(common) or not exclude.is_relative_to(common):
raise WorktreeError(f"Git exclude is outside its Git directory: {exclude}")
exclude.parent.mkdir(parents=True, exist_ok=True)
existing = exclude.read_text() if exclude.exists() else ""
missing = [entry for entry in EXCLUDES if entry not in existing.splitlines()]
if missing:
sep = "" if not existing or existing.endswith("\n") else "\n"
mode = stat.S_IMODE(exclude.stat().st_mode) if exclude.exists() else None
temp = exclude.with_name(f".exclude-{uuid4().hex}")
stream = temp.open("x")
try:
with stream:
stream.write(existing + sep + "\n".join(missing) + "\n")
if mode is not None:
temp.chmod(mode)
temp.replace(exclude)
finally:
temp.unlink(missing_ok=True)
while True:
fd = os.open(exclude, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o666)
with os.fdopen(fd, "rb") as stream:
fcntl.flock(fd, fcntl.LOCK_EX)
lines = set(stream.read().splitlines())
missing = [entry for entry in EXCLUDES if entry not in lines]
if missing:
# An editor can append an unterminated line before this write.
rules = b"\n" + b"\n".join(missing) + b"\n"
if os.write(fd, rules) != len(rules):
raise WorktreeError(f"incomplete write to Git exclude: {exclude}")
with suppress(FileNotFoundError):
if os.path.samestat(os.fstat(fd), exclude.lstat()):
return


def start(repo_root: Path, slug: str, base_branch: str) -> Path:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations

import base64
import http.client
import io
import json
import subprocess
import sys
import traceback
import urllib.error
import urllib.request

Expand All @@ -17,6 +19,26 @@ def response(payload: object) -> io.BytesIO:
return io.BytesIO(json.dumps(payload).encode())



@pytest.mark.parametrize(("operation", "args"), [
(mergify.api_get, ("acme/widgets", "/merge-queue/status")),
(mergify.dequeue, ("acme/widgets", 7)),
])
def test_malformed_authorization_is_not_logged(monkeypatch, operation, args):
fake_key = "synthetic-mergify-key"
monkeypatch.setenv("MERGIFY_API_KEY", fake_key + "\nsecond-line")
monkeypatch.setattr(urllib.request, "getproxies", dict)
monkeypatch.setattr(mergify, "_retry_sleep", lambda _delay: None)

def reject_network(_connection):
pytest.fail("invalid Authorization header reached the network")

monkeypatch.setattr(http.client.HTTPSConnection, "connect", reject_network)
with pytest.raises(mergify.MergifyError, match="invalid URL or header") as failure:
operation(*args)
assert fake_key not in "".join(traceback.format_exception(failure.value))


def test_membership_uses_bearer_and_validates_queue(monkeypatch):
monkeypatch.setenv("MERGIFY_API_KEY", "secret")
seen = []
Expand Down
27 changes: 21 additions & 6 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,21 +137,36 @@ def interrupt_after_add(cwd, *args, **kwargs):
assert task.read_text().endswith("(filled by `loopzero review`)\n")


@pytest.mark.parametrize("redirect", [None, "file", "directory"])
def test_start_excludes_worktrees_and_task_dir(repo: Path, redirect: str | None) -> None:
@pytest.mark.parametrize("case", ["regular", "file", "directory", "append", "replace"])
def test_start_excludes_worktrees_and_task_dir(repo: Path, monkeypatch, case: str) -> None:
exclude = repo / ".git" / "info" / "exclude"
exclude.write_text("*.log") # no trailing newline on purpose
if redirect:
link = exclude if redirect == "file" else exclude.parent
if case in ("file", "directory"):
link = exclude if case == "file" else exclude.parent
link.symlink_to(link.rename(repo.parent / "outside"))
with pytest.raises(worktree.WorktreeError, match="outside its Git directory"):
worktree.start(repo, "t1", "main")
assert exclude.read_text() == "*.log" and not (repo / ".worktrees").exists()
return
old_inode = exclude.stat().st_ino
write = worktree.os.write
replacement, concurrent = case == "replace", case in ("append", "replace")

def interleave(fd, rules):
if concurrent and rules.endswith(b".loopzero/\n"):
edit = exclude.with_suffix(".edited") if replacement else exclude
with edit.open("w" if replacement else "a") as stream:
stream.write("*.log\nlocal.env" if replacement else "\nlocal.env")
if replacement:
edit.replace(exclude)
monkeypatch.setattr(worktree.os, "write", write)
return write(fd, rules)

monkeypatch.setattr(worktree.os, "write", interleave)
wt = worktree.start(repo, "t1", "main")
assert exclude.stat().st_ino != old_inode
assert exclude.read_text().splitlines() == ["*.log", ".worktrees/", ".loopzero/"]
assert (exclude.stat().st_ino != old_inode) == replacement
expected = ["*.log", "local.env"] if concurrent else ["*.log"]
assert exclude.read_text().splitlines() == [*expected, ".worktrees/", ".loopzero/"]
assert not worktree.is_dirty(wt), "fresh worktree with task.md is clean"
assert git(repo, "status", "--porcelain") == ""
installed = exclude.stat()
Expand Down
Loading