@eduardo191labs/opencode-actions 0.1.2 → 0.1.3
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/README.md +192 -5
- package/action.yml +18 -0
- package/dist/actions.d.ts +266 -68
- package/dist/actions.js +134 -24
- package/dist/app-auth.d.ts +70 -0
- package/dist/app-auth.js +137 -0
- package/dist/cli.js +34 -3
- package/dist/commands.d.ts +3 -1
- package/dist/commands.js +59 -19
- package/dist/config.d.ts +5 -1
- package/dist/config.js +1 -1
- package/dist/detect.d.ts +37 -4
- package/dist/detect.js +101 -138
- package/dist/format.d.ts +3 -1
- package/dist/format.js +5 -2
- package/dist/git.d.ts +16 -0
- package/dist/git.js +23 -1
- package/dist/github.d.ts +9 -1
- package/dist/implement.d.ts +116 -0
- package/dist/implement.js +192 -0
- package/dist/install.js +195 -20
- package/dist/signals.d.ts +134 -0
- package/dist/signals.js +117 -0
- package/dist/summary.js +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Copilot workflow: an issue becomes a working branch and a pull request
|
|
3
|
+
* that keeps being edited until it is merged.
|
|
4
|
+
*
|
|
5
|
+
* The shape matters. Copilot's value is not that it writes a patch once; it is
|
|
6
|
+
* that the patch lives on a branch where the author can ask for another pass,
|
|
7
|
+
* commit to it, and merge it when it is right. This module keeps that state in
|
|
8
|
+
* the pull request itself rather than in the runner, because a run is over in
|
|
9
|
+
* minutes and the conversation is not.
|
|
10
|
+
*
|
|
11
|
+
* Everything here is opt-in through permissions: creating a branch needs
|
|
12
|
+
* `manage_branches`, editing a PR needs `manage_pull_requests`, merging needs
|
|
13
|
+
* `merge_pull_requests` (or `merge_protected` on a protected base).
|
|
14
|
+
*/
|
|
15
|
+
import { bot as botLayer, permission } from "./config.js";
|
|
16
|
+
import { assertBranchWrites, assertWorkflowWrites, commitAll, git, push, state } from "./git.js";
|
|
17
|
+
/**
|
|
18
|
+
* A branch name that identifies the issue and survives a second run.
|
|
19
|
+
*
|
|
20
|
+
* Stable matters: a follow-up command must commit onto the *same* branch, or
|
|
21
|
+
* the author ends up with four pull requests for one issue. The issue number is
|
|
22
|
+
* the only part that cannot change, so it leads.
|
|
23
|
+
*/
|
|
24
|
+
export function workBranch(config, issueNumber, title) {
|
|
25
|
+
const prefix = botLayer(config).work_branch_prefix ?? "opencode/";
|
|
26
|
+
const slug = title
|
|
27
|
+
.toLowerCase()
|
|
28
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
29
|
+
.replace(/^-+|-+$/g, "")
|
|
30
|
+
.slice(0, 40)
|
|
31
|
+
.replace(/-+$/g, "");
|
|
32
|
+
return `${prefix}issue-${issueNumber}${slug ? `-${slug}` : ""}`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The commit trailer that ties a branch back to its issue.
|
|
36
|
+
*
|
|
37
|
+
* Used instead of a runner-side store: the branch and the PR are durable, the
|
|
38
|
+
* runner is not. It is also how a later run finds the issue without being told.
|
|
39
|
+
*/
|
|
40
|
+
export function issueTrailer(issueNumber) {
|
|
41
|
+
return `Refs #${issueNumber}`;
|
|
42
|
+
}
|
|
43
|
+
/** Extract the issue a branch or PR belongs to, from a name or a trailer. */
|
|
44
|
+
export function issueFromText(text) {
|
|
45
|
+
const byName = /issue-(\d+)/.exec(text);
|
|
46
|
+
if (byName)
|
|
47
|
+
return Number(byName[1]);
|
|
48
|
+
const byRef = /\b(?:refs|closes|fixes|resolves)\s+#(\d+)/i.exec(text);
|
|
49
|
+
return byRef ? Number(byRef[1]) : null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create or reuse the working branch, let the agent write the change, and open a
|
|
53
|
+
* PR whose body is generated from the actual diff.
|
|
54
|
+
*
|
|
55
|
+
* Reuse is the point: `implement` on an issue twice must not produce two
|
|
56
|
+
* branches. The existing branch is checked out by name on the base and the agent
|
|
57
|
+
* works on top of it.
|
|
58
|
+
*/
|
|
59
|
+
export async function implementIssue(ctx, options, run) {
|
|
60
|
+
const { github, repo, config } = ctx;
|
|
61
|
+
const base = botLayer(config).base_branch ?? "main";
|
|
62
|
+
const branch = workBranch(config, options.issueNumber, options.title);
|
|
63
|
+
if (permission(config, "manage_branches") !== "allow") {
|
|
64
|
+
return { rejected: "manage_branches is not allowed" };
|
|
65
|
+
}
|
|
66
|
+
assertBranchWrites(config, branch);
|
|
67
|
+
const existing = await findPullForBranch(github, repo, branch);
|
|
68
|
+
const prompt = implementPrompt(options, branch, base, existing ? existing.number : null);
|
|
69
|
+
const result = await run(prompt);
|
|
70
|
+
const current = await state(ctx.workspace);
|
|
71
|
+
if (!current.dirty) {
|
|
72
|
+
return { unchanged: true, branch, pr: existing ? existing.number : null, text: result.text };
|
|
73
|
+
}
|
|
74
|
+
assertWorkflowWrites(config, current.changedFiles);
|
|
75
|
+
// The commit message carries the issue, so a later run can find it again
|
|
76
|
+
// without being told which issue the branch belongs to.
|
|
77
|
+
const commit = await commitAll(ctx.workspace, `${result.resultJson?.commit_message ?? `feat: address #${options.issueNumber}`}\n\n${issueTrailer(options.issueNumber)}`, config);
|
|
78
|
+
if (!commit)
|
|
79
|
+
return { unchanged: true, branch };
|
|
80
|
+
await ensureBranch(github, repo, branch, base, ctx.workspace, config);
|
|
81
|
+
const body = pullBody(options, result.resultJson, result.text);
|
|
82
|
+
if (existing) {
|
|
83
|
+
// A follow-up pass edits the same PR: the description describes the diff as
|
|
84
|
+
// it is now, and the title follows the change rather than the first draft.
|
|
85
|
+
if (permission(config, "manage_pull_requests") === "allow") {
|
|
86
|
+
await github.updatePull(repo, existing.number, {
|
|
87
|
+
body,
|
|
88
|
+
title: (result.resultJson?.pr_title ?? options.title).slice(0, 200),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return { branch, pr: existing.number, updated: true, model: result.model, cost: result.cost };
|
|
92
|
+
}
|
|
93
|
+
const pull = await github.createPull(repo, {
|
|
94
|
+
title: (result.resultJson?.pr_title ?? options.title).slice(0, 200),
|
|
95
|
+
head: branch,
|
|
96
|
+
base,
|
|
97
|
+
body,
|
|
98
|
+
draft: false,
|
|
99
|
+
});
|
|
100
|
+
ctx.log(`opened PR #${pull.number} for #${options.issueNumber}`);
|
|
101
|
+
if (permission(config, "comment") === "allow" && options.requestId) {
|
|
102
|
+
await github
|
|
103
|
+
.comment(repo, options.issueNumber, `Working on this in #${pull.number}, on branch \`${branch}\`.`)
|
|
104
|
+
.catch(() => { });
|
|
105
|
+
}
|
|
106
|
+
return { branch, pr: pull.number, model: result.model, cost: result.cost };
|
|
107
|
+
}
|
|
108
|
+
/** The PR a branch already has open, if any. */
|
|
109
|
+
export async function findPullForBranch(github, repo, branch) {
|
|
110
|
+
const pulls = await github.paginate(`/repos/${repo.owner}/${repo.repo}/pulls?state=open&head=${repo.owner}:${branch}&per_page=10`, 1);
|
|
111
|
+
const first = pulls[0];
|
|
112
|
+
return first ? { number: first.number, url: first.html_url } : null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Check the branch out locally and push the commit that is already staged.
|
|
116
|
+
*
|
|
117
|
+
* The branch may exist from a previous run, in which case it is fetched rather
|
|
118
|
+
* than recreated: recreating at the base would discard the earlier work.
|
|
119
|
+
*/
|
|
120
|
+
async function ensureBranch(github, repo, branch, base, workspace, config) {
|
|
121
|
+
const exists = await github.getRef(repo, branch).catch(() => null);
|
|
122
|
+
if (exists) {
|
|
123
|
+
// A previous pass left work here. Rebasing onto it keeps that work; resetting
|
|
124
|
+
// to the base would throw it away and make the second run a regression.
|
|
125
|
+
await git(workspace, ["fetch", "origin", branch, "--depth", "1"]).catch(() => null);
|
|
126
|
+
await git(workspace, ["rebase", "FETCH_HEAD"]).catch(async () => {
|
|
127
|
+
await git(workspace, ["rebase", "--abort"]).catch(() => null);
|
|
128
|
+
await git(workspace, ["reset", "--soft", "FETCH_HEAD"]).catch(() => null);
|
|
129
|
+
await commitAll(workspace, `chore: reapply on ${branch}`, config);
|
|
130
|
+
});
|
|
131
|
+
await git(workspace, ["checkout", "-B", branch]).catch(() => null);
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
const head = await github.getRef(repo, base);
|
|
135
|
+
await github.createRef(repo, branch, head.object.sha).catch(() => null);
|
|
136
|
+
await git(workspace, ["checkout", "-B", branch]).catch(() => null);
|
|
137
|
+
}
|
|
138
|
+
await push(workspace, branch, config);
|
|
139
|
+
}
|
|
140
|
+
function pullBody(options, json, text) {
|
|
141
|
+
const summary = json?.summary ?? text.trim();
|
|
142
|
+
const changes = Array.isArray(json?.changes) && json.changes.length ? json.changes.map((c) => `- ${c}`).join("\n") : "";
|
|
143
|
+
const tests = json?.tests ? `\n## Tests\n\n${json.tests}\n` : "";
|
|
144
|
+
return [
|
|
145
|
+
`Closes #${options.issueNumber}`,
|
|
146
|
+
"",
|
|
147
|
+
summary || `Implements #${options.issueNumber}.`,
|
|
148
|
+
changes ? `\n## What changed\n\n${changes}` : "",
|
|
149
|
+
tests,
|
|
150
|
+
"\n---\nGenerated by the bot from the issue. Push to this branch, or ask for another pass, and the description is rewritten from the diff.",
|
|
151
|
+
]
|
|
152
|
+
.filter(Boolean)
|
|
153
|
+
.join("\n");
|
|
154
|
+
}
|
|
155
|
+
function implementPrompt(options, branch, base, prNumber) {
|
|
156
|
+
return `# Task: implement issue #${options.issueNumber}
|
|
157
|
+
|
|
158
|
+
Branch: \`${branch}\` (already checked out; the base is \`${base}\`)
|
|
159
|
+
${prNumber ? `Pull request: #${prNumber} (open — this is another pass on the same work)` : ""}
|
|
160
|
+
|
|
161
|
+
## Issue
|
|
162
|
+
|
|
163
|
+
**${options.title}**
|
|
164
|
+
|
|
165
|
+
${options.body.slice(0, 8000)}
|
|
166
|
+
|
|
167
|
+
## What to do
|
|
168
|
+
|
|
169
|
+
1. Read the code this issue is about before changing anything. If the issue is
|
|
170
|
+
wrong or already fixed, say so and change nothing.
|
|
171
|
+
2. Make the smallest change that resolves it. Follow the existing style; do not
|
|
172
|
+
reformat unrelated code.
|
|
173
|
+
3. Run the project's tests or build if one exists and the issue affects it.
|
|
174
|
+
|
|
175
|
+
## Output
|
|
176
|
+
|
|
177
|
+
Reply with JSON only:
|
|
178
|
+
|
|
179
|
+
\`\`\`json
|
|
180
|
+
{
|
|
181
|
+
"fixable": true,
|
|
182
|
+
"summary": "two or three sentences on what the issue was and what you changed",
|
|
183
|
+
"pr_title": "a pull request title in conventional-commits form",
|
|
184
|
+
"commit_message": "the commit subject line",
|
|
185
|
+
"changes": ["src/file.ts: what changed and why"],
|
|
186
|
+
"tests": "what you ran and what it said, or an explanation of why nothing could be run"
|
|
187
|
+
}
|
|
188
|
+
\`\`\`
|
|
189
|
+
|
|
190
|
+
If the issue cannot be resolved without a decision only a person can make, set
|
|
191
|
+
"fixable": false and put the question in "summary".`;
|
|
192
|
+
}
|
package/dist/install.js
CHANGED
|
@@ -7,26 +7,66 @@
|
|
|
7
7
|
* For each repository it:
|
|
8
8
|
* 1. detects the stack (so the config can pick test/build commands),
|
|
9
9
|
* 2. skips archived, disabled and forked repositories,
|
|
10
|
-
* 3. writes the
|
|
10
|
+
* 3. writes the five workflows, one per event, replacing only files it owns,
|
|
11
11
|
* 4. copies FREEPI_JWT from the user's environment into the repository secret,
|
|
12
12
|
* 5. enables the permissions the workflows declare.
|
|
13
13
|
*
|
|
14
14
|
* Re-running is idempotent: the workflows carry a marker, and a file that lacks
|
|
15
15
|
* the marker is never overwritten.
|
|
16
|
+
*
|
|
17
|
+
* With GitHub App credentials in the environment, discovery goes through
|
|
18
|
+
* `/installation/repositories` instead of the account's repository list, so a
|
|
19
|
+
* repository created after the app was installed is found on the next run.
|
|
16
20
|
*/
|
|
17
21
|
import { createRequire } from "node:module";
|
|
18
22
|
import { GitHub, parseRepo } from "./github.js";
|
|
19
23
|
import { detect, workflowTemplates } from "./detect.js";
|
|
24
|
+
import { SKIP_CI } from "./git.js";
|
|
25
|
+
import { appCredentialsFromEnv, appJwt, findInstallation, installationRepos, installationToken, } from "./app-auth.js";
|
|
20
26
|
const MARKER = "uses: eduardo191-star/opencode-actions@";
|
|
27
|
+
/** `[skip ci]` on the subject line, which every workflow reads. */
|
|
28
|
+
function withSkipCi(message) {
|
|
29
|
+
const subject = message.split("\n")[0] ?? message;
|
|
30
|
+
if (subject.includes(SKIP_CI))
|
|
31
|
+
return message;
|
|
32
|
+
return `${subject} ${SKIP_CI}${message.slice(subject.length)}`;
|
|
33
|
+
}
|
|
21
34
|
async function main() {
|
|
22
35
|
const options = parseArgs(process.argv.slice(2));
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
36
|
+
// The app credentials are the same for every repository, so they are read
|
|
37
|
+
// once. Missing ones are simply not written: the repository then falls back
|
|
38
|
+
// to the token its workflow already receives.
|
|
39
|
+
const appId = process.env.OPENCODE_APP_ID ?? "";
|
|
40
|
+
const appKey = process.env.OPENCODE_APP_PRIVATE_KEY ?? "";
|
|
41
|
+
if (appId && appKey) {
|
|
42
|
+
options.extraSecrets = [
|
|
43
|
+
{ name: "OPENCODE_APP_ID", value: appId.trim() },
|
|
44
|
+
{ name: "OPENCODE_APP_PRIVATE_KEY", value: appKey.trim() },
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
const app = appCredentialsFromEnv();
|
|
48
|
+
// Two different credentials are in play and they are not interchangeable:
|
|
49
|
+
// the app JWT can only ask the app about itself (installations, tokens), so
|
|
50
|
+
// it lists repositories; the installation token is the one that writes to a
|
|
51
|
+
// repository. Using the JWT for writes is a guaranteed 403.
|
|
52
|
+
const appJwtClient = app ? new GitHub({ token: appJwt(app) }) : null;
|
|
53
|
+
const discovery = appJwtClient ?? new GitHub({ token: options.token });
|
|
54
|
+
const repos = await selectRepos(discovery, options, app);
|
|
55
|
+
console.error(`→ ${repos.length} repositories selected (${app ? "GitHub App" : "account token"})`);
|
|
56
|
+
/** The client that may write into `ref`: an installation token when using the app. */
|
|
57
|
+
const writerFor = async (ref) => {
|
|
58
|
+
if (!app || !appJwtClient)
|
|
59
|
+
return new GitHub({ token: options.token });
|
|
60
|
+
const installation = await findInstallation(appJwtClient, ref.owner, ref.repo);
|
|
61
|
+
if (!installation)
|
|
62
|
+
throw new Error(`the app is not installed on ${ref.owner}/${ref.repo}`);
|
|
63
|
+
return new GitHub({ token: (await installationToken(app, installation.id)).token });
|
|
64
|
+
};
|
|
26
65
|
const results = [];
|
|
27
66
|
for (const ref of repos) {
|
|
28
67
|
const name = `${ref.owner}/${ref.repo}`;
|
|
29
68
|
try {
|
|
69
|
+
const github = await writerFor(ref);
|
|
30
70
|
const found = await detect(github, ref);
|
|
31
71
|
const reason = skipReason(found, options);
|
|
32
72
|
if (reason) {
|
|
@@ -43,6 +83,11 @@ async function main() {
|
|
|
43
83
|
actionRef: options.actionRef,
|
|
44
84
|
stack: found.stack,
|
|
45
85
|
});
|
|
86
|
+
if (options.auto && found.installed) {
|
|
87
|
+
results.push({ repo: name, action: "skipped", detail: "already installed" });
|
|
88
|
+
console.error(`· ${name}: already installed`);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
46
91
|
if (options.dryRun) {
|
|
47
92
|
results.push({ repo: name, action: "dry-run", detail: workflows.map((w) => w.path).join(", ") });
|
|
48
93
|
console.error(` would write ${workflows.length} workflows`);
|
|
@@ -50,6 +95,7 @@ async function main() {
|
|
|
50
95
|
}
|
|
51
96
|
let written = 0;
|
|
52
97
|
let skipped = 0;
|
|
98
|
+
let removed = [];
|
|
53
99
|
for (const workflow of workflows) {
|
|
54
100
|
const existing = await github.getFile(ref, workflow.path).catch(() => null);
|
|
55
101
|
if (existing && !existing.content.includes(MARKER)) {
|
|
@@ -59,17 +105,34 @@ async function main() {
|
|
|
59
105
|
}
|
|
60
106
|
if (existing && existing.content.trim() === workflow.content.trim())
|
|
61
107
|
continue;
|
|
62
|
-
await putFile(github, ref, workflow.path, workflow.content, `chore:
|
|
108
|
+
await putFile(github, ref, workflow.path, workflow.content, `chore(install): add ${workflow.path.split("/").pop()}`, found.repo.defaultBranch, existing?.sha);
|
|
63
109
|
written++;
|
|
64
110
|
}
|
|
111
|
+
// Five files became one. Removing the old ones is part of installing, not
|
|
112
|
+
// a cleanup someone has to remember: a repository with both would run the
|
|
113
|
+
// same event twice and the second copy would fight the first.
|
|
114
|
+
removed = await removeRetiredWorkflows(github, ref, workflows.map((w) => w.path), found.repo.defaultBranch);
|
|
115
|
+
if (removed.length)
|
|
116
|
+
console.error(` - removed ${removed.join(", ")}`);
|
|
65
117
|
// The whole feature set depends on this secret; copy it from the caller.
|
|
66
118
|
if (options.secretValue) {
|
|
67
119
|
await putSecret(github, ref, options.secretName, options.secretValue);
|
|
68
120
|
}
|
|
69
|
-
//
|
|
121
|
+
// The app id and key travel with each repository, because the action
|
|
122
|
+
// mints its own installation token there. A token cannot be shared
|
|
123
|
+
// instead: it expires within the hour.
|
|
124
|
+
let secretsWritten = 0;
|
|
125
|
+
for (const secret of options.extraSecrets) {
|
|
126
|
+
await putSecret(github, ref, secret.name, secret.value);
|
|
127
|
+
secretsWritten++;
|
|
128
|
+
}
|
|
129
|
+
// Allow the workflows to create PRs and push fix branches. A read-only
|
|
130
|
+
// administration grant makes this a no-op; the workflows still work.
|
|
70
131
|
await enableWorkflowPermissions(github, ref).catch(() => { });
|
|
71
|
-
|
|
72
|
-
|
|
132
|
+
const secrets = secretsWritten + (options.secretValue ? 1 : 0);
|
|
133
|
+
const retired = removed.length ? `, ${removed.length} retired removed` : "";
|
|
134
|
+
results.push({ repo: name, action: "installed", detail: `${written} written, ${skipped} untouched, ${secrets} secrets${retired}` });
|
|
135
|
+
console.error(` ✓ ${written} workflows written, ${skipped} untouched, ${secrets} secrets${retired}`);
|
|
73
136
|
}
|
|
74
137
|
catch (error) {
|
|
75
138
|
results.push({ repo: name, action: "failed", detail: error.message });
|
|
@@ -87,6 +150,54 @@ async function main() {
|
|
|
87
150
|
if (summary.failed)
|
|
88
151
|
process.exitCode = 1;
|
|
89
152
|
}
|
|
153
|
+
async function selectRepos(github, options, app) {
|
|
154
|
+
if (options.repo) {
|
|
155
|
+
const ref = parseRepo(`${options.owner}/${options.repo}`);
|
|
156
|
+
return [ref];
|
|
157
|
+
}
|
|
158
|
+
if (!app)
|
|
159
|
+
return listRepos(github, options);
|
|
160
|
+
const candidates = await listAllInstalledRepos(github, options.owner, app);
|
|
161
|
+
return candidates
|
|
162
|
+
.filter((repo) => {
|
|
163
|
+
if (options.onlyPublic && repo.private)
|
|
164
|
+
return false;
|
|
165
|
+
if (!options.includeArchived && repo.archived)
|
|
166
|
+
return false;
|
|
167
|
+
if (options.excludeForks && repo.fork)
|
|
168
|
+
return false;
|
|
169
|
+
if (repo.disabled)
|
|
170
|
+
return false;
|
|
171
|
+
if (options.exclude.some((pattern) => repo.repo === pattern || `${repo.owner}/${repo.repo}` === pattern))
|
|
172
|
+
return false;
|
|
173
|
+
return true;
|
|
174
|
+
})
|
|
175
|
+
.map((repo) => ({ owner: repo.owner, repo: repo.repo }));
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Every repository reachable by the app installation that covers `owner`.
|
|
179
|
+
*
|
|
180
|
+
* An account-level installation covers future repositories automatically, so
|
|
181
|
+
* this call sees a repository seconds after it is created. A repository-scoped
|
|
182
|
+
* installation returns exactly its one repository, which is correct too.
|
|
183
|
+
*/
|
|
184
|
+
async function listAllInstalledRepos(github, owner, credentials) {
|
|
185
|
+
// A workflow passes `owner` because the CLI requires one, but in app mode the
|
|
186
|
+
// grant is the boundary: every installation the app has is in scope, and a
|
|
187
|
+
// repository the owner creates tomorrow appears here on its own. Filtering by
|
|
188
|
+
// the caller's login would silently skip a second account or an org.
|
|
189
|
+
const target = owner.startsWith("org:") ? owner.slice(4) : owner;
|
|
190
|
+
const repos = await installationRepos(github, credentials);
|
|
191
|
+
if (!target)
|
|
192
|
+
return repos;
|
|
193
|
+
const filtered = repos.filter((repo) => repo.owner === target);
|
|
194
|
+
if (filtered.length)
|
|
195
|
+
return filtered;
|
|
196
|
+
// `owner` may be a repository owner that is simply spelled differently from
|
|
197
|
+
// the installation account (an org install covering a personal repo, or a
|
|
198
|
+
// login change). Falling back to the full grant is safer than doing nothing.
|
|
199
|
+
return repos;
|
|
200
|
+
}
|
|
90
201
|
async function listRepos(github, options) {
|
|
91
202
|
const repos = [];
|
|
92
203
|
let page = 1;
|
|
@@ -114,7 +225,7 @@ async function listRepos(github, options) {
|
|
|
114
225
|
return false;
|
|
115
226
|
if (!options.includeArchived && repo.archived)
|
|
116
227
|
return false;
|
|
117
|
-
if (
|
|
228
|
+
if (options.excludeForks && repo.fork)
|
|
118
229
|
return false;
|
|
119
230
|
if (repo.disabled)
|
|
120
231
|
return false;
|
|
@@ -129,24 +240,75 @@ function skipReason(found, options) {
|
|
|
129
240
|
return "archived";
|
|
130
241
|
if (found.repo.disabled)
|
|
131
242
|
return "disabled";
|
|
132
|
-
if (found.repo.fork && !options.includeForks)
|
|
133
|
-
return "fork";
|
|
134
243
|
if (found.repo.private && options.onlyPublic)
|
|
135
244
|
return "private";
|
|
245
|
+
// Forks are included by default: they get pull requests and issues like any
|
|
246
|
+
// other repository, and skipping them left the bot out of exactly the place
|
|
247
|
+
// a contributor works. `--exclude-forks` opts out.
|
|
248
|
+
if (found.repo.fork && options.excludeForks)
|
|
249
|
+
return "fork";
|
|
136
250
|
return null;
|
|
137
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Delete the per-event workflows this installer used to write.
|
|
254
|
+
*
|
|
255
|
+
* Only files that still carry the bot's marker are removed: a workflow someone
|
|
256
|
+
* renamed and edited is theirs, and deleting it would undo their work.
|
|
257
|
+
*/
|
|
258
|
+
async function removeRetiredWorkflows(github, ref, keep, branch) {
|
|
259
|
+
const retired = [
|
|
260
|
+
".github/workflows/opencode-review.yml",
|
|
261
|
+
".github/workflows/opencode-commands.yml",
|
|
262
|
+
".github/workflows/opencode-comments.yml",
|
|
263
|
+
".github/workflows/opencode-commits.yml",
|
|
264
|
+
".github/workflows/opencode-issues.yml",
|
|
265
|
+
].filter((path) => !keep.includes(path));
|
|
266
|
+
const removed = [];
|
|
267
|
+
for (const path of retired) {
|
|
268
|
+
const file = await github.getFile(ref, path, branch).catch(() => null);
|
|
269
|
+
if (!file || !file.content.includes(MARKER))
|
|
270
|
+
continue;
|
|
271
|
+
await github
|
|
272
|
+
.delete(`/repos/${ref.owner}/${ref.repo}/contents/${path}`, {
|
|
273
|
+
message: withSkipCi(`chore(install): remove ${path.split("/").pop()}, replaced by opencode.yml`),
|
|
274
|
+
sha: file.sha,
|
|
275
|
+
branch,
|
|
276
|
+
})
|
|
277
|
+
.catch(() => null);
|
|
278
|
+
removed.push(path.split("/").pop() ?? path);
|
|
279
|
+
}
|
|
280
|
+
return removed;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Commit through the contents API with `[skip ci]`.
|
|
284
|
+
*
|
|
285
|
+
* The contents API does not honour a workflow's own conditions: a commit made
|
|
286
|
+
* here is a real push by the app, and GitHub starts the repository's `push`
|
|
287
|
+
* workflows for it. Without the marker, installing into a repository triggers
|
|
288
|
+
* its CI, which posts results, which can trigger the bot, which commits again.
|
|
289
|
+
*
|
|
290
|
+
* `commitAll` adds the marker for commits made with git. This is the other path,
|
|
291
|
+
* and forgetting it here is exactly how the loop came back.
|
|
292
|
+
*/
|
|
138
293
|
async function putFile(github, ref, path, content, message, branch, sha) {
|
|
139
294
|
await github.put(`/repos/${ref.owner}/${ref.repo}/contents/${path}`, {
|
|
140
|
-
message,
|
|
295
|
+
message: withSkipCi(message),
|
|
141
296
|
content: Buffer.from(content, "utf8").toString("base64"),
|
|
142
297
|
branch,
|
|
143
298
|
...(sha ? { sha } : {}),
|
|
144
299
|
});
|
|
145
300
|
}
|
|
146
301
|
async function putSecret(github, ref, name, value) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
302
|
+
const { key, key_id } = await github
|
|
303
|
+
.get(`/repos/${ref.owner}/${ref.repo}/actions/secrets/public-key`)
|
|
304
|
+
.catch((error) => {
|
|
305
|
+
if (error?.status === 403) {
|
|
306
|
+
throw new Error(`the credential cannot write secrets in ${ref.owner}/${ref.repo}. ` +
|
|
307
|
+
"A GitHub App needs the `secrets: write` permission and the installation must be re-approved " +
|
|
308
|
+
"after the permission is added; a classic token needs the `repo` scope.");
|
|
309
|
+
}
|
|
310
|
+
throw error;
|
|
311
|
+
});
|
|
150
312
|
const sealed = sealSecret(value, key);
|
|
151
313
|
await github.put(`/repos/${ref.owner}/${ref.repo}/actions/secrets/${name}`, {
|
|
152
314
|
encrypted_value: sealed,
|
|
@@ -191,11 +353,13 @@ function parseArgs(argv) {
|
|
|
191
353
|
token: process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? "",
|
|
192
354
|
secretName: "FREEPI_JWT",
|
|
193
355
|
secretValue: process.env.FREEPI_JWT,
|
|
356
|
+
extraSecrets: [],
|
|
194
357
|
dryRun: false,
|
|
195
|
-
|
|
358
|
+
excludeForks: false,
|
|
196
359
|
includeArchived: false,
|
|
197
360
|
onlyPublic: false,
|
|
198
361
|
exclude: [],
|
|
362
|
+
auto: false,
|
|
199
363
|
};
|
|
200
364
|
for (let index = 0; index < argv.length; index++) {
|
|
201
365
|
const arg = argv[index];
|
|
@@ -232,7 +396,10 @@ function parseArgs(argv) {
|
|
|
232
396
|
options.exclude.push(next());
|
|
233
397
|
break;
|
|
234
398
|
case "--include-forks":
|
|
235
|
-
|
|
399
|
+
// Kept so an existing call site does not fail; it is the default now.
|
|
400
|
+
break;
|
|
401
|
+
case "--exclude-forks":
|
|
402
|
+
options.excludeForks = true;
|
|
236
403
|
break;
|
|
237
404
|
case "--include-archived":
|
|
238
405
|
options.includeArchived = true;
|
|
@@ -240,6 +407,9 @@ function parseArgs(argv) {
|
|
|
240
407
|
case "--only-public":
|
|
241
408
|
options.onlyPublic = true;
|
|
242
409
|
break;
|
|
410
|
+
case "--auto":
|
|
411
|
+
options.auto = true;
|
|
412
|
+
break;
|
|
243
413
|
case "--dry-run":
|
|
244
414
|
options.dryRun = true;
|
|
245
415
|
break;
|
|
@@ -262,8 +432,11 @@ function parseArgs(argv) {
|
|
|
262
432
|
console.error("--config-repo is required (or set OPENCODE_ACTIONS_CONFIG_REPO)");
|
|
263
433
|
process.exit(2);
|
|
264
434
|
}
|
|
265
|
-
|
|
266
|
-
|
|
435
|
+
// With the app, the token is never used: discovery speaks as the app and
|
|
436
|
+
// every write uses an installation token minted for that repository.
|
|
437
|
+
const hasApp = Boolean(process.env.OPENCODE_APP_ID && process.env.OPENCODE_APP_PRIVATE_KEY);
|
|
438
|
+
if (!options.token && !hasApp) {
|
|
439
|
+
console.error("GITHUB_TOKEN is required unless OPENCODE_APP_ID and OPENCODE_APP_PRIVATE_KEY are set");
|
|
267
440
|
process.exit(2);
|
|
268
441
|
}
|
|
269
442
|
return options;
|
|
@@ -285,9 +458,11 @@ Flags:
|
|
|
285
458
|
--secret-name <name> Secret to copy (default: FREEPI_JWT)
|
|
286
459
|
--secret-value <text> Secret value; defaults to $FREEPI_JWT
|
|
287
460
|
--exclude <name> Repository to skip (repeatable)
|
|
288
|
-
--include-forks
|
|
461
|
+
--include-forks Accepted for compatibility (forks are included by default)
|
|
462
|
+
--exclude-forks Skip forked repositories
|
|
289
463
|
--include-archived Also install in archived repositories
|
|
290
464
|
--only-public Only public repositories
|
|
465
|
+
--auto Only repositories where the bot is not installed yet
|
|
291
466
|
--dry-run Detect and report; change nothing
|
|
292
467
|
|
|
293
468
|
The installer never overwrites a workflow file the bot did not create.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The small signals that make a bot feel present: a reaction while it works, an
|
|
3
|
+
* emoji when it is done, and an issue closed when its pull request merges.
|
|
4
|
+
*
|
|
5
|
+
* GitHub Copilot never leaves an author guessing whether a request was heard. A
|
|
6
|
+
* run takes minutes, and without an acknowledgement the comment looks ignored.
|
|
7
|
+
* The reaction is the acknowledgement, and the emoji at the end is the receipt.
|
|
8
|
+
*/
|
|
9
|
+
import type { GitHub, RepoRef } from "./github.js";
|
|
10
|
+
/** What the bot reacts with, in order of meaning. */
|
|
11
|
+
export declare const REACTIONS: {
|
|
12
|
+
/** Accepted: the request was understood and is running. */
|
|
13
|
+
readonly accepted: "eyes";
|
|
14
|
+
/** Finished, with a change. */
|
|
15
|
+
readonly done: "+1";
|
|
16
|
+
/** Finished, nothing to do or the request was refused. */
|
|
17
|
+
readonly nothing: "-1";
|
|
18
|
+
/** Failed. */
|
|
19
|
+
readonly failed: "confused";
|
|
20
|
+
};
|
|
21
|
+
export type ReactionName = (typeof REACTIONS)[keyof typeof REACTIONS];
|
|
22
|
+
/**
|
|
23
|
+
* React to a comment or issue.
|
|
24
|
+
*
|
|
25
|
+
* GitHub accepts a fixed set of reaction names; anything else is a 422, which is
|
|
26
|
+
* why the set is enumerated rather than free text. A failure is swallowed: a
|
|
27
|
+
* missing reaction must never fail the work the reaction was acknowledging.
|
|
28
|
+
*/
|
|
29
|
+
export declare function react(github: GitHub, repo: RepoRef, subject: {
|
|
30
|
+
kind: "issue" | "comment" | "pull";
|
|
31
|
+
number: number;
|
|
32
|
+
commentId?: number;
|
|
33
|
+
}, reaction: ReactionName): Promise<unknown>;
|
|
34
|
+
/** Pull requests and issues share the same issue-number space. */
|
|
35
|
+
export declare function subjectFor(input: {
|
|
36
|
+
commentId?: number;
|
|
37
|
+
number: number;
|
|
38
|
+
isPull?: boolean;
|
|
39
|
+
}): {
|
|
40
|
+
kind: "comment";
|
|
41
|
+
number: number;
|
|
42
|
+
commentId: number;
|
|
43
|
+
} | {
|
|
44
|
+
kind: "issue" | "pull";
|
|
45
|
+
number: number;
|
|
46
|
+
commentId?: undefined;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Close the issue a pull request belongs to, when the pull request closes it.
|
|
50
|
+
*
|
|
51
|
+
* GitHub does this itself for `Closes #n` in a merged PR body, but only for the
|
|
52
|
+
* default branch and only when the body was written correctly. Doing it
|
|
53
|
+
* explicitly covers the cases GitHub skips: a bot-written body, a merge into a
|
|
54
|
+
* release branch, and a PR whose body a person edited.
|
|
55
|
+
*/
|
|
56
|
+
export declare function closeLinkedIssues(github: GitHub, repo: RepoRef, pull: {
|
|
57
|
+
number: number;
|
|
58
|
+
body?: string | null;
|
|
59
|
+
title?: string;
|
|
60
|
+
}): Promise<{
|
|
61
|
+
closed: number[];
|
|
62
|
+
}>;
|
|
63
|
+
/**
|
|
64
|
+
* Announce a merge inside the pull request, so the thread ends with a result
|
|
65
|
+
* rather than a merge commit nobody reads.
|
|
66
|
+
*/
|
|
67
|
+
export declare function commentMerge(github: GitHub, repo: RepoRef, pullNumber: number, detail: {
|
|
68
|
+
sha?: string;
|
|
69
|
+
method?: string;
|
|
70
|
+
issues: number[];
|
|
71
|
+
}): Promise<unknown>;
|
|
72
|
+
/**
|
|
73
|
+
* Merge, and when GitHub refuses because the branch is behind or conflicting,
|
|
74
|
+
* say exactly which, because "merge failed" tells the author nothing.
|
|
75
|
+
*
|
|
76
|
+
* A conflict is not something a merge call can resolve: the branch has to be
|
|
77
|
+
* updated and the conflict committed. Returning the reason lets the caller run
|
|
78
|
+
* that step instead of retrying the same merge.
|
|
79
|
+
*/
|
|
80
|
+
export declare function mergeWithReason(github: GitHub, repo: RepoRef, pullNumber: number, method?: "merge" | "squash" | "rebase"): Promise<{
|
|
81
|
+
merged: boolean;
|
|
82
|
+
already: boolean;
|
|
83
|
+
sha: string | undefined;
|
|
84
|
+
conflict?: undefined;
|
|
85
|
+
reason?: undefined;
|
|
86
|
+
behind?: undefined;
|
|
87
|
+
blocked?: undefined;
|
|
88
|
+
method?: undefined;
|
|
89
|
+
} | {
|
|
90
|
+
merged: boolean;
|
|
91
|
+
conflict: boolean;
|
|
92
|
+
reason: string;
|
|
93
|
+
already?: undefined;
|
|
94
|
+
sha?: undefined;
|
|
95
|
+
behind?: undefined;
|
|
96
|
+
blocked?: undefined;
|
|
97
|
+
method?: undefined;
|
|
98
|
+
} | {
|
|
99
|
+
merged: boolean;
|
|
100
|
+
behind: boolean;
|
|
101
|
+
reason: string;
|
|
102
|
+
already?: undefined;
|
|
103
|
+
sha?: undefined;
|
|
104
|
+
conflict?: undefined;
|
|
105
|
+
blocked?: undefined;
|
|
106
|
+
method?: undefined;
|
|
107
|
+
} | {
|
|
108
|
+
merged: boolean;
|
|
109
|
+
blocked: boolean;
|
|
110
|
+
reason: string;
|
|
111
|
+
already?: undefined;
|
|
112
|
+
sha?: undefined;
|
|
113
|
+
conflict?: undefined;
|
|
114
|
+
behind?: undefined;
|
|
115
|
+
method?: undefined;
|
|
116
|
+
} | {
|
|
117
|
+
merged: boolean;
|
|
118
|
+
sha: string;
|
|
119
|
+
method: "merge" | "squash" | "rebase";
|
|
120
|
+
already?: undefined;
|
|
121
|
+
conflict?: undefined;
|
|
122
|
+
reason?: undefined;
|
|
123
|
+
behind?: undefined;
|
|
124
|
+
blocked?: undefined;
|
|
125
|
+
} | {
|
|
126
|
+
merged: boolean;
|
|
127
|
+
reason: any;
|
|
128
|
+
already?: undefined;
|
|
129
|
+
sha?: undefined;
|
|
130
|
+
conflict?: undefined;
|
|
131
|
+
behind?: undefined;
|
|
132
|
+
blocked?: undefined;
|
|
133
|
+
method?: undefined;
|
|
134
|
+
}>;
|