forked from datahub-project/datahub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
288 lines (259 loc) · 10.8 KB
/
utils.ts
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
import { SorterResult } from 'antd/lib/table/interface';
import * as diff from 'diff';
import {
EditableSchemaFieldInfo,
EditableSchemaMetadata,
EditableSchemaMetadataUpdate,
PlatformSchema,
SchemaField,
} from '../../../../../../types.generated';
import { convertTagsForUpdate } from '../../../../../shared/tags/utils/convertTagsForUpdate';
import { SchemaDiffSummary } from '../components/SchemaVersionSummary';
import { KEY_SCHEMA_PREFIX, UNION_TOKEN, VERSION_PREFIX } from './constants';
import { ExtendedSchemaFields } from './types';
export function convertEditableSchemaMeta(
editableSchemaMeta?: Array<EditableSchemaFieldInfo>,
fields?: Array<SchemaField>,
): Array<SchemaField> {
const updatedFields = [...(fields || [])] as Array<SchemaField>;
if (editableSchemaMeta && editableSchemaMeta.length > 0) {
editableSchemaMeta.forEach((updatedField) => {
const originalFieldIndex = updatedFields.findIndex((f) => f.fieldPath === updatedField.fieldPath);
if (originalFieldIndex > -1) {
updatedFields[originalFieldIndex] = {
...updatedFields[originalFieldIndex],
description: updatedField.description,
globalTags: { ...updatedField.globalTags },
};
}
});
}
return updatedFields;
}
export function convertEditableSchemaMetadataForUpdate(
editableSchemaMetadata: EditableSchemaMetadata | null | undefined,
): EditableSchemaMetadataUpdate {
return {
editableSchemaFieldInfo:
editableSchemaMetadata?.editableSchemaFieldInfo.map((editableSchemaFieldInfo) => ({
fieldPath: editableSchemaFieldInfo?.fieldPath,
description: editableSchemaFieldInfo?.description,
globalTags: { tags: convertTagsForUpdate(editableSchemaFieldInfo?.globalTags?.tags || []) },
})) || [],
};
}
export function filterKeyFieldPath(showKeySchema: boolean, field: SchemaField) {
return field.fieldPath.indexOf(KEY_SCHEMA_PREFIX) > -1 ? showKeySchema : !showKeySchema;
}
export function downgradeV2FieldPath(fieldPath?: string | null) {
if (!fieldPath) {
return fieldPath;
}
const cleanedFieldPath = fieldPath.replace(KEY_SCHEMA_PREFIX, '').replace(VERSION_PREFIX, '');
// strip out all annotation segments
return cleanedFieldPath
.split('.')
.map((segment) => (segment.startsWith('[') ? null : segment))
.filter(Boolean)
.join('.');
}
export function pathMatchesNewPath(fieldPathA?: string | null, fieldPathB?: string | null) {
return fieldPathA === fieldPathB || fieldPathA === downgradeV2FieldPath(fieldPathB);
}
// should use pathMatchesExact when rendering editable info so the user edits the correct field
export function pathMatchesExact(fieldPathA?: string | null, fieldPathB?: string | null) {
return fieldPathA === fieldPathB;
}
// group schema fields by fieldPath and grouping for hierarchy in schema table
export function groupByFieldPath(
schemaRows?: Array<SchemaField>,
options: {
showKeySchema: boolean;
} = { showKeySchema: false },
): Array<ExtendedSchemaFields> {
const rows = [
...(schemaRows?.filter(filterKeyFieldPath.bind({}, options.showKeySchema)) || []),
] as Array<ExtendedSchemaFields>;
const outputRows: Array<ExtendedSchemaFields> = [];
const outputRowByPath = {};
for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
let parentRow: null | ExtendedSchemaFields = null;
const row = { children: undefined, ...rows[rowIndex], depth: 0 };
for (let j = rowIndex - 1; j >= 0; j--) {
const rowTokens = row.fieldPath.split('.');
const isQualifyingUnionField = rowTokens[rowTokens.length - 3] === UNION_TOKEN;
if (isQualifyingUnionField) {
// in the case of unions, parent will not be a subset of the child
rowTokens.splice(rowTokens.length - 2, 1);
const parentPath = rowTokens.join('.');
if (rows[j].fieldPath === parentPath) {
parentRow = outputRowByPath[rows[j].fieldPath];
break;
}
} else {
// In the case of structs, arrays, etc, parent will be the first token from
// the left of this field's name(last token of the path) that does not enclosed in [].
let parentPath: null | string = null;
for (
let lastParentTokenIndex = rowTokens.length - 2;
lastParentTokenIndex >= 0;
--lastParentTokenIndex
) {
const lastParentToken: string = rowTokens[lastParentTokenIndex];
if (lastParentToken && lastParentToken[0] !== '[') {
parentPath = rowTokens.slice(0, lastParentTokenIndex + 1).join('.');
break;
}
}
if (parentPath && rows[j].fieldPath === parentPath) {
parentRow = outputRowByPath[rows[j].fieldPath];
break;
}
}
}
// if the parent field exists in the ouput, add the current row as a child
if (parentRow) {
row.depth = (parentRow.depth || 0) + 1;
row.parent = parentRow;
parentRow.children = [...(parentRow.children || []), row];
} else {
outputRows.push(row);
}
outputRowByPath[row.fieldPath] = row;
}
return outputRows;
}
export function diffMarkdown(oldStr: string, newStr: string) {
const diffArray = diff.diffChars(oldStr || '', newStr || '');
return diffArray
.map((diffOne) => {
if (diffOne.added) {
return `<ins class="diff">${diffOne.value}</ins>`;
}
if (diffOne.removed) {
return `<del class="diff">${diffOne.value}</del>`;
}
return diffOne.value;
})
.join('');
}
export function diffJson(oldStr: string, newStr: string) {
const diffArray = diff.diffJson(oldStr || '', newStr || '');
return diffArray
.map((diffOne) => {
if (diffOne.added) {
return `+${diffOne.value}`;
}
if (diffOne.removed) {
return `-${diffOne.value}`;
}
return diffOne.value;
})
.join('');
}
export function formatRawSchema(schemaValue?: string | null): string {
try {
if (!schemaValue) {
return schemaValue || '';
}
return JSON.stringify(JSON.parse(schemaValue), null, 2);
} catch (e) {
return schemaValue || '';
}
}
export function getRawSchema(schema: PlatformSchema | undefined | null, showKeySchema: boolean): string {
if (!schema) {
return '';
}
if (schema.__typename === 'TableSchema') {
return schema.schema;
}
if (schema.__typename === 'KeyValueSchema') {
return showKeySchema ? schema.keySchema : schema.valueSchema;
}
return '';
}
// Get diff summary between two versions and prepare to visualize description diff changes
export function getDiffSummary(
currentVersionRows?: Array<SchemaField>,
previousVersionRows?: Array<SchemaField>,
options: { showKeySchema: boolean } = { showKeySchema: false },
): {
rows: Array<ExtendedSchemaFields>;
diffSummary: SchemaDiffSummary;
} {
let rows = [
...(currentVersionRows?.filter(filterKeyFieldPath.bind({}, options.showKeySchema)) || []),
] as Array<ExtendedSchemaFields>;
const previousRows = [
...(previousVersionRows?.filter(filterKeyFieldPath.bind({}, options.showKeySchema)) || []),
] as Array<ExtendedSchemaFields>;
const diffSummary: SchemaDiffSummary = {
added: 0,
removed: 0,
updated: 0,
};
if (previousVersionRows && previousVersionRows.length > 0) {
rows.forEach((field, rowIndex) => {
const relevantPastFieldIndex = previousRows.findIndex(
(pf) => pf.type === rows[rowIndex].type && pf.fieldPath === rows[rowIndex].fieldPath,
);
if (relevantPastFieldIndex > -1) {
if (previousRows[relevantPastFieldIndex].description !== rows[rowIndex].description) {
rows[rowIndex] = {
...rows[rowIndex],
previousDescription: previousRows[relevantPastFieldIndex].description,
};
diffSummary.updated++; // Increase updated row number in diff summary
}
previousRows.splice(relevantPastFieldIndex, 1);
} else {
rows[rowIndex] = { ...rows[rowIndex], isNewRow: true };
diffSummary.added++; // Increase added row number in diff summary
}
});
rows = [...rows, ...previousRows.map((pf) => ({ ...pf, isDeletedRow: true }))];
diffSummary.removed = previousRows.length; // removed row number in diff summary
}
return { rows, diffSummary };
}
// we need to calculate excluding collapsed fields because Antd table expects
// an indexToScroll to only counting based on visible fields
export function findIndexOfFieldPathExcludingCollapsedFields(
fieldPath: string,
expandedRows: Set<string>,
rows: Array<ExtendedSchemaFields>,
sorter: SorterResult<any> | undefined,
compareFn: ((a: any, b: any) => number) | undefined,
) {
let index = 0; // This will keep track of the index across recursive calls
function search(shadowedRows) {
let sortedRows = shadowedRows;
if (sorter?.order === 'ascend') {
sortedRows = shadowedRows.toSorted(compareFn);
} else if (sorter?.order === 'descend') {
sortedRows = shadowedRows.toSorted(compareFn).toReversed();
}
// eslint-disable-next-line no-restricted-syntax
for (const row of sortedRows) {
// eslint-disable-next) {
// Check if the current row's ID matches the ID we're looking for
if (row.fieldPath === fieldPath) {
return index;
}
index++; // Increment index for the current row
// Check if current row is expanded and has children
if (expandedRows.has(row.fieldPath) && row.children && row.children.length) {
const foundIndex = search(row.children); // Recursively search children
if (foundIndex !== -1) {
// If found in children, return the found index
return foundIndex;
}
}
}
// Return -1 if the ID was not found in this branch
return -1;
}
// Start the recursive search
return search(rows);
}