next-issue 2.21.1 → 3.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.
Files changed (73) hide show
  1. package/README.md +89 -124
  2. package/dist/agent-reply.mjs +13 -0
  3. package/dist/agent-session.mjs +56 -0
  4. package/dist/agents.mjs +47 -88
  5. package/dist/args.mjs +26 -31
  6. package/dist/base-checks.mjs +37 -0
  7. package/dist/budget.mjs +16 -0
  8. package/dist/check-poll.mjs +73 -0
  9. package/dist/checks.mjs +67 -0
  10. package/dist/children.mjs +52 -0
  11. package/dist/cli.mjs +25 -15
  12. package/dist/command-records.mjs +15 -0
  13. package/dist/config-fields.mjs +32 -0
  14. package/dist/config.mjs +36 -71
  15. package/dist/conflict.mjs +43 -42
  16. package/dist/durations.mjs +37 -0
  17. package/dist/enter-review.mjs +13 -0
  18. package/dist/errors.mjs +20 -0
  19. package/dist/exec.mjs +71 -107
  20. package/dist/files.mjs +28 -0
  21. package/dist/fix.mjs +61 -50
  22. package/dist/gate.mjs +31 -43
  23. package/dist/gh.mjs +55 -0
  24. package/dist/git-commit.mjs +36 -0
  25. package/dist/git-land.mjs +30 -0
  26. package/dist/git-merge.mjs +42 -0
  27. package/dist/git.mjs +42 -166
  28. package/dist/github.mjs +32 -386
  29. package/dist/gitignore.mjs +13 -0
  30. package/dist/hand-over-comments.mjs +81 -0
  31. package/dist/handover.mjs +62 -103
  32. package/dist/implement.mjs +32 -0
  33. package/dist/interrupt.mjs +6 -19
  34. package/dist/job.mjs +28 -17
  35. package/dist/labels.mjs +65 -0
  36. package/dist/land.mjs +66 -0
  37. package/dist/lock.mjs +54 -0
  38. package/dist/logs.mjs +84 -62
  39. package/dist/loop.mjs +12 -37
  40. package/dist/observe.mjs +24 -98
  41. package/dist/open-job.mjs +39 -0
  42. package/dist/pending.mjs +46 -0
  43. package/dist/pipeline.mjs +34 -217
  44. package/dist/poll.mjs +20 -0
  45. package/dist/ports.mjs +18 -3
  46. package/dist/progress.mjs +36 -22
  47. package/dist/prompts.mjs +31 -36
  48. package/dist/protocol.mjs +17 -11
  49. package/dist/prune-runs.mjs +33 -0
  50. package/dist/pull-requests.mjs +60 -0
  51. package/dist/questions.mjs +45 -0
  52. package/dist/records.mjs +3 -0
  53. package/dist/render.mjs +19 -0
  54. package/dist/revert.mjs +27 -0
  55. package/dist/review.mjs +63 -83
  56. package/dist/run-logs.mjs +23 -0
  57. package/dist/run.mjs +59 -58
  58. package/dist/serve.mjs +46 -214
  59. package/dist/setup.mjs +2 -5
  60. package/dist/skip.mjs +54 -0
  61. package/dist/state.mjs +27 -39
  62. package/dist/summary.mjs +11 -7
  63. package/dist/text.mjs +15 -0
  64. package/dist/usage.mjs +45 -0
  65. package/dist/verdict.mjs +20 -13
  66. package/dist/watch.mjs +38 -0
  67. package/dist/worker-paths.mjs +16 -0
  68. package/dist/worker-run.mjs +56 -0
  69. package/dist/worker-server.mjs +56 -0
  70. package/dist/worktree-setup.mjs +25 -0
  71. package/dist/worktree.mjs +58 -0
  72. package/package.json +1 -1
  73. package/dist/merge.mjs +0 -75
package/dist/args.mjs CHANGED
@@ -1,4 +1,17 @@
1
- import { CONFIG_FILE } from './config.mjs';
1
+ import { CONFIG_FILE } from './config-fields.mjs';
2
+ const SWITCHES = new Map([
3
+ ['--force', 'force'],
4
+ ['--json', 'json'],
5
+ ['--help', 'help'],
6
+ ['--merge', 'merge'],
7
+ ['--watch', 'watch'],
8
+ ['--reset', 'reset'],
9
+ ['--once', 'once'],
10
+ ]);
11
+ const LEVELS = new Map([
12
+ ['--verbose', 'verbose'],
13
+ ['--quiet', 'quiet'],
14
+ ]);
2
15
  export const USAGE = `next-issue [command] [options]
3
16
 
4
17
  init write ${CONFIG_FILE} with the defaults
@@ -8,7 +21,7 @@ export const USAGE = `next-issue [command] [options]
8
21
 
9
22
  --once stop after the first handled issue
10
23
  --max <n> handle at most n issues
11
- --merge squash-merge the pull request after the approval
24
+ --merge no effect: an approved change always lands on the base branch
12
25
  --watch keep running and read the issues again after each pass
13
26
  --reset drop the saved budgets and findings first
14
27
  --json print the machine summary instead of the text one, or raw lines with logs
@@ -32,37 +45,13 @@ export function parseArgs(argv) {
32
45
  for (let index = 0; index < argv.length; index += 1) {
33
46
  const arg = argv[index];
34
47
  if (index === 0 && !arg.startsWith('-')) {
35
- if (arg !== 'init' && arg !== 'serve' && arg !== 'stop' && arg !== 'logs') {
36
- throw new Error(`Unknown command: ${arg}`);
37
- }
38
- args.command = arg;
48
+ args.command = command(arg);
39
49
  }
40
- else if (arg === '--force') {
41
- args.force = true;
50
+ else if (SWITCHES.has(arg)) {
51
+ args[SWITCHES.get(arg)] = true;
42
52
  }
43
- else if (arg === '--json') {
44
- args.json = true;
45
- }
46
- else if (arg === '--help') {
47
- args.help = true;
48
- }
49
- else if (arg === '--merge') {
50
- args.merge = true;
51
- }
52
- else if (arg === '--watch') {
53
- args.watch = true;
54
- }
55
- else if (arg === '--reset') {
56
- args.reset = true;
57
- }
58
- else if (arg === '--once') {
59
- args.once = true;
60
- }
61
- else if (arg === '--verbose') {
62
- args.level = 'verbose';
63
- }
64
- else if (arg === '--quiet') {
65
- args.level = 'quiet';
53
+ else if (LEVELS.has(arg)) {
54
+ args.level = LEVELS.get(arg);
66
55
  }
67
56
  else if (arg === '--max') {
68
57
  args.max = whole(argv[++index], arg);
@@ -73,6 +62,12 @@ export function parseArgs(argv) {
73
62
  }
74
63
  return args;
75
64
  }
65
+ function command(arg) {
66
+ if (arg !== 'init' && arg !== 'serve' && arg !== 'stop' && arg !== 'logs') {
67
+ throw new Error(`Unknown command: ${arg}`);
68
+ }
69
+ return arg;
70
+ }
76
71
  function whole(value, option) {
77
72
  const parsed = Number(value);
78
73
  if (value === undefined || !Number.isInteger(parsed) || parsed < 1) {
@@ -0,0 +1,37 @@
1
+ import { pollChecks } from './check-poll.mjs';
2
+ import { ghJson } from './gh.mjs';
3
+ import { runLogs } from './run-logs.mjs';
4
+ const FAILED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure']);
5
+ async function baseRuns(repo, sha) {
6
+ return ghJson(repo, [
7
+ 'run',
8
+ 'list',
9
+ '--commit',
10
+ sha,
11
+ '--json',
12
+ 'databaseId,name,status,conclusion',
13
+ ]);
14
+ }
15
+ function failedRun(entry) {
16
+ return entry.status === 'completed' && FAILED_CONCLUSIONS.has(entry.conclusion);
17
+ }
18
+ function baseState(runs) {
19
+ if (runs.some(failedRun)) {
20
+ return 'fail';
21
+ }
22
+ return runs.every((entry) => entry.status === 'completed') ? 'pass' : 'pending';
23
+ }
24
+ export function waitForBaseChecks(repo, sha, options) {
25
+ return pollChecks({
26
+ head: async () => sha,
27
+ lags: async () => true,
28
+ list: async () => ((await baseRuns(repo, sha)).length === 0 ? 'none' : 'some'),
29
+ watch: async () => baseState(await baseRuns(repo, sha)),
30
+ }, options);
31
+ }
32
+ export async function failedBaseLogs(repo, sha, maxChars) {
33
+ const failed = (await baseRuns(repo, sha))
34
+ .filter(failedRun)
35
+ .map((entry) => ({ heading: `## ${entry.name}`, runId: String(entry.databaseId) }));
36
+ return runLogs(repo, failed, maxChars);
37
+ }
@@ -0,0 +1,16 @@
1
+ import { escalateAndFinish } from './handover.mjs';
2
+ import { writeState } from './state.mjs';
3
+ const LIMITS = { ciFixes: 'maxCiFixes', reviewRounds: 'maxReviewRounds' };
4
+ export function budgetUse(job, budget) {
5
+ return { round: job.state[budget], limit: job.context.config[LIMITS[budget]] };
6
+ }
7
+ export async function spendBudget(job, budget, note, reason) {
8
+ const { context, state } = job;
9
+ const { round, limit } = budgetUse(job, budget);
10
+ if (round >= limit) {
11
+ return escalateAndFinish(job, note, reason);
12
+ }
13
+ state[budget] += 1;
14
+ await writeState(context.repo, state);
15
+ return undefined;
16
+ }
@@ -0,0 +1,73 @@
1
+ import { minutesToMs, secondsToMs } from './durations.mjs';
2
+ import { asError } from './errors.mjs';
3
+ import { pause, REAL_CLOCK } from './poll.mjs';
4
+ const READ_TRIES = 3;
5
+ export function checkPolling(config) {
6
+ return {
7
+ intervalSeconds: config.checkIntervalSeconds,
8
+ timeoutMs: minutesToMs(config.checkTimeoutMinutes),
9
+ };
10
+ }
11
+ export function checkWaiting(config, grace) {
12
+ return {
13
+ ...checkPolling(config),
14
+ graceMs: grace ? secondsToMs(config.checkGraceSeconds) : 0,
15
+ };
16
+ }
17
+ export async function pollChecks(probe, options, clock = REAL_CLOCK) {
18
+ const deadline = clock.now() + options.timeoutMs;
19
+ const rest = () => Math.max(0, deadline - clock.now());
20
+ let shown;
21
+ let failures = 0;
22
+ for (;;) {
23
+ if (rest() === 0) {
24
+ return 'timeout';
25
+ }
26
+ const state = await read(probe, options.head, rest(), () => (shown ??= clock.now()));
27
+ if (state === 'behind' && shown !== undefined) {
28
+ return 'moved';
29
+ }
30
+ if (state instanceof Error) {
31
+ failures += 1;
32
+ if (failures >= READ_TRIES) {
33
+ throw state;
34
+ }
35
+ }
36
+ else {
37
+ failures = 0;
38
+ const outcome = settled(state, clock.now() - (shown ?? 0), options.graceMs);
39
+ if (outcome !== undefined) {
40
+ return outcome;
41
+ }
42
+ }
43
+ await pause(clock, options, rest());
44
+ }
45
+ }
46
+ function settled(state, waitedMs, graceMs) {
47
+ if (state === 'none') {
48
+ return waitedMs >= graceMs ? 'none' : undefined;
49
+ }
50
+ return state === 'behind' || state === 'pending' ? undefined : state;
51
+ }
52
+ async function read(probe, head, timeoutMs, shown) {
53
+ try {
54
+ if (head !== undefined) {
55
+ const current = await probe.head();
56
+ if (current !== head) {
57
+ return (await probe.lags(current)) ? 'behind' : 'moved';
58
+ }
59
+ }
60
+ shown();
61
+ if ((await probe.list()) === 'none') {
62
+ return 'none';
63
+ }
64
+ const state = await probe.watch(timeoutMs);
65
+ if (head !== undefined && (await probe.head()) !== head) {
66
+ return 'moved';
67
+ }
68
+ return state;
69
+ }
70
+ catch (error) {
71
+ return asError(error);
72
+ }
73
+ }
@@ -0,0 +1,67 @@
1
+ import { pollChecks } from './check-poll.mjs';
2
+ import { failedWith, succeeded } from './exec.mjs';
3
+ import { ghRun } from './gh.mjs';
4
+ import { isAncestor } from './git.mjs';
5
+ import { prField } from './pull-requests.mjs';
6
+ import { runLogs } from './run-logs.mjs';
7
+ const CHECK_PENDING_CODE = 8;
8
+ const NO_CHECKS = /no checks reported/i;
9
+ function failedCheck(check) {
10
+ return check.bucket === 'fail';
11
+ }
12
+ async function readChecks(repo, pr) {
13
+ const result = await ghRun(repo, [
14
+ 'pr',
15
+ 'checks',
16
+ String(pr),
17
+ '--json',
18
+ 'name,bucket,link,description',
19
+ ]);
20
+ const output = result.stdout.trim();
21
+ if (output.length === 0) {
22
+ if (NO_CHECKS.test(result.stderr)) {
23
+ return 'none';
24
+ }
25
+ throw new Error(failedWith(`gh pr checks ${pr}`, result));
26
+ }
27
+ const checks = JSON.parse(output);
28
+ return checks.length === 0 ? 'none' : checks;
29
+ }
30
+ async function watchOnce(repo, pr, intervalSeconds, timeoutMs, show) {
31
+ const watch = await ghRun(repo, ['pr', 'checks', String(pr), '--watch', '--fail-fast', '--interval', String(intervalSeconds)], { show, timeoutMs });
32
+ if (watch.timedOut) {
33
+ return 'timeout';
34
+ }
35
+ if (succeeded(watch)) {
36
+ return 'pass';
37
+ }
38
+ if (watch.code === CHECK_PENDING_CODE) {
39
+ return 'pending';
40
+ }
41
+ const checks = await readChecks(repo, pr);
42
+ if (checks !== 'none' && checks.some(failedCheck)) {
43
+ return 'fail';
44
+ }
45
+ throw new Error(`gh pr checks ${pr} --watch failed with code ${watch.code} and no check failed: ${watch.stderr.trim()}`);
46
+ }
47
+ export function waitForChecks(repo, pr, options) {
48
+ return pollChecks({
49
+ head: () => prField(repo, pr, 'headRefOid'),
50
+ lags: (head) => options.head === undefined
51
+ ? Promise.resolve(true)
52
+ : isAncestor(repo.root, head, options.head),
53
+ list: async () => ((await readChecks(repo, pr)) === 'none' ? 'none' : 'some'),
54
+ watch: (timeoutMs) => watchOnce(repo, pr, options.intervalSeconds, timeoutMs, options.show),
55
+ }, options);
56
+ }
57
+ export async function failedCheckLogs(repo, pr, maxChars) {
58
+ const checks = await readChecks(repo, pr);
59
+ if (checks === 'none') {
60
+ return 'The checks failed, but gh reports no check for the pull request.';
61
+ }
62
+ const failed = checks.filter(failedCheck).map((check) => ({
63
+ heading: `## ${check.name}\n${check.description}`,
64
+ runId: /\/actions\/runs\/(\d+)/.exec(check.link)?.[1],
65
+ }));
66
+ return runLogs(repo, failed, maxChars);
67
+ }
@@ -0,0 +1,52 @@
1
+ const groups = new Set();
2
+ const stoppers = new Set();
3
+ export function onStop(stopper) {
4
+ stoppers.add(stopper);
5
+ return () => stoppers.delete(stopper);
6
+ }
7
+ export function stopChildren(signal) {
8
+ for (const stopper of stoppers) {
9
+ stopper();
10
+ }
11
+ stoppers.clear();
12
+ for (const pid of groups) {
13
+ try {
14
+ process.kill(-pid, signal);
15
+ }
16
+ catch { }
17
+ }
18
+ groups.clear();
19
+ process.off('SIGTERM', onTerminate);
20
+ process.kill(process.pid, signal);
21
+ }
22
+ const onTerminate = () => stopChildren('SIGTERM');
23
+ export function watch(pid) {
24
+ if (pid === undefined) {
25
+ return;
26
+ }
27
+ if (groups.size === 0) {
28
+ process.on('SIGTERM', onTerminate);
29
+ }
30
+ groups.add(pid);
31
+ }
32
+ export function unwatch(pid) {
33
+ if (pid === undefined) {
34
+ return;
35
+ }
36
+ groups.delete(pid);
37
+ if (groups.size === 0) {
38
+ process.off('SIGTERM', onTerminate);
39
+ }
40
+ }
41
+ export function killTree(child) {
42
+ if (child.pid === undefined) {
43
+ child.kill('SIGKILL');
44
+ return;
45
+ }
46
+ try {
47
+ process.kill(-child.pid, 'SIGKILL');
48
+ }
49
+ catch {
50
+ child.kill('SIGKILL');
51
+ }
52
+ }
package/dist/cli.mjs CHANGED
@@ -1,17 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs, USAGE } from './args.mjs';
3
3
  import { writeDefaultConfig } from './config.mjs';
4
- import { ensureIgnored, repoRoot, WORKTREE_DIR } from './git.mjs';
4
+ import { message } from './errors.mjs';
5
+ import { prettyJson } from './files.mjs';
6
+ import { repoRoot } from './git.mjs';
7
+ import { ensureIgnored } from './gitignore.mjs';
5
8
  import { listenForInterrupts } from './interrupt.mjs';
9
+ import { stopWorker } from './lock.mjs';
6
10
  import { followLog, newestRunLog } from './logs.mjs';
7
- import { message } from './observe.mjs';
8
11
  import { runRepo } from './run.mjs';
9
- import { serve, stopWorker, workerPaths } from './serve.mjs';
12
+ import { serve } from './serve.mjs';
10
13
  import { STATE_DIR } from './state.mjs';
11
14
  import { formatSummary } from './summary.mjs';
15
+ import { workerPaths } from './worker-paths.mjs';
16
+ import { WORKTREE_DIR } from './worktree.mjs';
12
17
  function write(stream, text) {
13
18
  return new Promise((resolve, reject) => {
14
- stream.write(text, (error) => error === null || error === undefined ? resolve() : reject(error));
19
+ stream.write(text, (error) => (error ? reject(error) : resolve()));
15
20
  });
16
21
  }
17
22
  async function main() {
@@ -25,11 +30,7 @@ async function main() {
25
30
  return serve(root);
26
31
  }
27
32
  if (args.command === 'stop') {
28
- const pid = await stopWorker(workerPaths(root).lockPath);
29
- await write(process.stdout, pid === undefined
30
- ? 'next-issue: no worker is running\n'
31
- : `next-issue: stopped the worker with process id ${pid}\n`);
32
- return 0;
33
+ return stop(root);
33
34
  }
34
35
  if (args.command === 'init') {
35
36
  return init(root, args.force);
@@ -37,12 +38,22 @@ async function main() {
37
38
  if (args.command === 'logs') {
38
39
  return logs(root, args.json);
39
40
  }
41
+ return run(root, args);
42
+ }
43
+ function run(root, args) {
40
44
  const interrupts = listenForInterrupts((text) => void write(process.stderr, `${text}\n`));
41
45
  return runRepo(root, args, {
42
46
  interrupts,
43
- print: (summary) => write(process.stdout, args.json ? `${JSON.stringify(summary, null, 2)}\n` : formatSummary(summary)),
47
+ print: (summary) => write(process.stdout, args.json ? prettyJson(summary) : formatSummary(summary)),
44
48
  });
45
49
  }
50
+ async function stop(root) {
51
+ const pid = await stopWorker(workerPaths(root).lockPath);
52
+ await write(process.stdout, pid === undefined
53
+ ? 'next-issue: no worker is running\n'
54
+ : `next-issue: stopped the worker with process id ${pid}\n`);
55
+ return 0;
56
+ }
46
57
  async function logs(root, json) {
47
58
  const file = await newestRunLog(root);
48
59
  if (file === undefined) {
@@ -55,11 +66,10 @@ async function logs(root, json) {
55
66
  async function init(root, force) {
56
67
  const path = await writeDefaultConfig(root, force);
57
68
  await write(process.stdout, `wrote ${path}\n`);
58
- if (await ensureIgnored(root, `${STATE_DIR}/`)) {
59
- await write(process.stdout, `added ${STATE_DIR}/ to .gitignore\n`);
60
- }
61
- if (await ensureIgnored(root, `${WORKTREE_DIR}/`)) {
62
- await write(process.stdout, `added ${WORKTREE_DIR}/ to .gitignore\n`);
69
+ for (const directory of [STATE_DIR, WORKTREE_DIR]) {
70
+ if (await ensureIgnored(root, `${directory}/`)) {
71
+ await write(process.stdout, `added ${directory}/ to .gitignore\n`);
72
+ }
63
73
  }
64
74
  return 0;
65
75
  }
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { setCommandObserver, succeeded } from './exec.mjs';
3
+ const commandRecorder = new AsyncLocalStorage();
4
+ setCommandObserver((record) => {
5
+ commandRecorder.getStore()?.event(succeeded(record) ? 'command' : 'command.fail', {
6
+ cmd: `${record.command} ${record.args.join(' ')}`,
7
+ code: record.code,
8
+ ms: record.ms,
9
+ stderr: record.stderr.length > 0 ? record.stderr : undefined,
10
+ timedOut: record.timedOut ? true : undefined,
11
+ }, succeeded(record) ? 'verbose' : 'quiet');
12
+ });
13
+ export function recordCommands(recorder, work) {
14
+ return commandRecorder.run(recorder, work);
15
+ }
@@ -0,0 +1,32 @@
1
+ export const CONFIG_FILE = 'next-issue.config.json';
2
+ export function record(value, what) {
3
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
4
+ throw new Error(`${CONFIG_FILE}: ${what} must be an object.`);
5
+ }
6
+ return value;
7
+ }
8
+ export function rejectUnknown(value, known, what) {
9
+ for (const key of Object.keys(value)) {
10
+ if (!known.includes(key)) {
11
+ throw new Error(`${CONFIG_FILE} holds an unknown ${what}: ${key}`);
12
+ }
13
+ }
14
+ }
15
+ export function whole(value, field, least) {
16
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < least) {
17
+ throw new Error(`${CONFIG_FILE}: ${field} must be a whole number of ${least} or more.`);
18
+ }
19
+ return value;
20
+ }
21
+ export function flag(value, field) {
22
+ if (typeof value !== 'boolean') {
23
+ throw new Error(`${CONFIG_FILE}: ${field} must be true or false.`);
24
+ }
25
+ return value;
26
+ }
27
+ export function text(value, field, allowEmpty) {
28
+ if (typeof value !== 'string' || (!allowEmpty && value.length === 0)) {
29
+ throw new Error(`${CONFIG_FILE}: ${field} must be ${allowEmpty ? 'text' : 'text that is not empty'}.`);
30
+ }
31
+ return value;
32
+ }
package/dist/config.mjs CHANGED
@@ -1,6 +1,7 @@
1
- import { readFile, writeFile } from 'node:fs/promises';
2
1
  import { join } from 'node:path';
3
- import { message } from './observe.mjs';
2
+ import { CONFIG_FILE, flag, record, rejectUnknown, text, whole } from './config-fields.mjs';
3
+ import { hasCode, message, parseJson } from './errors.mjs';
4
+ import { readTextIfPresent, writeJson } from './files.mjs';
4
5
  const DEFAULTS = {
5
6
  remote: 'origin',
6
7
  issueLimit: 100,
@@ -54,16 +55,16 @@ const FILE_DEFAULTS = {
54
55
  ...defaults(),
55
56
  models: Object.fromEntries(MODEL_ROLES.map((role) => [role, null])),
56
57
  };
57
- export const CONFIG_FILE = 'next-issue.config.json';
58
+ function configFile(root) {
59
+ return join(root, CONFIG_FILE);
60
+ }
58
61
  export async function writeDefaultConfig(root, force) {
59
- const path = join(root, CONFIG_FILE);
62
+ const path = configFile(root);
60
63
  try {
61
- await writeFile(path, `${JSON.stringify(FILE_DEFAULTS, null, 2)}\n`, {
62
- flag: force ? 'w' : 'wx',
63
- });
64
+ await writeJson(path, FILE_DEFAULTS, { flag: force ? 'w' : 'wx' });
64
65
  }
65
66
  catch (error) {
66
- if (error.code === 'EEXIST') {
67
+ if (hasCode(error, 'EEXIST')) {
67
68
  throw new Error(`${CONFIG_FILE} exists already. Use --force to replace it.`);
68
69
  }
69
70
  throw error;
@@ -73,30 +74,19 @@ export async function writeDefaultConfig(root, force) {
73
74
  export async function loadConfig(root) {
74
75
  let raw;
75
76
  try {
76
- raw = await readFile(join(root, CONFIG_FILE), 'utf8');
77
+ raw = await readTextIfPresent(configFile(root));
77
78
  }
78
79
  catch (error) {
79
- if (error.code === 'ENOENT') {
80
- return defaults();
81
- }
82
80
  throw new Error(`${CONFIG_FILE} cannot be read: ${message(error)}`);
83
81
  }
84
- let parsed;
85
- try {
86
- parsed = JSON.parse(raw);
87
- }
88
- catch (error) {
89
- throw new Error(`${CONFIG_FILE} is not valid JSON: ${message(error)}`);
82
+ if (raw === undefined) {
83
+ return defaults();
90
84
  }
91
- return parseConfig(parsed);
85
+ return parseConfig(parseJson(raw, (error) => `${CONFIG_FILE} is not valid JSON: ${message(error)}`));
92
86
  }
93
87
  function parseConfig(value) {
94
88
  const file = record(value, 'the file');
95
- for (const key of Object.keys(file)) {
96
- if (!FIELDS.includes(key)) {
97
- throw new Error(`${CONFIG_FILE} holds an unknown field: ${key}`);
98
- }
99
- }
89
+ rejectUnknown(file, FIELDS, 'field');
100
90
  const config = defaults();
101
91
  if (file.remote !== undefined) {
102
92
  config.remote = text(file.remote, 'remote', false);
@@ -107,66 +97,41 @@ function parseConfig(value) {
107
97
  }
108
98
  }
109
99
  if (file.draftPullRequest !== undefined) {
110
- if (typeof file.draftPullRequest !== 'boolean') {
111
- throw new Error(`${CONFIG_FILE}: draftPullRequest must be true or false.`);
112
- }
113
- config.draftPullRequest = file.draftPullRequest;
100
+ config.draftPullRequest = flag(file.draftPullRequest, 'draftPullRequest');
114
101
  }
115
102
  if (file.setupCommand !== undefined) {
116
103
  config.setupCommand = text(file.setupCommand, 'setupCommand', false);
117
104
  }
118
105
  if (file.models !== undefined) {
119
- const models = record(file.models, 'models');
120
- for (const key of Object.keys(models)) {
121
- if (!MODEL_ROLES.includes(key)) {
122
- throw new Error(`${CONFIG_FILE} holds an unknown model role: ${key}`);
123
- }
124
- }
125
- for (const role of MODEL_ROLES) {
126
- if (models[role] !== undefined && models[role] !== null) {
127
- config.models[role] = text(models[role], `models.${role}`, false);
128
- }
129
- }
106
+ config.models = parseModels(file.models);
130
107
  }
131
108
  if (file.labels !== undefined) {
132
- const labels = record(file.labels, 'labels');
133
- for (const key of Object.keys(labels)) {
134
- if (!LABEL_NAMES.includes(key)) {
135
- throw new Error(`${CONFIG_FILE} holds an unknown label name: ${key}`);
136
- }
137
- }
138
- for (const name of LABEL_NAMES) {
139
- if (labels[name] !== undefined) {
140
- config.labels[name] = text(labels[name], `labels.${name}`, name === 'ready');
141
- }
142
- }
109
+ config.labels = parseLabels(file.labels, config.labels);
143
110
  }
144
111
  return config;
145
112
  }
146
- function record(value, what) {
147
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
148
- throw new Error(`${CONFIG_FILE}: ${what} must be an object.`);
149
- }
150
- return value;
151
- }
152
- function whole(value, field, least) {
153
- if (typeof value !== 'number' || !Number.isInteger(value) || value < least) {
154
- throw new Error(`${CONFIG_FILE}: ${field} must be a whole number of ${least} or more.`);
113
+ function parseModels(value) {
114
+ const models = record(value, 'models');
115
+ rejectUnknown(models, MODEL_ROLES, 'model role');
116
+ const parsed = {};
117
+ for (const role of MODEL_ROLES) {
118
+ if (models[role] !== undefined && models[role] !== null) {
119
+ parsed[role] = text(models[role], `models.${role}`, false);
120
+ }
155
121
  }
156
- return value;
122
+ return parsed;
157
123
  }
158
- function text(value, field, allowEmpty) {
159
- if (typeof value !== 'string' || (!allowEmpty && value.length === 0)) {
160
- throw new Error(`${CONFIG_FILE}: ${field} must be ${allowEmpty ? 'text' : 'text that is not empty'}.`);
124
+ function parseLabels(value, defaultLabels) {
125
+ const labels = record(value, 'labels');
126
+ rejectUnknown(labels, LABEL_NAMES, 'label name');
127
+ const parsed = { ...defaultLabels };
128
+ for (const name of LABEL_NAMES) {
129
+ if (labels[name] !== undefined) {
130
+ parsed[name] = text(labels[name], `labels.${name}`, name === 'ready');
131
+ }
161
132
  }
162
- return value;
133
+ return parsed;
163
134
  }
164
135
  export function managedLabels(config) {
165
- return [
166
- config.labels.ready,
167
- config.labels.inProgress,
168
- config.labels.inReview,
169
- config.labels.done,
170
- config.labels.needsHuman,
171
- ];
136
+ return LABEL_NAMES.filter((name) => name !== 'skip').map((name) => config.labels[name]);
172
137
  }