Merge remote-tracking branch 'origin/main' into item-406
# Conflicts: # README.md # docs/reading-cost.md
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
"""Where an epic's repo is on this machine: its checkout and its project config, found by the repo's name.
|
||||
|
||||
A missing checkout is cloned from the host and owner of the epic's other repos (docs/decisions.md → `do-epic: drives one Jira epic …`). Where that is unclear, the answer is an Unsure."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
|
||||
from project_config.settings import by_name, CONFIG, ProjectConfig, PROJECTS
|
||||
from do_epic.config import DoEpicConfig
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import Git
|
||||
from forge.commands import url_beside
|
||||
|
||||
# One folder name, which can't be a path or a git option.
|
||||
REPO_NAME = r"\w[\w.-]*"
|
||||
# The addresses a clone may use: https, ssh, or scp-style `user@host:path`. Not ext:: or file:, which run a program or read this machine's files, and an origin can spell either.
|
||||
CLONE_ADDRESS = rf"https://[\w.-]+(:\d+)?/\S+|ssh://[\w.@-]+(:\d+)?/\S+|\w[\w.-]*@[\w.-]+:[\w./~-]+"
|
||||
# A clone that waits longer is stopped.
|
||||
CLONE_SECONDS = 600
|
||||
# git's options that make a password or a host key fail at once instead of prompting: an unattended run never waits on a prompt (docs/decisions.md → principle 6).
|
||||
NO_PROMPTS = ("-c", "core.askPass=true", "-c", "core.sshCommand=ssh -o BatchMode=yes")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Located:
|
||||
"""checkout is the repo's git checkout, and config the project config that names it."""
|
||||
checkout: pathlib.Path
|
||||
config: ProjectConfig
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unsure(Failure):
|
||||
"""reason is a question for the human."""
|
||||
|
||||
|
||||
def locate(name: str, others: list[pathlib.Path], config: DoEpicConfig, home: pathlib.Path, git: Git) -> Located | Failure:
|
||||
"""The checkout and project config of the repo called name; others are the checkouts of the epic's other repos.
|
||||
|
||||
A project config names the repo's checkout, and it is cloned where missing. Where no config names the repo, it is cloned into the clone folder, if it isn't there, and the human is asked to write the config, since the repo's plan, goals and records are theirs to place.
|
||||
A name that is no repo's name, or a config that can't be read, is a plain Failure. Any other fault is an Unsure."""
|
||||
if not re.fullmatch(REPO_NAME, name):
|
||||
return Failure(f"{name!r} is not a repo's name: one folder name that starts with a letter, digit or underscore")
|
||||
found = by_name(name, home)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
checkout = found.top if found else config.clone_folder / name
|
||||
cloned = ensure(name, checkout, others, git)
|
||||
if isinstance(cloned, Failure):
|
||||
return cloned
|
||||
if found is None:
|
||||
return Unsure(f"{checkout} {'was cloned' if cloned else 'holds the repo'}, but no project config names it. Write {home / PROJECTS}/<key>/{CONFIG} with `checkout = \"{checkout}\"`, as `project-config --help` shows, and run do-epic again.")
|
||||
return Located(checkout, found)
|
||||
|
||||
|
||||
def ensure(name: str, checkout: pathlib.Path, others: list[pathlib.Path], git: Git) -> bool | Failure:
|
||||
"""Whether checkout was cloned just now: False where it is a git checkout already. Else it is cloned there from the host and owner of the others, or an Unsure says why not."""
|
||||
if (checkout / ".git").exists():
|
||||
return False
|
||||
if checkout.exists() and (not checkout.is_dir() or any(checkout.iterdir())):
|
||||
return Unsure(f"{checkout} exists and is not a git checkout, so {name} cannot be cloned there. Where should it be cloned?")
|
||||
url = clone_url(name, others, git)
|
||||
if isinstance(url, Failure):
|
||||
return url
|
||||
cloned = git(*NO_PROMPTS, "clone", "--", url, str(checkout), timeout=CLONE_SECONDS)
|
||||
if isinstance(cloned, Failure):
|
||||
# What the clone began, and nothing else: checkout was absent or empty. A kept half-clone would pass for the repo on the next run.
|
||||
shutil.rmtree(checkout, ignore_errors=True)
|
||||
return Unsure(f"cannot clone {url} to {checkout}: {cloned.reason}. Where does {name} live?")
|
||||
return True
|
||||
|
||||
|
||||
def without_credentials(url: str) -> str:
|
||||
"""url without a `user:token@` after its scheme, so that a clone and a question for the team never carry one. The clone then uses git's own credentials."""
|
||||
return re.sub(r"^(https?://)[^/]*@", r"\1", url)
|
||||
|
||||
|
||||
def clone_url(name: str, others: list[pathlib.Path], git: Git) -> str | Failure:
|
||||
"""The address of the repo called name, under the host and owner all the others share. An Unsure where they share none or an address can't be built."""
|
||||
if not others:
|
||||
return Unsure(f"{name} is missing and no other repo of the epic shows what host to clone it from. Where does it live?")
|
||||
urls = set()
|
||||
for other in others:
|
||||
origin = git("remote", "get-url", "origin", cwd=str(other))
|
||||
if isinstance(origin, Failure):
|
||||
return Unsure(f"cannot read the origin of {other}: {origin.reason}. Where does {name} live?")
|
||||
beside = url_beside(without_credentials(origin.strip()), name)
|
||||
if beside is None:
|
||||
return Unsure(f"{other} has an origin, {without_credentials(origin.strip())}, with no host and owner to put another repo under. Where does {name} live?")
|
||||
urls.add(beside)
|
||||
if len(urls) > 1:
|
||||
return Unsure(f"The epic's other repos sit under more than one host or owner, so {name} could be at {' or '.join(sorted(urls))}. Which holds it?")
|
||||
url = next(iter(urls))
|
||||
if not re.fullmatch(CLONE_ADDRESS, url):
|
||||
return Unsure(f"{url} is not an https, ssh or scp-style address. Where does {name} live?")
|
||||
return url
|
||||
@@ -0,0 +1,184 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from do_epic.config import DoEpicConfig
|
||||
from failure import Failure
|
||||
from do_epic.repos import locate, Located, Unsure
|
||||
from project_config.settings import ProjectConfig
|
||||
from project_config.test_project_config import write_config
|
||||
|
||||
|
||||
class FakeGit:
|
||||
"""git as locate calls it: origins maps a checkout to its origin URL, cloned holds each `clone` that worked, and refused names a URL whose clone fails after it made the checkout's `.git`, as a stopped git does."""
|
||||
def __init__(self, origins: dict[str, str | Failure], refused: str | None = None) -> None:
|
||||
self.origins, self.refused = origins, refused
|
||||
self.cloned: list[tuple[str, str]] = []
|
||||
self.clone_timeouts: list[float | None] = []
|
||||
self.clone_options: list[tuple[str, ...]] = []
|
||||
|
||||
def __call__(self, *args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
|
||||
if args[:3] == ("remote", "get-url", "origin"):
|
||||
return self.origins[cwd or ""]
|
||||
clone = args.index("clone")
|
||||
self.clone_options.append(args[:clone])
|
||||
assert args[clone + 1] == "--", args
|
||||
url, destination = args[clone + 2:clone + 4]
|
||||
pathlib.Path(destination, ".git").mkdir(parents=True)
|
||||
if url == self.refused:
|
||||
return Failure("git clone: repository not found")
|
||||
self.cloned.append((url, destination))
|
||||
self.clone_timeouts.append(timeout)
|
||||
return ""
|
||||
|
||||
|
||||
class LocateTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
made = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(made.cleanup)
|
||||
self.home = pathlib.Path(made.name).resolve()
|
||||
self.projects = self.home / ".claude-projects"
|
||||
self.config = DoEpicConfig(self.projects / "do-epic", "https://acme.atlassian.net", self.home / "jira.env", self.home / "clones", "English", "claude-opus-5-5", "rule")
|
||||
self.billing, self.payments = self.home / "elsewhere" / "billing", self.home / "elsewhere" / "payments"
|
||||
self.origins: dict[str, str | Failure] = {str(self.billing): "git@github.com:acme/billing.git", str(self.payments): "git@github.com:acme/payments"}
|
||||
|
||||
def configure(self) -> None:
|
||||
write_config(self.home, self.home / "code" / "ledger")
|
||||
|
||||
def locate(self, git: FakeGit, name: str = "ledger") -> Located | Failure:
|
||||
return locate(name, [self.billing, self.payments], self.config, self.home, git)
|
||||
|
||||
def unsure(self, git: FakeGit, name: str = "ledger") -> str:
|
||||
found = self.locate(git, name)
|
||||
assert isinstance(found, Unsure), found
|
||||
return found.reason
|
||||
|
||||
def test_finds_a_checkout_that_exists_with_its_config_and_clones_nothing(self) -> None:
|
||||
self.configure()
|
||||
(self.home / "code" / "ledger" / ".git").mkdir(parents=True)
|
||||
git = FakeGit(self.origins)
|
||||
found = self.locate(git)
|
||||
assert isinstance(found, Located), found
|
||||
self.assertEqual((found.checkout, found.config.folder, git.cloned), (self.home / "code" / "ledger", self.projects / "ledger", []))
|
||||
|
||||
def test_clones_a_checkout_the_config_names_where_it_is_missing_from_the_place_of_the_other_repos(self) -> None:
|
||||
self.configure()
|
||||
git = FakeGit(self.origins)
|
||||
found = self.locate(git)
|
||||
assert isinstance(found, Located), found
|
||||
self.assertEqual((found.checkout, git.cloned), (self.home / "code" / "ledger", [("git@github.com:acme/ledger", str(self.home / "code" / "ledger"))]))
|
||||
assert isinstance(found.config, ProjectConfig)
|
||||
|
||||
def test_clones_into_the_clone_folder_and_asks_for_a_config_where_none_names_the_repo(self) -> None:
|
||||
git = FakeGit(self.origins)
|
||||
asked = self.unsure(git)
|
||||
clone = self.home / "clones" / "ledger"
|
||||
self.assertEqual(git.cloned, [("git@github.com:acme/ledger", str(clone))])
|
||||
self.assertIn(f"{clone} was cloned, but no project config names it", asked)
|
||||
self.assertIn(f"{self.projects}/<key>/config.toml with `checkout = \"{clone}\"`", asked)
|
||||
self.assertEqual(self.unsure(git), asked.replace("was cloned", "holds the repo"), "the second ask finds the clone and clones nothing")
|
||||
self.assertEqual(len(git.cloned), 1)
|
||||
|
||||
def test_asks_where_the_other_repos_sit_in_more_than_one_place(self) -> None:
|
||||
self.configure()
|
||||
self.origins[str(self.payments)] = "git@gitea.larvit.se:acme/payments"
|
||||
git = FakeGit(self.origins)
|
||||
asked = self.unsure(git)
|
||||
self.assertIn("git@gitea.larvit.se:acme/ledger or git@github.com:acme/ledger", asked)
|
||||
self.assertEqual(git.cloned, [])
|
||||
|
||||
def test_asks_where_the_other_repos_differ_only_by_owner(self) -> None:
|
||||
self.configure()
|
||||
self.origins[str(self.payments)] = "git@github.com:other/payments"
|
||||
self.assertIn("more than one host or owner", self.unsure(FakeGit(self.origins)))
|
||||
|
||||
def test_asks_where_no_other_repo_shows_where_to_clone_from(self) -> None:
|
||||
self.configure()
|
||||
found = locate("ledger", [], self.config, self.home, FakeGit({}))
|
||||
assert isinstance(found, Unsure), found
|
||||
self.assertIn("no other repo of the epic", found.reason)
|
||||
|
||||
def test_asks_where_an_others_origin_cannot_be_read_or_has_no_place(self) -> None:
|
||||
self.configure()
|
||||
self.origins[str(self.billing)] = Failure("git remote: no such remote 'origin'")
|
||||
self.assertIn(f"cannot read the origin of {self.billing}: git remote: no such remote 'origin'", self.unsure(FakeGit(self.origins)))
|
||||
self.origins[str(self.billing)] = "billing"
|
||||
self.assertIn(f"{self.billing} has an origin, billing, with no host and owner to put another repo under", self.unsure(FakeGit(self.origins)))
|
||||
|
||||
def test_asks_all_the_same_where_the_leftovers_of_a_failed_clone_cannot_be_removed(self) -> None:
|
||||
self.configure()
|
||||
with unittest.mock.patch("do_epic.repos.shutil.rmtree", side_effect=lambda path, ignore_errors: None if ignore_errors is True else self.fail("rmtree must ignore errors")):
|
||||
self.assertIn("cannot clone", self.unsure(FakeGit(self.origins, refused="git@github.com:acme/ledger")))
|
||||
|
||||
def test_asks_where_the_clone_fails_naming_the_url_and_the_reason(self) -> None:
|
||||
self.configure()
|
||||
asked = self.unsure(FakeGit(self.origins, refused="git@github.com:acme/ledger"))
|
||||
self.assertIn(f"cannot clone git@github.com:acme/ledger to {self.home / 'code' / 'ledger'}: git clone: repository not found", asked)
|
||||
|
||||
def test_asks_where_the_place_to_clone_into_holds_something_that_is_not_a_checkout(self) -> None:
|
||||
self.configure()
|
||||
(self.home / "code" / "ledger").mkdir(parents=True)
|
||||
(self.home / "code" / "ledger" / "notes.txt").write_text("x", encoding="utf-8")
|
||||
git = FakeGit(self.origins)
|
||||
self.assertIn(f"{self.home / 'code' / 'ledger'} exists and is not a git checkout", self.unsure(git))
|
||||
self.assertEqual(git.cloned, [])
|
||||
|
||||
def test_refuses_a_name_that_is_not_a_repo_name_before_it_forms_a_path_or_a_command(self) -> None:
|
||||
for name in ("../escape", "-flag", "a/b", ""):
|
||||
with self.subTest(name=name):
|
||||
found = self.locate(FakeGit(self.origins), name)
|
||||
assert isinstance(found, Failure) and not isinstance(found, Unsure), found
|
||||
self.assertIn("is not a repo's name", found.reason)
|
||||
|
||||
def test_refuses_an_origin_that_is_not_https_ssh_or_an_scp_style_address(self) -> None:
|
||||
self.configure()
|
||||
for origin in ("ext::sh -c touch% x/billing", "file:///srv/acme/billing", "/srv/acme/billing", "-oProxy=x:a/b"):
|
||||
with self.subTest(origin=origin):
|
||||
self.origins[str(self.billing)] = origin
|
||||
self.origins[str(self.payments)] = origin
|
||||
git = FakeGit(self.origins)
|
||||
self.assertIn("is not an https, ssh or scp-style address", self.unsure(git))
|
||||
self.assertEqual(git.cloned, [])
|
||||
|
||||
def test_clones_and_asks_without_the_credentials_an_origin_holds(self) -> None:
|
||||
self.configure()
|
||||
self.origins[str(self.billing)] = "https://bot:s3cret@gitea.larvit.se/acme/billing"
|
||||
self.origins[str(self.payments)] = "https://other:t0@ken@gitea.larvit.se/acme/payments.git"
|
||||
git = FakeGit(self.origins)
|
||||
self.assertIsInstance(self.locate(git), Located)
|
||||
self.assertEqual(git.cloned, [("https://gitea.larvit.se/acme/ledger", str(self.home / "code" / "ledger"))])
|
||||
self.origins[str(self.payments)] = "https://other:t0@ken@gitea.larvit.se/acme/payments"
|
||||
self.origins[str(self.billing)] = "https://bot:s3cret@gitea.larvit.se"
|
||||
self.assertNotIn("s3cret", self.unsure(FakeGit(self.origins), "stock"))
|
||||
|
||||
def test_stops_a_clone_that_waits_and_makes_a_prompt_fail(self) -> None:
|
||||
self.configure()
|
||||
git = FakeGit(self.origins)
|
||||
self.locate(git)
|
||||
self.assertEqual(git.clone_timeouts, [600])
|
||||
self.assertEqual(git.clone_options, [("-c", "core.askPass=true", "-c", "core.sshCommand=ssh -o BatchMode=yes")])
|
||||
|
||||
def test_removes_what_a_failed_clone_began_so_that_the_next_run_clones_again(self) -> None:
|
||||
self.configure()
|
||||
failing = FakeGit(self.origins, refused="git@github.com:acme/ledger")
|
||||
self.unsure(failing)
|
||||
self.assertFalse((self.home / "code" / "ledger").exists())
|
||||
found = self.locate(FakeGit(self.origins))
|
||||
self.assertIsInstance(found, Located)
|
||||
|
||||
def test_asks_where_the_place_to_clone_into_is_a_file(self) -> None:
|
||||
self.configure()
|
||||
(self.home / "code").mkdir()
|
||||
(self.home / "code" / "ledger").write_text("x", encoding="utf-8")
|
||||
self.assertIn("exists and is not a git checkout", self.unsure(FakeGit(self.origins)))
|
||||
|
||||
def test_fails_with_the_config_failure_where_a_config_cannot_be_read(self) -> None:
|
||||
(self.projects / "broken").mkdir(parents=True)
|
||||
(self.projects / "broken" / "config.toml").write_text("this is not toml", encoding="utf-8")
|
||||
found = self.locate(FakeGit(self.origins))
|
||||
self.assertIsInstance(found, Failure)
|
||||
self.assertNotIsInstance(found, Unsure)
|
||||
Reference in New Issue
Block a user