返回 CodeWhale
setup.mjs
根目录 / scripts / github-action / setup.mjs
1 import { lstatSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
2 import { resolve, join } from 'node:path';
3 import { fileURLToPath } from 'node:url';
4 import { spawnSync } from 'node:child_process';
5 import { parseArgs } from 'node:util';
6
7 export const KEYS = {
8 deepseek: 'DEEPSEEK_API_KEY', anthropic: 'ANTHROPIC_API_KEY',
9 openrouter: 'OPENROUTER_API_KEY', orcarouter: 'ORCAROUTER_API_KEY', zai: 'ZAI_API_KEY',
10 'modelstudio-token-plan': 'MODELSTUDIO_API_KEY', codewhale: 'CODEWHALE_API_KEY',
11 };
12
13 const HELP = `Create a Codewhale review bot workflow in your repository.
14
15 node setup.mjs --provider deepseek --model MODEL_ID --directory /path/to/repo
16
17 --provider NAME ${Object.keys(KEYS).join(', ')}
18 --model ID Exact model ID; account mode requires provider/model
19 --reasoning-effort E auto, off, low, medium, high, max (default: off)
20 --directory PATH Destination repository (default: current directory)
21 --version vX.Y.Z Checksummed CLI release (default: v0.10.2)
22 --action-ref SHA Reviewed Action commit (default: this clean source checkout)
23 --trigger-phrase NAME Mention to listen for (default: @codewhale)
24 --app-login LOGIN Optional existing GitHub App login, including [bot]
25 --max-output-tokens N Review output allowance (default: 16384; minimum: 8192)
26 --print Print YAML without writing files
27 --help Show this help
28
29 Creates .github/workflows/codewhale-review.yml without overwriting existing files.
30 Set the selected provider secret, then commit the workflow to the default branch.
31 Automatic reviews cover same-repository PRs. Maintainers can review fork PRs
32 with a manual run or an @codewhale review comment; PR code is never executed.
33 `;
34
35 export function workflow({ provider, model, version = 'v0.10.2', actionRef, triggerPhrase = '@codewhale', appLogin, maxOutputTokens = '16384', reasoningEffort = 'off' }) {
36 if (!Object.hasOwn(KEYS, provider)) throw new Error('Choose a supported --provider.');
37 if (!/^[A-Za-z0-9][A-Za-z0-9_./:@+-]{0,199}$/.test(model || '')
38 || (provider === 'codewhale' && !/^[A-Za-z0-9_.-]+\/.+/.test(model))) throw new Error('Choose an exact --model ID.');
39 if (!/^v\d+\.\d+\.\d+$/.test(version)) throw new Error('--version must be an exact vX.Y.Z release.');
40 if (!/^[a-f0-9]{40}$/i.test(actionRef || '')) throw new Error('--action-ref must be a full reviewed commit SHA.');
41 if (!/^@[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(triggerPhrase)) throw new Error('--trigger-phrase must be @ followed by a GitHub-style name.');
42 if (appLogin && !/^[a-zA-Z0-9][a-zA-Z0-9-]{0,99}\[bot\]$/.test(appLogin)) throw new Error('--app-login must include [bot].');
43 if (!/^[1-9][0-9]*$/.test(String(maxOutputTokens)) || Number(maxOutputTokens) < 8192 || Number(maxOutputTokens) > 1000000) throw new Error('--max-output-tokens must be between 8192 and 1000000.');
44 if (!['auto', 'off', 'low', 'medium', 'high', 'max'].includes(reasoningEffort)) throw new Error('Choose a supported --reasoning-effort.');
45 const action = `codewhale-hq/Codewhale@${actionRef}`;
46 const secret = KEYS[provider];
47 const expression = value => '${{ ' + value + ' }}';
48 const eligible = ` (github.event_name == 'workflow_dispatch') ||
49 (github.event_name == 'pull_request' && !github.event.pull_request.draft && github.event.pull_request.head.repo.full_name == github.repository) ||
50 ((github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') &&
51 (github.event.issue.pull_request || github.event.pull_request) &&
52 github.event.comment.user.type == 'User' && contains(github.event.comment.body, '${triggerPhrase}'))`;
53 const appToken = ` - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510
54 id: app-token
55 with:
56 app-id: ${expression('vars.CODEWHALE_APP_ID')}
57 private-key: ${expression('secrets.CODEWHALE_APP_PRIVATE_KEY')}
58 permission-contents: read
59 permission-pull-requests: write
60 `;
61 return `name: Codewhale PR Review
62 on:
63 pull_request:
64 types: [opened, synchronize, reopened, ready_for_review]
65 issue_comment:
66 types: [created]
67 pull_request_review_comment:
68 types: [created]
69 workflow_dispatch:
70 inputs:
71 pr-number:
72 description: Pull request number
73 required: true
74 type: string
75 permissions: {}
76 concurrency:
77 group: codewhale-review-${expression('github.event.pull_request.number || github.event.issue.number || inputs.pr-number')}
78 cancel-in-progress: false
79 jobs:
80 ${appLogin ? ` installation:
81 if: >-
82 ${eligible}
83 runs-on: ubuntu-latest
84 timeout-minutes: 5
85 permissions: {}
86 steps:
87 ${appToken}` : ''} review:
88 ${appLogin ? ' needs: installation\n' : ''} if: >-
89 ${eligible}
90 runs-on: ubuntu-latest
91 timeout-minutes: 25
92 permissions:
93 contents: read
94 pull-requests: read
95 outputs:
96 findings: ${expression('steps.review.outputs.findings')}
97 steps:
98 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
99 with:
100 node-version: '22'
101 - uses: ${action}
102 id: review
103 with:
104 version: '${version}'
105 provider: '${provider}'
106 model: '${model}'
107 reasoning-effort: '${reasoningEffort}'
108 max-output-tokens: '${maxOutputTokens}'
109 pr-number: ${expression('inputs.pr-number')}
110 trigger-phrase: '${triggerPhrase}'
111 allow-forks: 'true'
112 post: 'false'
113 env:
114 ${secret}: ${expression("(github.event_name == 'workflow_dispatch' || github.event_name == 'issue_comment' || github.event.pull_request.head.repo.full_name == github.repository) && secrets." + secret + " || ''")}
115 - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
116 if: steps.review.outputs.findings != ''
117 with:
118 name: codewhale-findings-${expression('github.run_id')}-${expression('github.run_attempt')}
119 path: ${expression('steps.review.outputs.findings')}
120 retention-days: 1
121 if-no-files-found: error
122 - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
123 if: always() && steps.review.outputs.receipt != ''
124 with:
125 name: codewhale-review-receipt-${expression('github.run_id')}-${expression('github.run_attempt')}
126 path: ${expression('steps.review.outputs.receipt')}
127 retention-days: 14
128 if-no-files-found: error
129 publish:
130 needs: review
131 if: needs.review.outputs.findings != ''
132 runs-on: ubuntu-latest
133 timeout-minutes: 10
134 permissions:
135 contents: read
136 pull-requests: write
137 steps:
138 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
139 with:
140 node-version: '22'
141 - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131
142 with:
143 name: codewhale-findings-${expression('github.run_id')}-${expression('github.run_attempt')}
144 path: findings
145 ${appLogin ? appToken : ''} - uses: codewhale-hq/Codewhale/scripts/github-action/publish@${actionRef}
146 id: publish
147 with:
148 findings: findings/findings.json
149 pr-number: ${expression('inputs.pr-number')}
150 trigger-phrase: '${triggerPhrase}'
151 allow-forks: 'true'
152 ${appLogin ? ` github-token: ${expression('steps.app-token.outputs.token')}
153 reviewer-login: '${appLogin}'
154 ` : ''} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
155 if: always() && steps.publish.outputs.receipt != ''
156 with:
157 name: codewhale-publication-receipt-${expression('github.run_id')}-${expression('github.run_attempt')}
158 path: ${expression('steps.publish.outputs.receipt')}
159 retention-days: 14
160 if-no-files-found: error
161 `;
162 }
163
164 export function setup(args = process.argv.slice(2)) {
165 const { values } = parseArgs({ args, options: {
166 provider: { type: 'string' }, model: { type: 'string' }, directory: { type: 'string' },
167 version: { type: 'string' }, 'action-ref': { type: 'string' }, 'trigger-phrase': { type: 'string' },
168 'app-login': { type: 'string' }, print: { type: 'boolean' }, help: { type: 'boolean' },
169 'max-output-tokens': { type: 'string' },
170 'reasoning-effort': { type: 'string' },
171 } });
172 if (values.help) { console.log(HELP); return; }
173 let actionRef = values['action-ref'];
174 if (!actionRef) {
175 const root = fileURLToPath(new URL('../../', import.meta.url));
176 const git = args => spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
177 const tracked = git(['cat-file', '-e', 'HEAD:scripts/github-action/setup.mjs']);
178 const clean = git(['diff', '--quiet', 'HEAD', '--', 'action.yml', 'scripts/github-action']);
179 const head = git(['rev-parse', 'HEAD']);
180 if (tracked.status !== 0 || clean.status !== 0 || head.status !== 0) throw new Error('Use a clean Codewhale source checkout or supply --action-ref with a reviewed commit.');
181 actionRef = head.stdout.trim();
182 }
183 const yaml = workflow({ provider: values.provider, model: values.model, version: values.version,
184 actionRef, triggerPhrase: values['trigger-phrase'], appLogin: values['app-login'], maxOutputTokens: values['max-output-tokens'], reasoningEffort: values['reasoning-effort'] });
185 if (values.print) { process.stdout.write(yaml); return; }
186 const directory = realpathSync(values.directory || process.cwd());
187 if (spawnSync('git', ['-C', directory, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout.trim() !== directory) throw new Error('--directory must be a Git repository root.');
188 let current = directory;
189 for (const name of ['.github', 'workflows']) {
190 current = join(current, name);
191 try { mkdirSync(current); } catch (error) { if (error.code !== 'EEXIST') throw error; }
192 if (!lstatSync(current).isDirectory() || lstatSync(current).isSymbolicLink()) throw new Error('Workflow directories must be real directories.');
193 }
194 const output = join(current, 'codewhale-review.yml');
195 writeFileSync(output, yaml, { flag: 'wx' });
196 console.log(`Created ${output}\nSet the ${KEYS[values.provider]} Actions secret, then commit the workflow to your default branch.\n${values['app-login'] ? 'The publisher also needs CODEWHALE_APP_ID and CODEWHALE_APP_PRIVATE_KEY.\n' : ''}Reviews use ${values.provider}/${values.model}. GitHub runner usage and model usage follow your account limits.`);
197 }
198
199 if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
200 try { setup(); } catch (error) { console.error(error.message); process.exitCode = 1; }
201 }
202
202 lines Plain Text