pi-odd-worktree 3.9.2 → 3.11.0
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/LICENSE +21 -0
- package/README.md +68 -40
- package/extensions/odd-worktree-tools.ts +1028 -17
- package/lib/gh-issues.js +65 -10
- package/lib/gh-prs.js +2011 -0
- package/lib/issue-preview.js +70 -4
- package/lib/issues-cache-store.js +4 -1
- package/lib/issues-section.js +346 -23
- package/lib/issues-view.js +116 -5
- package/lib/pr-preview.js +353 -0
- package/lib/prs-rail-store.js +317 -0
- package/lib/prs-view.js +2896 -0
- package/lib/user-prompt-card.js +477 -0
- package/package.json +1 -1
- package/tools/files-bridge.test.js +2 -2
- package/tools/files-command.test.js +1 -1
- package/tools/fixtures/gh-pr-connection-page.json +84 -0
- package/tools/fixtures/gh-pr-metadata.json +29 -0
- package/tools/fixtures/gh-pr-rail.json +61 -0
- package/tools/fixtures/gh-pr-search-page.json +82 -0
- package/tools/fixtures/gh-pr-view.json +159 -0
- package/tools/gh-issues.test.js +4 -2
- package/tools/gh-prs.test.js +1828 -0
- package/tools/issue-preview.test.js +119 -0
- package/tools/issues-cache-store.test.js +2 -2
- package/tools/issues-command.test.js +10 -3
- package/tools/issues-open-guard.test.js +15 -0
- package/tools/issues-section.test.js +618 -9
- package/tools/issues-view.test.js +297 -0
- package/tools/package-surface.test.js +21 -5
- package/tools/pr-preview.test.js +281 -0
- package/tools/prs-command.test.js +1280 -0
- package/tools/prs-rail-store.test.js +343 -0
- package/tools/prs-t10-safety.test.js +326 -0
- package/tools/prs-t12-safety.test.js +348 -0
- package/tools/prs-t13-independent.test.js +378 -0
- package/tools/prs-t14-safety.test.js +340 -0
- package/tools/prs-t15-independent.test.js +259 -0
- package/tools/prs-t18-safety.test.js +217 -0
- package/tools/prs-t7-safety.test.js +127 -0
- package/tools/prs-view.test.js +1462 -0
- package/tools/user-prompt-card.test.js +963 -0
package/lib/gh-prs.js
ADDED
|
@@ -0,0 +1,2011 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// `gh` client for the `/prs` panel (T1, S1-S3): the pull request sibling of
|
|
3
|
+
// lib/gh-issues.js. `/prs` reads, mutates and opens pull requests through this
|
|
4
|
+
// module alone, so it keeps the issue client's whole contract:
|
|
5
|
+
//
|
|
6
|
+
// - Every spawn is `child_process.execFile` with an argv array and NO shell
|
|
7
|
+
// string, under a bounded timeout (invariant 9). Nothing here prints or
|
|
8
|
+
// persists a token; authentication stays inside `gh`.
|
|
9
|
+
// - Every exported call returns `{ok:true, ...}` or `{ok:false, error}` and
|
|
10
|
+
// never throws — a missing binary, a non-zero exit, an empty body, malformed
|
|
11
|
+
// JSON and a rejected runner all fail closed.
|
|
12
|
+
// - The repository identity is PINNED and validated exactly as
|
|
13
|
+
// lib/gh-issues.js validates a pin (invariant 6): the caller hands back the
|
|
14
|
+
// identity it already displayed, it is normalized to `<host>/<owner>/<repo>`,
|
|
15
|
+
// it travels as `GH_REPO` and it ALWAYS wins over an ambient `GH_REPO`; a pin
|
|
16
|
+
// the live environment cannot honour refuses the call BEFORE any child runs.
|
|
17
|
+
// A write always resolves its scope fresh, so an action never runs on a
|
|
18
|
+
// cached identity.
|
|
19
|
+
// - Capabilities fail closed (invariant 7): only a literal permission role
|
|
20
|
+
// confirms one, and merge additionally needs a non-draft pull request and at
|
|
21
|
+
// least one method the repository allows.
|
|
22
|
+
//
|
|
23
|
+
// THE ISSUE CLIENT IS INJECTED, NEVER REQUIRED. lib/gh-issues.js holds
|
|
24
|
+
// process-wide state (its runner seam, repository-scope cache and session
|
|
25
|
+
// gate), and the extension owns exactly ONE instance of it, loaded through its
|
|
26
|
+
// own cache-purging `libRequire`. A plain Node `require` of that file from here
|
|
27
|
+
// would be a DIFFERENT instance, so `tools/package-surface.test.js` pins that no
|
|
28
|
+
// `lib/` module pulls the issue client that way. Every seam this client needs
|
|
29
|
+
// therefore arrives as the injected `issues` module:
|
|
30
|
+
//
|
|
31
|
+
// const client = createPrsClient({ issues }); // issues = lib/gh-issues.js
|
|
32
|
+
// const client = bindIssuesClient(issues); // same, for the convenience exports
|
|
33
|
+
//
|
|
34
|
+
// The injected module supplies `runGh`, `setGhRunner`, `normalizeScopeIdentity`,
|
|
35
|
+
// `reportedRepoName` and `checkoutRepoScope` (the fork override over gh's base
|
|
36
|
+
// answer) as it exports them; a seam the injected module does not export falls
|
|
37
|
+
// back to a local copy below, verbatim in behavior, which must be kept in step
|
|
38
|
+
// with its original. Unbound, the module-level exports work the same way
|
|
39
|
+
// against the local copies (gh's own resolution, no fork override).
|
|
40
|
+
//
|
|
41
|
+
// Structured data comes from `gh --json` and GraphQL. Verified shapes:
|
|
42
|
+
// - `gh pr view <n> --json` accepts number,title,state,isDraft,author,assignees,
|
|
43
|
+
// labels,createdAt,updatedAt,comments,reactionGroups,url,body,baseRefName,
|
|
44
|
+
// headRefName,headRepositoryOwner,additions,deletions,changedFiles,commits,
|
|
45
|
+
// reviewDecision,reviewRequests,latestReviews,statusCheckRollup,mergeable,
|
|
46
|
+
// mergeStateStatus,closingIssuesReferences.
|
|
47
|
+
// - `gh pr comment <n> --body …`, `gh pr close <n>`,
|
|
48
|
+
// `gh pr merge <n> --merge|--squash|--rebase [--subject …] [--body …]` (a
|
|
49
|
+
// rebase merge takes neither proposal) and `gh pr edit <n> --add-label …
|
|
50
|
+
// --remove-label … | --add-assignee … --remove-assignee … | --body …`.
|
|
51
|
+
// - The three scoped buckets are `search(type: ISSUE)` over
|
|
52
|
+
// `repo:<r> is:pr is:open <qualifier>`; the lazy `all` bucket is the
|
|
53
|
+
// `repository.pullRequests(states: OPEN)` connection, which reports an exact
|
|
54
|
+
// `totalCount` and pages past the search API's 1000-match cap.
|
|
55
|
+
// - `repository.viewerPermission`, `mergeCommitAllowed`, `squashMergeAllowed`
|
|
56
|
+
// and `rebaseMergeAllowed` are the repo-level facts the capabilities and the
|
|
57
|
+
// merge methods are derived from.
|
|
58
|
+
// - `gh label list/create` and `repository.assignableUsers` are
|
|
59
|
+
// repository-level, not issue-level, so their local copies here are
|
|
60
|
+
// unchanged.
|
|
61
|
+
|
|
62
|
+
const { execFile } = require('node:child_process');
|
|
63
|
+
|
|
64
|
+
const DEFAULT_TIMEOUT_MS = 30000;
|
|
65
|
+
const DEFAULT_PAGE_SIZE = 30;
|
|
66
|
+
// The largest page a single GraphQL request may ask for; a larger caller budget
|
|
67
|
+
// is filled by walking several server pages.
|
|
68
|
+
const MAX_PAGE_SIZE = 100;
|
|
69
|
+
// The search API answers at most 1000 matches. A bucket past that cap is a
|
|
70
|
+
// FAILED read, never a silently truncated list.
|
|
71
|
+
const SEARCH_MATCH_CAP = 1000;
|
|
72
|
+
// Search-syntax qualifier: this client asks `gh` for last-update ordering so
|
|
73
|
+
// every consumer inherits it, and a caller's own `sort:` is never doubled.
|
|
74
|
+
const LAST_UPDATED_SORT = 'sort:updated-desc';
|
|
75
|
+
// The rail's per-bucket row window and the linked-issue window each row carries.
|
|
76
|
+
const RAIL_WINDOW_DEFAULT = 50;
|
|
77
|
+
const RAIL_WINDOW_MAX = 100;
|
|
78
|
+
const LINKED_ISSUE_WINDOW = 100;
|
|
79
|
+
const LABEL_FETCH_MAX = 500;
|
|
80
|
+
// Runaway guard for a cursor walk that never ends, never a data cutoff.
|
|
81
|
+
const SNAPSHOT_MAX_PAGES = 2500;
|
|
82
|
+
|
|
83
|
+
const MERGE_FLAGS = { merge: '--merge', squash: '--squash', rebase: '--rebase' };
|
|
84
|
+
const MERGE_METHODS = ['merge', 'squash', 'rebase'];
|
|
85
|
+
const PERMITTED_ROLES = ['TRIAGE', 'WRITE', 'MAINTAIN', 'ADMIN'];
|
|
86
|
+
const MERGE_ROLES = ['WRITE', 'MAINTAIN', 'ADMIN'];
|
|
87
|
+
|
|
88
|
+
// The three S1 buckets, as the repository-search qualifier each one asks for.
|
|
89
|
+
const BUCKET_QUALIFIERS = {
|
|
90
|
+
mine: 'author:@me',
|
|
91
|
+
review: 'review-requested:@me',
|
|
92
|
+
involved: 'involves:@me',
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// The row of a list, and the head of the pane: the issue row's keys plus the
|
|
96
|
+
// two pull-request ones the panel's list draws.
|
|
97
|
+
const ROW_FIELDS = `
|
|
98
|
+
number
|
|
99
|
+
title
|
|
100
|
+
state
|
|
101
|
+
isDraft
|
|
102
|
+
url
|
|
103
|
+
createdAt
|
|
104
|
+
updatedAt
|
|
105
|
+
author { login }
|
|
106
|
+
labels(first: 50) { nodes { name color description } }
|
|
107
|
+
assignees(first: 10) { nodes { login } }
|
|
108
|
+
comments { totalCount }
|
|
109
|
+
reactionGroups { content users { totalCount } }
|
|
110
|
+
reviewDecision`;
|
|
111
|
+
|
|
112
|
+
const SEARCH_PAGE_QUERY = `query($search: String!, $first: Int!, $cursor: String) {
|
|
113
|
+
search(query: $search, type: ISSUE, first: $first, after: $cursor) {
|
|
114
|
+
issueCount
|
|
115
|
+
pageInfo { hasNextPage endCursor }
|
|
116
|
+
edges { cursor node { ... on PullRequest { ${ROW_FIELDS} } } }
|
|
117
|
+
}
|
|
118
|
+
}`;
|
|
119
|
+
|
|
120
|
+
const CONNECTION_PAGE_QUERY = `query($owner: String!, $name: String!, $first: Int!, $cursor: String) {
|
|
121
|
+
repository(owner: $owner, name: $name) {
|
|
122
|
+
pullRequests(states: OPEN, first: $first, after: $cursor, orderBy: {field: UPDATED_AT, direction: DESC}) {
|
|
123
|
+
totalCount
|
|
124
|
+
pageInfo { hasNextPage endCursor }
|
|
125
|
+
edges { cursor node { ${ROW_FIELDS} } }
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}`;
|
|
129
|
+
|
|
130
|
+
const DETAIL_JSON_FIELDS = [
|
|
131
|
+
'number', 'title', 'state', 'isDraft', 'author', 'assignees', 'labels',
|
|
132
|
+
'createdAt', 'updatedAt', 'comments', 'reactionGroups', 'url', 'body',
|
|
133
|
+
'baseRefName', 'headRefName', 'headRepositoryOwner', 'additions', 'deletions',
|
|
134
|
+
'changedFiles', 'commits', 'reviewDecision', 'reviewRequests', 'latestReviews',
|
|
135
|
+
'statusCheckRollup', 'mergeable', 'mergeStateStatus', 'closingIssuesReferences',
|
|
136
|
+
].join(',');
|
|
137
|
+
|
|
138
|
+
const LABEL_JSON_FIELDS = 'name,color,description';
|
|
139
|
+
|
|
140
|
+
// The repo-level facts ONE read answers: the viewer's role (the capability
|
|
141
|
+
// map), the merge methods the repository allows, whether the pull request is a
|
|
142
|
+
// draft (merge refuses one) and the linked issues with their truncation flag.
|
|
143
|
+
const PULL_REQUEST_METADATA_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
|
144
|
+
repository(owner: $owner, name: $name) {
|
|
145
|
+
viewerPermission
|
|
146
|
+
mergeCommitAllowed
|
|
147
|
+
squashMergeAllowed
|
|
148
|
+
rebaseMergeAllowed
|
|
149
|
+
pullRequest(number: $number) {
|
|
150
|
+
isDraft
|
|
151
|
+
state
|
|
152
|
+
closingIssuesReferences(first: ${LINKED_ISSUE_WINDOW}) { nodes { number repository { nameWithOwner } } pageInfo { hasNextPage } }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}`;
|
|
156
|
+
|
|
157
|
+
// S2/D2: the repository role every write reads for itself before it runs, so a
|
|
158
|
+
// capability that lapsed after the pane painted never reaches `gh`. It is the
|
|
159
|
+
// cheapest answer to "may this viewer write here?": no pull request is named.
|
|
160
|
+
const REPOSITORY_PERMISSION_QUERY = `query($owner: String!, $name: String!) {
|
|
161
|
+
repository(owner: $owner, name: $name) { viewerPermission }
|
|
162
|
+
}`;
|
|
163
|
+
|
|
164
|
+
// S2/D20: the role AND the fresh state of the pull request the write will name,
|
|
165
|
+
// in the same round trip, so a merged, closed or vanished pull request is
|
|
166
|
+
// refused by the one read that authorizes the write.
|
|
167
|
+
const REPOSITORY_WRITE_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
|
168
|
+
repository(owner: $owner, name: $name) {
|
|
169
|
+
viewerPermission
|
|
170
|
+
pullRequest(number: $number) { state }
|
|
171
|
+
}
|
|
172
|
+
}`;
|
|
173
|
+
|
|
174
|
+
// The permission read `editAssignees` needs, plus the authenticated login: the
|
|
175
|
+
// SAME request names the viewer, so a toggle for the viewer's own account is
|
|
176
|
+
// reported by the client instead of guessed from a display name.
|
|
177
|
+
const ASSIGNEE_ACCESS_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
|
178
|
+
repository(owner: $owner, name: $name) {
|
|
179
|
+
viewerPermission
|
|
180
|
+
pullRequest(number: $number) { state }
|
|
181
|
+
}
|
|
182
|
+
viewer { login }
|
|
183
|
+
}`;
|
|
184
|
+
|
|
185
|
+
const ASSIGNABLE_USERS_QUERY = `query($owner: String!, $name: String!, $cursor: String) {
|
|
186
|
+
repository(owner: $owner, name: $name) {
|
|
187
|
+
assignableUsers(first: 100, after: $cursor) {
|
|
188
|
+
nodes { login name }
|
|
189
|
+
pageInfo { hasNextPage endCursor }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}`;
|
|
193
|
+
|
|
194
|
+
const RAIL_ALIAS_QUALIFIERS = [
|
|
195
|
+
['mine', BUCKET_QUALIFIERS.mine],
|
|
196
|
+
['review', BUCKET_QUALIFIERS.review],
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
// Runner seam and the child-process helpers (local copies of lib/gh-issues.js).
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
let runnerOverride = null;
|
|
204
|
+
let boundIssues = null;
|
|
205
|
+
let boundClient = null;
|
|
206
|
+
|
|
207
|
+
// Test seam: inject `fn(bin, argv, runOpts)` (may be sync or async), or
|
|
208
|
+
// `null`/`undefined` to restore the default `execFile` runner. It moves the
|
|
209
|
+
// injected issue module's own seam too, so the seams this client delegates to
|
|
210
|
+
// it (the identity reads, the scope resolver) run the injected runner as well.
|
|
211
|
+
function setGhRunner(fn) {
|
|
212
|
+
if (fn !== null && fn !== undefined && typeof fn !== 'function') {
|
|
213
|
+
throw new TypeError('setGhRunner requires a function or null');
|
|
214
|
+
}
|
|
215
|
+
runnerOverride = fn === null || fn === undefined ? null : fn;
|
|
216
|
+
forwardRunner(boundIssues);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function forwardRunner(issues) {
|
|
220
|
+
if (issues && typeof issues === 'object' && typeof issues.setGhRunner === 'function') {
|
|
221
|
+
issues.setGhRunner(runnerOverride);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function ghBinary(opts = {}) {
|
|
226
|
+
if (typeof opts.ghBin === 'string' && opts.ghBin.length > 0) return opts.ghBin;
|
|
227
|
+
const env = opts.env || process.env;
|
|
228
|
+
const fromEnv = env && env.GH_BIN_PATH;
|
|
229
|
+
if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv;
|
|
230
|
+
return 'gh';
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Default runner over execFile: argv array, no shell, bounded timeout.
|
|
234
|
+
// Always resolves to {status, stdout, stderr, error}; never throws.
|
|
235
|
+
function defaultRunner(bin, argv, runOpts = {}) {
|
|
236
|
+
const timeout = Number.isFinite(runOpts.timeoutMs) && runOpts.timeoutMs > 0
|
|
237
|
+
? Math.floor(runOpts.timeoutMs)
|
|
238
|
+
: DEFAULT_TIMEOUT_MS;
|
|
239
|
+
return new Promise((resolve) => {
|
|
240
|
+
const spawnOpts = {
|
|
241
|
+
cwd: runOpts.cwd,
|
|
242
|
+
timeout,
|
|
243
|
+
encoding: 'utf8',
|
|
244
|
+
windowsHide: true,
|
|
245
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
246
|
+
};
|
|
247
|
+
if (runOpts.env) spawnOpts.env = runOpts.env;
|
|
248
|
+
try {
|
|
249
|
+
execFile(bin, argv, spawnOpts, (err, stdout, stderr) => {
|
|
250
|
+
if (!err) {
|
|
251
|
+
resolve({ status: 0, stdout: String(stdout || ''), stderr: String(stderr || ''), error: null });
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (err.code === 'ENOENT' || /ENOENT/i.test(err.message || '')) {
|
|
255
|
+
resolve({
|
|
256
|
+
status: null,
|
|
257
|
+
stdout: String(stdout || ''),
|
|
258
|
+
stderr: String(stderr || ''),
|
|
259
|
+
error: `spawn ${bin} ENOENT: gh CLI is not available`,
|
|
260
|
+
});
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (err.killed) {
|
|
264
|
+
resolve({
|
|
265
|
+
status: null,
|
|
266
|
+
stdout: String(stdout || ''),
|
|
267
|
+
stderr: String(stderr || ''),
|
|
268
|
+
error: `gh timed out after ${timeout}ms`,
|
|
269
|
+
});
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
resolve({
|
|
273
|
+
status: typeof err.code === 'number' ? err.code : null,
|
|
274
|
+
stdout: String(stdout || ''),
|
|
275
|
+
stderr: String(stderr || ''),
|
|
276
|
+
error: null,
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
} catch (err) {
|
|
280
|
+
resolve({ status: null, stdout: '', stderr: '', error: (err && err.message) || String(err) });
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// The env a gh child runs with: the caller's own environment plus the scope as
|
|
286
|
+
// GH_REPO. A scope ALWAYS wins over an ambient GH_REPO, so an environment
|
|
287
|
+
// variable can never move a read or a write to another repository behind a
|
|
288
|
+
// displayed identity's back.
|
|
289
|
+
function scopedEnv(opts, scope) {
|
|
290
|
+
if (!scope) return opts.env;
|
|
291
|
+
const base = opts.env || process.env || {};
|
|
292
|
+
return { ...base, GH_REPO: scope };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// S2/D23, D28: the API host a call can PROVE it targets. `gh api`/GraphQL take
|
|
296
|
+
// their host from GH_HOST or `--hostname`, NEVER from GH_REPO's host, so every
|
|
297
|
+
// `api` child has to carry it explicitly — github.com included, because gh's own
|
|
298
|
+
// default may itself be an Enterprise server. A host is proven by an explicit
|
|
299
|
+
// pin, by GH_HOST or by the host half of GH_REPO; an ambient repository proves
|
|
300
|
+
// nothing here (its host comes from the repository lookup, which is exactly the
|
|
301
|
+
// child that must keep the caller's environment verbatim).
|
|
302
|
+
function provenHost(opts = {}) {
|
|
303
|
+
const scope = typeof opts.scope === 'string' ? opts.scope.trim() : '';
|
|
304
|
+
if (scope !== '') {
|
|
305
|
+
const parts = scope.split('/');
|
|
306
|
+
return parts.length === 3 ? canonicalHost(parts[0]) : '';
|
|
307
|
+
}
|
|
308
|
+
const env = opts.env || process.env || {};
|
|
309
|
+
const selected = ghHostOf(env);
|
|
310
|
+
if (selected !== '') return canonicalHost(selected);
|
|
311
|
+
const repo = typeof env.GH_REPO === 'string' ? env.GH_REPO.trim() : '';
|
|
312
|
+
const parts = repo.split('/');
|
|
313
|
+
return parts.length === 3 ? canonicalHost(parts[0]) : '';
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// The host a host-qualified identity names (`<host>/<owner>/<repo>`).
|
|
317
|
+
function hostOfIdentity(identity) {
|
|
318
|
+
if (typeof identity !== 'string') return '';
|
|
319
|
+
const parts = identity.split('/');
|
|
320
|
+
return parts.length === 3 ? canonicalHost(parts[0]) : '';
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// The host a `gh repo view` URL names, or '' when the answer carries none.
|
|
324
|
+
function hostOfUrl(raw) {
|
|
325
|
+
if (typeof raw !== 'string' || raw.trim() === '') return '';
|
|
326
|
+
try {
|
|
327
|
+
return canonicalHost(new URL(raw).host);
|
|
328
|
+
} catch {
|
|
329
|
+
return '';
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// The options one host-qualified scope needs for the ONE resolution that
|
|
334
|
+
// validates it: `normalizeScopeIdentity` refuses an enterprise pin unless
|
|
335
|
+
// GH_HOST names the same server.
|
|
336
|
+
function withHostOptions(opts, host) {
|
|
337
|
+
if (host === '' || host === 'github.com') return opts;
|
|
338
|
+
const base = opts.env || process.env || {};
|
|
339
|
+
return { ...opts, env: { ...base, GH_HOST: host } };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// One child, with the host `gh` cannot read from GH_REPO: an `api` child gets
|
|
343
|
+
// `--hostname <host>` (after its own flags, so the `-f query=…` slot is
|
|
344
|
+
// unchanged) and every child of that scope gets GH_HOST. S2/D28: the host is
|
|
345
|
+
// named even when it IS github.com, so a public scope can never drift to an
|
|
346
|
+
// Enterprise default and an Enterprise one never drifts to api.github.com.
|
|
347
|
+
function withHost(argv, opts = {}, host) {
|
|
348
|
+
if (typeof host !== 'string' || host === '') return { argv, opts };
|
|
349
|
+
const base = opts.env || process.env || {};
|
|
350
|
+
return {
|
|
351
|
+
argv: Array.isArray(argv) && argv[0] === 'api' ? [...argv, '--hostname', host] : argv,
|
|
352
|
+
opts: { ...opts, env: { ...base, GH_HOST: host } },
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// The same, for a runner this client does not resolve the scope of (the injected
|
|
357
|
+
// issue client's own `runGh`): the host has to be proven by the call's own pin or
|
|
358
|
+
// environment. A caller environment that selects ANOTHER server is left exactly
|
|
359
|
+
// as given, so the identity resolution still refuses it before any child runs.
|
|
360
|
+
function withScopeHost(argv, opts = {}) {
|
|
361
|
+
const host = provenHost(opts);
|
|
362
|
+
if (host === '') return { argv, opts };
|
|
363
|
+
const selected = ghHostOf(opts.env || process.env || {});
|
|
364
|
+
return withHost(argv, opts, selected !== '' && selected !== host ? '' : host);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// The child runner, parameterized by the scope resolver: the fallback used when
|
|
368
|
+
// the injected issue module does not export `runGh`. Same shape, same
|
|
369
|
+
// fail-closed scope handling.
|
|
370
|
+
async function runGhWith(scopeResolve, argv, opts = {}) {
|
|
371
|
+
const bin = ghBinary(opts);
|
|
372
|
+
const scopeResult = await scopeResolve(opts);
|
|
373
|
+
// Fail closed: when the identity cannot be proven, no gh command runs at all.
|
|
374
|
+
if (scopeResult.ok !== true) {
|
|
375
|
+
return { bin, argv, status: null, stdout: '', stderr: '', error: scopeResult.error };
|
|
376
|
+
}
|
|
377
|
+
// S2/D28: the host is named AFTER the identity is resolved, so a checkout or
|
|
378
|
+
// ambient repository on any server hands its own host to every child, and the
|
|
379
|
+
// validation above still saw the caller's environment unchanged.
|
|
380
|
+
const identity = scopeResult.identity || null;
|
|
381
|
+
const hosted = withHost(argv, opts, identity === null ? provenHost(opts) : hostOfIdentity(identity));
|
|
382
|
+
const env = scopedEnv(hosted.opts, identity);
|
|
383
|
+
const runOpts = { cwd: opts.cwd, timeoutMs: opts.timeoutMs || DEFAULT_TIMEOUT_MS };
|
|
384
|
+
if (env) runOpts.env = env;
|
|
385
|
+
const run = runnerOverride || defaultRunner;
|
|
386
|
+
let raw;
|
|
387
|
+
try {
|
|
388
|
+
raw = await run(bin, hosted.argv, runOpts);
|
|
389
|
+
} catch (err) {
|
|
390
|
+
return {
|
|
391
|
+
bin, argv: hosted.argv, status: null, stdout: '', stderr: '',
|
|
392
|
+
error: (err && err.message) || String(err),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const outcome = raw && typeof raw === 'object' ? raw : {};
|
|
396
|
+
return {
|
|
397
|
+
bin,
|
|
398
|
+
argv: hosted.argv,
|
|
399
|
+
status: typeof outcome.status === 'number' ? outcome.status : null,
|
|
400
|
+
stdout: typeof outcome.stdout === 'string' ? outcome.stdout : '',
|
|
401
|
+
stderr: typeof outcome.stderr === 'string' ? outcome.stderr : '',
|
|
402
|
+
error: outcome.error === null || outcome.error === undefined ? null : String(outcome.error),
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ---------------------------------------------------------------------------
|
|
407
|
+
// Identity (local copy of lib/gh-issues.js: invariant 6's pin rules).
|
|
408
|
+
// ---------------------------------------------------------------------------
|
|
409
|
+
|
|
410
|
+
const GITHUB_HOSTS = new Set(['github.com', 'www.github.com']);
|
|
411
|
+
const GITHUB_OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
|
|
412
|
+
const GITHUB_REPO_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
|
|
413
|
+
|
|
414
|
+
function ghHostOf(env) {
|
|
415
|
+
const raw = env && typeof env.GH_HOST === 'string' ? env.GH_HOST.trim().toLowerCase() : '';
|
|
416
|
+
return raw.replace(/\/+$/, '');
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function canonicalHost(raw) {
|
|
420
|
+
const host = String(raw || '').trim().toLowerCase().replace(/\/+$/, '');
|
|
421
|
+
return host === 'www.github.com' ? 'github.com' : host;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// The server a pin may target. github.com is gh's default. Any other server is
|
|
425
|
+
// only reachable CONSISTENTLY when GH_HOST names it: repository-scoped commands
|
|
426
|
+
// take a host from GH_REPO, but `gh api`/GraphQL (every search and connection
|
|
427
|
+
// read) use the default host. With GH_HOST set, the pin must name that EXACT
|
|
428
|
+
// server; a different host is the same `owner/name` somewhere else.
|
|
429
|
+
function hostVerdict(authority, env) {
|
|
430
|
+
const required = ghHostOf(env);
|
|
431
|
+
if (required !== '') {
|
|
432
|
+
if (authority === required) return { ok: true };
|
|
433
|
+
return { ok: false, error: `is on ${authority}, but GH_HOST selects ${required}` };
|
|
434
|
+
}
|
|
435
|
+
if (GITHUB_HOSTS.has(authority)) return { ok: true };
|
|
436
|
+
if (authority.endsWith('.ghe.com') || authority.startsWith('github.') || authority.includes('.github.')) {
|
|
437
|
+
return { ok: false, error: `is on ${authority}, which gh reaches only when GH_HOST selects it` };
|
|
438
|
+
}
|
|
439
|
+
return { ok: false, error: `is on ${authority}, which is not a GitHub host` };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// A caller-supplied identity (`GH_REPO`, or the identity a caller already
|
|
443
|
+
// displayed) normalized to the HOST-QUALIFIED `<host>/<owner>/<repo>` form. A
|
|
444
|
+
// bare `owner/name` is qualified with the host gh would use (GH_HOST, else
|
|
445
|
+
// github.com). A value that names one server while GH_HOST selects another, or
|
|
446
|
+
// a host that is not provably GitHub, fails closed: a pin is never redirected.
|
|
447
|
+
function normalizeScopeIdentity(value, env = process.env) {
|
|
448
|
+
const text = String(value === undefined || value === null ? '' : value).trim();
|
|
449
|
+
if (text === '') return { ok: false, error: 'no repository identity was given' };
|
|
450
|
+
const segments = text.split('/');
|
|
451
|
+
let host;
|
|
452
|
+
let owner;
|
|
453
|
+
let name;
|
|
454
|
+
if (segments.length === 2) {
|
|
455
|
+
host = ghHostOf(env) || 'github.com';
|
|
456
|
+
owner = segments[0];
|
|
457
|
+
name = segments[1];
|
|
458
|
+
} else if (segments.length === 3) {
|
|
459
|
+
host = canonicalHost(segments[0]);
|
|
460
|
+
owner = segments[1];
|
|
461
|
+
name = segments[2];
|
|
462
|
+
} else {
|
|
463
|
+
return { ok: false, error: `repository identity "${text}" is not in [HOST/]OWNER/REPO form` };
|
|
464
|
+
}
|
|
465
|
+
const verdict = hostVerdict(host, env);
|
|
466
|
+
if (verdict.ok !== true) return { ok: false, error: verdict.error, host };
|
|
467
|
+
if (!GITHUB_OWNER_PATTERN.test(owner) || !GITHUB_REPO_PATTERN.test(name)
|
|
468
|
+
|| name === '.' || name === '..' || owner === '.' || owner === '..') {
|
|
469
|
+
return { ok: false, error: 'names an invalid GitHub repository', host };
|
|
470
|
+
}
|
|
471
|
+
const nameWithOwner = `${owner}/${name}`;
|
|
472
|
+
return { ok: true, host, nameWithOwner, identity: `${host}/${nameWithOwner}` };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function namesCheckout(opts) {
|
|
476
|
+
return typeof opts.cwd === 'string' && opts.cwd.length > 0;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// ---------------------------------------------------------------------------
|
|
480
|
+
// Parsing and normalizing helpers (local copies of lib/gh-issues.js).
|
|
481
|
+
// ---------------------------------------------------------------------------
|
|
482
|
+
|
|
483
|
+
function exitError(outcome, what) {
|
|
484
|
+
const stderr = (outcome.stderr || '').trim();
|
|
485
|
+
if (stderr) return `${what}: ${stderr.split('\n')[0].slice(0, 500)}`;
|
|
486
|
+
if (outcome.status !== null) return `${what}: gh exited with status ${outcome.status}`;
|
|
487
|
+
return `${what}: gh failed`;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function parseJsonBody(stdout, what) {
|
|
491
|
+
const text = (stdout || '').trim();
|
|
492
|
+
if (!text) return { ok: false, error: `${what}: gh returned an empty body` };
|
|
493
|
+
try {
|
|
494
|
+
return { ok: true, doc: JSON.parse(text) };
|
|
495
|
+
} catch {
|
|
496
|
+
return { ok: false, error: `${what}: gh returned unparseable output` };
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function asLogin(author) {
|
|
501
|
+
if (typeof author === 'string') return author;
|
|
502
|
+
if (author && typeof author === 'object' && typeof author.login === 'string') return author.login;
|
|
503
|
+
return '';
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function asLabel(raw) {
|
|
507
|
+
const entry = raw && typeof raw === 'object' ? raw : {};
|
|
508
|
+
return {
|
|
509
|
+
name: typeof entry.name === 'string' ? entry.name : '',
|
|
510
|
+
color: typeof entry.color === 'string' ? entry.color : '',
|
|
511
|
+
description: typeof entry.description === 'string' ? entry.description : '',
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function sumReactions(reactionGroups) {
|
|
516
|
+
let total = 0;
|
|
517
|
+
let plusOne = 0;
|
|
518
|
+
if (!Array.isArray(reactionGroups)) return { total: 0, plusOne: 0 };
|
|
519
|
+
for (const group of reactionGroups) {
|
|
520
|
+
if (!group || typeof group !== 'object') continue;
|
|
521
|
+
const count = group.users && typeof group.users.totalCount === 'number'
|
|
522
|
+
? group.users.totalCount
|
|
523
|
+
: (group.reactors && typeof group.reactors.totalCount === 'number'
|
|
524
|
+
? group.reactors.totalCount
|
|
525
|
+
: (typeof group.totalCount === 'number' ? group.totalCount : 0));
|
|
526
|
+
total += count;
|
|
527
|
+
if (group.content === 'THUMBS_UP') plusOne += count;
|
|
528
|
+
}
|
|
529
|
+
return { total, plusOne };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function normalizeComment(raw, fallbackId) {
|
|
533
|
+
const entry = raw && typeof raw === 'object' ? raw : {};
|
|
534
|
+
const id = typeof entry.id === 'string' || typeof entry.id === 'number'
|
|
535
|
+
? entry.id
|
|
536
|
+
: (typeof entry.databaseId === 'number' ? entry.databaseId : fallbackId);
|
|
537
|
+
return {
|
|
538
|
+
id,
|
|
539
|
+
author: asLogin(entry.author),
|
|
540
|
+
createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : '',
|
|
541
|
+
body: typeof entry.body === 'string' ? entry.body : '',
|
|
542
|
+
reactions: sumReactions(entry.reactionGroups || entry.reactions),
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Authentication, permission and transport wording always wins over a not-found
|
|
547
|
+
// pattern, because a private repository answers 404 for a pull request the
|
|
548
|
+
// reader merely cannot see.
|
|
549
|
+
const NOT_FOUND_PATTERN = /could not resolve to an? (?:issue|pull request)|no (?:such|matching) pull request/i;
|
|
550
|
+
const UNVERIFIABLE_PATTERN = /401|403|bad credentials|authenticat|permission|forbidden|saml|enoent|timed out|timeout|dial tcp|no such host|connection refused|network/i;
|
|
551
|
+
|
|
552
|
+
function pullRequestViewFailure(res, number) {
|
|
553
|
+
const text = `${res.stderr || ''}\n${res.stdout || ''}`;
|
|
554
|
+
const notFound = typeof res.status === 'number' && res.status !== 0
|
|
555
|
+
&& !UNVERIFIABLE_PATTERN.test(text)
|
|
556
|
+
&& NOT_FOUND_PATTERN.test(text);
|
|
557
|
+
return {
|
|
558
|
+
ok: false,
|
|
559
|
+
error: exitError(res, `cannot view pull request #${number}`),
|
|
560
|
+
status: res.status,
|
|
561
|
+
notFound,
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function countOrZero(value) {
|
|
566
|
+
return Number.isInteger(value) && value >= 0 ? value : 0;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// A GraphQL row carries labels and assignees as connections and comments as a
|
|
570
|
+
// count; reshape them into the payload `normalizePullRequestRow` reads.
|
|
571
|
+
function graphqlRow(node) {
|
|
572
|
+
const entry = node && typeof node === 'object' ? node : {};
|
|
573
|
+
const labelNodes = entry.labels && typeof entry.labels === 'object' && Array.isArray(entry.labels.nodes)
|
|
574
|
+
? entry.labels.nodes
|
|
575
|
+
: [];
|
|
576
|
+
const assigneeNodes = entry.assignees && typeof entry.assignees === 'object'
|
|
577
|
+
&& Array.isArray(entry.assignees.nodes)
|
|
578
|
+
? entry.assignees.nodes
|
|
579
|
+
: null;
|
|
580
|
+
const commentsTotal = entry.comments && typeof entry.comments === 'object'
|
|
581
|
+
&& Number.isInteger(entry.comments.totalCount)
|
|
582
|
+
? entry.comments.totalCount
|
|
583
|
+
: 0;
|
|
584
|
+
return {
|
|
585
|
+
...entry,
|
|
586
|
+
labels: labelNodes,
|
|
587
|
+
...(assigneeNodes === null ? {} : { assignees: assigneeNodes }),
|
|
588
|
+
comments: [],
|
|
589
|
+
commentsTotal,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function normalizePullRequestRow(raw) {
|
|
594
|
+
const entry = raw && typeof raw === 'object' ? raw : {};
|
|
595
|
+
const comments = Array.isArray(entry.comments) ? entry.comments : [];
|
|
596
|
+
return {
|
|
597
|
+
number: Number.isInteger(entry.number) ? entry.number : -1,
|
|
598
|
+
title: typeof entry.title === 'string' ? entry.title : '',
|
|
599
|
+
state: typeof entry.state === 'string' ? entry.state.toLowerCase() : '',
|
|
600
|
+
// The issue row carries a state reason; a pull request has none, so the
|
|
601
|
+
// honest default keeps the shape without inventing one.
|
|
602
|
+
stateReason: '',
|
|
603
|
+
author: asLogin(entry.author),
|
|
604
|
+
assignees: Array.isArray(entry.assignees)
|
|
605
|
+
? entry.assignees.map(asLogin).filter((login) => login !== '')
|
|
606
|
+
: [],
|
|
607
|
+
// `gh pr view --json` (like `gh issue view`) has no authorAssociation
|
|
608
|
+
// field; the honest default is ''.
|
|
609
|
+
authorAssociation: typeof entry.authorAssociation === 'string' ? entry.authorAssociation : '',
|
|
610
|
+
labels: Array.isArray(entry.labels) ? entry.labels.map(asLabel) : [],
|
|
611
|
+
createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : '',
|
|
612
|
+
updatedAt: typeof entry.updatedAt === 'string' ? entry.updatedAt : '',
|
|
613
|
+
commentsCount: Number.isInteger(entry.commentsTotal) && entry.commentsTotal >= 0
|
|
614
|
+
? entry.commentsTotal
|
|
615
|
+
: comments.length,
|
|
616
|
+
reactions: sumReactions(entry.reactionGroups || entry.reactions),
|
|
617
|
+
url: typeof entry.url === 'string' ? entry.url : '',
|
|
618
|
+
body: '',
|
|
619
|
+
isPullRequest: true,
|
|
620
|
+
isDraft: entry.isDraft === true,
|
|
621
|
+
reviewDecision: typeof entry.reviewDecision === 'string' ? entry.reviewDecision : '',
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// The reviews a pull request carries, as `[{login, state}]`. An outstanding
|
|
626
|
+
// review request is `REQUESTED`; a submitted review keeps the state GitHub
|
|
627
|
+
// reports for it. A team request carries no login, so it is not a reviewer this
|
|
628
|
+
// pane can name.
|
|
629
|
+
const REVIEW_STATES = ['REQUESTED', 'APPROVED', 'CHANGES_REQUESTED', 'COMMENTED', 'DISMISSED'];
|
|
630
|
+
|
|
631
|
+
function normalizeReviewers(reviewRequests, latestReviews) {
|
|
632
|
+
const states = new Map();
|
|
633
|
+
const order = [];
|
|
634
|
+
const remember = (login, state) => {
|
|
635
|
+
if (login === '') return;
|
|
636
|
+
if (!states.has(login)) order.push(login);
|
|
637
|
+
states.set(login, state);
|
|
638
|
+
};
|
|
639
|
+
if (Array.isArray(reviewRequests)) {
|
|
640
|
+
for (const request of reviewRequests) {
|
|
641
|
+
const reviewer = request && typeof request === 'object' ? request.requestedReviewer : null;
|
|
642
|
+
remember(asLogin(reviewer), 'REQUESTED');
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (Array.isArray(latestReviews)) {
|
|
646
|
+
for (const review of latestReviews) {
|
|
647
|
+
if (!review || typeof review !== 'object') continue;
|
|
648
|
+
const state = REVIEW_STATES.includes(review.state) && review.state !== 'REQUESTED'
|
|
649
|
+
? review.state
|
|
650
|
+
: 'COMMENTED';
|
|
651
|
+
remember(asLogin(review.author), state);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return order.map((login) => ({ login, state: states.get(login) }));
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function latestCommitDate(commits) {
|
|
658
|
+
let newest = '';
|
|
659
|
+
for (const commit of commits) {
|
|
660
|
+
const at = commit && typeof commit === 'object' && typeof commit.committedDate === 'string'
|
|
661
|
+
? commit.committedDate
|
|
662
|
+
: '';
|
|
663
|
+
if (at !== '' && at > newest) newest = at;
|
|
664
|
+
}
|
|
665
|
+
return newest;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// The checks summary S3 draws: how many ran, how many passed, whether one
|
|
669
|
+
// failed and which ones. A context GitHub reports in an unfamiliar shape is
|
|
670
|
+
// never claimed as a success: an unknown conclusion counts as a failure, and a
|
|
671
|
+
// run that has not completed is pending.
|
|
672
|
+
const PASSED_CONCLUSIONS = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);
|
|
673
|
+
const FAILED_STATES = new Set(['FAILURE', 'ERROR']);
|
|
674
|
+
|
|
675
|
+
function normalizeChecks(rollup) {
|
|
676
|
+
const contexts = Array.isArray(rollup) ? rollup : [];
|
|
677
|
+
let passed = 0;
|
|
678
|
+
let failed = 0;
|
|
679
|
+
let pending = 0;
|
|
680
|
+
const failing = [];
|
|
681
|
+
for (const context of contexts) {
|
|
682
|
+
if (!context || typeof context !== 'object') continue;
|
|
683
|
+
if (context.__typename === 'StatusContext') {
|
|
684
|
+
const name = typeof context.context === 'string' ? context.context : '';
|
|
685
|
+
const state = typeof context.state === 'string' ? context.state.toUpperCase() : '';
|
|
686
|
+
if (FAILED_STATES.has(state)) {
|
|
687
|
+
failed += 1;
|
|
688
|
+
if (name) failing.push(name);
|
|
689
|
+
} else if (state === 'SUCCESS') {
|
|
690
|
+
passed += 1;
|
|
691
|
+
} else {
|
|
692
|
+
pending += 1;
|
|
693
|
+
}
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
const name = typeof context.name === 'string' ? context.name : '';
|
|
697
|
+
const status = typeof context.status === 'string' ? context.status.toUpperCase() : '';
|
|
698
|
+
if (status !== '' && status !== 'COMPLETED') {
|
|
699
|
+
pending += 1;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
const conclusion = typeof context.conclusion === 'string' ? context.conclusion.toUpperCase() : '';
|
|
703
|
+
if (conclusion === '') {
|
|
704
|
+
pending += 1;
|
|
705
|
+
} else if (PASSED_CONCLUSIONS.has(conclusion)) {
|
|
706
|
+
passed += 1;
|
|
707
|
+
} else {
|
|
708
|
+
failed += 1;
|
|
709
|
+
if (name) failing.push(name);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const total = passed + failed + pending;
|
|
713
|
+
const state = total === 0
|
|
714
|
+
? 'NONE'
|
|
715
|
+
: (failed > 0 ? 'FAILURE' : (pending > 0 ? 'PENDING' : 'SUCCESS'));
|
|
716
|
+
return { total, passed, failed, pending, state, failing };
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// The numbers a `closingIssuesReferences` list names, deduplicated and sorted.
|
|
720
|
+
// `readable:false` means the relation could not be read at all, which the pane
|
|
721
|
+
// reports instead of claiming the pull request closes nothing.
|
|
722
|
+
function linkedIssueNumbers(raw) {
|
|
723
|
+
if (!Array.isArray(raw)) return { readable: false, numbers: [] };
|
|
724
|
+
const numbers = [];
|
|
725
|
+
for (const node of raw) {
|
|
726
|
+
const number = node && typeof node === 'object' ? node.number : undefined;
|
|
727
|
+
if (!Number.isInteger(number) || number <= 0) return { readable: false, numbers: [] };
|
|
728
|
+
if (!numbers.includes(number)) numbers.push(number);
|
|
729
|
+
}
|
|
730
|
+
return { readable: true, numbers: numbers.sort((a, b) => a - b) };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// S2/D29 (S6): a linked reference is identified by REPOSITORY and number. The
|
|
734
|
+
// Development relation only ever points at issues of the same repository
|
|
735
|
+
// (GitHub enforces it), so a node that names another repository is not this
|
|
736
|
+
// panel's target: it is dropped rather than shown as a number that would open a
|
|
737
|
+
// same-numbered issue here. A node that names no repository (a partial answer)
|
|
738
|
+
// is kept, because the read itself is repository-scoped.
|
|
739
|
+
function sameRepositoryReferences(raw, fullName) {
|
|
740
|
+
if (!Array.isArray(raw)) return raw;
|
|
741
|
+
const wanted = typeof fullName === 'string' ? fullName.toLowerCase() : '';
|
|
742
|
+
if (wanted === '') return raw;
|
|
743
|
+
return raw.filter((node) => {
|
|
744
|
+
const named = node && typeof node === 'object' && node.repository && typeof node.repository.nameWithOwner === 'string'
|
|
745
|
+
? node.repository.nameWithOwner.toLowerCase()
|
|
746
|
+
: '';
|
|
747
|
+
return named === '' || named === wanted;
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function normalizePullRequestDetail(raw) {
|
|
752
|
+
const entry = raw && typeof raw === 'object' ? raw : {};
|
|
753
|
+
const row = normalizePullRequestRow(entry);
|
|
754
|
+
const commits = Array.isArray(entry.commits) ? entry.commits : [];
|
|
755
|
+
const linked = linkedIssueNumbers(entry.closingIssuesReferences);
|
|
756
|
+
return {
|
|
757
|
+
...row,
|
|
758
|
+
body: typeof entry.body === 'string' ? entry.body : '',
|
|
759
|
+
baseRefName: typeof entry.baseRefName === 'string' ? entry.baseRefName : '',
|
|
760
|
+
headRefName: typeof entry.headRefName === 'string' ? entry.headRefName : '',
|
|
761
|
+
headRepositoryOwner: asLogin(entry.headRepositoryOwner),
|
|
762
|
+
additions: countOrZero(entry.additions),
|
|
763
|
+
deletions: countOrZero(entry.deletions),
|
|
764
|
+
changedFiles: countOrZero(entry.changedFiles),
|
|
765
|
+
commits: commits.length,
|
|
766
|
+
committedAt: latestCommitDate(commits),
|
|
767
|
+
reviewers: normalizeReviewers(entry.reviewRequests, entry.latestReviews),
|
|
768
|
+
linkedIssues: linked.numbers,
|
|
769
|
+
linkedIssuesTruncated: false,
|
|
770
|
+
checks: normalizeChecks(entry.statusCheckRollup),
|
|
771
|
+
mergeable: typeof entry.mergeable === 'string' ? entry.mergeable : '',
|
|
772
|
+
mergeStateStatus: typeof entry.mergeStateStatus === 'string' ? entry.mergeStateStatus : '',
|
|
773
|
+
mergeMethods: {},
|
|
774
|
+
mergeDefaults: {},
|
|
775
|
+
permissions: pullRequestPermissions(null),
|
|
776
|
+
viewerPermission: null,
|
|
777
|
+
unavailable: [],
|
|
778
|
+
metadataError: null,
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// ---------------------------------------------------------------------------
|
|
783
|
+
// Capabilities (invariant 7 + S2).
|
|
784
|
+
// ---------------------------------------------------------------------------
|
|
785
|
+
|
|
786
|
+
// The merge methods a `mergeMethods` object confirms, in GitHub's own order.
|
|
787
|
+
function allowedMergeMethods(mergeMethods) {
|
|
788
|
+
if (!mergeMethods || typeof mergeMethods !== 'object') return [];
|
|
789
|
+
return MERGE_METHODS.filter((method) => mergeMethods[method] === true);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// `repository.viewerPermission` → the six capabilities the panel gates on.
|
|
793
|
+
// Only a literal permitted role confirms anything: a missing field, an unknown
|
|
794
|
+
// string or a truthy non-string all read as "not permitted". Labels and
|
|
795
|
+
// assignees are triage-level, exactly like the issue client's; creating a
|
|
796
|
+
// repository label is write-level, and closing, merging and rewriting the body
|
|
797
|
+
// of a pull request need WRITE, which is the fail-closed reading of GitHub's
|
|
798
|
+
// own rule (a triage-only viewer cannot close somebody else's pull request).
|
|
799
|
+
// Merge ALSO needs the pull request facts: a draft is never mergeable, and a
|
|
800
|
+
// repository that allows no method offers none.
|
|
801
|
+
function pullRequestPermissions(permission, pullRequest = {}) {
|
|
802
|
+
const role = typeof permission === 'string' && PERMITTED_ROLES.includes(permission);
|
|
803
|
+
const mergeWrites = typeof permission === 'string' && MERGE_ROLES.includes(permission);
|
|
804
|
+
const facts = pullRequest && typeof pullRequest === 'object' ? pullRequest : {};
|
|
805
|
+
const methods = allowedMergeMethods(facts.mergeMethods);
|
|
806
|
+
return {
|
|
807
|
+
canEditLabels: role,
|
|
808
|
+
canCreateLabels: labelCreationAllowed(permission),
|
|
809
|
+
canEditAssignees: role,
|
|
810
|
+
canClosePullRequests: mergeWrites,
|
|
811
|
+
canMerge: mergeWrites && facts.isDraft !== true && methods.length > 0,
|
|
812
|
+
canEditLinkedIssues: mergeWrites,
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// Creating a repository label is write-level, exactly like the issue client's
|
|
817
|
+
// `canCreateLabels`: a triage-only viewer may apply an existing label but may
|
|
818
|
+
// not add one to the repository.
|
|
819
|
+
function labelCreationAllowed(permission) {
|
|
820
|
+
return typeof permission === 'string' && MERGE_ROLES.includes(permission);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// GitHub's own merge proposals, for exactly the methods the repository allows.
|
|
824
|
+
// The merge proposal is GitHub's default text (`Merge pull request #N from
|
|
825
|
+
// owner/branch`, with the pull request's title as the description), the squash
|
|
826
|
+
// one is the title alone, and a rebase merge takes neither.
|
|
827
|
+
function mergeDefaultsFor(pullRequest, mergeMethods) {
|
|
828
|
+
const defaults = {};
|
|
829
|
+
const head = [pullRequest.headRepositoryOwner, pullRequest.headRefName]
|
|
830
|
+
.filter((part) => typeof part === 'string' && part !== '')
|
|
831
|
+
.join('/');
|
|
832
|
+
for (const method of allowedMergeMethods(mergeMethods)) {
|
|
833
|
+
if (method === 'merge') {
|
|
834
|
+
defaults.merge = {
|
|
835
|
+
subject: head === ''
|
|
836
|
+
? `Merge pull request #${pullRequest.number}`
|
|
837
|
+
: `Merge pull request #${pullRequest.number} from ${head}`,
|
|
838
|
+
body: pullRequest.title,
|
|
839
|
+
};
|
|
840
|
+
} else if (method === 'squash') {
|
|
841
|
+
defaults.squash = { subject: pullRequest.title, body: '' };
|
|
842
|
+
} else {
|
|
843
|
+
defaults.rebase = {};
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
return defaults;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// ---------------------------------------------------------------------------
|
|
850
|
+
// Call parameters and paging.
|
|
851
|
+
// ---------------------------------------------------------------------------
|
|
852
|
+
|
|
853
|
+
const CALL_OPTION_KEYS = ['scope', 'env', 'cwd', 'ghBin', 'timeoutMs', 'freshScope'];
|
|
854
|
+
|
|
855
|
+
function splitParams(params, opts) {
|
|
856
|
+
const p = params && typeof params === 'object' && !Array.isArray(params) ? params : {};
|
|
857
|
+
const o = opts && typeof opts === 'object' && !Array.isArray(opts) ? opts : {};
|
|
858
|
+
const options = { ...o };
|
|
859
|
+
for (const key of CALL_OPTION_KEYS) {
|
|
860
|
+
if (options[key] === undefined && p[key] !== undefined) options[key] = p[key];
|
|
861
|
+
}
|
|
862
|
+
return { params: p, options };
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
const PAGE_ERROR = 'invalid pull request page: pageSize must be 1..1000 and cursor must be a non-empty string or null';
|
|
866
|
+
|
|
867
|
+
function normalizePageRequest(params) {
|
|
868
|
+
const pageSize = params.pageSize === undefined || params.pageSize === null
|
|
869
|
+
? DEFAULT_PAGE_SIZE
|
|
870
|
+
: params.pageSize;
|
|
871
|
+
const cursor = params.cursor === undefined ? null : params.cursor;
|
|
872
|
+
if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 1000) {
|
|
873
|
+
return { ok: false, error: PAGE_ERROR };
|
|
874
|
+
}
|
|
875
|
+
if (cursor !== null && (typeof cursor !== 'string' || cursor === '')) {
|
|
876
|
+
return { ok: false, error: PAGE_ERROR };
|
|
877
|
+
}
|
|
878
|
+
return { ok: true, pageSize, cursor };
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function withLastUpdatedSort(search) {
|
|
882
|
+
if (/\bsort:/i.test(search)) return search;
|
|
883
|
+
return search ? `${search} ${LAST_UPDATED_SORT}` : LAST_UPDATED_SORT;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// One cursor walk over a page source. Every page is validated before it is
|
|
887
|
+
// trusted: GraphQL errors fail the call, a cursor or pull request repeated
|
|
888
|
+
// inside one call is an error (a silent drop would make the totals lie), and a
|
|
889
|
+
// non-advancing or cursorless `hasNextPage` fails instead of looping. A short
|
|
890
|
+
// server page is a VALID page whose cursor belongs to the caller; filling it by
|
|
891
|
+
// issuing another request would skip that boundary.
|
|
892
|
+
async function readPages({ cursor, pageSize, isSearch, runPage, connectionOf }) {
|
|
893
|
+
const rows = [];
|
|
894
|
+
const seen = new Set();
|
|
895
|
+
const rowCursors = new Set(cursor === null ? [] : [cursor]);
|
|
896
|
+
const cursors = new Set(cursor === null ? [] : [cursor]);
|
|
897
|
+
let after = cursor;
|
|
898
|
+
let totalCount = 0;
|
|
899
|
+
let hasMore = false;
|
|
900
|
+
let nextCursor = null;
|
|
901
|
+
while (rows.length < pageSize) {
|
|
902
|
+
const first = Math.min(MAX_PAGE_SIZE, pageSize - rows.length);
|
|
903
|
+
const res = await runPage(first, after);
|
|
904
|
+
if (res.ok !== true) return res;
|
|
905
|
+
const connection = connectionOf(res.data);
|
|
906
|
+
if (!connection || typeof connection !== 'object' || Array.isArray(connection)
|
|
907
|
+
|| !Array.isArray(connection.edges) || typeof connection.pageInfo?.hasNextPage !== 'boolean') {
|
|
908
|
+
return { ok: false, error: 'GitHub returned an invalid pull request page' };
|
|
909
|
+
}
|
|
910
|
+
const total = isSearch === true ? connection.issueCount : connection.totalCount;
|
|
911
|
+
if (!Number.isInteger(total) || total < 0) {
|
|
912
|
+
return { ok: false, error: 'GitHub returned an invalid pull request page' };
|
|
913
|
+
}
|
|
914
|
+
if (isSearch === true && total > SEARCH_MATCH_CAP) {
|
|
915
|
+
return {
|
|
916
|
+
ok: false,
|
|
917
|
+
error: 'GitHub pull request search exceeds 1000 matches; narrow the filter',
|
|
918
|
+
truncated: true,
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
totalCount = total;
|
|
922
|
+
if (connection.edges.length > first) {
|
|
923
|
+
return { ok: false, error: 'GitHub exceeded the requested pull request page size' };
|
|
924
|
+
}
|
|
925
|
+
for (const edge of connection.edges) {
|
|
926
|
+
if (typeof edge?.cursor !== 'string' || !edge.cursor || !Number.isInteger(edge?.node?.number)
|
|
927
|
+
|| edge.node.number < 1 || seen.has(edge.node.number) || rowCursors.has(edge.cursor)) {
|
|
928
|
+
return { ok: false, error: 'GitHub returned an invalid pull request cursor or duplicate pull request' };
|
|
929
|
+
}
|
|
930
|
+
seen.add(edge.node.number);
|
|
931
|
+
rowCursors.add(edge.cursor);
|
|
932
|
+
rows.push({ ...normalizePullRequestRow(graphqlRow(edge.node)), cursor: edge.cursor });
|
|
933
|
+
}
|
|
934
|
+
hasMore = connection.pageInfo.hasNextPage;
|
|
935
|
+
if (!hasMore) {
|
|
936
|
+
nextCursor = null;
|
|
937
|
+
break;
|
|
938
|
+
}
|
|
939
|
+
const next = connection.pageInfo.endCursor;
|
|
940
|
+
if (typeof next !== 'string' || !next || cursors.has(next) || connection.edges.length === 0) {
|
|
941
|
+
return { ok: false, error: 'GitHub pull request pagination did not advance' };
|
|
942
|
+
}
|
|
943
|
+
cursors.add(next);
|
|
944
|
+
nextCursor = next;
|
|
945
|
+
if (connection.edges.length < first) break;
|
|
946
|
+
after = next;
|
|
947
|
+
}
|
|
948
|
+
return { ok: true, rows, hasMore, cursor: hasMore ? nextCursor : null, totalCount };
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// The rail's ONE aliased query: both buckets in the same `repo:` scope, each
|
|
952
|
+
// with its exact `issueCount`, sorted by last update.
|
|
953
|
+
function railQuery(fullName, first) {
|
|
954
|
+
const aliases = RAIL_ALIAS_QUALIFIERS.map(([alias, qualifier]) => {
|
|
955
|
+
const search = `repo:${fullName} is:pr is:open ${qualifier} ${LAST_UPDATED_SORT}`;
|
|
956
|
+
return ` ${alias}: search(query: ${JSON.stringify(search)}, type: ISSUE, first: ${first}) {
|
|
957
|
+
issueCount
|
|
958
|
+
nodes {
|
|
959
|
+
... on PullRequest {
|
|
960
|
+
number
|
|
961
|
+
closingIssuesReferences(first: ${LINKED_ISSUE_WINDOW}) { nodes { number } pageInfo { hasNextPage } }
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}`;
|
|
965
|
+
});
|
|
966
|
+
return `query {\n${aliases.join('\n')}\n}`;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// Fold the metadata read into the detail payload. A failed read leaves every
|
|
970
|
+
// capability false and names what is missing, so nothing is offered that was
|
|
971
|
+
// never confirmed.
|
|
972
|
+
function applyMetadata(pullRequest, metadata, linkedFallbackReadable) {
|
|
973
|
+
if (metadata.ok !== true) {
|
|
974
|
+
pullRequest.metadataError = metadata.error;
|
|
975
|
+
pullRequest.unavailable = ['permissions', 'merge methods'];
|
|
976
|
+
if (linkedFallbackReadable !== true) pullRequest.unavailable.push('linked issues');
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
const methods = metadata.mergeMethods;
|
|
980
|
+
pullRequest.mergeMethods = methods;
|
|
981
|
+
pullRequest.mergeDefaults = mergeDefaultsFor(pullRequest, methods);
|
|
982
|
+
pullRequest.viewerPermission = metadata.permission;
|
|
983
|
+
// S2/D31: the GraphQL metadata is the newest state read, so a MERGED or CLOSED
|
|
984
|
+
// answer wins over a `pr view` that still says open (GitHub's final state is
|
|
985
|
+
// never the optimistic one).
|
|
986
|
+
const metadataState = typeof metadata.state === 'string' ? metadata.state.toLowerCase() : '';
|
|
987
|
+
if (metadataState === 'merged' || metadataState === 'closed') pullRequest.state = metadataState;
|
|
988
|
+
pullRequest.permissions = pullRequestPermissions(metadata.permission, {
|
|
989
|
+
isDraft: pullRequest.isDraft === true || metadata.isDraft === true,
|
|
990
|
+
mergeMethods: methods,
|
|
991
|
+
});
|
|
992
|
+
if (metadata.linkedIssues !== null) {
|
|
993
|
+
pullRequest.linkedIssues = metadata.linkedIssues;
|
|
994
|
+
pullRequest.linkedIssuesTruncated = metadata.linkedIssuesTruncated === true;
|
|
995
|
+
} else if (linkedFallbackReadable !== true) {
|
|
996
|
+
pullRequest.unavailable.push('linked issues');
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
// ---------------------------------------------------------------------------
|
|
1001
|
+
// S2 (D27): the Development relation. GitHub exposes no mutation for it, so a
|
|
1002
|
+
// linked issue is a `Closes #N` line in the pull request body. These helpers no
|
|
1003
|
+
// longer INTERPRET Markdown: every line this panel writes carries a marker
|
|
1004
|
+
// comment, only a marked line is ever removed, a body whose structure cannot be
|
|
1005
|
+
// read safely is refused instead of guessed at, and every other byte of the
|
|
1006
|
+
// body is preserved.
|
|
1007
|
+
// ---------------------------------------------------------------------------
|
|
1008
|
+
|
|
1009
|
+
// The one marker this panel writes. It is what makes a line the panel's OWN: an
|
|
1010
|
+
// ordinary `Closes #N` a human wrote is never rewritten. The pattern below
|
|
1011
|
+
// accepts any of GitHub's closing keywords, case-insensitively, at COLUMN 0. An
|
|
1012
|
+
// indented one is a container's content or an indented code block, never a
|
|
1013
|
+
// declaration this panel may read.
|
|
1014
|
+
const LINK_MARKER = '<!-- odd-worktree:linked -->';
|
|
1015
|
+
const LINK_MARKER_PATTERN = LINK_MARKER.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1016
|
+
const CLOSING_KEYWORD = '(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)';
|
|
1017
|
+
const MARKED_LINE_PATTERN = new RegExp(
|
|
1018
|
+
`^${CLOSING_KEYWORD}[ \\t]+#(\\d+)[ \\t]*${LINK_MARKER_PATTERN}[ \\t]*$`, 'i',
|
|
1019
|
+
);
|
|
1020
|
+
const CLOSING_LINE_PATTERN = new RegExp(`^${CLOSING_KEYWORD}[ \\t]+#(\\d+)[ \\t]*$`, 'i');
|
|
1021
|
+
// The one line shape this panel ITSELF writes, byte for byte: one keyword, one
|
|
1022
|
+
// space, one number, one space, this marker and nothing else. Only a line that
|
|
1023
|
+
// matches it exactly is ever deleted, so a human's variant that merely LOOKS
|
|
1024
|
+
// like ours (another keyword, another spacing, a trailing space) is refused
|
|
1025
|
+
// instead of rewritten.
|
|
1026
|
+
const OWN_LINE_PATTERN = new RegExp(`^Closes #([1-9]\\d*) ${LINK_MARKER_PATTERN}$`);
|
|
1027
|
+
|
|
1028
|
+
// The refusals a body edit can carry, plus the concurrent-edit one.
|
|
1029
|
+
const BODY_UNREADABLE = 'the pull request body ends inside an unclosed code fence or comment';
|
|
1030
|
+
const LINK_NOT_OURS = 'that link was not added by this panel; remove it on GitHub';
|
|
1031
|
+
const BODY_MARKUP_LINK = 'that link sits inside a code fence or comment in the body; remove it on GitHub';
|
|
1032
|
+
const BODY_CHANGED = 'the pull request body changed while it was being edited';
|
|
1033
|
+
|
|
1034
|
+
// Split on '\n' while KEEPING each line's own ending, so re-joining the parts
|
|
1035
|
+
// reproduces the body byte for byte (CRLF included).
|
|
1036
|
+
function splitBodyLines(body) {
|
|
1037
|
+
const parts = [];
|
|
1038
|
+
let start = 0;
|
|
1039
|
+
for (let at = 0; at < body.length; at += 1) {
|
|
1040
|
+
if (body[at] !== '\n') continue;
|
|
1041
|
+
const hasCr = at > start && body[at - 1] === '\r';
|
|
1042
|
+
const textEnd = hasCr ? at - 1 : at;
|
|
1043
|
+
parts.push({ text: body.slice(start, textEnd), eol: body.slice(textEnd, at + 1) });
|
|
1044
|
+
start = at + 1;
|
|
1045
|
+
}
|
|
1046
|
+
if (start < body.length) parts.push({ text: body.slice(start), eol: '' });
|
|
1047
|
+
return parts;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
// The number ONE line declares at column 0, marked or not, or null. READing a
|
|
1051
|
+
// declaration is not OWNing it: only the exact line above is ever deleted.
|
|
1052
|
+
function declarationOf(text) {
|
|
1053
|
+
for (const pattern of [MARKED_LINE_PATTERN, CLOSING_LINE_PATTERN]) {
|
|
1054
|
+
const declared = pattern.exec(text);
|
|
1055
|
+
if (declared) return Number(declared[1]);
|
|
1056
|
+
}
|
|
1057
|
+
return null;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
// The number of a line that is EXACTLY this panel's own marked declaration, or
|
|
1061
|
+
// null. The `\r` of a CRLF ending is the single tolerated extra (splitBodyLines
|
|
1062
|
+
// already strips it from a CRLF line, so this only covers a bare final `\r`).
|
|
1063
|
+
function ownMarkedNumber(text) {
|
|
1064
|
+
const line = text.endsWith('\r') ? text.slice(0, -1) : text;
|
|
1065
|
+
const own = OWN_LINE_PATTERN.exec(line);
|
|
1066
|
+
return own === null ? null : Number(own[1]);
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// The line this panel adds for one issue.
|
|
1070
|
+
function markerLine(number) {
|
|
1071
|
+
return `Closes #${number} ${LINK_MARKER}`;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// S2/D27: the structure facts a body edit has to respect, read so that the
|
|
1075
|
+
// answer is safe by construction and NEVER rewritten by this scan.
|
|
1076
|
+
//
|
|
1077
|
+
// A fence run is any run of three or more backticks or tildes that starts a
|
|
1078
|
+
// line (indentation is spaces only). The first run opens a fence; only a run of
|
|
1079
|
+
// the SAME character, at least as long, with nothing but whitespace after it,
|
|
1080
|
+
// closes it — so a four-backtick fence holding a three-backtick run and an
|
|
1081
|
+
// example stays one code block. A run that lives inside a line of prose is not
|
|
1082
|
+
// a delimiter at all. An opening run still open at the end of the body, an
|
|
1083
|
+
// `<!--`/`-->` count that does not pair up, and a body whose comment scan ends
|
|
1084
|
+
// inside a comment all mean the last line may be code or commented out: each
|
|
1085
|
+
// refuses the whole edit, add and remove alike.
|
|
1086
|
+
//
|
|
1087
|
+
// Every line strictly INSIDE a paired fence or an HTML comment is MARKUP: a link
|
|
1088
|
+
// this panel wrote there is an example of the panel's own line, never a
|
|
1089
|
+
// declaration it may delete.
|
|
1090
|
+
function bodyStructure(parts, text) {
|
|
1091
|
+
const markup = new Set();
|
|
1092
|
+
let open = null;
|
|
1093
|
+
parts.forEach((part, index) => {
|
|
1094
|
+
const indent = /^ */.exec(part.text)[0].length;
|
|
1095
|
+
for (const run of part.text.matchAll(/`{3,}|~{3,}/g)) {
|
|
1096
|
+
if (run.index !== indent) continue;
|
|
1097
|
+
const fence = run[0];
|
|
1098
|
+
const after = part.text.slice(run.index + fence.length);
|
|
1099
|
+
if (open === null) {
|
|
1100
|
+
open = { char: fence[0], length: fence.length, line: index };
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
if (fence[0] !== open.char || fence.length < open.length) continue;
|
|
1104
|
+
if (!/^[ \t]*$/.test(after)) continue;
|
|
1105
|
+
for (let line = open.line + 1; line < index; line += 1) markup.add(line);
|
|
1106
|
+
open = null;
|
|
1107
|
+
}
|
|
1108
|
+
});
|
|
1109
|
+
const openedComments = text.match(/<!--/g) || [];
|
|
1110
|
+
const closedComments = text.match(/-->/g) || [];
|
|
1111
|
+
const starts = [];
|
|
1112
|
+
let offset = 0;
|
|
1113
|
+
for (const part of parts) {
|
|
1114
|
+
starts.push(offset);
|
|
1115
|
+
offset += part.text.length + part.eol.length;
|
|
1116
|
+
}
|
|
1117
|
+
let cursor = 0;
|
|
1118
|
+
let unterminated = false;
|
|
1119
|
+
while (cursor < text.length) {
|
|
1120
|
+
const from = text.indexOf('<!--', cursor);
|
|
1121
|
+
if (from < 0) break;
|
|
1122
|
+
const to = text.indexOf('-->', from + 4);
|
|
1123
|
+
if (to < 0) {
|
|
1124
|
+
unterminated = true;
|
|
1125
|
+
starts.forEach((start, index) => {
|
|
1126
|
+
if (start >= from) markup.add(index);
|
|
1127
|
+
});
|
|
1128
|
+
break;
|
|
1129
|
+
}
|
|
1130
|
+
starts.forEach((start, index) => {
|
|
1131
|
+
if (start >= from && start < to) markup.add(index);
|
|
1132
|
+
});
|
|
1133
|
+
cursor = to + 3;
|
|
1134
|
+
}
|
|
1135
|
+
return {
|
|
1136
|
+
safe: open === null && openedComments.length === closedComments.length && !unterminated,
|
|
1137
|
+
markup,
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// The body with this panel's own marked lines removed and a marked `Closes #N`
|
|
1142
|
+
// appended for each newly linked issue. A number the body already declares —
|
|
1143
|
+
// marked by this panel or written by a human — is never declared twice, so the
|
|
1144
|
+
// add is a no-op there. A removal deletes only the EXACT line this panel wrote,
|
|
1145
|
+
// and only where that line is not itself an example: a look-alike or a human's
|
|
1146
|
+
// declaration is refused (LINK_NOT_OURS), a line inside a code fence or a
|
|
1147
|
+
// comment is refused too (BODY_MARKUP_LINK), and a body whose fences or
|
|
1148
|
+
// comments do not pair up refuses both edits without changing a byte.
|
|
1149
|
+
function rewriteClosingLines(body, add, remove) {
|
|
1150
|
+
const parts = splitBodyLines(body);
|
|
1151
|
+
const structure = bodyStructure(parts, body);
|
|
1152
|
+
if (structure.safe !== true) return { body, appended: 0, refused: BODY_UNREADABLE };
|
|
1153
|
+
const eol = (parts.find((part) => part.eol !== '') || { eol: '\n' }).eol;
|
|
1154
|
+
// Every number the body declares at column 0 (marked or not), and for each
|
|
1155
|
+
// number the lines that are exactly this panel's own line and sit OUTSIDE any
|
|
1156
|
+
// code fence or comment (the only lines a removal may delete).
|
|
1157
|
+
const declaredNumbers = new Set();
|
|
1158
|
+
const own = new Map();
|
|
1159
|
+
parts.forEach((part, index) => {
|
|
1160
|
+
const declared = declarationOf(part.text);
|
|
1161
|
+
if (declared !== null) declaredNumbers.add(declared);
|
|
1162
|
+
const number = ownMarkedNumber(part.text);
|
|
1163
|
+
if (number === null) return;
|
|
1164
|
+
if (structure.markup.has(index)) {
|
|
1165
|
+
if (!own.has(number)) own.set(number, { deletable: [] });
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
const entry = own.get(number) || { deletable: [] };
|
|
1169
|
+
entry.deletable.push(index);
|
|
1170
|
+
own.set(number, entry);
|
|
1171
|
+
});
|
|
1172
|
+
const removable = new Set();
|
|
1173
|
+
for (const number of remove) {
|
|
1174
|
+
const entry = own.get(number);
|
|
1175
|
+
if (entry !== undefined && entry.deletable.length > 0) {
|
|
1176
|
+
for (const index of entry.deletable) removable.add(index);
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
// The panel's own line is there, but only inside a code fence or a comment:
|
|
1180
|
+
// deleting it would edit an example, so the removal is refused.
|
|
1181
|
+
if (entry !== undefined) return { body, appended: 0, refused: BODY_MARKUP_LINK };
|
|
1182
|
+
// Any other declaration is a human's — or a look-alike that only resembles
|
|
1183
|
+
// this panel's line — and is never rewritten.
|
|
1184
|
+
if (declaredNumbers.has(number)) return { body, appended: 0, refused: LINK_NOT_OURS };
|
|
1185
|
+
}
|
|
1186
|
+
const appended = [];
|
|
1187
|
+
for (const number of add) {
|
|
1188
|
+
if (declaredNumbers.has(number)) continue;
|
|
1189
|
+
declaredNumbers.add(number);
|
|
1190
|
+
appended.push(number);
|
|
1191
|
+
}
|
|
1192
|
+
const kept = parts.filter((_, index) => !removable.has(index));
|
|
1193
|
+
if (appended.length === 0 && kept.length === parts.length) {
|
|
1194
|
+
return { body, appended: 0 };
|
|
1195
|
+
}
|
|
1196
|
+
const out = kept.map((part) => ({ ...part }));
|
|
1197
|
+
if (appended.length > 0) {
|
|
1198
|
+
if (out.length === 0) {
|
|
1199
|
+
for (const number of appended) out.push({ text: markerLine(number), eol });
|
|
1200
|
+
} else {
|
|
1201
|
+
const last = out[out.length - 1];
|
|
1202
|
+
if (last.eol === '') last.eol = eol;
|
|
1203
|
+
// S2/D27: the link block starts on a line of its own.
|
|
1204
|
+
if (last.text.trim() !== '') out.push({ text: '', eol });
|
|
1205
|
+
for (const number of appended) out.push({ text: markerLine(number), eol });
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return {
|
|
1209
|
+
body: out.map((part) => part.text + part.eol).join(''),
|
|
1210
|
+
appended: appended.length,
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
function invalidNumber(number) {
|
|
1215
|
+
return { ok: false, error: `invalid pull request number ${JSON.stringify(number)}: want a positive integer` };
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
function isValidLogin(value) {
|
|
1219
|
+
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(value);
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// ---------------------------------------------------------------------------
|
|
1223
|
+
// The client. `issues` is the injected lib/gh-issues.js module; every seam it
|
|
1224
|
+
// exports is used, and a seam it does not export falls back to the local copy.
|
|
1225
|
+
// ---------------------------------------------------------------------------
|
|
1226
|
+
|
|
1227
|
+
function createPrsClient(options = {}) {
|
|
1228
|
+
const supplied = options && typeof options === 'object'
|
|
1229
|
+
? (options.issues && typeof options.issues === 'object' ? options.issues : null)
|
|
1230
|
+
: null;
|
|
1231
|
+
const seam = (name, fallback) => (supplied && typeof supplied[name] === 'function'
|
|
1232
|
+
? supplied[name]
|
|
1233
|
+
: fallback);
|
|
1234
|
+
|
|
1235
|
+
// The child seam. An injected `runGh` owns its own scope handling; otherwise
|
|
1236
|
+
// this client's own resolver (pin, fork override, gh's default) does. Either
|
|
1237
|
+
// way the scope's API host travels with the child (D23), because `gh api`
|
|
1238
|
+
// never reads it from GH_REPO.
|
|
1239
|
+
const injectedRunGh = seam('runGh', null);
|
|
1240
|
+
const baseRunGh = typeof injectedRunGh === 'function'
|
|
1241
|
+
? (argv, opts) => {
|
|
1242
|
+
// An injected runner owns the scope handling; the host its child must
|
|
1243
|
+
// target is still this client's to name (D23, D28).
|
|
1244
|
+
const hosted = withScopeHost(argv, opts);
|
|
1245
|
+
return injectedRunGh(hosted.argv, hosted.opts);
|
|
1246
|
+
}
|
|
1247
|
+
: (argv, opts) => runGhWith(scopeForCall, argv, opts);
|
|
1248
|
+
const runGh = (argv, opts = {}) => baseRunGh(argv, opts);
|
|
1249
|
+
const normalizeIdentity = seam('normalizeScopeIdentity', normalizeScopeIdentity);
|
|
1250
|
+
const checkoutScope = supplied && typeof supplied.checkoutRepoScope === 'function'
|
|
1251
|
+
? supplied.checkoutRepoScope
|
|
1252
|
+
: null;
|
|
1253
|
+
|
|
1254
|
+
// gh's OWN answer for the checkout, with no override applied. S2/D28: the
|
|
1255
|
+
// answer carries the repository's own URL, so the HOST gh resolved comes from
|
|
1256
|
+
// the repository itself instead of defaulting to github.com.
|
|
1257
|
+
const reportedRepoName = seam('reportedRepoName', async (opts) => {
|
|
1258
|
+
const repo = await runGh(['repo', 'view', '--json', 'nameWithOwner,url'], opts);
|
|
1259
|
+
if (repo.error) return { ok: false, error: repo.error };
|
|
1260
|
+
if (repo.status !== 0) {
|
|
1261
|
+
return {
|
|
1262
|
+
ok: false,
|
|
1263
|
+
error: exitError(repo, 'cannot resolve the repository'),
|
|
1264
|
+
...(/no git remotes/i.test(repo.stderr || '') ? { noRemote: true } : {}),
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
const parsed = parseJsonBody(repo.stdout, 'gh repo view');
|
|
1268
|
+
if (!parsed.ok) return parsed;
|
|
1269
|
+
const reported = parsed.doc && typeof parsed.doc.nameWithOwner === 'string'
|
|
1270
|
+
? parsed.doc.nameWithOwner
|
|
1271
|
+
: '';
|
|
1272
|
+
if (!reported) return { ok: false, error: 'gh repo view returned an unexpected shape' };
|
|
1273
|
+
return { ok: true, nameWithOwner: reported, host: hostOfUrl(parsed.doc.url) };
|
|
1274
|
+
});
|
|
1275
|
+
|
|
1276
|
+
// The scope a call runs with, as a host-qualified `GH_REPO` value or null. An
|
|
1277
|
+
// explicit scope is validated FIRST (a host mismatch or an invalid identity
|
|
1278
|
+
// fails closed before any spawn); a call that names a checkout resolves the
|
|
1279
|
+
// checkout's own repository through the injected resolver; anything else
|
|
1280
|
+
// keeps gh's default resolution.
|
|
1281
|
+
async function scopeForCall(opts) {
|
|
1282
|
+
if (opts.scope !== undefined) {
|
|
1283
|
+
if (opts.scope === null || opts.scope === '') return { ok: true, identity: null };
|
|
1284
|
+
const pinned = normalizeIdentity(opts.scope, opts.env || process.env);
|
|
1285
|
+
if (pinned.ok !== true) return { ok: false, error: `the pinned repository ${pinned.error}` };
|
|
1286
|
+
return { ok: true, identity: pinned.identity };
|
|
1287
|
+
}
|
|
1288
|
+
if (namesCheckout(opts) && checkoutScope) {
|
|
1289
|
+
return checkoutScope({ ...opts, fresh: opts.freshScope === true });
|
|
1290
|
+
}
|
|
1291
|
+
return { ok: true, identity: null };
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// The repository in scope, in `owner/name`: a caller's explicit pin wins and
|
|
1295
|
+
// is validated before anything runs; otherwise gh's own answer is overridden
|
|
1296
|
+
// by the checkout's own repository (fork scope), which the injected resolver
|
|
1297
|
+
// proves. An unresolvable checkout fails closed instead of being replaced by
|
|
1298
|
+
// gh's base answer.
|
|
1299
|
+
async function repoNameWithOwner(opts = {}) {
|
|
1300
|
+
if (opts.scope !== undefined) {
|
|
1301
|
+
if (opts.scope === null || opts.scope === '') {
|
|
1302
|
+
const reported = await reportedRepoName(opts);
|
|
1303
|
+
if (reported.ok !== true) return reported;
|
|
1304
|
+
return { ok: true, nameWithOwner: reported.nameWithOwner, host: reported.host || '' };
|
|
1305
|
+
}
|
|
1306
|
+
const pinned = normalizeIdentity(opts.scope, opts.env || process.env);
|
|
1307
|
+
if (pinned.ok !== true) return { ok: false, error: pinned.error };
|
|
1308
|
+
return { ok: true, nameWithOwner: pinned.nameWithOwner, host: pinned.host };
|
|
1309
|
+
}
|
|
1310
|
+
const reported = await reportedRepoName(opts);
|
|
1311
|
+
if (reported.ok !== true) return reported;
|
|
1312
|
+
if (!namesCheckout(opts) || !checkoutScope) {
|
|
1313
|
+
return { ok: true, nameWithOwner: reported.nameWithOwner, host: reported.host || '' };
|
|
1314
|
+
}
|
|
1315
|
+
const scope = await checkoutScope(opts);
|
|
1316
|
+
if (scope.ok !== true) return { ok: false, error: scope.error };
|
|
1317
|
+
const host = hostOfIdentity(scope.identity) || reported.host || '';
|
|
1318
|
+
return { ok: true, nameWithOwner: scope.nameWithOwner || reported.nameWithOwner, host };
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
async function repository(opts) {
|
|
1322
|
+
const repo = await repoNameWithOwner(opts);
|
|
1323
|
+
if (!repo.ok) return repo;
|
|
1324
|
+
// An injected identity seam that answers without a usable name fails closed
|
|
1325
|
+
// here instead of throwing on it.
|
|
1326
|
+
const fullName = typeof repo.nameWithOwner === 'string' ? repo.nameWithOwner : '';
|
|
1327
|
+
const parts = fullName.split('/');
|
|
1328
|
+
if (parts.length !== 2 || !parts.every((part) => part && !/\s/.test(part))) {
|
|
1329
|
+
return { ok: false, error: 'GitHub returned an invalid repository name' };
|
|
1330
|
+
}
|
|
1331
|
+
return {
|
|
1332
|
+
ok: true,
|
|
1333
|
+
owner: parts[0],
|
|
1334
|
+
name: parts[1],
|
|
1335
|
+
fullName,
|
|
1336
|
+
host: typeof repo.host === 'string' ? repo.host : '',
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
async function graphql(query, fields, opts) {
|
|
1341
|
+
const argv = ['api', 'graphql', '-f', `query=${query}`];
|
|
1342
|
+
for (const [name, value] of Object.entries(fields)) {
|
|
1343
|
+
if (value !== null && value !== undefined) argv.push('-F', `${name}=${value}`);
|
|
1344
|
+
}
|
|
1345
|
+
const res = await runGh(argv, opts);
|
|
1346
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1347
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, 'GitHub query failed') };
|
|
1348
|
+
const parsed = parseJsonBody(res.stdout, 'GitHub query');
|
|
1349
|
+
if (!parsed.ok) return parsed;
|
|
1350
|
+
if (Array.isArray(parsed.doc?.errors) && parsed.doc.errors.length > 0) {
|
|
1351
|
+
return { ok: false, error: parsed.doc.errors[0]?.message || 'GitHub query failed' };
|
|
1352
|
+
}
|
|
1353
|
+
if (!parsed.doc?.data || typeof parsed.doc.data !== 'object') {
|
|
1354
|
+
return { ok: false, error: 'GitHub query returned no data' };
|
|
1355
|
+
}
|
|
1356
|
+
return { ok: true, data: parsed.doc.data };
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
async function readSearchBucket({ bucket, query, cursor, pageSize }, opts) {
|
|
1360
|
+
const repo = await repository(opts);
|
|
1361
|
+
if (!repo.ok) return repo;
|
|
1362
|
+
const qualifier = BUCKET_QUALIFIERS[bucket] || '';
|
|
1363
|
+
const text = typeof query === 'string' ? query.trim() : '';
|
|
1364
|
+
const search = withLastUpdatedSort([`repo:${repo.fullName}`, 'is:pr', 'is:open', qualifier, text]
|
|
1365
|
+
.filter((part) => part !== '')
|
|
1366
|
+
.join(' '));
|
|
1367
|
+
return readPages({
|
|
1368
|
+
cursor,
|
|
1369
|
+
pageSize,
|
|
1370
|
+
isSearch: true,
|
|
1371
|
+
runPage: (first, after) => graphql(SEARCH_PAGE_QUERY, { search, first, cursor: after }, opts),
|
|
1372
|
+
connectionOf: (data) => data.search,
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
async function readConnectionPage({ cursor, pageSize }, opts) {
|
|
1377
|
+
const repo = await repository(opts);
|
|
1378
|
+
if (!repo.ok) return repo;
|
|
1379
|
+
return readPages({
|
|
1380
|
+
cursor,
|
|
1381
|
+
pageSize,
|
|
1382
|
+
isSearch: false,
|
|
1383
|
+
runPage: (first, after) => graphql(CONNECTION_PAGE_QUERY, {
|
|
1384
|
+
owner: repo.owner, name: repo.name, first, cursor: after,
|
|
1385
|
+
}, opts),
|
|
1386
|
+
connectionOf: (data) => (data.repository && typeof data.repository === 'object'
|
|
1387
|
+
? data.repository.pullRequests
|
|
1388
|
+
: null),
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// The repo-level metadata read: the viewer's role, the allowed merge methods,
|
|
1393
|
+
// the draft fact and the linked issues with their truncation flag.
|
|
1394
|
+
async function getPullRequestMetadata(number, opts = {}) {
|
|
1395
|
+
const repo = await repository(opts);
|
|
1396
|
+
if (!repo.ok) return repo;
|
|
1397
|
+
const res = await graphql(PULL_REQUEST_METADATA_QUERY, {
|
|
1398
|
+
owner: repo.owner, name: repo.name, number,
|
|
1399
|
+
}, opts);
|
|
1400
|
+
if (res.ok !== true) return res;
|
|
1401
|
+
const entry = res.data.repository;
|
|
1402
|
+
if (!entry || typeof entry !== 'object' || !entry.pullRequest || typeof entry.pullRequest !== 'object') {
|
|
1403
|
+
return { ok: false, error: 'pull request metadata is unavailable' };
|
|
1404
|
+
}
|
|
1405
|
+
// S2/D5: the draft fact is a PRECONDITION of merging, so a read that does
|
|
1406
|
+
// not carry it is a failed read, never a "not a draft".
|
|
1407
|
+
if (typeof entry.pullRequest.isDraft !== 'boolean') {
|
|
1408
|
+
return { ok: false, error: 'pull request metadata is unavailable: the draft state is missing' };
|
|
1409
|
+
}
|
|
1410
|
+
const mergeMethods = {};
|
|
1411
|
+
for (const [flag, method] of [
|
|
1412
|
+
['mergeCommitAllowed', 'merge'],
|
|
1413
|
+
['squashMergeAllowed', 'squash'],
|
|
1414
|
+
['rebaseMergeAllowed', 'rebase'],
|
|
1415
|
+
]) {
|
|
1416
|
+
if (entry[flag] === true) mergeMethods[method] = true;
|
|
1417
|
+
}
|
|
1418
|
+
const references = entry.pullRequest.closingIssuesReferences;
|
|
1419
|
+
const nodes = references && typeof references === 'object' && Array.isArray(references.nodes)
|
|
1420
|
+
? references.nodes
|
|
1421
|
+
: null;
|
|
1422
|
+
// S2/D29 (S6): only the references that name THIS repository — or name none —
|
|
1423
|
+
// are this pane's click targets; the same rule the issue pane applies to its
|
|
1424
|
+
// linked pull requests, read the other way round.
|
|
1425
|
+
const linked = nodes === null
|
|
1426
|
+
? { readable: false, numbers: [] }
|
|
1427
|
+
: linkedIssueNumbers(sameRepositoryReferences(nodes, repo.fullName));
|
|
1428
|
+
return {
|
|
1429
|
+
ok: true,
|
|
1430
|
+
permission: typeof entry.viewerPermission === 'string' ? entry.viewerPermission : null,
|
|
1431
|
+
mergeMethods,
|
|
1432
|
+
isDraft: entry.pullRequest.isDraft === true,
|
|
1433
|
+
// S2/D20: the state rides the read that already round-trips, so a merge
|
|
1434
|
+
// of a pull request that is no longer open is refused before the child.
|
|
1435
|
+
state: typeof entry.pullRequest.state === 'string' ? entry.pullRequest.state : null,
|
|
1436
|
+
linkedIssues: linked.readable === true ? linked.numbers : null,
|
|
1437
|
+
linkedIssuesTruncated: linked.readable === true && references.pageInfo?.hasNextPage === true,
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
// S1: one page of one bucket. `mine`, `review` and `involved` are repository
|
|
1442
|
+
// SEARCHES; `all` is the repository connection, which carries an exact total
|
|
1443
|
+
// and pages past the search API's cap — a typed query in `all` stays a capped
|
|
1444
|
+
// search, exactly like the issues panel's lazy bucket. The answer is
|
|
1445
|
+
// `{rows, hasMore, cursor, totalCount}` for the panel's list.
|
|
1446
|
+
async function getPullRequestPage(params = {}, opts = {}) {
|
|
1447
|
+
const { params: p, options } = splitParams(params, opts);
|
|
1448
|
+
const bucket = p.bucket === undefined || p.bucket === null ? 'mine' : String(p.bucket);
|
|
1449
|
+
if (BUCKET_QUALIFIERS[bucket] === undefined && bucket !== 'all') {
|
|
1450
|
+
return { ok: false, error: `invalid bucket ${JSON.stringify(p.bucket)}: want mine, review, involved or all` };
|
|
1451
|
+
}
|
|
1452
|
+
const page = normalizePageRequest(p);
|
|
1453
|
+
if (page.ok !== true) return page;
|
|
1454
|
+
const query = typeof p.query === 'string' ? p.query : '';
|
|
1455
|
+
if (bucket === 'all' && query.trim() === '') {
|
|
1456
|
+
return readConnectionPage({ cursor: page.cursor, pageSize: page.pageSize }, options);
|
|
1457
|
+
}
|
|
1458
|
+
return readSearchBucket({ bucket, query, cursor: page.cursor, pageSize: page.pageSize }, options);
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
// S1: the lazy `all prs` connection, page for page.
|
|
1462
|
+
async function getPullRequestConnectionPage(params = {}, opts = {}) {
|
|
1463
|
+
const { params: p, options } = splitParams(params, opts);
|
|
1464
|
+
const page = normalizePageRequest(p);
|
|
1465
|
+
if (page.ok !== true) return page;
|
|
1466
|
+
return readConnectionPage({ cursor: page.cursor, pageSize: page.pageSize }, options);
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// S3: the detail read — the row plus the body, the change counts, the commit
|
|
1470
|
+
// count and date, the reviewers, the checks rollup, the merge facts and, with
|
|
1471
|
+
// `includeMetadata`, the capability map and the linked issues.
|
|
1472
|
+
async function getPullRequest(number, options = {}, opts = {}) {
|
|
1473
|
+
const { params: p, options: callOpts } = splitParams(options, opts);
|
|
1474
|
+
if (!Number.isInteger(number) || number < 1) {
|
|
1475
|
+
return {
|
|
1476
|
+
ok: false,
|
|
1477
|
+
error: `invalid pull request number ${JSON.stringify(number)}: want a positive integer`,
|
|
1478
|
+
status: null,
|
|
1479
|
+
notFound: false,
|
|
1480
|
+
};
|
|
1481
|
+
}
|
|
1482
|
+
const res = await runGh(['pr', 'view', String(number), '--json', DETAIL_JSON_FIELDS], callOpts);
|
|
1483
|
+
if (res.error) return { ok: false, error: res.error, status: null, notFound: false };
|
|
1484
|
+
if (res.status !== 0) return pullRequestViewFailure(res, number);
|
|
1485
|
+
const parsed = parseJsonBody(res.stdout, `gh pr view ${number}`);
|
|
1486
|
+
if (!parsed.ok) return parsed;
|
|
1487
|
+
if (!parsed.doc || typeof parsed.doc !== 'object' || typeof parsed.doc.number !== 'number') {
|
|
1488
|
+
return { ok: false, error: `gh pr view ${number} returned an unexpected shape` };
|
|
1489
|
+
}
|
|
1490
|
+
const rawComments = Array.isArray(parsed.doc.comments) ? parsed.doc.comments : [];
|
|
1491
|
+
const pullRequest = normalizePullRequestDetail(parsed.doc);
|
|
1492
|
+
const linkedReadable = linkedIssueNumbers(parsed.doc.closingIssuesReferences).readable === true;
|
|
1493
|
+
if (p.includeMetadata === true) {
|
|
1494
|
+
const metadata = await getPullRequestMetadata(number, callOpts);
|
|
1495
|
+
applyMetadata(pullRequest, metadata, linkedReadable);
|
|
1496
|
+
}
|
|
1497
|
+
return {
|
|
1498
|
+
ok: true,
|
|
1499
|
+
pullRequest,
|
|
1500
|
+
comments: rawComments.map((entry, index) => normalizeComment(entry, index)),
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// S5 (T4's read): ONE aliased GraphQL answers the rail's two buckets, each
|
|
1505
|
+
// with its EXACT `issueCount` and the linked issues of every row it carries.
|
|
1506
|
+
// `viewer` is accepted for interface symmetry with the panel seams; `@me` is
|
|
1507
|
+
// already the authenticated viewer, so nothing here needs the login.
|
|
1508
|
+
async function listRailPullRequests(options = {}, opts = {}) {
|
|
1509
|
+
const { params: p, options: callOpts } = splitParams(options, opts);
|
|
1510
|
+
const first = p.first === undefined || p.first === null ? RAIL_WINDOW_DEFAULT : p.first;
|
|
1511
|
+
if (!Number.isInteger(first) || first < 1 || first > RAIL_WINDOW_MAX) {
|
|
1512
|
+
return { ok: false, error: `invalid first ${JSON.stringify(p.first)}: want an integer 1..100` };
|
|
1513
|
+
}
|
|
1514
|
+
const repo = await repository(callOpts);
|
|
1515
|
+
if (!repo.ok) return repo;
|
|
1516
|
+
const res = await graphql(railQuery(repo.fullName, first), {}, callOpts);
|
|
1517
|
+
if (res.ok !== true) return res;
|
|
1518
|
+
const rows = {};
|
|
1519
|
+
const counts = {};
|
|
1520
|
+
for (const [alias] of RAIL_ALIAS_QUALIFIERS) {
|
|
1521
|
+
const connection = res.data ? res.data[alias] : null;
|
|
1522
|
+
if (!connection || typeof connection !== 'object' || Array.isArray(connection)
|
|
1523
|
+
|| !Number.isInteger(connection.issueCount) || connection.issueCount < 0
|
|
1524
|
+
|| !Array.isArray(connection.nodes)) {
|
|
1525
|
+
return { ok: false, error: 'gh api graphql returned an unexpected shape' };
|
|
1526
|
+
}
|
|
1527
|
+
const bucketRows = [];
|
|
1528
|
+
for (const node of connection.nodes) {
|
|
1529
|
+
if (!node || typeof node !== 'object' || !Number.isInteger(node.number) || node.number <= 0) {
|
|
1530
|
+
return { ok: false, error: 'gh api graphql returned a pull request without a number' };
|
|
1531
|
+
}
|
|
1532
|
+
const references = node.closingIssuesReferences && typeof node.closingIssuesReferences === 'object'
|
|
1533
|
+
? node.closingIssuesReferences.nodes
|
|
1534
|
+
: null;
|
|
1535
|
+
bucketRows.push({ number: node.number, linkedIssues: linkedIssueNumbers(references).numbers });
|
|
1536
|
+
}
|
|
1537
|
+
rows[alias] = bucketRows;
|
|
1538
|
+
counts[alias] = connection.issueCount;
|
|
1539
|
+
}
|
|
1540
|
+
return {
|
|
1541
|
+
ok: true,
|
|
1542
|
+
mine: rows.mine,
|
|
1543
|
+
review: rows.review,
|
|
1544
|
+
counts: { mine: counts.mine, review: counts.review },
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// S2/D13: ONE resolved repository scope per write. The role read and the write
|
|
1549
|
+
// it authorizes both run in it, and it is resolved exactly once, so a checkout
|
|
1550
|
+
// whose remote moves between the two children can never authorize one
|
|
1551
|
+
// repository and write under another. S2/D24: with no explicit pin and no
|
|
1552
|
+
// checkout, gh's ambient answer is resolved ONCE and pinned host-qualified, so
|
|
1553
|
+
// a default that moves mid-action cannot do the same.
|
|
1554
|
+
async function writeScopeFor(options) {
|
|
1555
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
1556
|
+
const resolved = await scopeForCall({ ...opts, freshScope: true });
|
|
1557
|
+
if (resolved.ok !== true) return { ok: false, error: resolved.error };
|
|
1558
|
+
const identity = resolved.identity || null;
|
|
1559
|
+
if (identity === null) {
|
|
1560
|
+
const ambient = await repository({ ...opts, freshScope: true });
|
|
1561
|
+
if (ambient.ok !== true) return ambient;
|
|
1562
|
+
// S2/D28: the host comes from the repository lookup itself; github.com is
|
|
1563
|
+
// the last resort, never the assumption.
|
|
1564
|
+
const host = ambient.host || provenHost({ ...opts, scope: undefined }) || 'github.com';
|
|
1565
|
+
const pinned = `${host}/${ambient.owner}/${ambient.name}`;
|
|
1566
|
+
return {
|
|
1567
|
+
ok: true,
|
|
1568
|
+
owner: ambient.owner,
|
|
1569
|
+
name: ambient.name,
|
|
1570
|
+
scope: pinned,
|
|
1571
|
+
// Every child of this write runs with that pin, never with an ambient
|
|
1572
|
+
// resolution it would otherwise repeat.
|
|
1573
|
+
options: withHostOptions({ ...opts, scope: pinned, freshScope: true }, host),
|
|
1574
|
+
};
|
|
1575
|
+
}
|
|
1576
|
+
const repo = await repository({ ...opts, freshScope: true, scope: identity });
|
|
1577
|
+
if (repo.ok !== true) return repo;
|
|
1578
|
+
const host = canonicalHost(identity.split('/')[0]);
|
|
1579
|
+
return {
|
|
1580
|
+
ok: true,
|
|
1581
|
+
owner: repo.owner,
|
|
1582
|
+
name: repo.name,
|
|
1583
|
+
scope: identity,
|
|
1584
|
+
// Every child of this write runs with that pin, never with an ambient
|
|
1585
|
+
// resolution it would otherwise repeat.
|
|
1586
|
+
options: withHostOptions({ ...opts, scope: identity, freshScope: true }, host),
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// S2/D2: the ONE repository-role read every write runs for itself, so a
|
|
1591
|
+
// capability that lapsed after the pane painted still fails closed here. It
|
|
1592
|
+
// answers the options its write must run with, so the role and the write share
|
|
1593
|
+
// ONE resolved scope (D13). With a pull request number it answers that pull
|
|
1594
|
+
// request's fresh state in the same round trip (D20).
|
|
1595
|
+
async function repositoryRole(opts, number = null) {
|
|
1596
|
+
const scope = await writeScopeFor(opts);
|
|
1597
|
+
if (scope.ok !== true) return { ok: false, error: scope.error };
|
|
1598
|
+
const named = Number.isInteger(number) && number > 0;
|
|
1599
|
+
const res = named
|
|
1600
|
+
? await graphql(REPOSITORY_WRITE_QUERY, { owner: scope.owner, name: scope.name, number }, scope.options)
|
|
1601
|
+
: await graphql(REPOSITORY_PERMISSION_QUERY, { owner: scope.owner, name: scope.name }, scope.options);
|
|
1602
|
+
if (res.ok !== true) return res;
|
|
1603
|
+
const entry = res.data.repository;
|
|
1604
|
+
if (!entry || typeof entry !== 'object') {
|
|
1605
|
+
return { ok: false, error: 'GitHub returned no repository permission' };
|
|
1606
|
+
}
|
|
1607
|
+
const pullRequest = entry.pullRequest && typeof entry.pullRequest === 'object' ? entry.pullRequest : null;
|
|
1608
|
+
return {
|
|
1609
|
+
ok: true,
|
|
1610
|
+
permission: typeof entry.viewerPermission === 'string' ? entry.viewerPermission : null,
|
|
1611
|
+
state: pullRequest && typeof pullRequest.state === 'string' ? pullRequest.state : null,
|
|
1612
|
+
options: scope.options,
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
// Repository-level label calls, mirrored from the issue client (they are not
|
|
1617
|
+
// issue-specific, and that module is injected here rather than required).
|
|
1618
|
+
const localListLabels = async (opts = {}) => {
|
|
1619
|
+
const res = await runGh(['label', 'list', '--limit', String(LABEL_FETCH_MAX), '--json', LABEL_JSON_FIELDS], opts);
|
|
1620
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1621
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, 'gh label list failed') };
|
|
1622
|
+
const parsed = parseJsonBody(res.stdout, 'gh label list');
|
|
1623
|
+
if (!parsed.ok) return parsed;
|
|
1624
|
+
if (!Array.isArray(parsed.doc)) return { ok: false, error: 'gh label list returned an unexpected shape' };
|
|
1625
|
+
return { ok: true, labels: parsed.doc.map(asLabel) };
|
|
1626
|
+
};
|
|
1627
|
+
|
|
1628
|
+
const localCreateLabel = async ({ name, color, description } = {}, opts = {}) => {
|
|
1629
|
+
if (typeof name !== 'string' || name.trim() === '') {
|
|
1630
|
+
return { ok: false, error: 'label name must be a non-empty string' };
|
|
1631
|
+
}
|
|
1632
|
+
const argv = ['label', 'create', name];
|
|
1633
|
+
if (typeof color === 'string' && color !== '') argv.push('--color', color);
|
|
1634
|
+
if (typeof description === 'string' && description !== '') argv.push('--description', description);
|
|
1635
|
+
const res = await runGh(argv, { ...(opts || {}), freshScope: true });
|
|
1636
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1637
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, `cannot create label ${name}`) };
|
|
1638
|
+
return { ok: true, label: { name, color: color || '', description: description || '' } };
|
|
1639
|
+
};
|
|
1640
|
+
|
|
1641
|
+
// S2/D2: creating a repository label is a write, so it reads the role before
|
|
1642
|
+
// it delegates (the injected issue client's own call does not gate it).
|
|
1643
|
+
const delegateCreateLabel = seam('createLabel', localCreateLabel);
|
|
1644
|
+
async function createLabel({ name, color, description } = {}, opts = {}) {
|
|
1645
|
+
const options = opts && typeof opts === 'object' ? opts : {};
|
|
1646
|
+
if (typeof name !== 'string' || name.trim() === '') {
|
|
1647
|
+
return { ok: false, error: 'label name must be a non-empty string' };
|
|
1648
|
+
}
|
|
1649
|
+
const role = await repositoryRole(options);
|
|
1650
|
+
if (role.ok !== true) return { ok: false, error: role.error };
|
|
1651
|
+
if (pullRequestPermissions(role.permission).canCreateLabels !== true) {
|
|
1652
|
+
return { ok: false, error: 'Repository permission does not allow creating labels' };
|
|
1653
|
+
}
|
|
1654
|
+
return delegateCreateLabel({ name, color, description }, role.options);
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
const localListAssignableUsers = async (opts = {}) => {
|
|
1658
|
+
const repo = await repository(opts);
|
|
1659
|
+
if (!repo.ok) return repo;
|
|
1660
|
+
const users = [];
|
|
1661
|
+
const logins = new Set();
|
|
1662
|
+
const cursors = new Set();
|
|
1663
|
+
let cursor = null;
|
|
1664
|
+
for (let page = 0; page < SNAPSHOT_MAX_PAGES; page += 1) {
|
|
1665
|
+
const res = await graphql(ASSIGNABLE_USERS_QUERY, { owner: repo.owner, name: repo.name, cursor }, opts);
|
|
1666
|
+
if (!res.ok) return res;
|
|
1667
|
+
const connection = res.data.repository?.assignableUsers;
|
|
1668
|
+
if (!Array.isArray(connection?.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean') {
|
|
1669
|
+
return { ok: false, error: 'GitHub returned an invalid assignable-user page' };
|
|
1670
|
+
}
|
|
1671
|
+
for (const user of connection.nodes) {
|
|
1672
|
+
if (typeof user?.login !== 'string' || !user.login) {
|
|
1673
|
+
return { ok: false, error: 'GitHub returned an invalid assignable user' };
|
|
1674
|
+
}
|
|
1675
|
+
const id = user.login.toLowerCase();
|
|
1676
|
+
if (!logins.has(id)) {
|
|
1677
|
+
logins.add(id);
|
|
1678
|
+
users.push({ login: user.login, name: typeof user.name === 'string' ? user.name : '' });
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
if (!connection.pageInfo.hasNextPage) return { ok: true, users };
|
|
1682
|
+
const next = connection.pageInfo.endCursor;
|
|
1683
|
+
if (typeof next !== 'string' || !next || cursors.has(next)) {
|
|
1684
|
+
return { ok: false, error: 'Assignable-user pagination did not advance' };
|
|
1685
|
+
}
|
|
1686
|
+
cursors.add(next);
|
|
1687
|
+
cursor = next;
|
|
1688
|
+
}
|
|
1689
|
+
return { ok: false, error: 'Assignable-user pagination exceeded its safety budget' };
|
|
1690
|
+
};
|
|
1691
|
+
|
|
1692
|
+
// Commenting stays ungated, exactly like the issue client: the capability map
|
|
1693
|
+
// gates closing, merging, labelling, assigning and the body edit, not a
|
|
1694
|
+
// comment.
|
|
1695
|
+
async function commentPullRequest(number, body, opts = {}) {
|
|
1696
|
+
if (!Number.isInteger(number) || number < 1) return invalidNumber(number);
|
|
1697
|
+
if (typeof body !== 'string' || body.trim() === '') {
|
|
1698
|
+
return { ok: false, error: 'comment body must be a non-empty string' };
|
|
1699
|
+
}
|
|
1700
|
+
const res = await runGh(['pr', 'comment', String(number), '--body', body], {
|
|
1701
|
+
...(opts || {}), freshScope: true,
|
|
1702
|
+
});
|
|
1703
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1704
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, `cannot comment on pull request #${number}`) };
|
|
1705
|
+
return { ok: true };
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
// Labels on a pull request go through the pull request surface, `gh pr edit`,
|
|
1709
|
+
// so the exact argv names the resource the panel is showing. S2/D2: the role
|
|
1710
|
+
// is read again here, so a lapsed capability never issues a write child.
|
|
1711
|
+
// S2/D31: that read names the pull request and its state, so a pull request
|
|
1712
|
+
// that is no longer OPEN loses its editor here as well (the panel's decision
|
|
1713
|
+
// paragraph: a non-open pull request keeps only its comment key).
|
|
1714
|
+
async function editLabels(number, changes = {}, opts = {}) {
|
|
1715
|
+
const options = opts && typeof opts === 'object' ? opts : {};
|
|
1716
|
+
if (!Number.isInteger(number) || number < 1) return invalidNumber(number);
|
|
1717
|
+
const additions = Array.isArray(changes?.add)
|
|
1718
|
+
? changes.add.filter((entry) => typeof entry === 'string' && entry !== '')
|
|
1719
|
+
: [];
|
|
1720
|
+
const removals = Array.isArray(changes?.remove)
|
|
1721
|
+
? changes.remove.filter((entry) => typeof entry === 'string' && entry !== '')
|
|
1722
|
+
: [];
|
|
1723
|
+
if (additions.length === 0 && removals.length === 0) return { ok: true };
|
|
1724
|
+
const role = await repositoryRole(options, number);
|
|
1725
|
+
if (role.ok !== true) return { ok: false, error: role.error };
|
|
1726
|
+
if (pullRequestPermissions(role.permission).canEditLabels !== true) {
|
|
1727
|
+
return { ok: false, error: 'Repository permission does not allow editing pull request labels' };
|
|
1728
|
+
}
|
|
1729
|
+
if (role.state !== 'OPEN') {
|
|
1730
|
+
return { ok: false, error: `pull request #${number} is not open; its labels cannot be edited` };
|
|
1731
|
+
}
|
|
1732
|
+
const argv = ['pr', 'edit', String(number)];
|
|
1733
|
+
for (const name of additions) argv.push('--add-label', name);
|
|
1734
|
+
for (const name of removals) argv.push('--remove-label', name);
|
|
1735
|
+
const res = await runGh(argv, role.options);
|
|
1736
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1737
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, `cannot edit labels on pull request #${number}`) };
|
|
1738
|
+
return { ok: true };
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
// The assignee toggle S2 describes: one delta that adds and removes at once,
|
|
1742
|
+
// so the same key both assigns and unassigns. `self` says whether the delta
|
|
1743
|
+
// names the authenticated viewer, whose own buckets the rail draws.
|
|
1744
|
+
async function editAssignees(number, changes = {}, opts = {}) {
|
|
1745
|
+
const options = opts && typeof opts === 'object' ? opts : {};
|
|
1746
|
+
const entry = changes && typeof changes === 'object' && !Array.isArray(changes) ? changes : null;
|
|
1747
|
+
const add = entry && Array.isArray(entry.add) ? entry.add : [];
|
|
1748
|
+
const remove = entry && Array.isArray(entry.remove) ? entry.remove : [];
|
|
1749
|
+
if (!Number.isInteger(number) || number < 1 || entry === null
|
|
1750
|
+
|| !add.every(isValidLogin) || !remove.every(isValidLogin)
|
|
1751
|
+
|| add.some((name) => remove.some((other) => name.toLowerCase() === other.toLowerCase()))) {
|
|
1752
|
+
return { ok: false, error: 'invalid assignee changes: supply distinct GitHub logins to add or remove' };
|
|
1753
|
+
}
|
|
1754
|
+
if (add.length === 0 && remove.length === 0) return { ok: true, changed: false, self: false };
|
|
1755
|
+
// S2/D13: the access read and the toggle it authorizes share ONE scope.
|
|
1756
|
+
// S2/D31: it names the pull request too, so its state rides the same round
|
|
1757
|
+
// trip and a non-open pull request keeps no assignee editor.
|
|
1758
|
+
const scope = await writeScopeFor(options);
|
|
1759
|
+
if (scope.ok !== true) return { ok: false, error: scope.error };
|
|
1760
|
+
const access = await graphql(
|
|
1761
|
+
ASSIGNEE_ACCESS_QUERY, { owner: scope.owner, name: scope.name, number }, scope.options,
|
|
1762
|
+
);
|
|
1763
|
+
if (access.ok !== true) return access;
|
|
1764
|
+
if (!pullRequestPermissions(access.data.repository?.viewerPermission).canEditAssignees) {
|
|
1765
|
+
return { ok: false, error: 'Repository permission does not allow changing pull request assignees' };
|
|
1766
|
+
}
|
|
1767
|
+
const state = access.data.repository?.pullRequest?.state;
|
|
1768
|
+
if (state !== 'OPEN') {
|
|
1769
|
+
return { ok: false, error: `pull request #${number} is not open; its assignees cannot be edited` };
|
|
1770
|
+
}
|
|
1771
|
+
const argv = ['pr', 'edit', String(number)];
|
|
1772
|
+
for (const name of new Set(add)) argv.push('--add-assignee', name);
|
|
1773
|
+
for (const name of new Set(remove)) argv.push('--remove-assignee', name);
|
|
1774
|
+
const res = await runGh(argv, scope.options);
|
|
1775
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1776
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, 'Cannot edit pull request assignees') };
|
|
1777
|
+
const viewer = access.data && access.data.viewer && typeof access.data.viewer.login === 'string'
|
|
1778
|
+
? access.data.viewer.login.toLowerCase()
|
|
1779
|
+
: '';
|
|
1780
|
+
const self = viewer !== '' && [...new Set([...add, ...remove])].some((name) => name.toLowerCase() === viewer);
|
|
1781
|
+
return { ok: true, changed: true, self };
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// S2/D2: closing is a write, so the repository role is read first and an
|
|
1785
|
+
// unpermitted viewer never reaches `gh pr close`. D13: the close runs in the
|
|
1786
|
+
// ONE scope that role read proved. D20: the same read answers the fresh state,
|
|
1787
|
+
// so a pull request that is no longer open is refused here as well.
|
|
1788
|
+
async function closePullRequest(number, opts = {}) {
|
|
1789
|
+
const options = opts && typeof opts === 'object' ? opts : {};
|
|
1790
|
+
if (!Number.isInteger(number) || number < 1) return invalidNumber(number);
|
|
1791
|
+
const role = await repositoryRole(options, number);
|
|
1792
|
+
if (role.ok !== true) return { ok: false, error: role.error };
|
|
1793
|
+
if (pullRequestPermissions(role.permission).canClosePullRequests !== true) {
|
|
1794
|
+
return { ok: false, error: 'Repository permission does not allow closing pull requests' };
|
|
1795
|
+
}
|
|
1796
|
+
if (role.state !== 'OPEN') {
|
|
1797
|
+
return { ok: false, error: `pull request #${number} is not open; it cannot be closed` };
|
|
1798
|
+
}
|
|
1799
|
+
const res = await runGh(['pr', 'close', String(number)], role.options);
|
|
1800
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1801
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, `cannot close pull request #${number}`) };
|
|
1802
|
+
return { ok: true };
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
// S2: merge, refusing every case the repository does not allow before any
|
|
1806
|
+
// merge child runs — an unknown method, a method the repository does not
|
|
1807
|
+
// allow, a draft pull request, or a viewer who may not merge.
|
|
1808
|
+
async function mergePullRequest(number, changes = {}, opts = {}) {
|
|
1809
|
+
const options = opts && typeof opts === 'object' ? opts : {};
|
|
1810
|
+
const entry = changes && typeof changes === 'object' && !Array.isArray(changes) ? changes : {};
|
|
1811
|
+
if (!Number.isInteger(number) || number < 1) return invalidNumber(number);
|
|
1812
|
+
const method = entry.method;
|
|
1813
|
+
if (typeof method !== 'string' || MERGE_FLAGS[method] === undefined) {
|
|
1814
|
+
return { ok: false, error: `invalid merge method ${JSON.stringify(method)}: want merge, squash or rebase` };
|
|
1815
|
+
}
|
|
1816
|
+
// S2/D5: a field the caller CLEARED is not a field the caller omitted. An
|
|
1817
|
+
// empty description is sent empty; an empty commit message is refused, since
|
|
1818
|
+
// GitHub would replace it with its own proposal behind the reader's back.
|
|
1819
|
+
// A rebase merge takes neither field, so neither is inspected.
|
|
1820
|
+
const given = (key) => Object.prototype.hasOwnProperty.call(entry, key);
|
|
1821
|
+
if (method !== 'rebase' && given('subject') && !(typeof entry.subject === 'string' && entry.subject.trim() !== '')) {
|
|
1822
|
+
return { ok: false, error: 'the merge commit message must not be empty' };
|
|
1823
|
+
}
|
|
1824
|
+
// S2/D13: the metadata read is this write's role read, and it runs in the ONE
|
|
1825
|
+
// scope the merge child will run in.
|
|
1826
|
+
const scope = await writeScopeFor(options);
|
|
1827
|
+
if (scope.ok !== true) return { ok: false, error: scope.error };
|
|
1828
|
+
const metadata = await getPullRequestMetadata(number, scope.options);
|
|
1829
|
+
if (metadata.ok !== true) return { ok: false, error: metadata.error };
|
|
1830
|
+
const allowed = allowedMergeMethods(metadata.mergeMethods);
|
|
1831
|
+
if (allowed.includes(method) !== true) {
|
|
1832
|
+
if (allowed.length === 0) {
|
|
1833
|
+
return { ok: false, error: `the repository allows no merge method for pull request #${number}` };
|
|
1834
|
+
}
|
|
1835
|
+
return {
|
|
1836
|
+
ok: false,
|
|
1837
|
+
error: `the repository does not allow the ${JSON.stringify(method)} merge method (allowed: ${allowed.join(', ')})`,
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
if (metadata.isDraft === true) {
|
|
1841
|
+
return { ok: false, error: `pull request #${number} is a draft; it cannot be merged` };
|
|
1842
|
+
}
|
|
1843
|
+
if (metadata.state !== 'OPEN') {
|
|
1844
|
+
return { ok: false, error: `pull request #${number} is not open; it cannot be merged` };
|
|
1845
|
+
}
|
|
1846
|
+
const mergeable = pullRequestPermissions(metadata.permission, {
|
|
1847
|
+
isDraft: metadata.isDraft === true,
|
|
1848
|
+
mergeMethods: metadata.mergeMethods,
|
|
1849
|
+
});
|
|
1850
|
+
if (mergeable.canMerge !== true) {
|
|
1851
|
+
return { ok: false, error: 'Repository permission does not allow merging pull requests' };
|
|
1852
|
+
}
|
|
1853
|
+
const argv = ['pr', 'merge', String(number), MERGE_FLAGS[method]];
|
|
1854
|
+
// A rebase merge replays the commits it rewrites, so it takes neither a
|
|
1855
|
+
// subject nor a body: the proposals mean nothing there.
|
|
1856
|
+
if (method !== 'rebase') {
|
|
1857
|
+
if (given('subject')) argv.push('--subject', entry.subject);
|
|
1858
|
+
if (given('body') && typeof entry.body === 'string') argv.push('--body', entry.body);
|
|
1859
|
+
}
|
|
1860
|
+
const res = await runGh(argv, scope.options);
|
|
1861
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1862
|
+
if (res.status !== 0) return { ok: false, error: exitError(res, `cannot merge pull request #${number}`) };
|
|
1863
|
+
return { ok: true, method };
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
// S2: the Development relation. GitHub has no mutation for it, so the body is
|
|
1867
|
+
// read, the closing lines are rewritten and the body is written back — with
|
|
1868
|
+
// every other byte preserved.
|
|
1869
|
+
async function editLinkedIssues(number, changes = {}, opts = {}) {
|
|
1870
|
+
const options = opts && typeof opts === 'object' ? opts : {};
|
|
1871
|
+
const entry = changes && typeof changes === 'object' && !Array.isArray(changes) ? changes : null;
|
|
1872
|
+
const add = entry && Array.isArray(entry.add) ? entry.add : [];
|
|
1873
|
+
const remove = entry && Array.isArray(entry.remove) ? entry.remove : [];
|
|
1874
|
+
const positive = (values) => values.every((value) => Number.isInteger(value) && value > 0);
|
|
1875
|
+
if (!Number.isInteger(number) || number < 1 || entry === null
|
|
1876
|
+
|| !positive(add) || !positive(remove)
|
|
1877
|
+
|| add.some((value) => remove.includes(value))) {
|
|
1878
|
+
return { ok: false, error: 'invalid linked-issue changes: supply distinct positive issue numbers' };
|
|
1879
|
+
}
|
|
1880
|
+
if (add.length === 0 && remove.length === 0) return { ok: true, changed: false, body: null };
|
|
1881
|
+
// S2/D2: the body edit is a write, so the role is read first; D20: that read
|
|
1882
|
+
// also answers whether the pull request is still open.
|
|
1883
|
+
const role = await repositoryRole(options, number);
|
|
1884
|
+
if (role.ok !== true) return { ok: false, error: role.error };
|
|
1885
|
+
if (pullRequestPermissions(role.permission).canEditLinkedIssues !== true) {
|
|
1886
|
+
return { ok: false, error: 'Repository permission does not allow editing pull request linked issues' };
|
|
1887
|
+
}
|
|
1888
|
+
if (role.state !== 'OPEN') {
|
|
1889
|
+
return { ok: false, error: `pull request #${number} is not open; its linked issues cannot be edited` };
|
|
1890
|
+
}
|
|
1891
|
+
const view = await runGh(['pr', 'view', String(number), '--json', 'body'], role.options);
|
|
1892
|
+
if (view.error) return { ok: false, error: view.error };
|
|
1893
|
+
if (view.status !== 0) {
|
|
1894
|
+
return { ok: false, error: exitError(view, `cannot read the body of pull request #${number}`) };
|
|
1895
|
+
}
|
|
1896
|
+
const parsed = parseJsonBody(view.stdout, `gh pr view ${number}`);
|
|
1897
|
+
if (parsed.ok !== true) return parsed;
|
|
1898
|
+
const body = parsed.doc && typeof parsed.doc.body === 'string' ? parsed.doc.body : null;
|
|
1899
|
+
if (body === null) return { ok: false, error: `gh pr view ${number} returned an unexpected shape` };
|
|
1900
|
+
const next = rewriteClosingLines(body, add, remove);
|
|
1901
|
+
// S2/D27: a body whose fences or comments do not pair up is refused outright
|
|
1902
|
+
// (add or remove alike) instead of being interpreted.
|
|
1903
|
+
if (next.refused !== undefined) return { ok: false, error: next.refused };
|
|
1904
|
+
if (next.body === body) return { ok: true, changed: false, body };
|
|
1905
|
+
// S2/D27: the body is read AGAIN immediately before the write and compared
|
|
1906
|
+
// with the read the edit was prepared from, so an author's edit that landed
|
|
1907
|
+
// in between is never overwritten.
|
|
1908
|
+
// S2/T18: that last read answers the pull request STATE with the body, so a
|
|
1909
|
+
// pull request closed or merged during the reads is refused here instead of
|
|
1910
|
+
// being written after the fact. A re-read that proves neither refuses too:
|
|
1911
|
+
// a missing fact never counts as "still open".
|
|
1912
|
+
const again = await runGh(['pr', 'view', String(number), '--json', 'body,state'], role.options);
|
|
1913
|
+
if (again.error) return { ok: false, error: again.error };
|
|
1914
|
+
if (again.status !== 0) {
|
|
1915
|
+
return { ok: false, error: exitError(again, `cannot read the body of pull request #${number}`) };
|
|
1916
|
+
}
|
|
1917
|
+
const reread = parseJsonBody(again.stdout, `gh pr view ${number}`);
|
|
1918
|
+
if (reread.ok !== true) return reread;
|
|
1919
|
+
const current = reread.doc && typeof reread.doc.body === 'string' ? reread.doc.body : null;
|
|
1920
|
+
const currentState = reread.doc && typeof reread.doc.state === 'string' ? reread.doc.state : null;
|
|
1921
|
+
if (current === null || currentState === null) {
|
|
1922
|
+
return { ok: false, error: `gh pr view ${number} returned an unexpected shape` };
|
|
1923
|
+
}
|
|
1924
|
+
if (currentState !== 'OPEN') {
|
|
1925
|
+
return { ok: false, error: `pull request #${number} is not open; its linked issues cannot be edited` };
|
|
1926
|
+
}
|
|
1927
|
+
// The comparison stays exact: one byte of difference is an author's edit.
|
|
1928
|
+
if (current !== body) return { ok: false, error: BODY_CHANGED };
|
|
1929
|
+
const res = await runGh(['pr', 'edit', String(number), '--body', next.body], role.options);
|
|
1930
|
+
if (res.error) return { ok: false, error: res.error };
|
|
1931
|
+
if (res.status !== 0) {
|
|
1932
|
+
return { ok: false, error: exitError(res, `cannot edit the body of pull request #${number}`) };
|
|
1933
|
+
}
|
|
1934
|
+
return { ok: true, changed: true, body: next.body };
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
return {
|
|
1938
|
+
setGhRunner(fn) {
|
|
1939
|
+
setGhRunner(fn);
|
|
1940
|
+
forwardRunner(supplied);
|
|
1941
|
+
},
|
|
1942
|
+
normalizeScopeIdentity: normalizeIdentity,
|
|
1943
|
+
pullRequestPermissions,
|
|
1944
|
+
getPullRequestPage,
|
|
1945
|
+
getPullRequestConnectionPage,
|
|
1946
|
+
getPullRequest,
|
|
1947
|
+
getPullRequestMetadata,
|
|
1948
|
+
commentPullRequest,
|
|
1949
|
+
listLabels: seam('listLabels', localListLabels),
|
|
1950
|
+
createLabel,
|
|
1951
|
+
editLabels,
|
|
1952
|
+
listAssignableUsers: seam('listAssignableUsers', localListAssignableUsers),
|
|
1953
|
+
editAssignees,
|
|
1954
|
+
closePullRequest,
|
|
1955
|
+
mergePullRequest,
|
|
1956
|
+
editLinkedIssues,
|
|
1957
|
+
listRailPullRequests,
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
// ---------------------------------------------------------------------------
|
|
1962
|
+
// Binding: the extension injects its own issue client once and every
|
|
1963
|
+
// convenience export below delegates to the client bound to it.
|
|
1964
|
+
// ---------------------------------------------------------------------------
|
|
1965
|
+
|
|
1966
|
+
const CLIENT_FUNCTIONS = [
|
|
1967
|
+
'getPullRequestPage',
|
|
1968
|
+
'getPullRequestConnectionPage',
|
|
1969
|
+
'getPullRequest',
|
|
1970
|
+
'getPullRequestMetadata',
|
|
1971
|
+
'commentPullRequest',
|
|
1972
|
+
'listLabels',
|
|
1973
|
+
'createLabel',
|
|
1974
|
+
'editLabels',
|
|
1975
|
+
'listAssignableUsers',
|
|
1976
|
+
'editAssignees',
|
|
1977
|
+
'closePullRequest',
|
|
1978
|
+
'mergePullRequest',
|
|
1979
|
+
'editLinkedIssues',
|
|
1980
|
+
'listRailPullRequests',
|
|
1981
|
+
];
|
|
1982
|
+
|
|
1983
|
+
// Bind the injected issue client and answer the client bound to it.
|
|
1984
|
+
function bindIssuesClient(issues) {
|
|
1985
|
+
boundIssues = issues && typeof issues === 'object' ? issues : null;
|
|
1986
|
+
boundClient = createPrsClient({ issues: boundIssues });
|
|
1987
|
+
forwardRunner(boundIssues);
|
|
1988
|
+
return boundClient;
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
function bound() {
|
|
1992
|
+
if (boundClient === null) {
|
|
1993
|
+
boundClient = createPrsClient({ issues: boundIssues });
|
|
1994
|
+
forwardRunner(boundIssues);
|
|
1995
|
+
}
|
|
1996
|
+
return boundClient;
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
const exported = {
|
|
2000
|
+
createPrsClient,
|
|
2001
|
+
bindIssuesClient,
|
|
2002
|
+
setGhRunner,
|
|
2003
|
+
normalizeScopeIdentity,
|
|
2004
|
+
pullRequestPermissions,
|
|
2005
|
+
};
|
|
2006
|
+
|
|
2007
|
+
for (const name of CLIENT_FUNCTIONS) {
|
|
2008
|
+
exported[name] = (...args) => bound()[name](...args);
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
module.exports = exported;
|