workdash 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- workdash/__init__.py +12 -0
- workdash/__main__.py +5 -0
- workdash/analysis_cache.py +184 -0
- workdash/analyzer.py +229 -0
- workdash/backend.py +248 -0
- workdash/config.py +207 -0
- workdash/github_client.py +1079 -0
- workdash/included_items.py +58 -0
- workdash/launcher.py +378 -0
- workdash/models.py +50 -0
- workdash/prompts/__init__.py +0 -0
- workdash/prompts/analyze_issue.txt +120 -0
- workdash/prompts/analyze_pr.txt +147 -0
- workdash/prompts/launch_issue.txt +20 -0
- workdash/prompts/launch_pr.txt +20 -0
- workdash/prompts/launch_review.txt +20 -0
- workdash/repo_resolver.py +112 -0
- workdash/repo_worktree.py +304 -0
- workdash/tui.py +608 -0
- workdash/workdash.py +207 -0
- workdash-0.1.0.dist-info/METADATA +890 -0
- workdash-0.1.0.dist-info/RECORD +26 -0
- workdash-0.1.0.dist-info/WHEEL +5 -0
- workdash-0.1.0.dist-info/entry_points.txt +2 -0
- workdash-0.1.0.dist-info/licenses/LICENSE +674 -0
- workdash-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
You are reviewing a GitHub pull request to assess whether it is a good, solid,
|
|
2
|
+
robust, and simple approach to the problem it addresses.
|
|
3
|
+
|
|
4
|
+
Use the provided metadata and discussion as your starting context. The full
|
|
5
|
+
unified diff for this pull request has been saved to a local file — read it
|
|
6
|
+
before assessing code quality, test design, or code flow:
|
|
7
|
+
|
|
8
|
+
{diff_path}
|
|
9
|
+
|
|
10
|
+
Do not invent facts not present in the metadata, discussion, or diff file.
|
|
11
|
+
|
|
12
|
+
If you have access to specialized agents or tools for code review, bug hunting,
|
|
13
|
+
quality assurance, or test design, delegate the relevant parts of this review to
|
|
14
|
+
them. Use whatever review capabilities are available to produce the most thorough
|
|
15
|
+
and multi-perspective assessment possible.
|
|
16
|
+
|
|
17
|
+
TASK:
|
|
18
|
+
|
|
19
|
+
1. Understand the context — Study all discussion on the PR. Identify related issues,
|
|
20
|
+
design documents, or historical context referenced in the conversation. Understand
|
|
21
|
+
what problem this PR is solving and what solution approach was chosen or agreed
|
|
22
|
+
upon.
|
|
23
|
+
|
|
24
|
+
2. Assess the approach — Is this a good solution to the problem? Is it simple,
|
|
25
|
+
robust, and well-scoped? Are there simpler alternatives that were overlooked?
|
|
26
|
+
Does it introduce unnecessary complexity or coupling?
|
|
27
|
+
|
|
28
|
+
3. Review code quality — Examine the diff for: unclear naming, excessive complexity,
|
|
29
|
+
duplicated logic, poor separation of concerns, missing error handling that
|
|
30
|
+
matters, or patterns that diverge from the rest of the codebase. Focus on issues
|
|
31
|
+
that affect correctness and maintainability, not style nitpicks.
|
|
32
|
+
|
|
33
|
+
4. Evaluate test design — Are the tests meaningful and sufficient? Do they cover
|
|
34
|
+
edge cases and failure modes, not just the happy path? Are they testing behavior
|
|
35
|
+
or just implementation details? Is anything important left untested?
|
|
36
|
+
|
|
37
|
+
5. Identify risks — What could go wrong? Backward compatibility concerns, performance
|
|
38
|
+
implications, security issues, or subtle bugs in the implementation. Consider
|
|
39
|
+
what breaks if assumptions in the PR turn out to be wrong.
|
|
40
|
+
|
|
41
|
+
6. Trace the code flow — Identify the key actors (components, classes, services,
|
|
42
|
+
goroutines, etc.) involved in the PR's changes. Walk through the execution path
|
|
43
|
+
step by step: what triggers the flow, what calls what, where decisions branch,
|
|
44
|
+
and what the outcome is. For small, targeted PRs, trace the broader execution
|
|
45
|
+
context that the changed code participates in. For large PRs touching many
|
|
46
|
+
components, focus on the flow through the changed code itself. Use your judgment
|
|
47
|
+
on which framing is most useful for understanding the PR.
|
|
48
|
+
|
|
49
|
+
OUTPUT:
|
|
50
|
+
|
|
51
|
+
Produce a Markdown document with exactly these sections. Write substantive content
|
|
52
|
+
in each section, not placeholders.
|
|
53
|
+
The output MUST be valid, well-formed CommonMark Markdown.
|
|
54
|
+
When using lists, use valid Markdown list syntax (`1.` for ordered lists or `-`
|
|
55
|
+
for bullets), and leave a blank line before the first list item.
|
|
56
|
+
Whenever you mention a specific struct, type, class, interface, function, method,
|
|
57
|
+
or file from the repository — in ANY section of the document — wrap it in a
|
|
58
|
+
Markdown link that points to the exact definition line on GitHub.
|
|
59
|
+
- Preferred format: [`StructName`](https://github.com/{repo}/blob/<headRefName>/path/to/file.go#L42)
|
|
60
|
+
- For file+line references: [`path/to/file.py:123`](https://github.com/{repo}/blob/<headRefName>/path/to/file.py#L123)
|
|
61
|
+
- For line ranges: `#L10-L20`
|
|
62
|
+
- Use `headRefName` from the provided GITHUB CONTEXT.
|
|
63
|
+
- Keep backtick formatting around the symbol name — the link wraps the backticked text.
|
|
64
|
+
- Do not output plain backticked references to in-repo symbols without links.
|
|
65
|
+
- If you cannot determine the exact file or line for a symbol, you may still
|
|
66
|
+
mention it in backticks without a link, but prefer linked references.
|
|
67
|
+
|
|
68
|
+
Output the Markdown document directly. Your response must begin with the `# `
|
|
69
|
+
heading shown below and end with the last line of the template. Do not wrap
|
|
70
|
+
your response in code fences, do not include the `<template>` tags themselves,
|
|
71
|
+
and do not add any preamble or trailing commentary.
|
|
72
|
+
|
|
73
|
+
<template>
|
|
74
|
+
# {title}
|
|
75
|
+
|
|
76
|
+
> [{repo}#{number}]({url})
|
|
77
|
+
|
|
78
|
+
## Summary
|
|
79
|
+
|
|
80
|
+
One paragraph: what this PR does and the problem it solves.
|
|
81
|
+
|
|
82
|
+
## Context
|
|
83
|
+
|
|
84
|
+
Related issues, design decisions, and key points from discussion. What approach
|
|
85
|
+
was agreed upon and why.
|
|
86
|
+
|
|
87
|
+
## Approach Assessment
|
|
88
|
+
|
|
89
|
+
Is this a good, simple, robust solution? Are there simpler alternatives? Does the
|
|
90
|
+
scope match the problem? Does it introduce unnecessary complexity?
|
|
91
|
+
|
|
92
|
+
## Code Quality
|
|
93
|
+
|
|
94
|
+
Concrete findings with file and line references where possible. Focus on issues
|
|
95
|
+
that affect correctness and maintainability.
|
|
96
|
+
|
|
97
|
+
## Test Design
|
|
98
|
+
|
|
99
|
+
Coverage assessment. Missing edge cases or failure modes. Quality of test
|
|
100
|
+
assertions. If there are no tests, say so.
|
|
101
|
+
|
|
102
|
+
## Risks & Concerns
|
|
103
|
+
|
|
104
|
+
Backward compatibility, performance, security, subtle bugs, or anything that could
|
|
105
|
+
cause problems after merge. Omit this section if there are genuinely no concerns.
|
|
106
|
+
|
|
107
|
+
## Code Flow
|
|
108
|
+
|
|
109
|
+
Trace how the code involved in this PR executes, step by step.
|
|
110
|
+
|
|
111
|
+
### Components
|
|
112
|
+
|
|
113
|
+
List the key actors (structs, classes, functions, services, goroutines, modules)
|
|
114
|
+
that participate in the flow. Each must be a GitHub-linked reference.
|
|
115
|
+
|
|
116
|
+
### Execution Trace
|
|
117
|
+
|
|
118
|
+
Numbered steps showing the execution path. Each step names the actor and action,
|
|
119
|
+
links to the source line, and explains what happens and why. Use arrow connectors
|
|
120
|
+
(→ or ↓) to show flow direction. Call out key decision points, branching, and
|
|
121
|
+
error paths.
|
|
122
|
+
|
|
123
|
+
### Flow Diagram
|
|
124
|
+
|
|
125
|
+
An ASCII text diagram showing how the components interact. Use a swim-lane or
|
|
126
|
+
sequence-diagram style when multiple concurrent actors are involved. For linear
|
|
127
|
+
flows, a simple vertical trace is fine. The diagram should make it possible to
|
|
128
|
+
see the full flow at a glance without reading every step.
|
|
129
|
+
|
|
130
|
+
## Recommendation
|
|
131
|
+
|
|
132
|
+
Clear recommendation: approve, request changes, or needs discussion. List specific
|
|
133
|
+
items that must be addressed versus items that are suggestions.
|
|
134
|
+
</template>
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
WORK ITEM:
|
|
139
|
+
- type: {item_type}
|
|
140
|
+
- kind: {kind}
|
|
141
|
+
- repo: {repo}
|
|
142
|
+
- number: {number}
|
|
143
|
+
- title: {title}
|
|
144
|
+
- url: {url}
|
|
145
|
+
|
|
146
|
+
GITHUB CONTEXT (PR metadata and discussion; diff is available at the path above):
|
|
147
|
+
{github_context_json}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
You are starting an interactive coding session for this GitHub issue.
|
|
2
|
+
Read the context below, then gather and confirm any additional context you need
|
|
3
|
+
from the local repository checkout.
|
|
4
|
+
Propose a concrete implementation plan and clarifying questions.
|
|
5
|
+
Do not start implementing code yet.
|
|
6
|
+
|
|
7
|
+
WORK ITEM:
|
|
8
|
+
- type: {item_type}
|
|
9
|
+
- kind: {kind}
|
|
10
|
+
- repo: {repo}
|
|
11
|
+
- number: {number}
|
|
12
|
+
- title: {title}
|
|
13
|
+
- url: {url}
|
|
14
|
+
|
|
15
|
+
LOCAL REPOSITORY:
|
|
16
|
+
- expected local checkout path: {repo_path}
|
|
17
|
+
- confirm this checkout corresponds to {repo} before any code changes.{merge_base_section}
|
|
18
|
+
{analysis_section}
|
|
19
|
+
GITHUB CONTEXT (from gh):
|
|
20
|
+
{github_context_json}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
You are starting an interactive coding session for this GitHub pull request.
|
|
2
|
+
Read the context below, then gather and confirm any additional context you need
|
|
3
|
+
from the local repository checkout.
|
|
4
|
+
Propose a concrete implementation plan and clarifying questions.
|
|
5
|
+
Do not start implementing code yet.
|
|
6
|
+
|
|
7
|
+
WORK ITEM:
|
|
8
|
+
- type: {item_type}
|
|
9
|
+
- kind: {kind}
|
|
10
|
+
- repo: {repo}
|
|
11
|
+
- number: {number}
|
|
12
|
+
- title: {title}
|
|
13
|
+
- url: {url}
|
|
14
|
+
|
|
15
|
+
LOCAL REPOSITORY:
|
|
16
|
+
- expected local checkout path: {repo_path}
|
|
17
|
+
- confirm this checkout corresponds to {repo} before any code changes.{merge_base_section}
|
|
18
|
+
{analysis_section}
|
|
19
|
+
GITHUB CONTEXT (from gh):
|
|
20
|
+
{github_context_json}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
You are starting an interactive coding session to review this GitHub pull request.
|
|
2
|
+
Read the context below, then gather and confirm any additional context you need
|
|
3
|
+
from the local repository checkout.
|
|
4
|
+
Discuss review findings, risks, and open questions for the author.
|
|
5
|
+
Do not start implementing code changes.
|
|
6
|
+
|
|
7
|
+
WORK ITEM:
|
|
8
|
+
- type: {item_type}
|
|
9
|
+
- kind: {kind}
|
|
10
|
+
- repo: {repo}
|
|
11
|
+
- number: {number}
|
|
12
|
+
- title: {title}
|
|
13
|
+
- url: {url}
|
|
14
|
+
|
|
15
|
+
LOCAL REPOSITORY:
|
|
16
|
+
- expected local checkout path: {repo_path}
|
|
17
|
+
- confirm this checkout corresponds to {repo} before any code changes.{merge_base_section}
|
|
18
|
+
{analysis_section}
|
|
19
|
+
GITHUB CONTEXT (from gh):
|
|
20
|
+
{github_context_json}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Repository selector resolution."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
_OWNER_PATTERN = r"[a-z0-9][a-z0-9-]*"
|
|
8
|
+
_REPOSITORY_PATTERN = r"[a-z0-9._-]+"
|
|
9
|
+
_REPOSITORY_SELECTOR_PATTERN = re.compile(
|
|
10
|
+
rf"^(?:{_OWNER_PATTERN}/\*|{_OWNER_PATTERN}/{_REPOSITORY_PATTERN})$"
|
|
11
|
+
)
|
|
12
|
+
_FULL_REPOSITORY_PATTERN = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")
|
|
13
|
+
_OWNER_WILDCARD_PATTERN = re.compile(rf"^(?P<owner>{_OWNER_PATTERN})/\*$")
|
|
14
|
+
_DEFAULT_REPO_LIST_LIMIT = 1000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def validate_repository_selectors(selectors: list[str]) -> list[str]:
|
|
18
|
+
"""Validate repository selectors and return the cleaned list."""
|
|
19
|
+
|
|
20
|
+
validated: list[str] = []
|
|
21
|
+
for position, selector in enumerate(selectors, start=1):
|
|
22
|
+
stripped = selector.strip()
|
|
23
|
+
if not stripped:
|
|
24
|
+
continue
|
|
25
|
+
if not _REPOSITORY_SELECTOR_PATTERN.fullmatch(stripped):
|
|
26
|
+
raise ValueError(f"Invalid repository selector at position {position}: {stripped!r}")
|
|
27
|
+
validated.append(stripped)
|
|
28
|
+
return validated
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _list_owner_repositories(owner: str, limit: int = _DEFAULT_REPO_LIST_LIMIT) -> list[str]:
|
|
32
|
+
"""List repositories accessible for an owner using gh."""
|
|
33
|
+
|
|
34
|
+
command = [
|
|
35
|
+
"gh",
|
|
36
|
+
"repo",
|
|
37
|
+
"list",
|
|
38
|
+
owner,
|
|
39
|
+
"--json",
|
|
40
|
+
"nameWithOwner",
|
|
41
|
+
"--limit",
|
|
42
|
+
str(limit),
|
|
43
|
+
]
|
|
44
|
+
try:
|
|
45
|
+
completed = subprocess.run(
|
|
46
|
+
command,
|
|
47
|
+
check=True,
|
|
48
|
+
capture_output=True,
|
|
49
|
+
text=True,
|
|
50
|
+
)
|
|
51
|
+
except FileNotFoundError as error:
|
|
52
|
+
raise RuntimeError(
|
|
53
|
+
"Failed to run gh repo listing: gh CLI is not installed or not on PATH."
|
|
54
|
+
) from error
|
|
55
|
+
except subprocess.CalledProcessError as error:
|
|
56
|
+
stderr = (error.stderr or "").strip()
|
|
57
|
+
raise RuntimeError(
|
|
58
|
+
f"Failed to list repositories for owner {owner!r} via gh: "
|
|
59
|
+
f"{stderr or f'process exited with code {error.returncode}'}"
|
|
60
|
+
) from error
|
|
61
|
+
try:
|
|
62
|
+
payload = json.loads(completed.stdout)
|
|
63
|
+
except json.JSONDecodeError as error:
|
|
64
|
+
raise RuntimeError(
|
|
65
|
+
f"Failed to parse gh repository list JSON for owner {owner!r}: {error.msg}"
|
|
66
|
+
) from error
|
|
67
|
+
if not isinstance(payload, list):
|
|
68
|
+
raise RuntimeError(
|
|
69
|
+
f"Invalid gh repository list payload for owner {owner!r}: expected a JSON array."
|
|
70
|
+
)
|
|
71
|
+
repositories: list[str] = []
|
|
72
|
+
for entry in payload:
|
|
73
|
+
if not isinstance(entry, dict):
|
|
74
|
+
raise RuntimeError(
|
|
75
|
+
f"Invalid gh repository list payload for owner {owner!r}: expected objects in array."
|
|
76
|
+
)
|
|
77
|
+
name_with_owner = entry.get("nameWithOwner")
|
|
78
|
+
if not isinstance(name_with_owner, str) or not _FULL_REPOSITORY_PATTERN.fullmatch(
|
|
79
|
+
name_with_owner
|
|
80
|
+
):
|
|
81
|
+
raise RuntimeError(
|
|
82
|
+
f"Invalid gh repository list entry for owner {owner!r}: missing or invalid nameWithOwner."
|
|
83
|
+
)
|
|
84
|
+
repositories.append(name_with_owner)
|
|
85
|
+
return repositories
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def expand_repository_selectors(selectors: list[str]) -> list[str]:
|
|
89
|
+
"""Expand owner wildcards into full owner/repo names."""
|
|
90
|
+
|
|
91
|
+
repositories: list[str] = []
|
|
92
|
+
for selector in selectors:
|
|
93
|
+
owner_wildcard_match = _OWNER_WILDCARD_PATTERN.fullmatch(selector)
|
|
94
|
+
if owner_wildcard_match is None:
|
|
95
|
+
repositories.append(selector)
|
|
96
|
+
continue
|
|
97
|
+
repositories.extend(_list_owner_repositories(owner_wildcard_match.group("owner")))
|
|
98
|
+
return repositories
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def resolve_repositories(selectors: list[str]) -> list[str]:
|
|
102
|
+
"""Resolve selectors into deterministic concrete owner/repo names."""
|
|
103
|
+
|
|
104
|
+
repositories = sorted(
|
|
105
|
+
set(expand_repository_selectors(validate_repository_selectors(selectors)))
|
|
106
|
+
)
|
|
107
|
+
for repository in repositories:
|
|
108
|
+
if _FULL_REPOSITORY_PATTERN.fullmatch(repository) is None:
|
|
109
|
+
raise RuntimeError(
|
|
110
|
+
f"Expanded repository entry is not a concrete owner/repo value: {repository!r}"
|
|
111
|
+
)
|
|
112
|
+
return repositories
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Git worktree management for work items."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import json
|
|
5
|
+
import subprocess
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .models import WorkItem, WorkItemType
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main_repo_path(workdir: str, repo: str) -> Path:
|
|
12
|
+
"""Return the local clone directory for a repository.
|
|
13
|
+
|
|
14
|
+
:param str workdir: Base working directory (may use ~ for home).
|
|
15
|
+
:param str repo: Repository in "owner/repo" format.
|
|
16
|
+
"""
|
|
17
|
+
parts = repo.split("/")
|
|
18
|
+
if len(parts) != 2 or not parts[0] or not parts[1]:
|
|
19
|
+
raise ValueError(f"Invalid repo format {repo!r}, expected 'owner/repo'")
|
|
20
|
+
return Path(workdir).expanduser() / f"{parts[0]}_{parts[1]}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def worktree_path(workdir: str, repo: str, number: int) -> Path:
|
|
24
|
+
"""Return the worktree directory for a work item in the given repo.
|
|
25
|
+
|
|
26
|
+
:param str workdir: Base working directory (may use ~ for home).
|
|
27
|
+
:param str repo: Repository in "owner/repo" format.
|
|
28
|
+
:param int number: The issue or PR number.
|
|
29
|
+
"""
|
|
30
|
+
main = main_repo_path(workdir, repo)
|
|
31
|
+
return main.parent / f"{main.name}_{number}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _clone_repo(repo: str, target: Path) -> None:
|
|
35
|
+
try:
|
|
36
|
+
subprocess.run(
|
|
37
|
+
["gh", "repo", "clone", repo, str(target)],
|
|
38
|
+
check=True,
|
|
39
|
+
capture_output=True,
|
|
40
|
+
text=True,
|
|
41
|
+
)
|
|
42
|
+
except FileNotFoundError as exc:
|
|
43
|
+
raise RuntimeError(
|
|
44
|
+
"Failed to clone repository: gh CLI is not installed or not on PATH."
|
|
45
|
+
) from exc
|
|
46
|
+
except subprocess.CalledProcessError as exc:
|
|
47
|
+
stderr = (exc.stderr or "").strip()
|
|
48
|
+
raise RuntimeError(
|
|
49
|
+
f"Failed to clone {repo}: {stderr or f'exit code {exc.returncode}'}"
|
|
50
|
+
) from exc
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _fetch_origin(main_path: Path) -> None:
|
|
54
|
+
try:
|
|
55
|
+
subprocess.run(
|
|
56
|
+
["git", "fetch", "origin"],
|
|
57
|
+
cwd=main_path,
|
|
58
|
+
check=True,
|
|
59
|
+
capture_output=True,
|
|
60
|
+
text=True,
|
|
61
|
+
)
|
|
62
|
+
except FileNotFoundError as exc:
|
|
63
|
+
raise RuntimeError("Failed to fetch origin: git is not installed or not on PATH.") from exc
|
|
64
|
+
except subprocess.CalledProcessError as exc:
|
|
65
|
+
stderr = (exc.stderr or "").strip()
|
|
66
|
+
raise RuntimeError(
|
|
67
|
+
f"Failed to fetch origin: {stderr or f'exit code {exc.returncode}'}"
|
|
68
|
+
) from exc
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _get_pr_head_info(item: WorkItem) -> tuple[str, str]:
|
|
72
|
+
"""Return (head_ref_name, head_repo) for a PR.
|
|
73
|
+
|
|
74
|
+
For same-repo PRs head_repo equals item.repo; for fork PRs it is
|
|
75
|
+
the contributor's fork (e.g. "contributor/repo").
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
result = subprocess.run(
|
|
79
|
+
[
|
|
80
|
+
"gh",
|
|
81
|
+
"pr",
|
|
82
|
+
"view",
|
|
83
|
+
str(item.number),
|
|
84
|
+
"--repo",
|
|
85
|
+
item.repo,
|
|
86
|
+
"--json",
|
|
87
|
+
"headRefName,headRepository,headRepositoryOwner",
|
|
88
|
+
],
|
|
89
|
+
check=True,
|
|
90
|
+
capture_output=True,
|
|
91
|
+
text=True,
|
|
92
|
+
)
|
|
93
|
+
except FileNotFoundError as exc:
|
|
94
|
+
raise RuntimeError(
|
|
95
|
+
"Failed to get PR head info: gh CLI is not installed or not on PATH."
|
|
96
|
+
) from exc
|
|
97
|
+
except subprocess.CalledProcessError as exc:
|
|
98
|
+
stderr = (exc.stderr or "").strip()
|
|
99
|
+
raise RuntimeError(
|
|
100
|
+
f"Failed to get PR head info for {item.repo}#{item.number}: "
|
|
101
|
+
f"{stderr or f'exit code {exc.returncode}'}"
|
|
102
|
+
) from exc
|
|
103
|
+
payload = json.loads(result.stdout)
|
|
104
|
+
if not isinstance(payload, dict):
|
|
105
|
+
raise RuntimeError(
|
|
106
|
+
f"Invalid gh output for {item.repo}#{item.number}: expected a JSON object"
|
|
107
|
+
)
|
|
108
|
+
head_ref = payload.get("headRefName")
|
|
109
|
+
if not isinstance(head_ref, str):
|
|
110
|
+
raise RuntimeError(
|
|
111
|
+
f"Missing or invalid headRefName in gh output for {item.repo}#{item.number}"
|
|
112
|
+
)
|
|
113
|
+
# Reconstruct head repo from headRepositoryOwner.login + headRepository.name
|
|
114
|
+
head_repo_owner = payload.get("headRepositoryOwner", {})
|
|
115
|
+
head_repo_info = payload.get("headRepository", {})
|
|
116
|
+
owner_login = head_repo_owner.get("login", "") if isinstance(head_repo_owner, dict) else ""
|
|
117
|
+
repo_name = head_repo_info.get("name", "") if isinstance(head_repo_info, dict) else ""
|
|
118
|
+
head_repo = f"{owner_login}/{repo_name}" if owner_login and repo_name else item.repo
|
|
119
|
+
return head_ref, head_repo
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _local_branch_exists(main_path: Path, branch: str) -> bool:
|
|
123
|
+
result = subprocess.run(
|
|
124
|
+
["git", "show-ref", "--verify", "--quiet", f"refs/heads/{branch}"],
|
|
125
|
+
cwd=main_path,
|
|
126
|
+
capture_output=True,
|
|
127
|
+
)
|
|
128
|
+
return result.returncode == 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _create_worktree(main_path: Path, wt_path: Path, branch: str, start_point: str) -> None:
|
|
132
|
+
subprocess.run(
|
|
133
|
+
["git", "worktree", "prune"],
|
|
134
|
+
cwd=main_path,
|
|
135
|
+
capture_output=True,
|
|
136
|
+
)
|
|
137
|
+
try:
|
|
138
|
+
if _local_branch_exists(main_path, branch):
|
|
139
|
+
subprocess.run(
|
|
140
|
+
["git", "branch", "-f", branch, start_point],
|
|
141
|
+
cwd=main_path,
|
|
142
|
+
capture_output=True,
|
|
143
|
+
)
|
|
144
|
+
subprocess.run(
|
|
145
|
+
["git", "worktree", "add", str(wt_path), branch],
|
|
146
|
+
cwd=main_path,
|
|
147
|
+
check=True,
|
|
148
|
+
capture_output=True,
|
|
149
|
+
text=True,
|
|
150
|
+
)
|
|
151
|
+
else:
|
|
152
|
+
subprocess.run(
|
|
153
|
+
["git", "worktree", "add", "-b", branch, str(wt_path), start_point],
|
|
154
|
+
cwd=main_path,
|
|
155
|
+
check=True,
|
|
156
|
+
capture_output=True,
|
|
157
|
+
text=True,
|
|
158
|
+
)
|
|
159
|
+
except subprocess.CalledProcessError as exc:
|
|
160
|
+
stderr = (exc.stderr or "").strip()
|
|
161
|
+
raise RuntimeError(f"Failed to create worktree for branch {branch}: {stderr}") from exc
|
|
162
|
+
_set_branch_upstream(main_path, branch)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _set_branch_upstream(main_path: Path, branch: str) -> None:
|
|
166
|
+
"""Configure the local branch to track origin/<branch> for push/pull."""
|
|
167
|
+
subprocess.run(
|
|
168
|
+
["git", "config", f"branch.{branch}.remote", "origin"],
|
|
169
|
+
cwd=main_path,
|
|
170
|
+
capture_output=True,
|
|
171
|
+
)
|
|
172
|
+
subprocess.run(
|
|
173
|
+
["git", "config", f"branch.{branch}.merge", f"refs/heads/{branch}"],
|
|
174
|
+
cwd=main_path,
|
|
175
|
+
capture_output=True,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def get_merge_base(worktree: str) -> str | None:
|
|
180
|
+
"""Return the merge-base commit between HEAD and origin's default branch.
|
|
181
|
+
|
|
182
|
+
Returns None if the merge-base cannot be determined (e.g. shallow clone).
|
|
183
|
+
"""
|
|
184
|
+
# Resolve default branch name from origin/HEAD
|
|
185
|
+
result = subprocess.run(
|
|
186
|
+
["git", "rev-parse", "--abbrev-ref", "origin/HEAD"],
|
|
187
|
+
cwd=worktree,
|
|
188
|
+
capture_output=True,
|
|
189
|
+
text=True,
|
|
190
|
+
)
|
|
191
|
+
if result.returncode != 0:
|
|
192
|
+
return None
|
|
193
|
+
default_branch = result.stdout.strip()
|
|
194
|
+
if not default_branch:
|
|
195
|
+
return None
|
|
196
|
+
result = subprocess.run(
|
|
197
|
+
["git", "merge-base", "HEAD", default_branch],
|
|
198
|
+
cwd=worktree,
|
|
199
|
+
capture_output=True,
|
|
200
|
+
text=True,
|
|
201
|
+
)
|
|
202
|
+
if result.returncode != 0:
|
|
203
|
+
return None
|
|
204
|
+
commit = result.stdout.strip()
|
|
205
|
+
return commit if commit else None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _find_worktree_for_branch(main_path: Path, branch: str) -> Path | None:
|
|
209
|
+
"""Find an existing worktree checked out on the given branch via git."""
|
|
210
|
+
if not main_path.is_dir():
|
|
211
|
+
return None
|
|
212
|
+
result = subprocess.run(
|
|
213
|
+
["git", "worktree", "list", "--porcelain"],
|
|
214
|
+
cwd=main_path,
|
|
215
|
+
capture_output=True,
|
|
216
|
+
text=True,
|
|
217
|
+
)
|
|
218
|
+
if result.returncode != 0:
|
|
219
|
+
return None
|
|
220
|
+
current_path = None
|
|
221
|
+
for line in result.stdout.splitlines():
|
|
222
|
+
if line.startswith("worktree "):
|
|
223
|
+
current_path = line[len("worktree ") :]
|
|
224
|
+
elif line.startswith("branch refs/heads/"):
|
|
225
|
+
wt_branch = line[len("branch refs/heads/") :]
|
|
226
|
+
if wt_branch == branch and current_path is not None:
|
|
227
|
+
wt = Path(current_path)
|
|
228
|
+
if wt.is_dir():
|
|
229
|
+
return wt
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _find_existing_worktree(workdir: str, item: WorkItem) -> Path | None:
|
|
234
|
+
"""Find an existing worktree without a network call.
|
|
235
|
+
|
|
236
|
+
Checks the item.repo-based path first (issues and same-repo PRs),
|
|
237
|
+
then scans for fork worktrees by matching on repo name and number.
|
|
238
|
+
"""
|
|
239
|
+
base = Path(workdir).expanduser()
|
|
240
|
+
if not base.exists():
|
|
241
|
+
return None
|
|
242
|
+
# Direct match covers issues and same-repo PRs
|
|
243
|
+
direct = worktree_path(workdir, item.repo, item.number)
|
|
244
|
+
if direct.is_dir():
|
|
245
|
+
return direct
|
|
246
|
+
if item.item_type == WorkItemType.PR:
|
|
247
|
+
_, _, repo_name = item.repo.partition("/")
|
|
248
|
+
suffix = f"_{repo_name}_{item.number}"
|
|
249
|
+
for candidate in base.iterdir():
|
|
250
|
+
if candidate.is_dir() and candidate.name.endswith(suffix):
|
|
251
|
+
return candidate
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def ensure_worktree(workdir: str, item: WorkItem) -> str:
|
|
256
|
+
"""Ensure a worktree exists for the given work item and return its path.
|
|
257
|
+
|
|
258
|
+
Clones the repository if it does not exist locally, fetches the latest
|
|
259
|
+
changes, and creates a worktree checked out to the appropriate branch.
|
|
260
|
+
|
|
261
|
+
:param str workdir: Base working directory (may use ~ for home).
|
|
262
|
+
:param WorkItem item: The work item to prepare a worktree for.
|
|
263
|
+
"""
|
|
264
|
+
existing = _find_existing_worktree(workdir, item)
|
|
265
|
+
if existing is not None:
|
|
266
|
+
# Local divergence or missing upstream shouldn't block the user.
|
|
267
|
+
with contextlib.suppress(subprocess.CalledProcessError, OSError):
|
|
268
|
+
subprocess.run(
|
|
269
|
+
["git", "pull", "--ff-only"],
|
|
270
|
+
cwd=existing,
|
|
271
|
+
capture_output=True,
|
|
272
|
+
text=True,
|
|
273
|
+
)
|
|
274
|
+
return str(existing)
|
|
275
|
+
# Worktree doesn't exist — resolve the target repo and create it
|
|
276
|
+
if item.item_type == WorkItemType.PR:
|
|
277
|
+
head_ref, head_repo = _get_pr_head_info(item)
|
|
278
|
+
repo = head_repo
|
|
279
|
+
else:
|
|
280
|
+
repo = item.repo
|
|
281
|
+
wt = worktree_path(workdir, repo, item.number)
|
|
282
|
+
main = main_repo_path(workdir, repo)
|
|
283
|
+
branch = head_ref if item.item_type == WorkItemType.PR else f"issue-{item.number}"
|
|
284
|
+
# Check if git already tracks a worktree for this branch (covers cases
|
|
285
|
+
# where the directory-name scan missed, e.g. fork repo name mismatch).
|
|
286
|
+
git_existing = _find_worktree_for_branch(main, branch)
|
|
287
|
+
if git_existing is not None:
|
|
288
|
+
with contextlib.suppress(subprocess.CalledProcessError, OSError):
|
|
289
|
+
subprocess.run(
|
|
290
|
+
["git", "pull", "--ff-only"],
|
|
291
|
+
cwd=git_existing,
|
|
292
|
+
capture_output=True,
|
|
293
|
+
text=True,
|
|
294
|
+
)
|
|
295
|
+
return str(git_existing)
|
|
296
|
+
Path(workdir).expanduser().mkdir(parents=True, exist_ok=True)
|
|
297
|
+
if not main.exists():
|
|
298
|
+
_clone_repo(repo, main)
|
|
299
|
+
_fetch_origin(main)
|
|
300
|
+
if item.item_type == WorkItemType.PR:
|
|
301
|
+
_create_worktree(main, wt, head_ref, f"origin/{head_ref}")
|
|
302
|
+
else:
|
|
303
|
+
_create_worktree(main, wt, f"issue-{item.number}", "origin/HEAD")
|
|
304
|
+
return str(wt)
|