release-cherry-pick 0.0.0-stage → 1.0.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.
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const { execFileSync } = require('child_process');
8
+ const { ConfigError } = require('../utils/errors');
9
+ const { parseRemoteUrl } = require('../git/remote-url');
10
+ const { getDefaultConfig } = require('./defaults');
11
+ const { validateConfig } = require('./validator');
12
+
13
+ // The config can hold secrets (gitlab.token, ai.apiKey), so it lives in the developer's home
14
+ // directory, never inside the project, where it could end up committed. One file per project.
15
+ // RELEASE_CHERRY_PICK_CONFIG_DIR overrides the directory (used by the sandbox and tests).
16
+ function getConfigDir() {
17
+ return process.env.RELEASE_CHERRY_PICK_CONFIG_DIR || path.join(os.homedir(), '.release-cherry-pick');
18
+ }
19
+
20
+ function runGit(args) {
21
+ try {
22
+ return execFileSync('git', args, { cwd: process.cwd(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
23
+ } catch {
24
+ return '';
25
+ }
26
+ }
27
+
28
+ function toFileName(value) {
29
+ return value.toLowerCase().replace(/[^a-z0-9._-]+/g, '_').replace(/^[_.]+|_+$/g, '');
30
+ }
31
+
32
+ // Identifies the current project: from the origin remote (host + project path, e.g.
33
+ // "gitlab.example.com_group_proj"), so it's unique even when two checkouts share a folder name and
34
+ // stable if the folder is moved or renamed; without a usable remote, from the repository folder name
35
+ // plus a short hash of its absolute path.
36
+ function getProjectKey() {
37
+ const remote = parseRemoteUrl(runGit(['remote', 'get-url', 'origin']));
38
+ if (remote && remote.host && remote.projectPath) {
39
+ return toFileName(`${remote.host}_${remote.projectPath}`);
40
+ }
41
+
42
+ const root = path.resolve(runGit(['rev-parse', '--show-toplevel']) || process.cwd());
43
+ const normalizedRoot = process.platform === 'win32' ? root.toLowerCase() : root;
44
+ const hash = crypto.createHash('sha1').update(normalizedRoot).digest('hex').slice(0, 8);
45
+ return `${toFileName(path.basename(root)) || 'project'}-${hash}`;
46
+ }
47
+
48
+ // Resolved once per run (per working directory): the project doesn't change during a release.
49
+ const configPathCache = new Map();
50
+ function getConfigPath() {
51
+ const cwd = process.cwd();
52
+ if (!configPathCache.has(cwd)) {
53
+ configPathCache.set(cwd, path.join(getConfigDir(), `${getProjectKey()}.json`));
54
+ }
55
+ return configPathCache.get(cwd);
56
+ }
57
+
58
+ function isPlainObject(value) {
59
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
60
+ }
61
+
62
+ // Recursively fills in whatever `config` is missing from `defaults`. Values present in `config`
63
+ // win (arrays are replaced, not merged); keys unknown to the defaults are kept as-is.
64
+ function mergeWithDefaults(defaults, config) {
65
+ if (!isPlainObject(defaults) || !isPlainObject(config)) {
66
+ return config === undefined ? defaults : config;
67
+ }
68
+
69
+ const merged = { ...defaults };
70
+ for (const [key, value] of Object.entries(config)) {
71
+ merged[key] = key in defaults ? mergeWithDefaults(defaults[key], value) : value;
72
+ }
73
+ return merged;
74
+ }
75
+
76
+ // Returns the config file merged over the defaults (so options added in newer versions are always
77
+ // present), or null if there's no config file. Validates the result unless `validate` is false.
78
+ function loadConfig({ validate = true } = {}) {
79
+ const configPath = getConfigPath();
80
+
81
+ if (!fs.existsSync(configPath)) {
82
+ return null;
83
+ }
84
+
85
+ let fileConfig;
86
+ try {
87
+ fileConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
88
+ } catch (error) {
89
+ throw new ConfigError(`Error reading config file ${configPath}: ${error.message}`);
90
+ }
91
+
92
+ if (!isPlainObject(fileConfig)) {
93
+ throw new ConfigError(`Config file ${configPath} must contain a JSON object`);
94
+ }
95
+
96
+ const config = mergeWithDefaults(getDefaultConfig(), fileConfig);
97
+ if (validate) {
98
+ validateConfig(config, configPath);
99
+ }
100
+ return config;
101
+ }
102
+
103
+ function saveConfig(config) {
104
+ const configPath = getConfigPath();
105
+
106
+ try {
107
+ // Owner-only permissions (applied on Linux/macOS; on Windows the home folder is already private)
108
+ fs.mkdirSync(path.dirname(configPath), { recursive: true, mode: 0o700 });
109
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), { encoding: 'utf8', mode: 0o600 });
110
+ return true;
111
+ } catch (error) {
112
+ throw new ConfigError(`Error saving config file ${configPath}: ${error.message}`);
113
+ }
114
+ }
115
+
116
+ function configExists() {
117
+ return fs.existsSync(getConfigPath());
118
+ }
119
+
120
+ module.exports = {
121
+ loadConfig,
122
+ saveConfig,
123
+ configExists,
124
+ getConfigPath,
125
+ getConfigDir,
126
+ mergeWithDefaults
127
+ };
@@ -0,0 +1,463 @@
1
+ 'use strict';
2
+
3
+ const inquirer = require('inquirer');
4
+ const { searchableList } = require('../utils/prompts');
5
+ const { loadConfig, saveConfig, getConfigPath } = require('./loader');
6
+ const { getDefaultConfig } = require('./defaults');
7
+ const { validateConfig } = require('./validator');
8
+ const gitlab = require('../gitlab/client');
9
+ const { findDefaultReviewers } = require('../gitlab/reviewer-selector');
10
+ const logger = require('../utils/logger');
11
+ const {
12
+ DEFAULT_PROVIDER,
13
+ loadProviderCatalog,
14
+ getProviderChoices,
15
+ getEnvKeyNames,
16
+ findEnvValue,
17
+ resolveBaseURL,
18
+ listModelsForProvider
19
+ } = require('./ai-providers');
20
+
21
+ const CUSTOM_MODEL_CHOICE = '__custom_model__';
22
+ const BACK_CHOICE = '__back__';
23
+ const RESTORE_SAVED_CHOICE = '__restore_saved__';
24
+ const RESET_MODEL_CHOICE = '__reset_model__';
25
+
26
+ // Sequential flow like OpenCode's /connect: list all providers → enter API key
27
+ // (skipped when the env var is already set) → connect and list that provider's models.
28
+ // Supports going back (model → provider) and restoring the previously saved selection.
29
+ async function promptAiProviderAndModel(config) {
30
+ const catalog = await loadProviderCatalog();
31
+ const choices = getProviderChoices(catalog);
32
+ const savedProvider = (config.ai && config.ai.provider) || DEFAULT_PROVIDER;
33
+ const savedModel = config.ai && config.ai.model;
34
+ const hasSaved = Boolean(config.ai && config.ai.provider && config.ai.model);
35
+
36
+ for (;;) {
37
+ const providerChoices = [...choices];
38
+ if (hasSaved) {
39
+ providerChoices.unshift({
40
+ name: `↺ Restore saved selection (${config.ai.provider} / ${config.ai.model})`,
41
+ value: RESTORE_SAVED_CHOICE
42
+ });
43
+ }
44
+
45
+ const { aiProvider } = await inquirer.prompt([
46
+ searchableList({
47
+ name: 'aiProvider',
48
+ message: `AI provider (${choices.length} available), type to search:`,
49
+ pageSize: 20,
50
+ default: hasSaved
51
+ ? RESTORE_SAVED_CHOICE
52
+ : (choices.some((choice) => choice.value === savedProvider) ? savedProvider : undefined)
53
+ }, providerChoices)
54
+ ]);
55
+
56
+ if (aiProvider === RESTORE_SAVED_CHOICE) {
57
+ logger.info('Restored saved AI selection');
58
+ return {
59
+ provider: config.ai.provider,
60
+ model: config.ai.model,
61
+ apiKey: config.ai.apiKey || '',
62
+ baseURL: config.ai.baseURL || ''
63
+ };
64
+ }
65
+
66
+ const provider = catalog[aiProvider] || { id: aiProvider, name: aiProvider, env: '', models: {} };
67
+ const envKeyNames = getEnvKeyNames(provider);
68
+ const envValue = findEnvValue(envKeyNames);
69
+ const savedKey = config.ai && config.ai.provider === aiProvider ? config.ai.apiKey || '' : '';
70
+
71
+ let apiKey = envValue || savedKey;
72
+ if (!apiKey) {
73
+ const { enteredKey } = await inquirer.prompt([
74
+ {
75
+ type: 'password',
76
+ name: 'enteredKey',
77
+ message: envKeyNames.length
78
+ ? `API key for ${provider.name} (env ${envKeyNames.join(' or ')} not set):`
79
+ : `API key for ${provider.name} (leave blank if not required):`,
80
+ mask: '*',
81
+ when: () => true,
82
+ filter: (value) => (value ? String(value).trim() : '')
83
+ }
84
+ ]);
85
+ apiKey = enteredKey || '';
86
+ }
87
+
88
+ const baseURL = resolveBaseURL(aiProvider, provider, config);
89
+
90
+ if (apiKey || baseURL) {
91
+ logger.info(`Connecting to ${provider.name || aiProvider} to list models...`);
92
+ }
93
+ const { models, source } = await listModelsForProvider(aiProvider, provider, apiKey, baseURL);
94
+
95
+ if (source === 'live') {
96
+ logger.success(`Connected to ${provider.name || aiProvider}: ${models.length} model(s) available`);
97
+ } else if (source === 'catalog') {
98
+ logger.warn(`Could not reach ${provider.name || aiProvider} API; showing models.dev catalog (${models.length} model(s))`);
99
+ } else {
100
+ logger.warn(`No models found for ${provider.name || aiProvider}; you can enter a model ID manually`);
101
+ }
102
+
103
+ const modelChoices = [...models];
104
+ if (savedModel && !modelChoices.includes(savedModel)) {
105
+ modelChoices.unshift(savedModel);
106
+ }
107
+ modelChoices.push({ name: 'Custom model (enter manually)', value: CUSTOM_MODEL_CHOICE });
108
+ modelChoices.push({
109
+ name: `← Back (choose another provider)`,
110
+ value: BACK_CHOICE
111
+ });
112
+ if (savedModel) {
113
+ modelChoices.push({
114
+ name: `↺ Reset to saved model (${savedModel})`,
115
+ value: RESET_MODEL_CHOICE
116
+ });
117
+ }
118
+
119
+ const defaultModel = savedModel && modelChoices.includes(savedModel)
120
+ ? savedModel
121
+ : (models[0] || CUSTOM_MODEL_CHOICE);
122
+
123
+ const { aiModelChoice } = await inquirer.prompt([
124
+ searchableList({
125
+ name: 'aiModelChoice',
126
+ message: `Models from ${provider.name || aiProvider}, type to search:`,
127
+ pageSize: 15,
128
+ default: defaultModel
129
+ }, modelChoices)
130
+ ]);
131
+
132
+ if (aiModelChoice === BACK_CHOICE) {
133
+ continue;
134
+ }
135
+
136
+ if (aiModelChoice === RESET_MODEL_CHOICE) {
137
+ logger.info(`Reset model to saved selection: ${savedModel}`);
138
+ return {
139
+ provider: aiProvider,
140
+ model: savedModel,
141
+ apiKey,
142
+ baseURL: baseURL || ''
143
+ };
144
+ }
145
+
146
+ let model = aiModelChoice;
147
+ if (aiModelChoice === CUSTOM_MODEL_CHOICE) {
148
+ const { aiModelCustom } = await inquirer.prompt([
149
+ {
150
+ type: 'input',
151
+ name: 'aiModelCustom',
152
+ message: 'Custom AI model ID (leave blank to go back):',
153
+ filter: (value) => (value ? String(value).trim() : '')
154
+ }
155
+ ]);
156
+ const custom = aiModelCustom || '';
157
+ if (!custom) {
158
+ continue;
159
+ }
160
+ model = custom;
161
+ }
162
+
163
+ return {
164
+ provider: aiProvider,
165
+ model,
166
+ apiKey,
167
+ baseURL: baseURL || ''
168
+ };
169
+ }
170
+ }
171
+
172
+ // If AI is enabled but provider/model were never saved, ask for them and persist.
173
+ async function ensureAiSettings(config) {
174
+ if (!config || !config.ai || !config.ai.enabled) {
175
+ return config;
176
+ }
177
+ if (config.ai.provider && config.ai.model) {
178
+ return config;
179
+ }
180
+
181
+ logger.warn('AI is enabled but provider/model is not saved in configuration');
182
+ const selection = await promptAiProviderAndModel(config);
183
+
184
+ config.ai.provider = selection.provider;
185
+ config.ai.model = selection.model;
186
+ config.ai.apiKey = selection.apiKey || (config.ai.apiKey || '');
187
+ config.ai.baseURL = selection.baseURL || (config.ai.baseURL || '');
188
+ saveConfig(config);
189
+ logger.success('AI provider and model saved to configuration');
190
+ return config;
191
+ }
192
+
193
+ async function setupWizard() {
194
+ logger.header('Configuration Setup');
195
+
196
+ // Start from the existing config (merged with defaults) without validating it, so the wizard
197
+ // can also be used to repair an invalid file.
198
+ let config;
199
+ try {
200
+ config = loadConfig({ validate: false }) || getDefaultConfig();
201
+ } catch (error) {
202
+ logger.warn(`${error.message}\nStarting from the default configuration instead.`);
203
+ config = getDefaultConfig();
204
+ }
205
+ if (!config.release || !Array.isArray(config.release.branches)) {
206
+ config.release = { ...(config.release || {}), branches: [] };
207
+ }
208
+ if (!config.ai || typeof config.ai !== 'object') {
209
+ config.ai = getDefaultConfig().ai;
210
+ }
211
+
212
+ const questions = [
213
+ {
214
+ type: 'input',
215
+ name: 'stagingBranch',
216
+ message: 'Staging branch name:',
217
+ default: config.git.stagingBranch
218
+ },
219
+ {
220
+ type: 'input',
221
+ name: 'featurePrefix',
222
+ message: 'Feature branch prefix:',
223
+ default: config.git.branchPrefix.feature
224
+ },
225
+ {
226
+ type: 'input',
227
+ name: 'hotfixPrefix',
228
+ message: 'Hotfix branch prefix:',
229
+ default: config.git.branchPrefix.hotfix
230
+ },
231
+ {
232
+ type: 'input',
233
+ name: 'releasePrefix',
234
+ message: 'Release branch prefix:',
235
+ default: config.git.branchPrefix.release
236
+ },
237
+ {
238
+ type: 'input',
239
+ name: 'gitlabHost',
240
+ message: 'GitLab hostname, e.g. gitlab.example.com (leave blank to use the host of the origin remote):',
241
+ default: config.gitlab.host,
242
+ // Keeps only the host if a project/page URL is pasted (see normalizeGitlabHost)
243
+ filter: (value) => gitlab.normalizeGitlabHost(value)
244
+ },
245
+ {
246
+ type: 'password',
247
+ name: 'gitlabToken',
248
+ message: 'GitLab personal access token, scope "api" (leave blank to keep current / use GITLAB_TOKEN env):',
249
+ mask: '*',
250
+ when: () => true,
251
+ filter: (value) => (value ? String(value).trim() : ''),
252
+ validate: (value) =>
253
+ value === '' || value === undefined || value.length >= 8 || 'Token looks too short (min 8 chars)'
254
+ },
255
+ {
256
+ type: 'confirm',
257
+ name: 'aiEnabled',
258
+ message: 'Enable AI for MR titles/descriptions?',
259
+ default: config.ai.enabled
260
+ },
261
+ {
262
+ type: 'confirm',
263
+ name: 'autoCreateMR',
264
+ message: 'Push release branches and create GitLab MRs automatically? (no = only prepare branches locally)',
265
+ default: config.release.autoCreateMR
266
+ },
267
+ {
268
+ type: 'input',
269
+ name: 'mrTitleFormat',
270
+ message: 'MR title template when AI is off ({taskId} and {description} are replaced):',
271
+ when: (answers) => answers.autoCreateMR,
272
+ default: config.release.mrTitleFormat
273
+ },
274
+ {
275
+ type: 'confirm',
276
+ name: 'mrSquash',
277
+ message: 'Check "Squash commits" on created MRs?',
278
+ when: (answers) => answers.autoCreateMR,
279
+ default: config.release.mrSquash
280
+ },
281
+ {
282
+ type: 'confirm',
283
+ name: 'mrRemoveSourceBranch',
284
+ message: 'Check "Delete source branch" on created MRs?',
285
+ when: (answers) => answers.autoCreateMR,
286
+ default: config.release.mrRemoveSourceBranch
287
+ }
288
+ ];
289
+
290
+ const answers = await inquirer.prompt(questions);
291
+
292
+ let aiSelection = null;
293
+ if (answers.aiEnabled) {
294
+ aiSelection = await promptAiProviderAndModel(config);
295
+ }
296
+
297
+ const newConfig = {
298
+ git: {
299
+ stagingBranch: answers.stagingBranch,
300
+ branchPrefix: {
301
+ feature: answers.featurePrefix,
302
+ hotfix: answers.hotfixPrefix,
303
+ release: answers.releasePrefix
304
+ }
305
+ },
306
+ gitlab: {
307
+ host: answers.gitlabHost,
308
+ token: answers.gitlabToken || (config.gitlab.token || '')
309
+ },
310
+ ai: answers.aiEnabled && aiSelection
311
+ ? {
312
+ enabled: true,
313
+ provider: aiSelection.provider,
314
+ apiKey: aiSelection.apiKey || '',
315
+ model: aiSelection.model,
316
+ baseURL: aiSelection.baseURL || ''
317
+ }
318
+ : {
319
+ enabled: false,
320
+ provider: config.ai.provider || DEFAULT_PROVIDER,
321
+ apiKey: config.ai.apiKey || '',
322
+ model: config.ai.model || '',
323
+ baseURL: config.ai.baseURL || ''
324
+ },
325
+ release: {
326
+ ...config.release,
327
+ autoCreateMR: answers.autoCreateMR
328
+ }
329
+ };
330
+
331
+ if (answers.autoCreateMR) {
332
+ newConfig.release.mrTitleFormat = answers.mrTitleFormat;
333
+ newConfig.release.mrSquash = answers.mrSquash;
334
+ newConfig.release.mrRemoveSourceBranch = answers.mrRemoveSourceBranch;
335
+
336
+ await selectDefaultMembers(newConfig);
337
+ }
338
+
339
+ const { reviewAction } = await inquirer.prompt([
340
+ {
341
+ type: 'list',
342
+ name: 'reviewAction',
343
+ message: 'Review configuration:',
344
+ choices: [
345
+ { name: '✔ Save configuration', value: 'save' },
346
+ { name: '← Back (edit again from initial values)', value: 'back' },
347
+ { name: '✖ Cancel (discard changes)', value: 'cancel' }
348
+ ],
349
+ default: 'save'
350
+ }
351
+ ]);
352
+
353
+ if (reviewAction === 'back') {
354
+ logger.info('Returning to the start of the setup wizard');
355
+ return setupWizard();
356
+ }
357
+
358
+ if (reviewAction === 'cancel') {
359
+ logger.warn('Configuration setup cancelled; no changes were saved');
360
+ return config;
361
+ }
362
+
363
+ try {
364
+ validateConfig(newConfig);
365
+ saveConfig(newConfig);
366
+ logger.success(`Configuration saved to ${getConfigPath()}`);
367
+ return newConfig;
368
+ } catch (error) {
369
+ logger.error(error.message);
370
+ return null;
371
+ }
372
+ }
373
+
374
+ // Sets release.defaultReviewers / release.defaultAssignees, picking from the real GitLab project
375
+ // members (REST API, with the token just configured) when possible, or typed usernames otherwise.
376
+ async function selectDefaultMembers(config) {
377
+ const release = config.release;
378
+ const members = await fetchProjectMembers(config);
379
+
380
+ if (members) {
381
+ const reviewerDefaults = findDefaultReviewers(members, release).map(m => m.username);
382
+ release.defaultReviewers = await pickMembers(
383
+ 'defaultReviewers',
384
+ members,
385
+ reviewerDefaults,
386
+ release.defaultReviewers,
387
+ 'Default MR reviewer(s) (preselected in each MR\'s reviewer prompt):'
388
+ );
389
+ release.defaultAssignees = await pickMembers(
390
+ 'defaultAssignees',
391
+ members,
392
+ release.defaultAssignees,
393
+ release.defaultAssignees,
394
+ 'Default MR assignee(s) (assigned automatically to every MR):'
395
+ );
396
+ } else {
397
+ release.defaultReviewers = await askUsernames('defaultReviewers', 'Default MR reviewer usernames (comma-separated, blank for none):', release.defaultReviewers);
398
+ release.defaultAssignees = await askUsernames('defaultAssignees', 'Default MR assignee usernames (comma-separated, blank for none):', release.defaultAssignees);
399
+ }
400
+
401
+ // Reviewers are now an explicit list; the legacy regex has been migrated into it
402
+ delete release.defaultReviewerPattern;
403
+ }
404
+
405
+ async function fetchProjectMembers(config) {
406
+ // Not gitlab.ensureAuthenticated(): it prompts for a token and saves the config to disk, which
407
+ // would bypass the wizard's review/cancel step. Without a token, fall back to typed usernames.
408
+ if (!gitlab.getToken(config)) {
409
+ logger.warn('No GitLab token configured (gitlab.token / GITLAB_TOKEN), so project members can\'t be listed; enter usernames manually instead.');
410
+ return null;
411
+ }
412
+
413
+ try {
414
+ logger.info('Loading GitLab project members...');
415
+ const members = await gitlab.getProjectMembers(config);
416
+ if (members.length === 0) {
417
+ logger.warn('The GitLab project has no members to choose from; enter usernames manually instead.');
418
+ return null;
419
+ }
420
+ return members;
421
+ } catch (error) {
422
+ logger.warn(`Could not load GitLab project members (${error.message}); enter usernames manually instead.`);
423
+ return null;
424
+ }
425
+ }
426
+
427
+ async function pickMembers(name, members, checkedUsernames, configuredUsernames, message) {
428
+ const checked = new Set(checkedUsernames.map(u => u.toLowerCase()));
429
+ const choices = members.map(m => ({
430
+ name: `${m.name} (@${m.username})`,
431
+ value: m.username,
432
+ checked: checked.has(m.username.toLowerCase())
433
+ }));
434
+
435
+ // Keep previously configured usernames that are no longer project members visible, so they
436
+ // aren't dropped silently — the user decides whether to keep them.
437
+ for (const username of configuredUsernames) {
438
+ if (!members.some(m => m.username.toLowerCase() === username.toLowerCase())) {
439
+ choices.push({ name: `@${username} (not found among project members)`, value: username, checked: true });
440
+ }
441
+ }
442
+
443
+ const answers = await inquirer.prompt([
444
+ { type: 'checkbox', name, message, pageSize: 15, choices }
445
+ ]);
446
+ return answers[name];
447
+ }
448
+
449
+ async function askUsernames(name, message, current) {
450
+ const answers = await inquirer.prompt([
451
+ { type: 'input', name, message, default: current.join(', ') }
452
+ ]);
453
+ return String(answers[name])
454
+ .split(',')
455
+ .map(u => u.trim().replace(/^@/, ''))
456
+ .filter(Boolean);
457
+ }
458
+
459
+ module.exports = {
460
+ setupWizard,
461
+ ensureAiSettings,
462
+ promptAiProviderAndModel
463
+ };
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+
3
+ const { ConfigError } = require('../utils/errors');
4
+
5
+ function isPlainObject(value) {
6
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ }
8
+
9
+ // Validates a complete (already merged with defaults) config. Collects every problem and throws a
10
+ // single ConfigError listing them all, so a broken file is reported up front with a clear message.
11
+ function validateConfig(config, source = 'configuration') {
12
+ const errors = [];
13
+
14
+ const expect = (value, name, check, description) => {
15
+ if (!check(value)) {
16
+ errors.push(`${name} must be ${description} (got ${JSON.stringify(value)})`);
17
+ }
18
+ };
19
+ const isString = v => typeof v === 'string';
20
+ const isNonEmptyString = v => typeof v === 'string' && v.trim() !== '';
21
+ const isBoolean = v => typeof v === 'boolean';
22
+ const isStringArray = v => Array.isArray(v) && v.every(isNonEmptyString);
23
+
24
+ for (const section of ['git', 'gitlab', 'ai', 'release']) {
25
+ if (!isPlainObject(config[section])) {
26
+ errors.push(`${section} must be an object`);
27
+ }
28
+ }
29
+
30
+ if (errors.length === 0) {
31
+ const { git, gitlab, ai, release } = config;
32
+
33
+ expect(git.stagingBranch, 'git.stagingBranch', isNonEmptyString, 'a non-empty string');
34
+ if (isPlainObject(git.branchPrefix)) {
35
+ for (const [type, prefix] of Object.entries(git.branchPrefix)) {
36
+ expect(prefix, `git.branchPrefix.${type}`, isString, 'a string');
37
+ }
38
+ expect(git.branchPrefix.release, 'git.branchPrefix.release', isNonEmptyString, 'a non-empty string');
39
+ } else {
40
+ errors.push('git.branchPrefix must be an object');
41
+ }
42
+
43
+ expect(gitlab.host, 'gitlab.host', isString, 'a string');
44
+ expect(gitlab.token, 'gitlab.token', isString, 'a string');
45
+
46
+ // provider/model may be empty: the wizard saves them blank when AI is off, and
47
+ // ensureAiSettings asks for them at release time when AI is on but they're missing
48
+ expect(ai.enabled, 'ai.enabled', isBoolean, 'true or false');
49
+ expect(ai.provider, 'ai.provider', isString, 'a string');
50
+ expect(ai.apiKey, 'ai.apiKey', isString, 'a string');
51
+ expect(ai.model, 'ai.model', isString, 'a string');
52
+ expect(ai.baseURL, 'ai.baseURL', isString, 'a string');
53
+
54
+ expect(release.autoCreateMR, 'release.autoCreateMR', isBoolean, 'true or false');
55
+ expect(release.mrTitleFormat, 'release.mrTitleFormat', isNonEmptyString, 'a non-empty string');
56
+ expect(release.mrSquash, 'release.mrSquash', isBoolean, 'true or false');
57
+ expect(release.mrRemoveSourceBranch, 'release.mrRemoveSourceBranch', isBoolean, 'true or false');
58
+ expect(release.defaultReviewers, 'release.defaultReviewers', isStringArray, 'a list of GitLab usernames');
59
+ expect(release.defaultAssignees, 'release.defaultAssignees', isStringArray, 'a list of GitLab usernames');
60
+ expect(release.branches, 'release.branches', isStringArray, 'a list of branch names');
61
+
62
+ if (release.defaultReviewerPattern !== undefined) {
63
+ try {
64
+ new RegExp(release.defaultReviewerPattern, 'i');
65
+ } catch (error) {
66
+ errors.push(`release.defaultReviewerPattern is not a valid regular expression: ${error.message}`);
67
+ }
68
+ }
69
+ }
70
+
71
+ if (errors.length > 0) {
72
+ throw new ConfigError(`Invalid ${source}:\n - ${errors.join('\n - ')}`);
73
+ }
74
+
75
+ return true;
76
+ }
77
+
78
+ module.exports = {
79
+ validateConfig
80
+ };