pacework 1.7.4 → 1.7.5
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.
- package/bin/pacework-runner.mjs +92 -26
- package/lib/branch-sync.mjs +110 -0
- package/lib/superseded-pr.mjs +53 -0
- package/package.json +1 -1
package/bin/pacework-runner.mjs
CHANGED
|
@@ -35,6 +35,8 @@ import { automationDenyRules, automationLimits } from "../lib/automation-limits.
|
|
|
35
35
|
import { truncateSummary } from "../lib/summary-text.mjs"
|
|
36
36
|
import { activityForStreamEvent, createActivityTracker, createStreamReader, helpSupportsStreamJson, parseClaudeJsonResult } from "../lib/claude-activity.mjs"
|
|
37
37
|
import { RUNNER_VERSION } from "../lib/version.mjs"
|
|
38
|
+
import { catchUpWithRemote, isPushRefused, pushKeepingRemoteCommits, remoteBranchExists, switchToBranch } from "../lib/branch-sync.mjs"
|
|
39
|
+
import { closeSupersededPullRequest } from "../lib/superseded-pr.mjs"
|
|
38
40
|
import {
|
|
39
41
|
buildFixInstructions,
|
|
40
42
|
checkEnvironment,
|
|
@@ -1472,6 +1474,21 @@ async function fetchGithubToken(state, workspaceId, projectId, teamId = null, ta
|
|
|
1472
1474
|
*/
|
|
1473
1475
|
const GIT_IGNORE_STORED_AUTH = ["-c", "http.https://github.com/.extraheader="]
|
|
1474
1476
|
|
|
1477
|
+
/**
|
|
1478
|
+
* `git <args>` in a directory, resolving { code, stdout, stderr } instead of
|
|
1479
|
+
* throwing. On failure `stderr` is the full error message, command included.
|
|
1480
|
+
*/
|
|
1481
|
+
function gitIn(dir, options = []) {
|
|
1482
|
+
return async (args) => {
|
|
1483
|
+
try {
|
|
1484
|
+
const result = await execCommand("git", ["-C", dir, ...options, ...args], dir)
|
|
1485
|
+
return { code: 0, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }
|
|
1486
|
+
} catch (error) {
|
|
1487
|
+
return { code: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) }
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1475
1492
|
async function pushBranchToGitHub(worktreePath, branch, githubToken, repo, onRetry = () => {}) {
|
|
1476
1493
|
// Worktrees of one repository share its config, remote URL included: a run
|
|
1477
1494
|
// pushing while another swaps the URL would push without the token, or leave
|
|
@@ -1491,19 +1508,16 @@ async function pushBranchWithToken(worktreePath, branch, githubToken, repo, onRe
|
|
|
1491
1508
|
// A GitHub 500 or a dropped connection is retried a few times before the
|
|
1492
1509
|
// run gives up; one hiccup used to throw a finished run away.
|
|
1493
1510
|
await retryTransient(async () => {
|
|
1494
|
-
//
|
|
1495
|
-
//
|
|
1496
|
-
//
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
["-C", worktreePath, ...GIT_IGNORE_STORED_AUTH, "push", "--set-upstream", "origin", branch, "--force-with-lease"],
|
|
1505
|
-
worktreePath,
|
|
1506
|
-
)
|
|
1511
|
+
// Never forced: the branch may be a person's pull request, and a forced
|
|
1512
|
+
// push removed the commits they pushed while the run worked (PWK-370).
|
|
1513
|
+
// Commits GitHub has and this checkout lacks are merged in first.
|
|
1514
|
+
const authed = gitIn(worktreePath, GIT_IGNORE_STORED_AUTH)
|
|
1515
|
+
await pushKeepingRemoteCommits({
|
|
1516
|
+
exec: gitIn(worktreePath),
|
|
1517
|
+
fetch: () => authed(["fetch", "origin", branch]),
|
|
1518
|
+
push: () => authed(["push", "--set-upstream", "origin", branch]),
|
|
1519
|
+
branch,
|
|
1520
|
+
})
|
|
1507
1521
|
}, {
|
|
1508
1522
|
onRetry,
|
|
1509
1523
|
// `--set-upstream` writes the shared config: a lock held by another git
|
|
@@ -1960,26 +1974,34 @@ async function prepareWorktreeCheckout(run, runRepoRoot, worktreePath, branch) {
|
|
|
1960
1974
|
// Branch exists from a prior run — reuse it instead of -b
|
|
1961
1975
|
await execCommand("git", ["-C", runRepoRoot, "worktree", "add", worktreePath, branch], runRepoRoot)
|
|
1962
1976
|
} else {
|
|
1977
|
+
// A branch GitHub already has (an open pull request, rework begun on
|
|
1978
|
+
// another machine) starts from GitHub's copy, not from main: starting
|
|
1979
|
+
// from main dropped its commits and the push was rejected (PWK-370).
|
|
1963
1980
|
// --no-track: the run's branch must not follow the base branch, and
|
|
1964
1981
|
// recording an upstream writes .git/config, the lock runs collided on.
|
|
1965
|
-
await
|
|
1982
|
+
const startPoint = await remoteBranchExists(gitIn(runRepoRoot), branch) ? `origin/${branch}` : upToDateBase
|
|
1983
|
+
await execCommand("git", ["-C", runRepoRoot, "worktree", "add", "--no-track", "-b", branch, worktreePath, startPoint], runRepoRoot)
|
|
1966
1984
|
}
|
|
1967
1985
|
} else if (worktreeKnown) {
|
|
1968
1986
|
const checkedOutBranch = await currentBranch(worktreePath)
|
|
1969
1987
|
if (checkedOutBranch && checkedOutBranch !== branch) {
|
|
1970
1988
|
// The worktree may be left on a branch from a previous executor (the
|
|
1971
1989
|
// branch prefix is per-executor), so the target branch can be absent.
|
|
1972
|
-
// Create it when missing instead of failing the whole run
|
|
1973
|
-
|
|
1974
|
-
await
|
|
1975
|
-
|
|
1976
|
-
targetExists
|
|
1977
|
-
? ["-C", worktreePath, "checkout", branch]
|
|
1978
|
-
: ["-C", worktreePath, "checkout", "-b", branch],
|
|
1979
|
-
worktreePath,
|
|
1980
|
-
)
|
|
1990
|
+
// Create it when missing instead of failing the whole run: from GitHub's
|
|
1991
|
+
// copy when GitHub has it (a person's pull request), so its commits are kept.
|
|
1992
|
+
const switched = await switchToBranch(gitIn(worktreePath), branch)
|
|
1993
|
+
if (switched.code !== 0) throw new Error(switched.stderr || `Could not check out ${branch}`)
|
|
1981
1994
|
}
|
|
1982
1995
|
}
|
|
1996
|
+
|
|
1997
|
+
// GitHub's copy may have moved since this machine last saw it: the merger
|
|
1998
|
+
// brought it up to date with main, or another runner pushed. Catch up now so
|
|
1999
|
+
// the agent works on the latest; a branch that diverged is left as it is, and
|
|
2000
|
+
// the push merges GitHub's commits in instead of replacing them.
|
|
2001
|
+
const synced = await catchUpWithRemote(gitIn(worktreePath), branch)
|
|
2002
|
+
if (synced === "fast_forwarded" || synced === "diverged" || synced === "failed") {
|
|
2003
|
+
runnerBaseLogger.child({ run_id: run.id, task_id: run.task_id }).info("runner.branch.sync", `Branch ${branch} vs GitHub: ${synced}`, { meta: { branch, result: synced } })
|
|
2004
|
+
}
|
|
1983
2005
|
}
|
|
1984
2006
|
|
|
1985
2007
|
function buildPrompt(run, branch, worktreePath, options = {}) {
|
|
@@ -3183,6 +3205,10 @@ async function runExecutor(run, state) {
|
|
|
3183
3205
|
)
|
|
3184
3206
|
if (started?.branch) {
|
|
3185
3207
|
run.__serverBranch = started.branch
|
|
3208
|
+
// The open pull request this run continues on, or the one a new
|
|
3209
|
+
// branch replaces (closed by the runner once the new one is open).
|
|
3210
|
+
run.__openPullRequest = started.pull_request || null
|
|
3211
|
+
run.__supersededPullRequest = started.superseded_pull_request || null
|
|
3186
3212
|
runLogger.info("runner.run.start_work", "Server assigned the working branch", {
|
|
3187
3213
|
meta: { branch: started.branch, base: started.base, repo: started.repo },
|
|
3188
3214
|
})
|
|
@@ -3200,7 +3226,11 @@ async function runExecutor(run, state) {
|
|
|
3200
3226
|
}
|
|
3201
3227
|
|
|
3202
3228
|
runLogger.info("runner.run.prepare", "Preparing worktree")
|
|
3203
|
-
const
|
|
3229
|
+
const preparedWorktree = await prepareWorktree(run)
|
|
3230
|
+
const { runRoot, worktreePath, localCheckoutMode, gitAvailable } = preparedWorktree
|
|
3231
|
+
// Reassigned only when the pull request's branch refuses the push and the
|
|
3232
|
+
// work moves to a new branch.
|
|
3233
|
+
let branch = preparedWorktree.branch
|
|
3204
3234
|
// Where a commit that could not reach GitHub is noted; only this issue's own
|
|
3205
3235
|
// checkout has a folder of its own to hold the note.
|
|
3206
3236
|
const pendingPushDir = gitAvailable && branch && localCheckoutMode !== "repo_root" ? path.dirname(worktreePath) : null
|
|
@@ -3874,11 +3904,32 @@ async function runExecutor(run, state) {
|
|
|
3874
3904
|
|
|
3875
3905
|
if (githubToken && repo?.owner && repo?.repo) {
|
|
3876
3906
|
publishStage = "push"
|
|
3877
|
-
|
|
3907
|
+
const onPushRetry = ({ attempt, delayMs, error }) => {
|
|
3878
3908
|
runLogger.warn("runner.run.push_retry", `GitHub push failed (attempt ${attempt}), retrying in ${Math.round(delayMs / 1000)}s`, {
|
|
3879
3909
|
meta: { branch, reason: describeGitFailure(error instanceof Error ? error.message : String(error), 300) },
|
|
3880
3910
|
})
|
|
3881
|
-
}
|
|
3911
|
+
}
|
|
3912
|
+
/** Why the old pull request is being replaced, for the comment left on it. */
|
|
3913
|
+
let supersededReason = "It could not be continued on its own branch (for example, it comes from a fork)."
|
|
3914
|
+
try {
|
|
3915
|
+
await pushBranchToGitHub(worktreePath, branch, githubToken, repo, onPushRetry)
|
|
3916
|
+
} catch (pushRefused) {
|
|
3917
|
+
// The open pull request's branch does not accept this runner's push
|
|
3918
|
+
// (protected, or no permission). The work goes to a new branch and a
|
|
3919
|
+
// new pull request, and the old one is closed below with a link to it.
|
|
3920
|
+
const refusal = pushRefused instanceof Error ? pushRefused.message : String(pushRefused)
|
|
3921
|
+
if (!run.__openPullRequest || !isPushRefused(refusal)) throw pushRefused
|
|
3922
|
+
const fallbackBranch = `agent/${buildIssueToken(run.task, run.id)}-${shortBranchToken(run.id)}`
|
|
3923
|
+
const cut = await gitIn(worktreePath)(["checkout", "-b", fallbackBranch])
|
|
3924
|
+
if (cut.code !== 0) throw pushRefused
|
|
3925
|
+
runLogger.warn("runner.run.push_refused", `GitHub refused the push to ${branch}; continuing on ${fallbackBranch}`, {
|
|
3926
|
+
meta: { branch, fallback_branch: fallbackBranch, reason: describeGitFailure(refusal, 300) },
|
|
3927
|
+
})
|
|
3928
|
+
supersededReason = `The runner is not allowed to push to \`${branch}\`, so the work moved to \`${fallbackBranch}\`.`
|
|
3929
|
+
branch = fallbackBranch
|
|
3930
|
+
run.__supersededPullRequest = run.__openPullRequest
|
|
3931
|
+
await pushBranchToGitHub(worktreePath, branch, githubToken, repo, onPushRetry)
|
|
3932
|
+
}
|
|
3882
3933
|
publishStage = "pull_request"
|
|
3883
3934
|
|
|
3884
3935
|
// Base the PR on the target repo's base branch, never on the branch
|
|
@@ -3901,6 +3952,21 @@ async function runExecutor(run, state) {
|
|
|
3901
3952
|
|
|
3902
3953
|
pushResult = { pushed: true, repo: `${repo.owner}/${repo.repo}`, pr_url: pr.html_url, pr_number: pr.number }
|
|
3903
3954
|
|
|
3955
|
+
// One issue, one open pull request: the one this replaces is closed
|
|
3956
|
+
// with a comment linking the new one.
|
|
3957
|
+
if (run.__supersededPullRequest) {
|
|
3958
|
+
const superseded = await closeSupersededPullRequest({
|
|
3959
|
+
token: githubToken, repo, oldUrl: run.__supersededPullRequest, newUrl: pr.html_url, reason: supersededReason,
|
|
3960
|
+
})
|
|
3961
|
+
if (superseded.result === "closed") {
|
|
3962
|
+
runLogger.info("runner.pr.superseded_closed", `Closed ${run.__supersededPullRequest} in favour of ${pr.html_url}`)
|
|
3963
|
+
await postIssueMilestone(mcpKey, run.task_id, `Closed the earlier pull request ${run.__supersededPullRequest}: ${pr.html_url} continues the work. ${supersededReason}`, "info").catch(() => {})
|
|
3964
|
+
} else if (superseded.result === "failed") {
|
|
3965
|
+
runLogger.warn("runner.pr.superseded_close_failed", `Could not close ${run.__supersededPullRequest}`, { meta: { reason: superseded.reason } })
|
|
3966
|
+
await postIssueMilestone(mcpKey, run.task_id, `The earlier pull request ${run.__supersededPullRequest} is still open and could not be closed automatically (${superseded.reason}). Close it by hand: ${pr.html_url} continues the work.`, "warning").catch(() => {})
|
|
3967
|
+
}
|
|
3968
|
+
}
|
|
3969
|
+
|
|
3904
3970
|
// Post PR URL back to the issue via MCP. This is what moves the
|
|
3905
3971
|
// issue to in_review and starts the reviewer handoff, so a
|
|
3906
3972
|
// silent failure here strands a finished pull request with no
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep a run's branch in step with GitHub's copy of it (PWK-370).
|
|
3
|
+
*
|
|
4
|
+
* The branch a run works on often already has commits on GitHub that this
|
|
5
|
+
* machine has not seen: an open pull request a person or another runner
|
|
6
|
+
* opened, rework on a different Mac than the first build, or the merger
|
|
7
|
+
* bringing the branch up to date with main (PWK-365). Creating the branch
|
|
8
|
+
* from main dropped those commits, and a local branch left behind GitHub's
|
|
9
|
+
* was rejected on push.
|
|
10
|
+
*
|
|
11
|
+
* `exec(args)` runs `git <args>` and resolves `{ code, stdout }` without
|
|
12
|
+
* throwing, so the caller decides where commands run.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Whether `origin/<branch>` exists in this checkout's remote-tracking refs. */
|
|
16
|
+
export async function remoteBranchExists(exec, branch) {
|
|
17
|
+
const result = await exec(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`])
|
|
18
|
+
return result.code === 0 && result.stdout.trim().length > 0
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Bring a checked-out branch up to GitHub's copy when GitHub is ahead.
|
|
23
|
+
* - "current": already at or ahead of GitHub's copy
|
|
24
|
+
* - "fast_forwarded": moved to GitHub's copy
|
|
25
|
+
* - "diverged": both have commits the other lacks; left alone, and
|
|
26
|
+
* pushKeepingRemoteCommits merges the two at push time
|
|
27
|
+
* - "no_remote": GitHub has no copy yet
|
|
28
|
+
* - "failed": the fast-forward did not apply (for example, uncommitted changes)
|
|
29
|
+
*/
|
|
30
|
+
export async function catchUpWithRemote(exec, branch) {
|
|
31
|
+
if (!await remoteBranchExists(exec, branch)) return "no_remote"
|
|
32
|
+
const remote = `origin/${branch}`
|
|
33
|
+
const [head, theirs] = await Promise.all([exec(["rev-parse", "HEAD"]), exec(["rev-parse", remote])])
|
|
34
|
+
if (head.code !== 0 || theirs.code !== 0) return "failed"
|
|
35
|
+
if (head.stdout.trim() === theirs.stdout.trim()) return "current"
|
|
36
|
+
// GitHub's copy already contained in ours: we are ahead (an unpushed commit).
|
|
37
|
+
if ((await exec(["merge-base", "--is-ancestor", remote, "HEAD"])).code === 0) return "current"
|
|
38
|
+
if ((await exec(["merge-base", "--is-ancestor", "HEAD", remote])).code !== 0) return "diverged"
|
|
39
|
+
return (await exec(["merge", "--ff-only", "--quiet", remote])).code === 0 ? "fast_forwarded" : "failed"
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Switch an existing checkout to the run's branch. A branch only GitHub has
|
|
44
|
+
* (a person's pull request) is created from GitHub's copy: cutting it from
|
|
45
|
+
* whatever the checkout was on left the pull request's commits out, and the
|
|
46
|
+
* push then replaced them.
|
|
47
|
+
* `exec` must throw or return a non-zero code on failure; the result of the
|
|
48
|
+
* checkout is returned.
|
|
49
|
+
*/
|
|
50
|
+
export async function switchToBranch(exec, branch) {
|
|
51
|
+
if ((await exec(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`])).code === 0) {
|
|
52
|
+
return exec(["checkout", branch])
|
|
53
|
+
}
|
|
54
|
+
if (await remoteBranchExists(exec, branch)) {
|
|
55
|
+
return exec(["checkout", "--no-track", "-b", branch, `origin/${branch}`])
|
|
56
|
+
}
|
|
57
|
+
return exec(["checkout", "-b", branch])
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const NON_FAST_FORWARD = /non-fast-forward|fetch first|stale info|\[rejected\]/i
|
|
61
|
+
|
|
62
|
+
/** GitHub refused the push because of who is pushing or where, not because of what. */
|
|
63
|
+
export function isPushRefused(message) {
|
|
64
|
+
return /protected branch|permission to \S+ denied|permission .* denied|returned error: 403|pre-receive hook declined|GH006|GH013/i.test(String(message ?? ""))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Push a branch without ever replacing commits GitHub has and this checkout
|
|
69
|
+
* lacks. The runner used to push with --force-with-lease right after a fetch,
|
|
70
|
+
* so the lease always matched: fine on an agent/ branch only it writes to, but
|
|
71
|
+
* on a person's pull request branch it removed whatever they had pushed while
|
|
72
|
+
* the run worked.
|
|
73
|
+
*
|
|
74
|
+
* GitHub's commits are merged into the branch first, then the branch is pushed
|
|
75
|
+
* plainly. A merge that conflicts is undone and reported; nothing is pushed.
|
|
76
|
+
*
|
|
77
|
+
* `fetch()` and `push()` resolve `{ code, stderr }` (they carry the caller's
|
|
78
|
+
* auth options); `exec(args)` runs local git the same way.
|
|
79
|
+
* Returns "pushed" or "merged_and_pushed"; throws with a readable message.
|
|
80
|
+
*/
|
|
81
|
+
export async function pushKeepingRemoteCommits({ exec, fetch, push, branch, attempts = 3 }) {
|
|
82
|
+
let merged = false
|
|
83
|
+
let last = null
|
|
84
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
85
|
+
// A failed fetch (GitHub has no such branch yet, or is unreachable) leaves
|
|
86
|
+
// nothing trustworthy to merge: a remote-tracking ref may be left over from
|
|
87
|
+
// a branch deleted after its merge. The plain push below is still safe.
|
|
88
|
+
const fetched = (await fetch()).code === 0
|
|
89
|
+
const remote = `origin/${branch}`
|
|
90
|
+
if (fetched && await remoteBranchExists(exec, branch) && (await exec(["merge-base", "--is-ancestor", remote, "HEAD"])).code !== 0) {
|
|
91
|
+
const merge = await exec(["merge", "--no-edit", remote])
|
|
92
|
+
if (merge.code !== 0) {
|
|
93
|
+
await exec(["merge", "--abort"])
|
|
94
|
+
const error = new Error(
|
|
95
|
+
`${branch} has commits on GitHub that this run did not have, and they conflict with the run's changes. `
|
|
96
|
+
+ "Nothing was pushed and nothing on GitHub was changed. "
|
|
97
|
+
+ `Merge origin/${branch} into the branch and resolve the conflicts, or run the agent again so it starts from GitHub's copy.`,
|
|
98
|
+
)
|
|
99
|
+
error.code = "REMOTE_CONFLICT"
|
|
100
|
+
throw error
|
|
101
|
+
}
|
|
102
|
+
merged = true
|
|
103
|
+
}
|
|
104
|
+
last = await push()
|
|
105
|
+
if (last.code === 0) return merged ? "merged_and_pushed" : "pushed"
|
|
106
|
+
// Someone pushed between the fetch and the push: take their commits and try again.
|
|
107
|
+
if (!NON_FAST_FORWARD.test(last.stderr || "") || isPushRefused(last.stderr)) break
|
|
108
|
+
}
|
|
109
|
+
throw new Error(last?.stderr || `git push origin ${branch} failed`)
|
|
110
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One issue, one open pull request (PWK-370).
|
|
3
|
+
*
|
|
4
|
+
* Work on an issue normally continues on its open pull request. When it cannot
|
|
5
|
+
* (the pull request comes from a fork, or its branch refuses the runner's
|
|
6
|
+
* push) the runner opens a new one, and the old one is closed here with a
|
|
7
|
+
* comment that links the new one, so nobody has to notice and close it.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** { owner, repo, number } from a GitHub pull request URL, or null. */
|
|
11
|
+
export function parsePullRequestUrl(url) {
|
|
12
|
+
const match = /github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/i.exec(String(url ?? ""))
|
|
13
|
+
return match ? { owner: match[1], repo: match[2], number: Number(match[3]) } : null
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Close `oldUrl` in favour of `newUrl` when it is another, still open pull
|
|
18
|
+
* request in the same repository. Returns what happened:
|
|
19
|
+
* "closed", "same", "other_repository", "not_open", or "failed" (with `reason`).
|
|
20
|
+
* Never throws: the new pull request is already open and must still be linked.
|
|
21
|
+
*/
|
|
22
|
+
export async function closeSupersededPullRequest({ token, repo, oldUrl, newUrl, reason = "", fetchImpl = fetch }) {
|
|
23
|
+
const old = parsePullRequestUrl(oldUrl)
|
|
24
|
+
const next = parsePullRequestUrl(newUrl)
|
|
25
|
+
if (!old || !next) return { result: "same" }
|
|
26
|
+
const same = (a, b) => String(a).toLowerCase() === String(b).toLowerCase()
|
|
27
|
+
if (!same(old.owner, repo.owner) || !same(old.repo, repo.repo)) return { result: "other_repository" }
|
|
28
|
+
if (old.number === next.number) return { result: "same" }
|
|
29
|
+
|
|
30
|
+
const api = `https://api.github.com/repos/${repo.owner}/${repo.repo}`
|
|
31
|
+
const headers = {
|
|
32
|
+
Authorization: `Bearer ${token}`,
|
|
33
|
+
Accept: "application/vnd.github+json",
|
|
34
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const current = await fetchImpl(`${api}/pulls/${old.number}`, { headers })
|
|
39
|
+
if (!current.ok) return { result: "failed", reason: `GitHub answered ${current.status} for pull request #${old.number}` }
|
|
40
|
+
if ((await current.json())?.state !== "open") return { result: "not_open" }
|
|
41
|
+
|
|
42
|
+
const body = `Closed in favour of #${next.number} (${newUrl}), which continues this work.`
|
|
43
|
+
+ (reason ? ` ${reason}` : "")
|
|
44
|
+
// Comment first: a pull request closed without a word is the worse outcome.
|
|
45
|
+
const comment = await fetchImpl(`${api}/issues/${old.number}/comments`, { method: "POST", headers, body: JSON.stringify({ body }) })
|
|
46
|
+
if (!comment.ok) return { result: "failed", reason: `GitHub answered ${comment.status} to the comment on #${old.number}` }
|
|
47
|
+
const closed = await fetchImpl(`${api}/pulls/${old.number}`, { method: "PATCH", headers, body: JSON.stringify({ state: "closed" }) })
|
|
48
|
+
if (!closed.ok) return { result: "failed", reason: `GitHub answered ${closed.status} when closing #${old.number}` }
|
|
49
|
+
return { result: "closed", number: old.number }
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return { result: "failed", reason: error instanceof Error ? error.message : String(error) }
|
|
52
|
+
}
|
|
53
|
+
}
|