36 lines
2.3 KiB
Python
36 lines
2.3 KiB
Python
"""The pure choices the preflight's steps act on."""
|
|
import pathlib
|
|
|
|
from forge.commands import Forge
|
|
|
|
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
|
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
|
|
|
|
|
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
|
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
|
|
return next((path for path, on, _ in worktrees(porcelain) if on == branch), None)
|
|
|
|
|
|
def worktrees(porcelain: str) -> list[tuple[pathlib.Path, str, str]]:
|
|
"""Each worktree on a branch, in what `git worktree list --porcelain` printed: its path, its branch and its head commit."""
|
|
blocks = [dict(line.partition(" ")[::2] for line in block.splitlines()) for block in porcelain.split("\n\n")]
|
|
return [(pathlib.Path(fields["worktree"]), fields["branch"].removeprefix("refs/heads/"), fields.get("HEAD", "")) for fields in blocks if fields.get("branch", "").startswith("refs/heads/")]
|
|
|
|
|
|
def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]:
|
|
"""The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default."""
|
|
if local:
|
|
return ["worktree", "add", "--quiet", str(path), branch], f"added on the branch {branch}, which existed already."
|
|
if pushed:
|
|
return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added on the new branch {branch}, made off origin/{branch}."
|
|
# --no-track: tracking the default branch would point a bare `git push` at it.
|
|
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
|
|
|
|
|
|
def pulls_command(forge: Forge, branch: str) -> list[str]:
|
|
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
|
|
if forge == "gh":
|
|
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
|
|
return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"]
|