Repository navigation
373 lines (331 loc) · 15.3 KB
/
Copy pathwizard-ci-trigger.yml
File metadata and controls
373 lines (331 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
name: Wizard CI Trigger
on:
pull_request:
types: [opened]
issue_comment:
types: [created]
workflow_dispatch:
inputs:
pr_number:
description: 'Pull request number to post the hint comment on'
required: true
type: number
permissions:
contents: read
issues: write
pull-requests: write
jobs:
# ============================================================================
# POST WELCOME: First-time hint with all available apps
# ============================================================================
post-welcome:
if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Fetch available apps from wizard-workbench
id: fetch-apps
run: |
# Fetch app categories from wizard-workbench repo
CATEGORIES=$(curl -s "https://api.github.com/repos/PostHog/wizard-workbench/contents/apps" \
-H "Accept: application/vnd.github.v3+json" \
| jq -r '[.[] | select(.type == "dir") | .name] | sort | .[]')
# Only advertise directories whose workflow is CI-capable (apps/manifest.json).
# Left empty on fetch failure, in which case no filtering is applied.
CI_CAPABLE=$(curl -s "https://api.github.com/repos/PostHog/wizard-workbench/contents/apps/manifest.json" \
-H "Accept: application/vnd.github.raw" \
| jq -r '[.workflows[] | select(.ciCapable == true) | .dir] | .[]' 2>/dev/null || echo "")
# Build lists by category
CATEGORY_LIST=""
APP_LIST_VISIBLE=""
APP_LIST_COLLAPSED=""
APP_COUNT=0
VISIBLE_COUNT=3
for category in $CATEGORIES; do
# Skip directories the manifest marks as not CI-capable.
if [ -n "$CI_CAPABLE" ] && ! echo "$CI_CAPABLE" | grep -qxF "$category"; then
continue
fi
# Fetch apps in this category
APPS=$(curl -s "https://api.github.com/repos/PostHog/wizard-workbench/contents/apps/$category" \
-H "Accept: application/vnd.github.v3+json" \
| jq -r '[.[] | select(.type == "dir") | .name] | sort | .[]' 2>/dev/null || echo "")
if [ -n "$APPS" ]; then
# Add to category list
CATEGORY_LIST="$CATEGORY_LIST- \`/wizard-ci $category\`\n"
# Add apps to visible or collapsed list
for app in $APPS; do
if [ $APP_COUNT -lt $VISIBLE_COUNT ]; then
APP_LIST_VISIBLE="$APP_LIST_VISIBLE- \`/wizard-ci $category/$app\`\n"
else
APP_LIST_COLLAPSED="$APP_LIST_COLLAPSED- \`/wizard-ci $category/$app\`\n"
fi
APP_COUNT=$((APP_COUNT + 1))
done
fi
done
# Use heredoc for multiline outputs
{
echo "categories<<EOF"
echo -e "$CATEGORY_LIST"
echo "EOF"
} >> $GITHUB_OUTPUT
{
echo "apps_visible<<EOF"
echo -e "$APP_LIST_VISIBLE"
echo "EOF"
} >> $GITHUB_OUTPUT
{
echo "apps_collapsed<<EOF"
echo -e "$APP_LIST_COLLAPSED"
echo "EOF"
} >> $GITHUB_OUTPUT
- name: Post wizard-ci hint
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0
env:
CATEGORIES_OUTPUT: ${{ steps.fetch-apps.outputs.categories }}
APPS_VISIBLE_OUTPUT: ${{ steps.fetch-apps.outputs.apps_visible }}
APPS_COLLAPSED_OUTPUT: ${{ steps.fetch-apps.outputs.apps_collapsed }}
PR_NUMBER: ${{ inputs.pr_number }}
with:
script: |
const categories = process.env.CATEGORIES_OUTPUT || '';
const appsVisible = process.env.APPS_VISIBLE_OUTPUT || '';
const appsCollapsed = process.env.APPS_COLLAPSED_OUTPUT || '';
const inputPrNumber = process.env.PR_NUMBER;
const bodyParts = [
'## 🧙 Wizard CI',
'',
'Run the Wizard CI and test your changes against [wizard-workbench](https://github.com/PostHog/wizard-workbench) example apps by replying with a GitHub comment using one of the following commands:',
'',
'**Test all apps:**',
'- `/wizard-ci all`',
'',
'**Test all apps in a directory:**',
categories.trim(),
'',
'**Test an individual app:**',
appsVisible.trim()
];
if (appsCollapsed.trim()) {
bodyParts.push('');
bodyParts.push('<details>');
bodyParts.push('<summary>Show more apps</summary>');
bodyParts.push('');
bodyParts.push(appsCollapsed.trim());
bodyParts.push('</details>');
}
bodyParts.push('');
bodyParts.push('**Test against a Context Mill branch:**');
bodyParts.push('- `/wizard-ci all context-mill:my-branch`');
bodyParts.push('');
bodyParts.push('Add `context-mill:<branch>` to any command above to pin the Context Mill branch. It defaults to `main`.');
bodyParts.push('');
bodyParts.push('Results will be posted here when complete.');
const body = bodyParts.join('\n');
const prNumber = context.eventName === 'workflow_dispatch'
? parseInt(inputPrNumber, 10)
: context.payload.pull_request.number;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body
});
# ============================================================================
# HANDLE COMMAND: Parse /wizard-ci and trigger workflow
# ============================================================================
handle-command:
if: |
github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association) &&
startsWith(github.event.comment.body, '/wizard-ci') &&
!startsWith(github.event.comment.body, '/wizard-ci-snapshots')
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1.12.0
with:
app-id: ${{ secrets.GH_APP_POSTHOG_WIZARD_CI_BOT_APP_ID }}
private-key: ${{ secrets.GH_APP_POSTHOG_WIZARD_CI_BOT_PRIVATE_KEY }}
owner: PostHog
repositories: wizard-workbench,wizard
- name: Parse command and trigger
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0
with:
github-token: ${{ steps.app-token.outputs.token }}
script: |
// Get PR details first to check state
const pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.issue.number
});
// Only allow triggers on open PRs (including drafts)
if (pr.data.state !== 'open') {
console.log(`PR is ${pr.data.state}, skipping trigger`);
return;
}
const comment = context.payload.comment.body;
const match = comment.match(/\/wizard-ci\s+(\S+)/);
const firstArg = match ? match[1] : 'all';
// A reviewer can pin the companion repo with `context-mill:<ref>`.
// A lone pin is not an app name, so fall back to every app.
const app = firstArg.startsWith('context-mill:') ? 'all' : firstArg;
// The ref arrives in a PR comment, so treat it as untrusted. Accept
// git ref characters only. Reject traversal, a leading dash and a
// trailing slash.
const isPlausibleRef = (ref) =>
ref.length <= 200 &&
/^[A-Za-z0-9._\/-]+$/.test(ref) &&
!ref.includes('..') &&
!ref.startsWith('-') &&
!ref.startsWith('/') &&
!ref.endsWith('/');
// Read the pin from the command line only, not from later prose.
const companion = comment
.split(/\r?\n/)[0]
.match(/(?:^|\s)context-mill:(\S+)/);
const contextMillRef = companion ? companion[1] : null;
if (contextMillRef && !isPlausibleRef(contextMillRef)) {
core.setFailed(
'The context-mill ref is not a valid git ref. ' +
'Use `/wizard-ci <app> context-mill:<branch>`.'
);
return;
}
// React with rocket to show we're processing
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'rocket'
});
// Trigger wizard-ci on wizard-workbench
await github.rest.repos.createDispatchEvent({
owner: 'PostHog',
repo: 'wizard-workbench',
event_type: 'wizard-ci-trigger',
client_payload: {
app: app,
source: 'wizard-pr',
source_repo: 'wizard',
source_pr_number: context.payload.issue.number,
source_pr_url: pr.data.html_url,
wizard_ref: pr.data.head.ref,
// Omit the key when unpinned. The workbench then uses `main`.
...(contextMillRef ? { context_mill_ref: contextMillRef } : {}),
notify_slack: 'false',
notify_pr: 'true'
}
});
const pinNote = contextMillRef ? ` (context-mill ref ${contextMillRef})` : '';
console.log(`Triggered wizard-ci for app: ${app}${pinNote}`);
# ============================================================================
# HANDLE SNAPSHOTS: Parse /wizard-ci-snapshots and trigger the snapshots workflow
# ============================================================================
# Same write-access restriction as handle-command above. This job matters more:
# its positional `[ref]` argument is attacker-chosen, not the PR's own branch.
handle-snapshots-command:
if: |
github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association) &&
startsWith(github.event.comment.body, '/wizard-ci-snapshots')
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1.12.0
with:
app-id: ${{ secrets.GH_APP_POSTHOG_WIZARD_CI_BOT_APP_ID }}
private-key: ${{ secrets.GH_APP_POSTHOG_WIZARD_CI_BOT_PRIVATE_KEY }}
owner: PostHog
repositories: wizard-workbench,wizard
- name: Parse command and trigger snapshots
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0
with:
github-token: ${{ steps.app-token.outputs.token }}
script: |
// Only trigger on open PRs (including drafts).
const pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.issue.number
});
if (pr.data.state !== 'open') {
console.log(`PR is ${pr.data.state}, skipping trigger`);
return;
}
const body = context.payload.comment.body;
// The ref arrives in a PR comment, so treat it as untrusted. Accept
// git ref characters only. Reject traversal, a leading dash and a
// trailing slash.
const isPlausibleRef = (ref) =>
ref.length <= 200 &&
/^[A-Za-z0-9._\/-]+$/.test(ref) &&
!ref.includes('..') &&
!ref.startsWith('-') &&
!ref.startsWith('/') &&
!ref.endsWith('/');
// Optional companion pin. Read it from the command line only.
const companionToken = /(?:^|\s)context-mill:(\S+)/;
const companion = body.split(/\r?\n/)[0].match(companionToken);
const contextMillRef = companion ? companion[1] : null;
if (contextMillRef && !isPlausibleRef(contextMillRef)) {
core.setFailed(
'The context-mill ref is not a valid git ref. Use ' +
'`/wizard-ci-snapshots <app> context-mill:<branch>`.'
);
return;
}
// Remove the pin so the positional ref cannot capture it.
const args = contextMillRef ? body.replace(companionToken, ' ') : body;
// /wizard-ci-snapshots <app> [wizard_ref] [context-mill:<ref>] —
// wizard_ref defaults to this PR's branch.
const m = args.match(/\/wizard-ci-snapshots\s+(\S+)(?:\s+(\S+))?/);
const app = m ? m[1] : 'basic-integration/javascript-node/express-todo';
// The positional ref also comes from the comment. Check it too.
const wizardRefArg = m && m[2] ? m[2] : null;
if (wizardRefArg && !isPlausibleRef(wizardRefArg)) {
core.setFailed(
'The wizard ref is not a valid git ref. Use ' +
'`/wizard-ci-snapshots <app> <wizard-branch>`.'
);
return;
}
const wizardRef = wizardRefArg || pr.data.head.ref;
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'rocket'
});
// Same wizard-ci-trigger dispatch as /wizard-ci, plus snapshots:true —
// wizard-ci.yml's one SNAPSHOTS branch runs the real-TUI review instead
// of the evaluator. It checks out its own trusted ref; no untrusted PR
// code is checked out here.
await github.rest.repos.createDispatchEvent({
owner: 'PostHog',
repo: 'wizard-workbench',
event_type: 'wizard-ci-trigger',
client_payload: {
app: app,
source: 'wizard-pr',
source_repo: 'wizard',
source_pr_number: context.payload.issue.number,
source_pr_url: pr.data.html_url,
wizard_ref: wizardRef,
// Omit the key when unpinned. The workbench then uses `main`.
...(contextMillRef ? { context_mill_ref: contextMillRef } : {}),
notify_slack: 'false',
notify_pr: 'true',
snapshots: true
}
});
const pinNote = contextMillRef ? `, context-mill ref ${contextMillRef}` : '';
console.log(`Triggered snapshots for app: ${app} (ref ${wizardRef}${pinNote})`);