relayrunner 0.1.1 → 0.2.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/README.md +47 -31
- package/dist/cli.js +1110 -126
- package/package.json +13 -6
- package/dist/SKILL.md +0 -15
- package/dist/routing.js +0 -74
- package/dist/runner.js +0 -152
- package/dist/system.js +0 -41
- package/dist/workflows.js +0 -109
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "relayrunner",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Run GitHub Actions jobs on your machine through the RelayRunner gateway.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/
|
|
7
|
+
"url": "git+https://github.com/relayrunner/relayrunner.git",
|
|
8
8
|
"directory": "apps/cli"
|
|
9
9
|
},
|
|
10
10
|
"type": "module",
|
|
@@ -18,10 +18,17 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"
|
|
21
|
+
"@clack/prompts": "^1.8.1",
|
|
22
|
+
"citty": "^0.2.2",
|
|
23
|
+
"zod": "^4.6.7"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@relayrunner/machine-protocol": "0.0.0",
|
|
27
|
+
"@types/ws": "^8.18.2",
|
|
28
|
+
"tsdown": "^0.23.5",
|
|
29
|
+
"ws": "^8.22.1"
|
|
22
30
|
},
|
|
23
31
|
"scripts": {
|
|
24
|
-
"build": "
|
|
25
|
-
"test": "vitest run"
|
|
32
|
+
"build": "tsdown"
|
|
26
33
|
}
|
|
27
34
|
}
|
package/dist/SKILL.md
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: relayrunner
|
|
3
|
-
description: Set up RelayRunner, switch between local and GitHub-hosted runners, and check routing for selected GitHub Actions jobs in a private repository. Discover jobs, show the workflow patch, and install and verify the developer's GitHub runner.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
Use the RelayRunner CLI from a trusted installed copy. If it is unavailable, use the installation instructions in the RelayRunner repository README. Run commands with `--json` and use `--cwd` to target the developer's checkout.
|
|
7
|
-
|
|
8
|
-
1. Run `relayrunner discover --cwd <checkout> --json`. Confirm the repository and let the user select jobs using the returned IDs. A job needs to be compatible with the developer's OS and tools. Check its steps and dependencies before recommending it.
|
|
9
|
-
2. Run `relayrunner preview --cwd <checkout> --job <id> --json`, repeating `--job` for every selected job. Show the actual patch, target branch, and the hosted fallback. Explain that setup starts GitHub's runner under the developer's local account. Use the user's existing authorization if it covers the displayed patch and runner setup. Otherwise obtain it before proceeding. Only set up repositories whose workflow authors the user trusts.
|
|
10
|
-
3. Run `relayrunner setup` with the same checkout and job arguments, plus `--approve <fingerprint> --json`. Use the fingerprint from the authorized preview. For a stale preview, show the new patch before applying it. For an interrupted setup, rerun the same command if the fingerprint is still current. If the patch was applied, a fresh preview can verify that no workflow changes remain.
|
|
11
|
-
4. Report the returned online status, runner label, and local workflow changes. The checkout changes need to go through the usual commit and push workflow before GitHub can use them. Commit or push only within the user's authorization.
|
|
12
|
-
|
|
13
|
-
For `GITHUB_ACCESS`, report the need for authorized GitHub CLI credentials and repository administration permission. If the environment restricts existing credential access, use its approved execution mechanism. Keep authentication and runner registration inside the CLI. Setup leaves routing inactive.
|
|
14
|
-
|
|
15
|
-
After the setup changes are committed and pushed, use `relayrunner switch local` to route opted-in jobs across the repository. Use `relayrunner status` to report the current route and runner availability. Use `relayrunner switch hosted` when the user wants to restore hosted execution for future jobs, and report any queued jobs or warning returned by the command.
|
package/dist/routing.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { api, SetupError } from "./system.js";
|
|
2
|
-
import { registeredRunner, runnerLabel, withRunnerLock } from "./runner.js";
|
|
3
|
-
import { workflows } from "./workflows.js";
|
|
4
|
-
const refKey = 'RELAYRUNNER_REF';
|
|
5
|
-
const labelKey = 'RELAYRUNNER_LABEL';
|
|
6
|
-
function pages(endpoint, query = '') {
|
|
7
|
-
return api(`${endpoint}?per_page=100${query}`, ['--paginate', '--slurp']);
|
|
8
|
-
}
|
|
9
|
-
function setVariable(endpoint, variables, name, value) {
|
|
10
|
-
if (variables.get(name) === value)
|
|
11
|
-
return;
|
|
12
|
-
if (variables.has(name)) {
|
|
13
|
-
api(`${endpoint}/${name}`, ['-X', 'PATCH', '-f', `value=${value}`]);
|
|
14
|
-
}
|
|
15
|
-
else {
|
|
16
|
-
api(endpoint, ['-X', 'POST', '-f', `name=${name}`, '-f', `value=${value}`]);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
function queuedJobs(actions, label) {
|
|
20
|
-
if (!label)
|
|
21
|
-
return [];
|
|
22
|
-
const runIds = new Set(['queued', 'in_progress'].flatMap(status => pages(`${actions}/runs`, `&status=${status}`)
|
|
23
|
-
.flatMap(page => page.workflow_runs.map(run => run.id))));
|
|
24
|
-
return [...runIds]
|
|
25
|
-
.flatMap(id => pages(`${actions}/runs/${id}/jobs`).flatMap(page => page.jobs))
|
|
26
|
-
.filter(job => job.status === 'queued' && job.labels.some(item => item.toLowerCase() === label.toLowerCase()))
|
|
27
|
-
.map(({ id, name, html_url: url }) => ({ id, name, url }));
|
|
28
|
-
}
|
|
29
|
-
function routing(target, mode) {
|
|
30
|
-
const actions = `repos/${target.repo}/actions`;
|
|
31
|
-
const endpoint = `${actions}/variables`;
|
|
32
|
-
const variables = new Map(pages(endpoint).flatMap(page => page.variables)
|
|
33
|
-
.map(({ name, value }) => [name, value]));
|
|
34
|
-
const label = variables.get(labelKey);
|
|
35
|
-
if (mode === 'hosted') {
|
|
36
|
-
for (const name of [labelKey, refKey]) {
|
|
37
|
-
if (variables.has(name))
|
|
38
|
-
api(`${endpoint}/${name}`, ['-X', 'DELETE']);
|
|
39
|
-
}
|
|
40
|
-
const result = { repo: target.repo, route: 'hosted' };
|
|
41
|
-
try {
|
|
42
|
-
return { ...result, queuedJobs: queuedJobs(actions, label || runnerLabel(target)) };
|
|
43
|
-
}
|
|
44
|
-
catch (error) {
|
|
45
|
-
if (!(error instanceof SetupError))
|
|
46
|
-
throw error;
|
|
47
|
-
return { ...result, queuedJobs: null, warning: `Could not check queued jobs. ${error.message}` };
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
const localLabel = runnerLabel(target);
|
|
51
|
-
if (mode === 'local' && label && label !== localLabel) {
|
|
52
|
-
throw new SetupError('ROUTE_CONFLICT', `Local routing already targets ${label}. Run relayrunner switch hosted first.`);
|
|
53
|
-
}
|
|
54
|
-
const selectedLabel = label || localLabel;
|
|
55
|
-
const runner = registeredRunner(target, selectedLabel);
|
|
56
|
-
const online = runner?.status === 'online' && runner.labels?.some(item => item.name === selectedLabel);
|
|
57
|
-
const availability = !selectedLabel ? null : online ? (runner.busy ? 'busy' : 'online') : 'offline';
|
|
58
|
-
const runnerStatus = selectedLabel ? { label: selectedLabel, status: availability } : null;
|
|
59
|
-
if (mode === 'status') {
|
|
60
|
-
return { repo: target.repo, route: label ? 'local' : 'hosted', runner: runnerStatus };
|
|
61
|
-
}
|
|
62
|
-
if (!online || !localLabel)
|
|
63
|
-
throw new SetupError('RUNNER_OFFLINE', 'Set up this checkout and verify its local runner is online before switching.');
|
|
64
|
-
if (!workflows(target.root).some(job => job.alreadySetUp && !job.needsUpdate)) {
|
|
65
|
-
throw new SetupError('WORKFLOW_SETUP_REQUIRED', 'Set up or upgrade at least one eligible job and commit and push the workflow changes.');
|
|
66
|
-
}
|
|
67
|
-
if (variables.has(refKey))
|
|
68
|
-
api(`${endpoint}/${refKey}`, ['-X', 'DELETE']);
|
|
69
|
-
setVariable(endpoint, variables, labelKey, localLabel);
|
|
70
|
-
return { repo: target.repo, route: 'local', runner: runnerStatus };
|
|
71
|
-
}
|
|
72
|
-
export function routeJobs(target, mode) {
|
|
73
|
-
return mode === 'status' ? routing(target, mode) : withRunnerLock(target, () => routing(target, mode));
|
|
74
|
-
}
|
package/dist/runner.js
DELETED
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
-
import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
4
|
-
import { arch, homedir, platform } from 'node:os';
|
|
5
|
-
import { join, resolve } from 'node:path';
|
|
6
|
-
import { setTimeout as sleep } from 'node:timers/promises';
|
|
7
|
-
import { api, run, SetupError } from "./system.js";
|
|
8
|
-
const runnerEnv = Object.fromEntries(['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL', 'TMPDIR', 'SHELL'].flatMap(key => process.env[key] === undefined ? [] : [[key, process.env[key]]]));
|
|
9
|
-
async function install(dir, endpoint) {
|
|
10
|
-
const system = platform();
|
|
11
|
-
const os = system === 'darwin' ? 'osx' : system;
|
|
12
|
-
const architecture = arch();
|
|
13
|
-
if ((os !== 'osx' && os !== 'linux') || (architecture !== 'x64' && architecture !== 'arm64') || process.getuid?.() === 0) {
|
|
14
|
-
throw new SetupError('UNSUPPORTED_MACHINE', 'Run as a regular user on macOS or Linux (x64 or arm64).');
|
|
15
|
-
}
|
|
16
|
-
const download = api(`${endpoint}/downloads`).find(item => item.os === os && item.architecture === architecture);
|
|
17
|
-
if (!download || !/^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/.test(download.download_url) ||
|
|
18
|
-
!/^[a-f\d]{64}$/i.test(download.sha256_checksum)) {
|
|
19
|
-
throw new SetupError('RUNNER_DOWNLOAD', 'GitHub did not provide a supported runner archive with a SHA-256 checksum.');
|
|
20
|
-
}
|
|
21
|
-
const temp = mkdtempSync(join(dir, 'install-'));
|
|
22
|
-
try {
|
|
23
|
-
const archive = join(temp, 'runner.tar.gz');
|
|
24
|
-
const result = run('curl', ['-q', '--fail', '--silent', '--show-error', '--location',
|
|
25
|
-
'--proto', '=https', '--proto-redir', '=https', '--output', archive, download.download_url], { env: runnerEnv, timeout: 600_000 });
|
|
26
|
-
if (result.status !== 0)
|
|
27
|
-
throw new SetupError('RUNNER_DOWNLOAD', 'Runner download failed. Check curl and network access.');
|
|
28
|
-
const hash = createHash('sha256');
|
|
29
|
-
for await (const chunk of createReadStream(archive))
|
|
30
|
-
hash.update(chunk);
|
|
31
|
-
if (hash.digest('hex') !== download.sha256_checksum.toLowerCase()) {
|
|
32
|
-
throw new SetupError('RUNNER_CHECKSUM', 'The runner archive failed SHA-256 verification.');
|
|
33
|
-
}
|
|
34
|
-
const unpacked = join(temp, 'runner');
|
|
35
|
-
mkdirSync(unpacked, { mode: 0o700 });
|
|
36
|
-
if (run('tar', ['-xzf', archive, '-C', unpacked], { env: runnerEnv }).status !== 0) {
|
|
37
|
-
throw new SetupError('RUNNER_EXTRACT', 'Could not unpack the runner archive. Check tar and available disk space.');
|
|
38
|
-
}
|
|
39
|
-
renameSync(unpacked, join(dir, 'runner'));
|
|
40
|
-
}
|
|
41
|
-
finally {
|
|
42
|
-
rmSync(temp, { recursive: true, force: true });
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
function runnerDirectory(target) {
|
|
46
|
-
if (!Number.isSafeInteger(target.id))
|
|
47
|
-
throw new SetupError('GITHUB_REQUEST_FAILED', 'GitHub returned an invalid repository ID.');
|
|
48
|
-
return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), '.relayrunner'), String(target.id));
|
|
49
|
-
}
|
|
50
|
-
export function runnerLabel(target) {
|
|
51
|
-
const identity = join(runnerDirectory(target), 'identity');
|
|
52
|
-
if (!existsSync(identity))
|
|
53
|
-
return null;
|
|
54
|
-
const label = readFileSync(identity, 'utf8');
|
|
55
|
-
if (!/^relayrunner-[a-f\d-]{36}$/.test(label))
|
|
56
|
-
throw new SetupError('RUNNER_STATE', 'Runner identity is invalid.');
|
|
57
|
-
return label;
|
|
58
|
-
}
|
|
59
|
-
export function registeredRunner(target, label) {
|
|
60
|
-
if (!label)
|
|
61
|
-
return null;
|
|
62
|
-
return api(`repos/${target.repo}/actions/runners?per_page=100`, ['--paginate', '--slurp'])
|
|
63
|
-
.flatMap(page => page.runners).find(runner => runner.name === label) ?? null;
|
|
64
|
-
}
|
|
65
|
-
export async function withRunnerLock(target, work) {
|
|
66
|
-
const dir = runnerDirectory(target);
|
|
67
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
68
|
-
const lock = join(dir, 'setup.lock');
|
|
69
|
-
try {
|
|
70
|
-
symlinkSync(String(process.pid), lock);
|
|
71
|
-
}
|
|
72
|
-
catch (error) {
|
|
73
|
-
if (error.code !== 'EEXIST')
|
|
74
|
-
throw error;
|
|
75
|
-
throw new SetupError('SETUP_LOCKED', `Setup is locked at ${lock}. If its recorded PID has exited, remove the lock and retry.`);
|
|
76
|
-
}
|
|
77
|
-
try {
|
|
78
|
-
return await work(dir);
|
|
79
|
-
}
|
|
80
|
-
finally {
|
|
81
|
-
rmSync(lock);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
export async function withRunner(target, finish) {
|
|
85
|
-
return withRunnerLock(target, async (dir) => {
|
|
86
|
-
const cwd = join(dir, 'runner');
|
|
87
|
-
const endpoint = `repos/${target.repo}/actions/runners`;
|
|
88
|
-
const identity = join(dir, 'identity');
|
|
89
|
-
if (!existsSync(identity)) {
|
|
90
|
-
writeFileSync(`${identity}.tmp`, `relayrunner-${randomUUID()}`, { mode: 0o600 });
|
|
91
|
-
renameSync(`${identity}.tmp`, identity);
|
|
92
|
-
}
|
|
93
|
-
const label = runnerLabel(target);
|
|
94
|
-
if (!label)
|
|
95
|
-
throw new SetupError('RUNNER_STATE', 'Runner identity is missing.');
|
|
96
|
-
const lookup = () => registeredRunner(target, label);
|
|
97
|
-
const existing = lookup();
|
|
98
|
-
if (!existsSync(cwd))
|
|
99
|
-
await install(dir, endpoint);
|
|
100
|
-
const config = join(cwd, '.runner');
|
|
101
|
-
if (!existsSync(config)) {
|
|
102
|
-
if (existing?.status === 'online' || existing?.busy) {
|
|
103
|
-
throw new SetupError('RUNNER_STATE', 'The runner identity is already active. Recover its local configuration before retrying.');
|
|
104
|
-
}
|
|
105
|
-
const { token } = api(`${endpoint}/registration-token`, ['-X', 'POST']);
|
|
106
|
-
if (!token)
|
|
107
|
-
throw new SetupError('RUNNER_CONFIG', 'GitHub did not provide a registration token.');
|
|
108
|
-
const args = ['--unattended', '--url', `https://github.com/${target.repo}`,
|
|
109
|
-
'--name', label, '--labels', label, '--no-default-labels'];
|
|
110
|
-
if (existing)
|
|
111
|
-
args.push('--replace');
|
|
112
|
-
const result = run('./config.sh', args, {
|
|
113
|
-
cwd, env: { ...runnerEnv, ACTIONS_RUNNER_INPUT_TOKEN: token }, stdio: 'ignore',
|
|
114
|
-
});
|
|
115
|
-
if (result.status !== 0) {
|
|
116
|
-
throw new SetupError('RUNNER_CONFIG', 'Runner registration failed. Check organization policy and the official runner runtime prerequisites, then retry.');
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
else if (!existing) {
|
|
120
|
-
throw new SetupError('RUNNER_STATE', 'Local configuration exists but GitHub cannot find the runner. Restore or remove the stale local installation before retrying.');
|
|
121
|
-
}
|
|
122
|
-
let runner = lookup();
|
|
123
|
-
if (runner?.status !== 'online') {
|
|
124
|
-
const pidFile = join(dir, 'listener.pid');
|
|
125
|
-
let running = false;
|
|
126
|
-
if (existsSync(pidFile)) {
|
|
127
|
-
const pid = readFileSync(pidFile, 'utf8').trim();
|
|
128
|
-
if (/^[1-9]\d*$/.test(pid)) {
|
|
129
|
-
const result = run('ps', ['-p', pid, '-o', 'command=']);
|
|
130
|
-
running = result.status === 0 && result.stdout.includes(join(cwd, 'run.sh'));
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
if (!running) {
|
|
134
|
-
const child = spawn(join(cwd, 'run.sh'), [], { cwd, env: runnerEnv, detached: true, stdio: 'ignore' });
|
|
135
|
-
await new Promise((resolve, reject) => {
|
|
136
|
-
child.once('spawn', resolve);
|
|
137
|
-
child.once('error', () => reject(new SetupError('RUNNER_START', 'Could not start the official runner.')));
|
|
138
|
-
});
|
|
139
|
-
child.unref();
|
|
140
|
-
writeFileSync(pidFile, String(child.pid), { mode: 0o600 });
|
|
141
|
-
}
|
|
142
|
-
for (let attempt = 0; attempt < 20 && runner?.status !== 'online'; attempt++) {
|
|
143
|
-
await sleep(1500);
|
|
144
|
-
runner = lookup();
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
if (runner?.status !== 'online' || !runner.labels?.some(item => item.name === label)) {
|
|
148
|
-
throw new SetupError('RUNNER_OFFLINE', `GitHub has not confirmed the runner online with label ${label}. Check runner diagnostics under ${cwd}/_diag and retry.`);
|
|
149
|
-
}
|
|
150
|
-
return finish({ id: runner.id, label, status: runner.status });
|
|
151
|
-
});
|
|
152
|
-
}
|
package/dist/system.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { spawnSync } from 'node:child_process';
|
|
2
|
-
export class SetupError extends Error {
|
|
3
|
-
code;
|
|
4
|
-
constructor(code, message) {
|
|
5
|
-
super(message);
|
|
6
|
-
this.code = code;
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
export function run(command, args, options = {}) {
|
|
10
|
-
return spawnSync(command, args, {
|
|
11
|
-
encoding: 'utf8',
|
|
12
|
-
maxBuffer: 16 * 1024 * 1024,
|
|
13
|
-
timeout: 120_000,
|
|
14
|
-
...options,
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
export function git(cwd, args, options) {
|
|
18
|
-
const result = run('git', args, { cwd, ...options });
|
|
19
|
-
if (result.status !== 0) {
|
|
20
|
-
throw new SetupError('GIT_FAILED', `git ${args[0]} failed. Check the checkout and preview again.`);
|
|
21
|
-
}
|
|
22
|
-
return result.stdout;
|
|
23
|
-
}
|
|
24
|
-
export function api(endpoint, args = []) {
|
|
25
|
-
const { GH_DEBUG: _ghDebug, DEBUG: _debug, ...env } = process.env;
|
|
26
|
-
const result = run('gh', ['api', '--hostname', 'github.com', endpoint, ...args], {
|
|
27
|
-
env: { ...env, GH_PROMPT_DISABLED: '1' },
|
|
28
|
-
});
|
|
29
|
-
if (result.error?.code === 'ENOENT') {
|
|
30
|
-
throw new SetupError('MISSING_GH', 'Install the GitHub CLI and make it available on PATH.');
|
|
31
|
-
}
|
|
32
|
-
if (result.status !== 0) {
|
|
33
|
-
const status = result.stderr?.match(/HTTP (\d{3})/)?.[1];
|
|
34
|
-
if (['401', '403', '404'].includes(status ?? '') ||
|
|
35
|
-
/auth login|no oauth token|token invalid|requires authentication/i.test(result.stderr ?? '')) {
|
|
36
|
-
throw new SetupError('GITHUB_ACCESS', 'Use an authorized GitHub CLI session with access to this private repository. Runner setup requires repository administration access and must be allowed by organization policy.');
|
|
37
|
-
}
|
|
38
|
-
throw new SetupError('GITHUB_REQUEST_FAILED', 'GitHub API request failed. Check network access and retry.');
|
|
39
|
-
}
|
|
40
|
-
return result.stdout.trim() ? JSON.parse(result.stdout) : undefined;
|
|
41
|
-
}
|
package/dist/workflows.js
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { mkdtempSync, readFileSync, rmSync, writeFileSync, lstatSync } from 'node:fs';
|
|
3
|
-
import { tmpdir } from 'node:os';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import { isMap, isScalar, parseDocument } from 'yaml';
|
|
6
|
-
import { api, git, run, SetupError } from "./system.js";
|
|
7
|
-
const hosted = /^(?:ubuntu-(?:latest|(?:20|22|24|26)\.04(?:-arm)?)|macos-(?:latest|(?:13|14|15|26)(?:-intel)?)|windows-(?:latest|2019|2022|2025))$/;
|
|
8
|
-
const legacyRoute = "${{ github.event_name == 'push' && github.ref_type == 'branch' && github.ref == vars.RELAYRUNNER_REF && vars.RELAYRUNNER_LABEL != '' && vars.RELAYRUNNER_LABEL || '{hosted}' }}";
|
|
9
|
-
const branchRoute = "${{ ((github.event.pull_request && github.event.pull_request.head.repo.id == fromJSON(github.repository_id) && format('refs/heads/{0}', github.head_ref) == vars.RELAYRUNNER_REF) || (!github.event.pull_request && github.ref_type == 'branch' && github.ref == vars.RELAYRUNNER_REF)) && vars.RELAYRUNNER_LABEL != '' && vars.RELAYRUNNER_LABEL || '{hosted}' }}";
|
|
10
|
-
const route = "${{ vars.RELAYRUNNER_LABEL || '{hosted}' }}";
|
|
11
|
-
export function repository(cwd) {
|
|
12
|
-
const root = git(cwd, ['rev-parse', '--show-toplevel']).trim();
|
|
13
|
-
const origin = git(root, ['remote', 'get-url', 'origin']).trim();
|
|
14
|
-
const remote = origin.match(/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w-]+\/[\w.-]+?)\/?$/i);
|
|
15
|
-
if (!remote)
|
|
16
|
-
throw new SetupError('UNSUPPORTED_REMOTE', 'Use a checkout with a github.com origin.');
|
|
17
|
-
const repo = api(`repos/${remote[1].replace(/\.git$/, '')}`);
|
|
18
|
-
if (repo.visibility !== 'private' || repo.fork || !/^[\w-]+\/[\w.-]+$/.test(repo.full_name)) {
|
|
19
|
-
throw new SetupError('UNSUPPORTED_REPO', 'Setup requires a private, non-fork GitHub repository.');
|
|
20
|
-
}
|
|
21
|
-
return { root, repo: repo.full_name, id: repo.id };
|
|
22
|
-
}
|
|
23
|
-
export function workflows(root) {
|
|
24
|
-
const files = git(root, ['ls-files', '-z', '--', '.github/workflows']).split('\0')
|
|
25
|
-
.filter(file => /^\.github\/workflows\/[\w.-]+\.ya?ml$/.test(file));
|
|
26
|
-
return [...new Set(files)].flatMap(file => {
|
|
27
|
-
const path = join(root, file);
|
|
28
|
-
try {
|
|
29
|
-
if (!lstatSync(path).isFile() || !lstatSync(join(root, '.github')).isDirectory() ||
|
|
30
|
-
!lstatSync(join(root, '.github/workflows')).isDirectory())
|
|
31
|
-
return [];
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
if (error.code === 'ENOENT')
|
|
35
|
-
return [];
|
|
36
|
-
throw error;
|
|
37
|
-
}
|
|
38
|
-
const source = readFileSync(path, 'utf8');
|
|
39
|
-
const doc = parseDocument(source);
|
|
40
|
-
if (doc.errors.length)
|
|
41
|
-
throw new SetupError('INVALID_WORKFLOW', `Cannot parse ${file}.`);
|
|
42
|
-
const jobs = doc.get('jobs');
|
|
43
|
-
if (!isMap(jobs) || jobs.anchor)
|
|
44
|
-
return [];
|
|
45
|
-
return jobs.items.flatMap(({ key, value }) => {
|
|
46
|
-
if (!isScalar(key) || typeof key.value !== 'string' || !isMap(value) || value.anchor)
|
|
47
|
-
return [];
|
|
48
|
-
const node = value.get('runs-on', true);
|
|
49
|
-
if (!isScalar(node) || typeof node.value !== 'string' || node.anchor || node.tag ||
|
|
50
|
-
!['PLAIN', 'QUOTE_SINGLE', 'QUOTE_DOUBLE'].includes(node.type ?? '') || !node.range)
|
|
51
|
-
return [];
|
|
52
|
-
const [start, end] = node.range;
|
|
53
|
-
if (/[\r\n]/.test(source.slice(start, end)))
|
|
54
|
-
return [];
|
|
55
|
-
const fallback = node.value.match(/\|\| '([^']+)' \}\}$/)?.[1];
|
|
56
|
-
const alreadySetUp = fallback !== undefined && hosted.test(fallback) &&
|
|
57
|
-
route.replace('{hosted}', fallback) === node.value;
|
|
58
|
-
const needsUpdate = fallback !== undefined && hosted.test(fallback) &&
|
|
59
|
-
[legacyRoute, branchRoute].some(template => template.replace('{hosted}', fallback) === node.value);
|
|
60
|
-
if (!alreadySetUp && !needsUpdate && !hosted.test(node.value))
|
|
61
|
-
return [];
|
|
62
|
-
const hostedRunner = alreadySetUp || needsUpdate ? fallback : node.value;
|
|
63
|
-
return [{ id: `${file}:${key.value}`, file, source, start, end, runsOn: node.value,
|
|
64
|
-
alreadySetUp: alreadySetUp || needsUpdate, needsUpdate, hostedRunner }];
|
|
65
|
-
});
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
function patchFor(file, before, after) {
|
|
69
|
-
const dir = mkdtempSync(join(tmpdir(), 'relayrunner-patch-'));
|
|
70
|
-
try {
|
|
71
|
-
writeFileSync(join(dir, 'before'), before);
|
|
72
|
-
writeFileSync(join(dir, 'after'), after);
|
|
73
|
-
const diff = run('git', ['diff', '--no-index', '--no-color', '--no-ext-diff', '--text', '--', 'before', 'after'], { cwd: dir });
|
|
74
|
-
if (diff.status !== 1 || !diff.stdout.includes('\n@@ ')) {
|
|
75
|
-
throw new SetupError('PATCH_FAILED', `Could not generate patch for ${file}.`);
|
|
76
|
-
}
|
|
77
|
-
return `diff --git a/${file} b/${file}\n--- a/${file}\n+++ b/${file}\n` +
|
|
78
|
-
diff.stdout.slice(diff.stdout.indexOf('\n@@ ') + 1);
|
|
79
|
-
}
|
|
80
|
-
finally {
|
|
81
|
-
rmSync(dir, { recursive: true, force: true });
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
export function plan(target, ids) {
|
|
85
|
-
const available = workflows(target.root);
|
|
86
|
-
const selected = [...new Set(ids)].sort().map(id => {
|
|
87
|
-
const job = available.find(candidate => candidate.id === id);
|
|
88
|
-
if (!job)
|
|
89
|
-
throw new SetupError('INELIGIBLE_JOB', `Job is unavailable or unsupported: ${id}`);
|
|
90
|
-
return job;
|
|
91
|
-
});
|
|
92
|
-
const files = Map.groupBy(selected.filter(job => !job.alreadySetUp || job.needsUpdate), job => job.file);
|
|
93
|
-
const patch = [...files].map(([file, jobs]) => {
|
|
94
|
-
const before = jobs[0].source;
|
|
95
|
-
let after = before;
|
|
96
|
-
for (const { start, end, hostedRunner } of jobs.sort((a, b) => b.start - a.start)) {
|
|
97
|
-
after = after.slice(0, start) + JSON.stringify(route.replace('{hosted}', hostedRunner)) + after.slice(end);
|
|
98
|
-
}
|
|
99
|
-
return patchFor(file, before, after);
|
|
100
|
-
}).join('');
|
|
101
|
-
const head = git(target.root, ['rev-parse', 'HEAD']).trim();
|
|
102
|
-
const branch = git(target.root, ['branch', '--show-current']).trim();
|
|
103
|
-
if (!branch)
|
|
104
|
-
throw new SetupError('DETACHED_HEAD', 'Switch to a named branch before previewing setup.');
|
|
105
|
-
const fingerprint = createHash('sha256').update(JSON.stringify([
|
|
106
|
-
target.repo, head, branch, selected.map(({ id, source }) => [id, source]), patch,
|
|
107
|
-
])).digest('hex');
|
|
108
|
-
return { repo: target.repo, branch, jobs: selected.map(job => job.id), fingerprint, patch };
|
|
109
|
-
}
|