bdy 1.25.39-dev → 1.25.39-dev-pr

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 (103) hide show
  1. package/distTs/package.json +2 -1
  2. package/distTs/src/api/client.js +191 -1
  3. package/distTs/src/autocomplete.js +90 -0
  4. package/distTs/src/cliError.js +5 -0
  5. package/distTs/src/cliIndex.js +3 -0
  6. package/distTs/src/command/artifact/downloadDir.js +110 -0
  7. package/distTs/src/command/autocomplete/install.js +16 -0
  8. package/distTs/src/command/autocomplete/uninstall.js +16 -0
  9. package/distTs/src/command/autocomplete.js +14 -0
  10. package/distTs/src/command/environment/resolve.js +39 -0
  11. package/distTs/src/command/login.js +1 -1
  12. package/distTs/src/command/package/create.js +64 -0
  13. package/distTs/src/command/package/delete.js +38 -0
  14. package/distTs/src/command/package/docker/login.js +26 -0
  15. package/distTs/src/command/package/docker.js +11 -0
  16. package/distTs/src/command/package/download.js +138 -0
  17. package/distTs/src/command/package/get.js +36 -0
  18. package/distTs/src/command/package/list.js +31 -0
  19. package/distTs/src/command/package/publish.js +241 -0
  20. package/distTs/src/command/package/version/delete.js +39 -0
  21. package/distTs/src/command/package/version/get.js +45 -0
  22. package/distTs/src/command/package/version/list.js +47 -0
  23. package/distTs/src/command/package/version.js +16 -0
  24. package/distTs/src/command/package.js +26 -0
  25. package/distTs/src/command/pipeline/run/apply.js +62 -0
  26. package/distTs/src/command/pr/comment/add.js +66 -0
  27. package/distTs/src/command/pr/comment/list.js +167 -0
  28. package/distTs/src/command/pr/comment/status.js +50 -0
  29. package/distTs/src/command/pr/comment.js +19 -0
  30. package/distTs/src/command/pr/create.js +44 -0
  31. package/distTs/src/command/pr/diff.js +337 -0
  32. package/distTs/src/command/pr/file/list.js +139 -0
  33. package/distTs/src/command/pr/file/mark.js +45 -0
  34. package/distTs/src/command/pr/file.js +16 -0
  35. package/distTs/src/command/pr/get.js +29 -0
  36. package/distTs/src/command/pr/list.js +79 -0
  37. package/distTs/src/command/pr/merge.js +67 -0
  38. package/distTs/src/command/pr/review/request.js +30 -0
  39. package/distTs/src/command/pr/review/start.js +29 -0
  40. package/distTs/src/command/pr/review/verdict.js +81 -0
  41. package/distTs/src/command/pr/review.js +18 -0
  42. package/distTs/src/command/pr/shared.js +704 -0
  43. package/distTs/src/command/pr/state.js +38 -0
  44. package/distTs/src/command/pr/summary.js +341 -0
  45. package/distTs/src/command/pr/update.js +56 -0
  46. package/distTs/src/command/pr/updateBranch.js +22 -0
  47. package/distTs/src/command/pr/versions.js +42 -0
  48. package/distTs/src/command/pr.js +39 -0
  49. package/distTs/src/command/scrape/validation.js +154 -0
  50. package/distTs/src/command/scrape.js +144 -0
  51. package/distTs/src/command/suiteLink.js +14 -0
  52. package/distTs/src/command/tests/visual/result/download.js +31 -0
  53. package/distTs/src/command/tests/visual/result/get.js +68 -0
  54. package/distTs/src/command/tests/visual/result/list.js +49 -0
  55. package/distTs/src/command/tests/visual/result.js +23 -0
  56. package/distTs/src/command/tests/visual/session/get.js +70 -0
  57. package/distTs/src/command/tests/visual/session/list.js +69 -0
  58. package/distTs/src/command/tests/visual/session/open.js +22 -0
  59. package/distTs/src/command/tests/visual/session/reviewUrl.js +37 -0
  60. package/distTs/src/command/tests/visual/session/update.js +26 -0
  61. package/distTs/src/command/tests/visual/shared/context.js +144 -0
  62. package/distTs/src/command/tests/visual/shared/diffRegions.js +172 -0
  63. package/distTs/src/command/tests/visual/shared/format.js +21 -0
  64. package/distTs/src/command/tests/visual/shared/lookup.js +107 -0
  65. package/distTs/src/command/tests/visual/shared/options.js +90 -0
  66. package/distTs/src/command/tests/visual/shared/review.js +146 -0
  67. package/distTs/src/command/tests/visual/shared/reviewUrl.js +62 -0
  68. package/distTs/src/command/tests/visual/shared/session.js +217 -0
  69. package/distTs/src/command/tests/visual/snapshot/get.js +46 -0
  70. package/distTs/src/command/tests/visual/snapshot/list.js +68 -0
  71. package/distTs/src/command/tests/visual/snapshot/open.js +26 -0
  72. package/distTs/src/command/tests/visual/snapshot/reviewUrl.js +48 -0
  73. package/distTs/src/command/tests/visual/snapshot.js +28 -0
  74. package/distTs/src/command/tests/visual/suite/create.js +38 -0
  75. package/distTs/src/command/tests/visual/suite/delete.js +29 -0
  76. package/distTs/src/command/tests/visual/suite/get.js +43 -0
  77. package/distTs/src/command/tests/visual/suite/list.js +35 -0
  78. package/distTs/src/command/tests/visual/suite/open.js +20 -0
  79. package/distTs/src/command/tests/visual/suite/update.js +47 -0
  80. package/distTs/src/command/tests/visual/suite.js +30 -0
  81. package/distTs/src/command/ut/upload.js +86 -0
  82. package/distTs/src/command/ut.js +12 -0
  83. package/distTs/src/command/vt/close.js +27 -0
  84. package/distTs/src/command/vt/compare/validation.js +46 -0
  85. package/distTs/src/command/vt/compare.js +100 -0
  86. package/distTs/src/command/vt/exec.js +82 -0
  87. package/distTs/src/command/vt/installBrowser.js +20 -0
  88. package/distTs/src/command/vt/shared/validation.js +145 -0
  89. package/distTs/src/command/vt/storybook.js +138 -0
  90. package/distTs/src/command/vt.js +20 -0
  91. package/distTs/src/command/yaml/agents.js +88 -0
  92. package/distTs/src/command/yaml/init.js +110 -0
  93. package/distTs/src/main.js +190 -0
  94. package/distTs/src/output/pipeline.js +54 -56
  95. package/distTs/src/output.js +85 -22
  96. package/distTs/src/texts.js +509 -1
  97. package/distTs/src/tunnel/output/interactive/tunnel.js +14 -10
  98. package/distTs/src/tunnel/output/noninteractive/tunnel.js +3 -1
  99. package/distTs/src/types/options.js +2 -0
  100. package/distTs/src/types/scrape.js +2 -0
  101. package/distTs/src/types/visualTests.js +2 -0
  102. package/distTs/src/utils.js +142 -6
  103. package/package.json +2 -1
@@ -0,0 +1,704 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.formatPatchLine = exports.hunkHeaderText = exports.patchColumnWidth = exports.codeAround = exports.parsePatch = exports.conflictVersion = exports.isVersionConflict = exports.noteVersionBehind = exports.threadOrigin = exports.threadHeader = exports.threadState = exports.threadStatusWithResolution = exports.resolutionText = exports.threadStatusText = exports.isAuthor = exports.positionText = exports.anchorText = exports.versionKind = exports.firstLine = exports.sameMember = exports.memberName = exports.verdictText = exports.mergeableText = exports.processingStatusText = exports.prStateText = exports.formatDate = exports.shortSha = exports.rev = exports.fetchMustReview = exports.sortFilesForReading = exports.buildBatches = exports.fileSizeText = exports.changeTypeText = exports.fileStatusText = exports.filePriorityText = exports.tokensOf = exports.symbolLines = exports.field = exports.fetchAllThreads = exports.fetchAllFiles = exports.requireMyReview = exports.getMyReview = exports.readText = exports.splitNumberArgs = exports.resolveNumber = exports.parseRev = exports.parseLine = exports.currentGitBranch = exports.prScope = exports.addPrOptions = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_os_1 = require("node:os");
9
+ const node_path_1 = require("node:path");
10
+ const node_child_process_1 = require("node:child_process");
11
+ const cliError_1 = __importDefault(require("../../cliError"));
12
+ const input_1 = __importDefault(require("../../input"));
13
+ const output_1 = __importDefault(require("../../output"));
14
+ const utils_1 = require("../../utils");
15
+ const texts_1 = require("../../texts");
16
+ /**
17
+ * Options every pr command takes. --rev where the command works on a version;
18
+ * 'ignored' where it does not, so a printed command carrying --rev still runs.
19
+ */
20
+ const addPrOptions = (command, rev = false) => {
21
+ command.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
22
+ command.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
23
+ if (rev)
24
+ command.option('--rev <vK>', rev === 'ignored' ? texts_1.OPTION_PR_REV_IGNORED : texts_1.OPTION_PR_REV);
25
+ command.option('--format <text|json>', texts_1.OPTION_FORMAT);
26
+ };
27
+ exports.addPrOptions = addPrOptions;
28
+ const prScope = (options) => {
29
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
30
+ const project = input_1.default.restApiProject(options.project);
31
+ const client = input_1.default.restApiTokenClient();
32
+ // only what came as a flag: a linked or default project needs no flag in the next command either
33
+ const flags = [
34
+ options.workspace ? ` -w ${options.workspace}` : '',
35
+ options.project ? ` -p ${options.project}` : '',
36
+ ].join('');
37
+ return { client, workspace, project, cmd: (args) => `bdy pr ${args}${flags}` };
38
+ };
39
+ exports.prScope = prScope;
40
+ const currentGitBranch = () => {
41
+ try {
42
+ // symbolic-ref works before the first commit too (rev-parse HEAD does not)
43
+ // and fails on a detached HEAD, which has no branch
44
+ const branch = (0, node_child_process_1.execFileSync)('git', ['symbolic-ref', '--short', '-q', 'HEAD'], {
45
+ encoding: 'utf8',
46
+ stdio: ['ignore', 'pipe', 'ignore'],
47
+ }).trim();
48
+ return branch || null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ };
54
+ exports.currentGitBranch = currentGitBranch;
55
+ const parsePositive = (value, error) => {
56
+ if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) {
57
+ throw new cliError_1.default('usage_error', error);
58
+ }
59
+ return Number(value);
60
+ };
61
+ /**
62
+ * `--new-line 42` -> { line: 42 }; `--new-line 270-276` -> { line: 276, start: 270 }
63
+ * (the API's line is the last line of a range, start_line its first); a
64
+ * range of one line is a plain line.
65
+ */
66
+ const parseLine = (value, option) => {
67
+ if (value === undefined)
68
+ return {};
69
+ const match = /^\s*(\d+)\s*-\s*(\d+)\s*$/.exec(value);
70
+ if (!match)
71
+ return { line: parsePositive(value.trim(), (0, texts_1.ERR_PR_LINE)(option)) };
72
+ const start = parsePositive(match[1], (0, texts_1.ERR_PR_LINE)(option));
73
+ const line = parsePositive(match[2], (0, texts_1.ERR_PR_LINE)(option));
74
+ if (start > line)
75
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_PR_LINE_RANGE)(option, value));
76
+ return start === line ? { line } : { line, start };
77
+ };
78
+ exports.parseLine = parseLine;
79
+ /** `v3` or `3` -> 3; undefined stays undefined (the current version). */
80
+ const parseRev = (rev) => {
81
+ if (rev === undefined)
82
+ return undefined;
83
+ const match = /^v?([1-9]\d*)$/i.exec(rev.trim());
84
+ if (!match)
85
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_PR_REV)(rev));
86
+ return Number(match[1]);
87
+ };
88
+ exports.parseRev = parseRev;
89
+ /**
90
+ * The pull request number: the one given, or the open pull request of the
91
+ * current git branch.
92
+ */
93
+ const resolveNumber = async (scope, number) => {
94
+ if (number !== undefined)
95
+ return parsePositive(number, texts_1.ERR_PR_NUMBER);
96
+ const branch = (0, exports.currentGitBranch)();
97
+ if (!branch)
98
+ throw new cliError_1.default('usage_error', texts_1.ERR_PR_NO_BRANCH);
99
+ const result = await scope.client.getPullRequests(scope.workspace, scope.project, { state: utils_1.PR_STATE.OPEN, head: branch, per_page: 100 });
100
+ const prs = result?.pull_requests || [];
101
+ if (prs.length === 0) {
102
+ throw new cliError_1.default('not_found', (0, texts_1.ERR_PR_NOT_FOUND_FOR_BRANCH)(branch));
103
+ }
104
+ if (prs.length > 1) {
105
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_PR_MANY_FOR_BRANCH)(branch, prs.map((pr) => `#${pr.number}`).join(', ')));
106
+ }
107
+ return prs[0].number;
108
+ };
109
+ exports.resolveNumber = resolveNumber;
110
+ /**
111
+ * `[N] <x...>` arguments: the first one is the number only when it is an
112
+ * integer and more arguments follow, so a lone argument is always the path
113
+ * or login.
114
+ */
115
+ const splitNumberArgs = (args) => {
116
+ if (args.length > 1 && /^\d+$/.test(args[0])) {
117
+ return { number: args[0], rest: args.slice(1) };
118
+ }
119
+ return { rest: args };
120
+ };
121
+ exports.splitNumberArgs = splitNumberArgs;
122
+ /**
123
+ * The text of -m <text|-> or -F/--message-file <path|->. -m is always the
124
+ * text itself (`-` reads stdin), so `@First Last` in it is a mention and never
125
+ * a file; a file is read only with -F, where a missing file or a directory is
126
+ * an error. A lone `@word` in -m is refused: it cannot be a mention, and it is
127
+ * how a file was passed before -F, so it is not posted as a literal `@path`.
128
+ */
129
+ const readText = (options, required = true) => {
130
+ const { message, messageFile } = options;
131
+ if (message !== undefined && messageFile !== undefined) {
132
+ throw new cliError_1.default('usage_error', texts_1.ERR_PR_MESSAGE_BOTH);
133
+ }
134
+ if (messageFile !== undefined && messageFile !== '') {
135
+ if (messageFile === '-')
136
+ return node_fs_1.default.readFileSync(0, 'utf8');
137
+ // the shell does not expand ~ inside a quoted value
138
+ const path = (0, node_path_1.resolve)(/^~(?=$|\/)/.test(messageFile) ? `${(0, node_os_1.homedir)()}${messageFile.slice(1)}` : messageFile);
139
+ if (!node_fs_1.default.existsSync(path))
140
+ throw new cliError_1.default('file_not_found', (0, texts_1.ERR_PR_MESSAGE_FILE)(path));
141
+ if (!node_fs_1.default.statSync(path).isFile())
142
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_PR_MESSAGE_NOT_FILE)(path));
143
+ return node_fs_1.default.readFileSync(path, 'utf8');
144
+ }
145
+ if (message === undefined || message === '') {
146
+ if (required)
147
+ throw new cliError_1.default('usage_error', texts_1.ERR_PR_MESSAGE_REQUIRED);
148
+ return undefined;
149
+ }
150
+ if (message === '-')
151
+ return node_fs_1.default.readFileSync(0, 'utf8');
152
+ if (/^@\S+$/.test(message.trim())) {
153
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_PR_MESSAGE_AT_FILE)(message.trim().slice(1)));
154
+ }
155
+ return message;
156
+ };
157
+ exports.readText = readText;
158
+ /** The caller's review, or null when they have none (404). */
159
+ const getMyReview = async (scope, number) => {
160
+ try {
161
+ return await scope.client.getPullRequestReview(scope.workspace, scope.project, number);
162
+ }
163
+ catch (err) {
164
+ if (err instanceof cliError_1.default && err.status === 404)
165
+ return null;
166
+ throw err;
167
+ }
168
+ };
169
+ exports.getMyReview = getMyReview;
170
+ const requireMyReview = async (scope, number) => {
171
+ const review = await (0, exports.getMyReview)(scope, number);
172
+ if (!review)
173
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_PR_NO_REVIEW)(scope.cmd, number));
174
+ return review;
175
+ };
176
+ exports.requireMyReview = requireMyReview;
177
+ /** Every page of the files of a version. */
178
+ const fetchAllFiles = async (scope, number, query) => {
179
+ const perPage = 500;
180
+ const files = [];
181
+ let first = null;
182
+ for (let page = 1;; page += 1) {
183
+ const result = await scope.client.getPullRequestFiles(scope.workspace, scope.project, number, { ...query, page, per_page: perPage });
184
+ if (!first)
185
+ first = result;
186
+ const items = result?.files || [];
187
+ files.push(...items);
188
+ const total = Number(result?.total ?? files.length);
189
+ if (items.length < perPage || files.length >= total)
190
+ break;
191
+ }
192
+ return { ...first, files };
193
+ };
194
+ exports.fetchAllFiles = fetchAllFiles;
195
+ /** Every page of the threads of a version. */
196
+ const fetchAllThreads = async (scope, number, query) => {
197
+ const perPage = 100;
198
+ const threads = [];
199
+ let first = null;
200
+ for (let page = 1;; page += 1) {
201
+ const result = await scope.client.getPullRequestThreads(scope.workspace, scope.project, number, { ...query, page, per_page: perPage });
202
+ if (!first)
203
+ first = result;
204
+ const items = result?.threads || [];
205
+ threads.push(...items);
206
+ const total = Number(result?.total ?? threads.length);
207
+ if (items.length < perPage || threads.length >= total)
208
+ break;
209
+ }
210
+ return { ...first, threads };
211
+ };
212
+ exports.fetchAllThreads = fetchAllThreads;
213
+ /** `name value` with the name in a darker grey than the value, so the values stand out. */
214
+ const field = (name, value) => `${output_1.default.getMutedColor(name)} ${output_1.default.getLabelColor(value)}`;
215
+ exports.field = field;
216
+ /**
217
+ * One line per changed symbol, `name change` with the change in color (added
218
+ * green, modified yellow, removed red); a class or interface whose members are
219
+ * listed too is left out.
220
+ */
221
+ const symbolLines = (symbols) => {
222
+ const shown = symbols.filter((s) => !symbols.some((o) => o !== s && String(o.name).startsWith(`${s.name}.`)));
223
+ const width = Math.max(...shown.map((s) => String(s.name).length));
224
+ return shown.map((s) => {
225
+ const change = String(s.change || '').toLowerCase();
226
+ const colored = change === 'added'
227
+ ? output_1.default.getGreenColor(change)
228
+ : change === 'removed'
229
+ ? output_1.default.getRedColor(change)
230
+ : output_1.default.getYellowColor(change);
231
+ return `${String(s.name).padEnd(width)} ${colored}`;
232
+ });
233
+ };
234
+ exports.symbolLines = symbolLines;
235
+ const tokensOf = (file) => Math.ceil(Number(file?.analysis?.diff_size || 0) / 4);
236
+ exports.tokensOf = tokensOf;
237
+ /**
238
+ * must review (yellow) / unclear (cyan) / safe to skip (grey). A file without
239
+ * triage has none, unless `untriaged` is asked for: then `not triaged`, so a
240
+ * column never shows a bare `-` that could mean anything.
241
+ */
242
+ const filePriorityText = (priority, untriaged = false) => {
243
+ switch (priority) {
244
+ case utils_1.PR_REVIEW_PRIORITY.MUST_REVIEW:
245
+ return output_1.default.getYellowColor(texts_1.TXT_PR_FILE_MUST_REVIEW);
246
+ case utils_1.PR_REVIEW_PRIORITY.UNCLEAR:
247
+ return output_1.default.getCyanColor(texts_1.TXT_PR_FILE_UNCLEAR);
248
+ case utils_1.PR_REVIEW_PRIORITY.SKIP:
249
+ return output_1.default.getMutedColor(texts_1.TXT_PR_FILE_SKIP);
250
+ default:
251
+ return untriaged ? output_1.default.getMutedColor(texts_1.TXT_PR_FILE_NOT_TRIAGED) : null;
252
+ }
253
+ };
254
+ exports.filePriorityText = filePriorityText;
255
+ /** ADDED green, DELETED red, RENAMED blue, MODIFIED as is. */
256
+ const fileStatusText = (status) => {
257
+ if (status === utils_1.PR_FILE_STATUS.ADDED)
258
+ return output_1.default.getGreenColor(status);
259
+ if (status === utils_1.PR_FILE_STATUS.DELETED)
260
+ return output_1.default.getRedColor(status);
261
+ if (status === utils_1.PR_FILE_STATUS.RENAMED)
262
+ return output_1.default.getBlueColor(status);
263
+ return status || '-';
264
+ };
265
+ exports.fileStatusText = fileStatusText;
266
+ /**
267
+ * change_type by group: a change of code (CODE, ADDED, DELETED) as is, no
268
+ * change of behaviour (FORMATTING_ONLY, IMPORTS_ONLY, RENAME_ONLY) grey, not
269
+ * analyzed (NOT_PARSED, BINARY) purple, PARSE_ERROR red.
270
+ */
271
+ const changeTypeText = (type) => {
272
+ switch (type) {
273
+ case utils_1.PR_CHANGE_TYPE.FORMATTING_ONLY:
274
+ case utils_1.PR_CHANGE_TYPE.IMPORTS_ONLY:
275
+ case utils_1.PR_CHANGE_TYPE.RENAME_ONLY:
276
+ return output_1.default.getMutedColor(type);
277
+ case utils_1.PR_CHANGE_TYPE.NOT_PARSED:
278
+ case utils_1.PR_CHANGE_TYPE.BINARY:
279
+ return output_1.default.getPurpleColor(type);
280
+ case utils_1.PR_CHANGE_TYPE.PARSE_ERROR:
281
+ return output_1.default.getRedColor(type);
282
+ default:
283
+ return type || '-';
284
+ }
285
+ };
286
+ exports.changeTypeText = changeTypeText;
287
+ /** `3kB/~56`: the patch size and its estimate in tokens; `-` until the version is analyzed. */
288
+ const fileSizeText = (file) => {
289
+ const size = Number(file?.analysis?.diff_size || 0);
290
+ if (!file?.analysis)
291
+ return '-';
292
+ return `${(0, utils_1.formatBytes)(size)}/~${(0, exports.tokensOf)(file)}`;
293
+ };
294
+ exports.fileSizeText = fileSizeText;
295
+ const dirOf = (path) => {
296
+ const slash = path.lastIndexOf('/');
297
+ return slash < 0 ? '' : path.slice(0, slash);
298
+ };
299
+ /**
300
+ * Directories segment by segment, so a subdirectory comes right after its
301
+ * parent: `src`, `src/api`, `src-gen` (as plain strings `-` and `.` sort
302
+ * before `/` and would put `src-gen` between `src` and `src/api`).
303
+ */
304
+ const compareDirs = (a, b) => {
305
+ const x = a === '' ? [] : a.split('/');
306
+ const y = b === '' ? [] : b.split('/');
307
+ for (let i = 0; i < Math.min(x.length, y.length); i += 1) {
308
+ if (x[i] !== y[i])
309
+ return x[i] < y[i] ? -1 : 1;
310
+ }
311
+ return x.length - y.length;
312
+ };
313
+ /**
314
+ * Batches of the MUST_REVIEW files for subagents, made only from
315
+ * PR_BATCH_MIN_FILES files or PR_BATCH_MIN_TOKENS tokens on; empty when the
316
+ * list is small enough for one agent. A directory goes to one batch where it
317
+ * can, so files that call each other are read by the same subagent: a batch
318
+ * takes the next directory whole while it stays within PR_BATCH_MAX_TOKENS
319
+ * plus a fifth, a directory that does not fit starts a new batch once the
320
+ * current one is at least half full, and only a directory bigger than a whole
321
+ * batch is cut file by file. Deterministic: pr get, pr file ls --batch, pr diff
322
+ * --batch and a refused approval cut the same batches.
323
+ */
324
+ const buildBatches = (mustReview) => {
325
+ const total = mustReview.reduce((sum, file) => sum + (0, exports.tokensOf)(file), 0);
326
+ if (mustReview.length < utils_1.PR_BATCH_MIN_FILES && total < utils_1.PR_BATCH_MIN_TOKENS) {
327
+ return [];
328
+ }
329
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
330
+ // by directory, then name: a directory's own files stay together, before its subdirectories
331
+ const sorted = [...mustReview].sort((a, b) => compareDirs(dirOf(a.file_name), dirOf(b.file_name)) || compare(a.file_name, b.file_name));
332
+ const groups = [];
333
+ for (const file of sorted) {
334
+ const last = groups[groups.length - 1];
335
+ if (last && dirOf(last.files[0].file_name) === dirOf(file.file_name)) {
336
+ last.files.push(file);
337
+ last.tokens += (0, exports.tokensOf)(file);
338
+ }
339
+ else {
340
+ groups.push({ files: [file], tokens: (0, exports.tokensOf)(file) });
341
+ }
342
+ }
343
+ const batches = [];
344
+ let current = null;
345
+ const open = () => {
346
+ current = { batch: batches.length + 1, files: [], tokens: 0 };
347
+ batches.push(current);
348
+ return current;
349
+ };
350
+ for (const group of groups) {
351
+ let batch = current;
352
+ if (batch && batch.tokens + group.tokens <= utils_1.PR_BATCH_MAX_TOKENS * 1.2) {
353
+ batch.files.push(...group.files);
354
+ batch.tokens += group.tokens;
355
+ continue;
356
+ }
357
+ if (group.tokens <= utils_1.PR_BATCH_MAX_TOKENS && (!batch || batch.tokens >= utils_1.PR_BATCH_MAX_TOKENS / 2)) {
358
+ batch = open();
359
+ batch.files.push(...group.files);
360
+ batch.tokens += group.tokens;
361
+ continue;
362
+ }
363
+ // too big for one batch, or the current batch is too empty to close: file by file
364
+ for (const file of group.files) {
365
+ const tokens = (0, exports.tokensOf)(file);
366
+ if (!batch || (batch.files.length > 0 && batch.tokens + tokens > utils_1.PR_BATCH_MAX_TOKENS)) {
367
+ batch = open();
368
+ }
369
+ batch.files.push(file);
370
+ batch.tokens += tokens;
371
+ }
372
+ }
373
+ return batches;
374
+ };
375
+ exports.buildBatches = buildBatches;
376
+ /**
377
+ * The order `pr file ls` lists files in, what is left to read first: unviewed
378
+ * before viewed; within each MUST_REVIEW, UNCLEAR, files without triage, SKIP
379
+ * last; then the triage's review order, and the smallest first where there is none.
380
+ */
381
+ const sortFilesForReading = (files) => {
382
+ const rank = (file) => {
383
+ switch (file.triage?.review_priority) {
384
+ case utils_1.PR_REVIEW_PRIORITY.MUST_REVIEW:
385
+ return 0;
386
+ case utils_1.PR_REVIEW_PRIORITY.UNCLEAR:
387
+ return 1;
388
+ case utils_1.PR_REVIEW_PRIORITY.SKIP:
389
+ return 3;
390
+ default:
391
+ return 2;
392
+ }
393
+ };
394
+ const order = (file) => file.triage?.review_order ?? Number.MAX_SAFE_INTEGER;
395
+ return [...files].sort((a, b) => Number(!!a.viewed) - Number(!!b.viewed) ||
396
+ rank(a) - rank(b) ||
397
+ order(a) - order(b) ||
398
+ Number(a.analysis?.diff_size || 0) - Number(b.analysis?.diff_size || 0));
399
+ };
400
+ exports.sortFilesForReading = sortFilesForReading;
401
+ /** Every MUST_REVIEW file of a version, in review order. */
402
+ const fetchMustReview = async (scope, number, version) => (0, exports.fetchAllFiles)(scope, number, {
403
+ version,
404
+ review_priority: utils_1.PR_REVIEW_PRIORITY.MUST_REVIEW,
405
+ sort: utils_1.PR_FILES_SORT.REVIEW_ORDER,
406
+ });
407
+ exports.fetchMustReview = fetchMustReview;
408
+ const rev = (version) => `v${version}`;
409
+ exports.rev = rev;
410
+ const shortSha = (sha) => (sha ? sha.slice(0, 7) : '-');
411
+ exports.shortSha = shortSha;
412
+ const formatDate = (date) => {
413
+ if (!date)
414
+ return '-';
415
+ const d = new Date(date);
416
+ if (Number.isNaN(d.getTime()))
417
+ return date;
418
+ return d.toISOString().replace('T', ' ').slice(0, 16);
419
+ };
420
+ exports.formatDate = formatDate;
421
+ /** OPEN green, MERGED purple, CLOSED red; a draft adds a muted `draft`. */
422
+ const prStateText = (pr) => {
423
+ const state = String(pr?.state || '-');
424
+ const colored = state === utils_1.PR_STATE.OPEN
425
+ ? output_1.default.getGreenColor(state)
426
+ : state === utils_1.PR_STATE.MERGED
427
+ ? output_1.default.getPurpleColor(state)
428
+ : state === utils_1.PR_STATE.CLOSED
429
+ ? output_1.default.getRedColor(state)
430
+ : state;
431
+ return pr?.draft ? `${colored} ${output_1.default.getMutedColor(texts_1.TXT_PR_DRAFT)}` : colored;
432
+ };
433
+ exports.prStateText = prStateText;
434
+ /** Analysis / triage status: READY green, PENDING yellow, FAILED red. */
435
+ const processingStatusText = (status) => {
436
+ if (status === utils_1.PR_PROCESSING_STATUS.READY)
437
+ return output_1.default.getGreenColor(status);
438
+ if (status === utils_1.PR_PROCESSING_STATUS.PENDING)
439
+ return output_1.default.getYellowColor(status);
440
+ if (status === utils_1.PR_PROCESSING_STATUS.FAILED)
441
+ return output_1.default.getRedColor(status);
442
+ return status || '-';
443
+ };
444
+ exports.processingStatusText = processingStatusText;
445
+ /** MERGEABLE green, CONFLICTING red, UNKNOWN yellow. */
446
+ const mergeableText = (mergeable) => {
447
+ if (!mergeable)
448
+ return '-';
449
+ if (mergeable === utils_1.PR_MERGEABLE.MERGEABLE)
450
+ return output_1.default.getGreenColor(mergeable);
451
+ if (mergeable === utils_1.PR_MERGEABLE.CONFLICTING)
452
+ return output_1.default.getRedColor(mergeable);
453
+ return output_1.default.getYellowColor(mergeable);
454
+ };
455
+ exports.mergeableText = mergeableText;
456
+ /** APPROVED green, CHANGE_REQUESTED red, PENDING yellow. */
457
+ const verdictText = (verdict) => {
458
+ if (!verdict)
459
+ return '-';
460
+ if (verdict === utils_1.PR_VERDICT.APPROVED)
461
+ return output_1.default.getGreenColor(verdict);
462
+ if (verdict === utils_1.PR_VERDICT.CHANGE_REQUESTED)
463
+ return output_1.default.getRedColor(verdict);
464
+ return output_1.default.getYellowColor(verdict);
465
+ };
466
+ exports.verdictText = verdictText;
467
+ const memberName = (member) => member?.name || member?.email || (member?.id !== undefined ? `#${member.id}` : '-');
468
+ exports.memberName = memberName;
469
+ const sameMember = (a, b) => !!a && !!b && a.id !== undefined && a.id === b.id;
470
+ exports.sameMember = sameMember;
471
+ const firstLine = (text) => (text || '').split('\n').find((line) => line.trim() !== '')?.trim() || '';
472
+ exports.firstLine = firstLine;
473
+ /** `rebase` / `force` for a version that was not a plain push, else null. */
474
+ const versionKind = (forced) => forced === utils_1.PR_VERSION_FORCED.REBASE
475
+ ? texts_1.TXT_PR_VERSION_KIND_REBASE
476
+ : forced === utils_1.PR_VERSION_FORCED.REWRITE
477
+ ? texts_1.TXT_PR_VERSION_KIND_REWRITE
478
+ : null;
479
+ exports.versionKind = versionKind;
480
+ const anchorText = (state) => {
481
+ switch (state) {
482
+ case utils_1.PR_ANCHOR_STATE.INTACT:
483
+ return texts_1.TXT_PR_ANCHOR_INTACT;
484
+ case utils_1.PR_ANCHOR_STATE.TOUCHED:
485
+ return texts_1.TXT_PR_ANCHOR_TOUCHED;
486
+ case utils_1.PR_ANCHOR_STATE.MOVED:
487
+ return texts_1.TXT_PR_ANCHOR_MOVED;
488
+ case utils_1.PR_ANCHOR_STATE.GONE:
489
+ return texts_1.TXT_PR_ANCHOR_GONE;
490
+ default:
491
+ return null;
492
+ }
493
+ };
494
+ exports.anchorText = anchorText;
495
+ /**
496
+ * `path:42` or `path:270-276` on the head side, `path:17 (base)` or
497
+ * `path:270-276 (base)` on the base side, or `-` when the code is gone. The
498
+ * line part is what --new-line / --old-line take; `(base)` says which one.
499
+ */
500
+ const positionText = (position) => {
501
+ if (!position?.path)
502
+ return '-';
503
+ const line = position.new_line || position.old_line;
504
+ if (!line)
505
+ return position.path;
506
+ const range = position.start_line && position.start_line < line ? `${position.start_line}-${line}` : String(line);
507
+ return `${position.path}:${range}${position.new_line ? '' : ` ${texts_1.TXT_PR_POSITION_BASE}`}`;
508
+ };
509
+ exports.positionText = positionText;
510
+ /** Whether the invoker (GET /user) is the author of the pull request. */
511
+ const isAuthor = (pr, invoker) => !!pr?.author && !!invoker && ((0, exports.sameMember)(pr.author, invoker) ||
512
+ (!!pr.author.email && pr.author.email === invoker.email));
513
+ exports.isAuthor = isAuthor;
514
+ /** "OPEN, code changed, no reply" / "RESOLVED (FIXED), code unchanged". */
515
+ /** OPEN yellow (waits for someone), RESOLVED cyan (to be verified), CLOSED green (done). */
516
+ const threadStatusText = (status) => {
517
+ if (status === utils_1.PR_THREAD_STATUS.OPEN)
518
+ return output_1.default.getYellowColor(status);
519
+ if (status === utils_1.PR_THREAD_STATUS.RESOLVED)
520
+ return output_1.default.getCyanColor(status);
521
+ if (status === utils_1.PR_THREAD_STATUS.CLOSED)
522
+ return output_1.default.getGreenColor(status);
523
+ return status || '-';
524
+ };
525
+ exports.threadStatusText = threadStatusText;
526
+ /** FIXED green, BY_DESIGN blue, WONTFIX grey. */
527
+ const resolutionText = (resolution) => {
528
+ if (resolution === utils_1.PR_THREAD_RESOLUTION.FIXED)
529
+ return output_1.default.getGreenColor(resolution);
530
+ if (resolution === utils_1.PR_THREAD_RESOLUTION.BY_DESIGN)
531
+ return output_1.default.getBlueColor(resolution);
532
+ if (resolution === utils_1.PR_THREAD_RESOLUTION.WONTFIX)
533
+ return output_1.default.getMutedColor(resolution);
534
+ return resolution || '';
535
+ };
536
+ exports.resolutionText = resolutionText;
537
+ /** `STATUS (RESOLUTION)` in colors; the resolution only when there is one. */
538
+ const threadStatusWithResolution = (status, resolution) => resolution
539
+ ? `${(0, exports.threadStatusText)(status)} (${(0, exports.resolutionText)(resolution)})`
540
+ : (0, exports.threadStatusText)(status);
541
+ exports.threadStatusWithResolution = threadStatusWithResolution;
542
+ const threadState = (thread) => {
543
+ const parts = [(0, exports.threadStatusWithResolution)(thread.status, thread.resolution)];
544
+ const anchor = (0, exports.anchorText)(thread.position?.anchor_state);
545
+ if (anchor)
546
+ parts.push(anchor);
547
+ const replies = thread.comments || [];
548
+ if (replies.length === 0)
549
+ parts.push(texts_1.TXT_PR_NO_REPLY);
550
+ else {
551
+ const last = replies[replies.length - 1];
552
+ parts.push((0, texts_1.TXT_PR_LAST_REPLY)((0, exports.memberName)(last.user), (0, exports.formatDate)(last.create_date)));
553
+ }
554
+ return parts.join(', ');
555
+ };
556
+ exports.threadState = threadState;
557
+ /**
558
+ * `path:line symbol - state` of a thread, its id last and muted: the id is
559
+ * what --thread takes, the path is what a reader looks for.
560
+ */
561
+ const threadHeader = (thread, extra = '') => {
562
+ const symbol = thread.position?.symbol ? ` ${thread.position.symbol}` : '';
563
+ // a thread whose code is gone has no position: it starts with its state
564
+ const where = thread.position?.path ? `${(0, exports.positionText)(thread.position)}${symbol} - ` : '';
565
+ return `${where}${(0, exports.threadState)(thread)}${extra} ${output_1.default.getMutedColor(`· ${thread.id}`)}`;
566
+ };
567
+ exports.threadHeader = threadHeader;
568
+ /**
569
+ * Where a MOVED or GONE thread was opened: its position in the version it was
570
+ * created in (the thread view carries only the position in the version asked
571
+ * for). Null for other threads or when it cannot be read.
572
+ */
573
+ const threadOrigin = async (scope, number, thread) => {
574
+ const state = thread.position?.anchor_state;
575
+ if (state !== utils_1.PR_ANCHOR_STATE.MOVED && state !== utils_1.PR_ANCHOR_STATE.GONE)
576
+ return null;
577
+ if (!thread.created_version)
578
+ return null;
579
+ try {
580
+ const origin = await scope.client.getPullRequestThread(scope.workspace, scope.project, number, thread.id, thread.created_version);
581
+ return origin?.position || null;
582
+ }
583
+ catch {
584
+ return null;
585
+ }
586
+ };
587
+ exports.threadOrigin = threadOrigin;
588
+ /** Prints that the pull request moved on when the command works on an older version. */
589
+ const noteVersionBehind = (current, working) => {
590
+ if (current && working && current !== working) {
591
+ output_1.default.noteWarning((0, texts_1.TXT_PR_VERSION_BEHIND)(current, working));
592
+ }
593
+ };
594
+ exports.noteVersionBehind = noteVersionBehind;
595
+ const isVersionConflict = (err) => err instanceof cliError_1.default && err.status === 409;
596
+ exports.isVersionConflict = isVersionConflict;
597
+ const conflictVersion = (err) => {
598
+ const value = err.body?.current_version;
599
+ return typeof value === 'number' ? value : undefined;
600
+ };
601
+ exports.conflictVersion = conflictVersion;
602
+ /** Splits a unified patch into hunks with the old and new line number of every line. */
603
+ const parsePatch = (patch) => {
604
+ if (!patch)
605
+ return [];
606
+ const hunks = [];
607
+ let hunk = null;
608
+ let oldLine = 0;
609
+ let newLine = 0;
610
+ const lines = patch.split('\n');
611
+ if (lines.length > 0 && lines[lines.length - 1] === '')
612
+ lines.pop();
613
+ for (const text of lines) {
614
+ const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(text);
615
+ if (header) {
616
+ oldLine = Number(header[1]);
617
+ newLine = Number(header[2]);
618
+ hunk = { header: text, oldStart: oldLine, newStart: newLine, lines: [] };
619
+ hunks.push(hunk);
620
+ continue;
621
+ }
622
+ if (!hunk)
623
+ continue;
624
+ if (text.startsWith('+')) {
625
+ hunk.lines.push({ type: 'add', text: text.slice(1), newLine });
626
+ newLine += 1;
627
+ }
628
+ else if (text.startsWith('-')) {
629
+ hunk.lines.push({ type: 'del', text: text.slice(1), oldLine });
630
+ oldLine += 1;
631
+ }
632
+ else if (text.startsWith('\\')) {
633
+ hunk.lines.push({ type: 'meta', text });
634
+ }
635
+ else {
636
+ hunk.lines.push({ type: 'context', text: text.slice(1), oldLine, newLine });
637
+ oldLine += 1;
638
+ newLine += 1;
639
+ }
640
+ }
641
+ return hunks;
642
+ };
643
+ exports.parsePatch = parsePatch;
644
+ /** A few lines of the patch around a line of one side (the whole range of a thread on several lines), for a thread listing. */
645
+ const codeAround = (hunks, position, radius = 2) => {
646
+ const side = position?.new_line ? 'newLine' : 'oldLine';
647
+ const line = position?.new_line || position?.old_line;
648
+ if (!line)
649
+ return [];
650
+ const start = position?.start_line && position.start_line < line ? position.start_line : line;
651
+ for (const hunk of hunks) {
652
+ const last = hunk.lines.findIndex((l) => l[side] === line);
653
+ if (last < 0)
654
+ continue;
655
+ const found = hunk.lines.findIndex((l) => l[side] === start);
656
+ const first = found >= 0 && found <= last ? found : last;
657
+ return hunk.lines.slice(Math.max(0, first - radius), last + radius + 1);
658
+ }
659
+ return [];
660
+ };
661
+ exports.codeAround = codeAround;
662
+ /** Width of the line number columns: the longest number in the hunks, at least `old`. */
663
+ const patchColumnWidth = (hunks) => {
664
+ let max = 0;
665
+ for (const hunk of hunks) {
666
+ for (const line of hunk.lines)
667
+ max = Math.max(max, line.oldLine ?? 0, line.newLine ?? 0);
668
+ }
669
+ return Math.max(texts_1.TXT_PR_DIFF_COLUMN_OLD.length, texts_1.TXT_PR_DIFF_COLUMN_NEW.length, String(max).length);
670
+ };
671
+ exports.patchColumnWidth = patchColumnWidth;
672
+ /**
673
+ * A hunk separator instead of `@@ -25,19 +30,9 @@ export class UserService {`:
674
+ * ` old new ── 25–43 → 30–38 ── export class UserService {`, with `old` and
675
+ * `new` right above the line number columns of that width.
676
+ */
677
+ const hunkHeaderText = (header, width = 5) => {
678
+ const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/.exec(header);
679
+ const columns = output_1.default.getMutedColor(`${texts_1.TXT_PR_DIFF_COLUMN_OLD.padStart(width)} ${texts_1.TXT_PR_DIFF_COLUMN_NEW.padStart(width)}`);
680
+ if (!match)
681
+ return `${columns} ${output_1.default.getCyanColor(header)}`;
682
+ const range = (start, count) => {
683
+ const from = Number(start);
684
+ const n = count === undefined ? 1 : Number(count);
685
+ if (n === 0)
686
+ return '-';
687
+ return n === 1 ? String(from) : `${from}–${from + n - 1}`;
688
+ };
689
+ const lines = `${range(match[1], match[2])} → ${range(match[3], match[4])}`;
690
+ const context = match[5] ? ` ${output_1.default.getLabelColor(match[5].trim())}` : '';
691
+ return `${columns} ${output_1.default.getCyanColor(`── ${lines} ──`)}${context}`;
692
+ };
693
+ exports.hunkHeaderText = hunkHeaderText;
694
+ const formatPatchLine = (line, width = 5) => {
695
+ const num = (n) => (n === undefined ? '' : String(n)).padStart(width);
696
+ const sign = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' ';
697
+ const text = `${num(line.oldLine)} ${num(line.newLine)} ${sign} ${line.text}`;
698
+ if (line.type === 'add')
699
+ return output_1.default.getGreenColor(text);
700
+ if (line.type === 'del')
701
+ return output_1.default.getRedColor(text);
702
+ return text;
703
+ };
704
+ exports.formatPatchLine = formatPatchLine;