forked from webprofusion/OpenAudio
-
Notifications
You must be signed in to change notification settings - Fork 0
452 lines (381 loc) · 17.2 KB
/
Copy pathprocess-submission.yml
File metadata and controls
452 lines (381 loc) · 17.2 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
name: Process Submission
on:
issues:
types: [opened]
workflow_dispatch:
inputs:
issue_number:
description: "Issue number to process (for example: 123)"
required: true
type: string
jobs:
process:
if: |
github.event_name == 'workflow_dispatch' ||
startsWith(github.event.issue.title, '[Plugin]') ||
startsWith(github.event.issue.title, '[App]') ||
startsWith(github.event.issue.title, '[Library]') ||
startsWith(github.event.issue.title, '[Collection]')
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: cd generator && npm ci
- name: Parse issue and create entry
id: parse
uses: actions/github-script@v9
with:
script: |
let issueNumber;
let issue;
if (context.eventName === 'workflow_dispatch') {
const rawIssueNumber = `${context.payload.inputs?.issue_number ?? ''}`.trim();
issueNumber = Number.parseInt(rawIssueNumber, 10);
if (!Number.isInteger(issueNumber) || issueNumber <= 0) {
core.setFailed('Invalid issue_number input. Provide a positive integer.');
return;
}
const response = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber
});
issue = response.data;
} else {
issue = context.payload.issue;
issueNumber = issue.number;
}
const body = issue.body;
const title = issue.title;
// Determine type from title prefix
const isPlugin = title.startsWith('[Plugin]');
const isApp = title.startsWith('[App]');
const isLibrary = title.startsWith('[Library]');
const isCollection = title.startsWith('[Collection]');
if (!isPlugin && !isApp && !isLibrary && !isCollection) {
core.setFailed('Issue title must start with [Plugin], [App], [Library], or [Collection].');
return;
}
// Parse form fields from issue body
const parseField = (fieldName) => {
const regex = new RegExp(`### ${fieldName}\\s*\\n\\s*([^\\n#]+)`, 'i');
const match = body.match(regex);
if (!match) return '';
const value = match[1].trim();
return value === '_No response_' ? '' : value;
};
const parseMultiSelect = (fieldName) => {
const regex = new RegExp(`### ${fieldName}\\s*\\n\\s*([^#]+?)(?=###|$)`, 'i');
const match = body.match(regex);
if (!match) return [];
return match[1]
.split(',')
.map(s => s.trim())
.filter(s => s && s !== '_No response_' && s.toLowerCase() !== 'none' && s.toLowerCase() !== 'no framework');
};
const normalizeRepository = (repoType, repoUser, repoName) => {
const normalizedUser = repoUser === '_No response_' ? '' : repoUser;
const normalizedName = repoName === '_No response_' ? '' : repoName;
if (!normalizedUser && ['GitHub', 'GitLab', 'Codeberg', 'SourceHut'].includes(repoType)) {
const patterns = {
GitHub: /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i,
GitLab: /^(?:https?:\/\/)?(?:www\.)?gitlab\.com\/([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i,
Codeberg: /^(?:https?:\/\/)?(?:www\.)?codeberg\.org\/([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i,
SourceHut: /^(?:https?:\/\/)?(?:git\.)?sr\.ht\/~?([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i,
};
const match = normalizedName.match(patterns[repoType]);
if (match) {
return {
repoUser: match[1],
repoName: match[2],
};
}
}
return {
repoUser: normalizedUser,
repoName: normalizedName,
};
};
let entry = {};
let targetFile = '';
let entryType = '';
if (isPlugin) {
entryType = 'plugin';
targetFile = 'data/plugins.json';
entry = {
name: parseField('Plugin Name'),
url: parseField('Plugin URL'),
description: parseField('Description'),
type: parseField('Plugin Type'),
frameworks: parseMultiSelect('Frameworks')
};
} else if (isApp) {
entryType = 'app';
targetFile = 'data/apps.json';
const repoType = parseField('Repository Type');
const {repoUser, repoName} = normalizeRepository(
repoType,
parseField('Repository User/Workspace'),
parseField('Repository Name'),
);
let repository = {};
if (repoType === 'GitHub' || repoType === 'GitLab' || repoType === 'Codeberg' || repoType === 'SourceHut') {
repository = { type: repoType, user: repoUser, repo: repoName };
} else if (repoType === 'Bitbucket') {
repository = { type: repoType, workspace: repoUser, repo: repoName };
} else if (repoType === 'SourceForge') {
repository = { type: repoType, project: repoName };
} else if (repoType === 'Assembla') {
repository = { type: repoType, space: repoName };
}
entry = {
name: parseField('App Name'),
description: parseField('Description'),
repository: repository
};
const url = parseField('App URL \\(optional\\)');
if (url && url !== '_No response_') {
entry.url = url;
}
} else if (isLibrary) {
entryType = 'library';
targetFile = 'data/libraries.json';
const repoType = parseField('Repository Type');
const {repoUser, repoName} = normalizeRepository(
repoType,
parseField('Repository User/Workspace'),
parseField('Repository Name'),
);
let repository = {};
if (repoType === 'GitHub' || repoType === 'GitLab' || repoType === 'Codeberg' || repoType === 'SourceHut') {
repository = { type: repoType, user: repoUser, repo: repoName };
} else if (repoType === 'Bitbucket') {
repository = { type: repoType, workspace: repoUser, repo: repoName };
} else if (repoType === 'SourceForge') {
repository = { type: repoType, project: repoName };
} else if (repoType === 'Assembla') {
repository = { type: repoType, space: repoName };
}
entry = {
name: parseField('Library Name'),
description: parseField('Description'),
repository: repository
};
const url = parseField('Library URL \\(optional\\)');
if (url && url !== '_No response_') {
entry.url = url;
}
} else if (isCollection) {
const collectionType = parseField('Type');
entryType = 'collection';
if (collectionType.toLowerCase().includes('resource')) {
targetFile = 'data/resources.json';
} else if (collectionType.toLowerCase().includes('sample')) {
targetFile = 'data/samples.json';
} else {
targetFile = 'data/collections.json';
}
entry = {
name: parseField('Name'),
url: parseField('URL'),
description: parseField('Description')
};
}
core.setOutput('entry', JSON.stringify(entry));
core.setOutput('targetFile', targetFile);
core.setOutput('entryType', entryType);
core.setOutput('entryName', entry.name);
core.setOutput('issueNumber', issueNumber.toString());
- name: Insert entry into JSON file
run: |
node << 'EOF'
const fs = require('fs');
const path = require('path');
const main = async () => {
const entry = JSON.parse(process.env.ENTRY);
const targetFile = process.env.TARGET_FILE;
const eol = '\n';
const defaultIndent = ' ';
// Track top-level object ranges so the new entry can be spliced into the source without reformatting existing items.
const collectTopLevelObjectRanges = source => {
const ranges = [];
let depth = 0;
let inString = false;
let isEscaped = false;
let objectStartIndex = -1;
for (let charIndex = 0; charIndex < source.length; charIndex += 1) {
const char = source[charIndex];
if (inString) {
if (isEscaped) {
isEscaped = false;
continue;
}
if (char === '\\') {
isEscaped = true;
continue;
}
if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === '[' || char === '{') {
if (char === '{' && depth === 1) {
objectStartIndex = charIndex;
}
depth += 1;
continue;
}
if (char === ']' || char === '}') {
if (char === '}' && depth === 2 && objectStartIndex !== -1) {
ranges.push({
start: objectStartIndex,
end: charIndex + 1,
});
objectStartIndex = -1;
}
depth -= 1;
}
}
return ranges;
};
const inferItemIndent = (source, ranges) => {
if (ranges.length === 0) {
return defaultIndent;
}
const firstItemStart = ranges[0].start;
const lineStart = source.lastIndexOf(eol, firstItemStart - 1);
const indent = lineStart === -1
? ''
: source.slice(lineStart + 1, firstItemStart);
return /^[ \t]*$/.test(indent) ? indent : defaultIndent;
};
const formatEntry = (value, indent) =>
JSON.stringify(value, null, 2)
.split('\n')
.map(line => `${indent}${line}`)
.join(eol);
// Insert the formatted entry at the computed top-level position while preserving all untouched source text.
const insertEntryIntoArraySource = (source, value, insertIndex, itemCount, fileName) => {
const ranges = collectTopLevelObjectRanges(source);
const indent = inferItemIndent(source, ranges);
const formattedEntry = formatEntry(value, indent);
if (ranges.length === 0) {
const openBracketIndex = source.indexOf('[');
const closeBracketIndex = source.lastIndexOf(']');
return `${source.slice(0, openBracketIndex + 1)}${eol}${formattedEntry}${eol}${source.slice(closeBracketIndex)}`;
}
if (ranges.length !== itemCount) {
throw new Error(`Top-level JSON item range count (${ranges.length}) does not match parsed entry count (${itemCount}). This may indicate malformed JSON or unexpected file content in ${fileName}.`);
}
if (insertIndex === itemCount) {
const previousItemRange = ranges.at(-1);
return `${source.slice(0, previousItemRange.end)},${eol}${formattedEntry}${source.slice(previousItemRange.end)}`;
}
const nextItemRange = ranges[insertIndex];
return `${source.slice(0, nextItemRange.start)}${formattedEntry},${eol}${source.slice(nextItemRange.start)}`;
};
// Read existing data
const filePath = path.join(process.cwd(), targetFile);
const source = fs.readFileSync(filePath, 'utf8');
const data = JSON.parse(source);
// Find insertion index (alphabetical by name, case-insensitive, locale-aware)
const insertIndex = data.findIndex(item =>
item.name.localeCompare(entry.name, undefined, {sensitivity: 'accent'}) > 0
);
const normalizedInsertIndex = insertIndex === -1 ? data.length : insertIndex;
const updatedSource = insertEntryIntoArraySource(source, entry, normalizedInsertIndex, data.length, targetFile);
fs.writeFileSync(filePath, updatedSource);
console.log(`Inserted "${entry.name}" into ${targetFile}`);
};
main().catch(error => {
console.error('Failed to insert the submission entry into the target JSON file.');
console.error(error);
process.exit(1);
});
EOF
env:
ENTRY: ${{ steps.parse.outputs.entry }}
TARGET_FILE: ${{ steps.parse.outputs.targetFile }}
- name: Run validation tests
id: validate
run: |
cd generator
npm test -- --run 2>&1 | tee test-output.txt
echo "test_passed=$?" >> $GITHUB_OUTPUT
continue-on-error: true
- name: Create Pull Request
if: steps.validate.outcome == 'success'
uses: peter-evans/create-pull-request@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
add-paths: |
${{ steps.parse.outputs.targetFile }}
commit-message: "Add ${{ steps.parse.outputs.entryType }}: ${{ steps.parse.outputs.entryName }}"
branch: submission/${{ steps.parse.outputs.entryType }}/${{ steps.parse.outputs.issueNumber }}
title: "Add ${{ steps.parse.outputs.entryType }}: ${{ steps.parse.outputs.entryName }}"
body: |
## Automated Submission
This PR was automatically generated from issue #${{ steps.parse.outputs.issueNumber }}.
**Type:** ${{ steps.parse.outputs.entryType }}
**Name:** ${{ steps.parse.outputs.entryName }}
### Entry Details
```json
${{ steps.parse.outputs.entry }}
```
---
✅ Validation tests passed
Please review this submission before merging.
Closes #${{ steps.parse.outputs.issueNumber }}
labels: |
submission
needs-review
- name: Comment on issue (success)
if: steps.validate.outcome == 'success'
uses: actions/github-script@v9
env:
ISSUE_NUMBER: ${{ steps.parse.outputs.issueNumber }}
with:
script: |
const issueNumber = Number.parseInt(process.env.ISSUE_NUMBER, 10);
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
body: `✅ Your submission has been processed successfully!\n\nA pull request has been created for review. Once approved by a maintainer, your entry will be added to the list.\n\nThank you for contributing!`
});
- name: Comment on issue (failure)
if: steps.validate.outcome == 'failure'
uses: actions/github-script@v9
env:
ISSUE_NUMBER: ${{ steps.parse.outputs.issueNumber }}
with:
script: |
const issueNumber = Number.parseInt(process.env.ISSUE_NUMBER, 10);
const fs = require('fs');
const testOutput = fs.readFileSync('generator/test-output.txt', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
body: `❌ Your submission could not be validated. Please check the details below and update your submission.\n\n<details>\n<summary>Validation Output</summary>\n\n\`\`\`\n${testOutput}\n\`\`\`\n</details>\n\nCommon issues:\n- Missing required fields\n- Invalid URL format\n- Invalid repository information`
});
github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: ['validation-failed']
});