-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdiff.ts
More file actions
324 lines (283 loc) · 10.7 KB
/
Copy pathdiff.ts
File metadata and controls
324 lines (283 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import chalk from 'chalk';
import { loadConfig } from '../utils/config.js';
import {
printHeader,
printSuccess,
printWarning,
printError,
printErrorToStderr,
printInfo,
printStep,
createTimer,
emitJson,
errorCodeFields,
isReportedError,
} from '../utils/format.js';
// ─── Types ──────────────────────────────────────────────────────────
interface DiffEntry {
type: 'added' | 'removed' | 'modified';
category: string;
name: string;
detail?: string;
breaking: boolean;
}
// ─── Helpers ────────────────────────────────────────────────────────
function getNames(items: any[] | undefined): Map<string, any> {
const map = new Map<string, any>();
if (!Array.isArray(items)) return map;
for (const item of items) {
if (item?.name) map.set(item.name, item);
}
return map;
}
function getFieldNames(obj: any): string[] {
if (!obj?.fields || typeof obj.fields !== 'object') return [];
return Object.keys(obj.fields);
}
function getFieldType(obj: any, fieldName: string): string | undefined {
return obj?.fields?.[fieldName]?.type;
}
function isFieldRequired(obj: any, fieldName: string): boolean {
return obj?.fields?.[fieldName]?.required === true;
}
function diffNamedArrays(
beforeItems: any[] | undefined,
afterItems: any[] | undefined,
category: string,
detectFieldChanges: boolean,
): DiffEntry[] {
const entries: DiffEntry[] = [];
const beforeMap = getNames(beforeItems);
const afterMap = getNames(afterItems);
// Removed items
for (const [name] of beforeMap) {
if (!afterMap.has(name)) {
entries.push({
type: 'removed',
category,
name,
breaking: true,
});
}
}
// Added items
for (const [name] of afterMap) {
if (!beforeMap.has(name)) {
entries.push({
type: 'added',
category,
name,
breaking: false,
});
}
}
// Modified items — field-level diff for objects
if (detectFieldChanges) {
for (const [name, beforeObj] of beforeMap) {
const afterObj = afterMap.get(name);
if (!afterObj) continue;
const beforeFields = getFieldNames(beforeObj);
const afterFields = getFieldNames(afterObj);
const beforeSet = new Set(beforeFields);
const afterSet = new Set(afterFields);
// Removed fields
for (const f of beforeFields) {
if (!afterSet.has(f)) {
entries.push({
type: 'removed',
category: `${category}.${name}.fields`,
name: f,
breaking: true,
detail: 'field removed',
});
}
}
// Added fields
for (const f of afterFields) {
if (!beforeSet.has(f)) {
const breaking = isFieldRequired(afterObj, f);
entries.push({
type: 'added',
category: `${category}.${name}.fields`,
name: f,
breaking,
detail: breaking ? 'required field added' : 'optional field added',
});
}
}
// Type changes
for (const f of beforeFields) {
if (!afterSet.has(f)) continue;
const oldType = getFieldType(beforeObj, f);
const newType = getFieldType(afterObj, f);
if (oldType && newType && oldType !== newType) {
entries.push({
type: 'modified',
category: `${category}.${name}.fields`,
name: f,
breaking: true,
detail: `type changed: ${oldType} → ${newType}`,
});
}
}
// Label / ownership changes on the object itself
if (beforeObj.label !== afterObj.label) {
entries.push({
type: 'modified',
category,
name,
breaking: false,
detail: `label changed: "${beforeObj.label ?? '(none)'}" → "${afterObj.label ?? '(none)'}"`,
});
}
}
}
return entries;
}
// ─── Command ────────────────────────────────────────────────────────
export default class Diff extends Command {
static override description = 'Compare two ObjectStack configurations and detect breaking changes';
static override args = {
before: Args.string({ description: 'Path to the "before" config file', required: false }),
after: Args.string({ description: 'Path to the "after" config file', required: false }),
};
static override flags = {
before: Flags.string({ description: 'Path to the "before" config (alternative)' }),
after: Flags.string({ description: 'Path to the "after" config (alternative)' }),
json: Flags.boolean({ description: 'Output as JSON' }),
'breaking-only': Flags.boolean({ description: 'Show only breaking changes' }),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Diff);
const timer = createTimer();
const beforePath: string | undefined = args.before || flags.before;
const afterPath: string | undefined = args.after || flags.after;
// This refusal goes to STDERR, and it is the one write in this file that
// has to (#15697).
//
// It sits ABOVE the first `if (!flags.json)` below, so it is reached with
// the face still undecided and fires in BOTH — the text face and the
// machine face alike. Measured on the published entry `bin/run.js` with
// `NO_COLOR=1` and the streams captured separately, it used to answer
// `os diff --json` with **exit 1, 141 bytes of prose on stdout and an empty
// stderr**: `JSON.parse(stdout)` threw, on the one stream `--json` reserves
// for the machine (`utils/json-stdout.ts`). Both faces measured identically,
// because there is no branch here to tell them apart.
//
// ⚠️ Every other diagnostic in this file stays on stdout deliberately: they
// sit INSIDE a `!flags.json` branch, i.e. the command has already decided it
// is rendering its text face, which is exactly the case `printError` is for
// (see the note on {@link printErrorToStderr}).
//
// ⛔ Moving the bytes is the whole change. The exit code stays 1, the
// wording stays identical, and no payload is invented: what `--json` should
// emit on a refusal is an open envelope question (#15549) touching this
// command family at once, and settling it is above this fix's authority.
if (!beforePath || !afterPath) {
printErrorToStderr('Two config file paths are required.');
console.error('');
console.error(chalk.dim(' Usage: objectstack diff <before> <after>'));
console.error(chalk.dim(' or: objectstack diff --before path1 --after path2'));
process.exit(1);
}
if (!flags.json) {
printHeader('Diff');
printStep('Loading configurations...');
}
try {
const { config: beforeConfig } = await loadConfig(beforePath);
const { config: afterConfig } = await loadConfig(afterPath);
if (!flags.json) {
printInfo(`Before: ${chalk.white(beforePath)}`);
printInfo(`After: ${chalk.white(afterPath)}`);
}
// ── Diff all categories ──
const allDiffs: DiffEntry[] = [];
// Objects (with field-level diff)
allDiffs.push(...diffNamedArrays(beforeConfig.objects, afterConfig.objects, 'objects', true));
// Views, Flows, Agents, Apps (name-level diff)
const simpleCats: Array<{ key: string; label: string }> = [
{ key: 'views', label: 'views' },
{ key: 'flows', label: 'flows' },
{ key: 'agents', label: 'agents' },
{ key: 'apps', label: 'apps' },
{ key: 'dashboards', label: 'dashboards' },
{ key: 'actions', label: 'actions' },
{ key: 'workflows', label: 'workflows' },
{ key: 'apis', label: 'apis' },
{ key: 'positions', label: 'positions' },
];
for (const cat of simpleCats) {
allDiffs.push(
...diffNamedArrays(beforeConfig[cat.key], afterConfig[cat.key], cat.label, false),
);
}
// ── Filter ──
const diffs = flags['breaking-only']
? allDiffs.filter((d) => d.breaking)
: allDiffs;
const breakingCount = allDiffs.filter((d) => d.breaking).length;
// ── Output ──
if (flags.json) {
await emitJson({
before: beforePath,
after: afterPath,
total: diffs.length,
breaking: breakingCount,
changes: diffs,
duration: timer.elapsed(),
});
return;
}
console.log('');
if (diffs.length === 0) {
printSuccess(flags['breaking-only']
? 'No breaking changes detected.'
: 'No changes detected.');
console.log('');
return;
}
// Group by category
const grouped = new Map<string, DiffEntry[]>();
for (const d of diffs) {
const key = d.category;
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key)!.push(d);
}
for (const [category, items] of grouped) {
console.log(` ${chalk.bold(category)}`);
for (const item of items) {
const icon = item.type === 'added' ? '+' : item.type === 'removed' ? '-' : '~';
const color = item.type === 'added' ? chalk.green : item.type === 'removed' ? chalk.red : chalk.yellow;
const breakingTag = item.breaking ? chalk.bgRed.white(' BREAKING ') + ' ' : '';
const detail = item.detail ? chalk.dim(` (${item.detail})`) : '';
console.log(` ${color(icon)} ${breakingTag}${color(item.name)}${detail}`);
}
console.log('');
}
// Summary
if (breakingCount > 0) {
printError(`${breakingCount} breaking change(s) detected`);
} else {
printSuccess('No breaking changes');
}
console.log(chalk.dim(` ${diffs.length} total change(s) in ${timer.display()}`));
console.log('');
} catch (error: any) {
if (flags.json) {
await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true });
process.exit(1);
}
// [#15547] `resolveConfigPath()` already wrote its refusal and hint
// lines to stderr before throwing; printing the sentence again here
// would put a second copy on stdout.
if (!isReportedError(error)) {
console.log('');
printError(error.message || String(error));
}
process.exit(1);
}
}
}