-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathfile.ts
More file actions
388 lines (356 loc) · 12.9 KB
/
file.ts
File metadata and controls
388 lines (356 loc) · 12.9 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import type { CopyOptions, Editor } from 'mem-fs-editor';
import type { TabInfo } from '../common/types';
import { sep, normalize } from 'node:path';
import { findFilesByExtension, isUI5IdUnique } from '@sap-ux/project-access';
/**
* Options for creating an ID generator with cached file contents.
*/
export interface CreateIdGeneratorWithCacheOptions {
basePath?: never;
fsEditor?: never;
/**
*
* cache for file contents to optimize ID generation.
*/
fileContentCache: string[];
}
/**
* Options for creating an ID generator with filesystem access.
*/
export interface CreateIdGeneratorWithFilesystemOptions {
/**
* Base path of the project.
*/
basePath: string;
/**
* mem-fs-editor instance.
*/
fsEditor: Editor;
fileContentCache?: string[];
}
/**
* Options for creating an empty ID generator (no validation).
*/
export interface CreateIdGeneratorEmptyOptions {
basePath?: never;
fsEditor?: never;
fileContentCache?: never;
}
/**
* Options for creating an ID generator.
*/
export type CreateIdGeneratorOptions =
| CreateIdGeneratorWithCacheOptions
| CreateIdGeneratorWithFilesystemOptions
| CreateIdGeneratorEmptyOptions;
const CHAR_SPACE = ' ';
const CHAR_TAB = '\t';
interface ButtonGroup {
id?: string;
}
export type IdGeneratorFunction = (baseId: string, validatedIds?: string[]) => string;
export interface TemplateContext {
buttonGroups?: ButtonGroup[];
name?: string;
data?: {
buttonGroups?: ButtonGroup[];
};
}
export const CONFIG = {
['page/custom/1.94/ext/View.xml']: {
getData: (generateId: IdGeneratorFunction, context?: TemplateContext): { ids: Record<string, string> } => {
return {
ids: {
page: generateId(context?.name ?? 'Page')
}
};
}
},
['page/custom/1.84/ext/View.xml']: {
getData: (generateId: IdGeneratorFunction, context?: TemplateContext): { ids: Record<string, string> } => {
return {
ids: {
page: generateId(context?.name ?? 'Page')
}
};
}
},
['common/FragmentWithForm.xml']: {
getData: (generateId: IdGeneratorFunction): { ids: Record<string, string> } => {
return {
ids: {
formElement: generateId('FormElement')
}
};
}
},
['common/FragmentWithVBox.xml']: {
getData: (generateId: IdGeneratorFunction): { ids: Record<string, string> } => {
return {
ids: {
vbox: generateId('VBox')
}
};
}
},
['view/ext/CustomViewWithTable.xml']: {
getData: (generateId: IdGeneratorFunction): { ids: Record<string, string> } => {
return {
ids: {
table: generateId('Table')
}
};
}
},
['filter/fragment.xml']: {
getData: (generateId: IdGeneratorFunction): { ids: Record<string, string> } => {
const item1 = generateId('Item');
const item2 = generateId('Item', [item1]);
const item3 = generateId('Item', [item1, item2]);
return {
ids: {
comboBox: generateId('ComboBox'),
item1,
item2,
item3
}
};
}
},
['building-block/rich-text-editor-button-groups/View.xml']: {
getData: (
generateId: IdGeneratorFunction,
context?: Partial<TemplateContext>
): { ids: Record<string, string> } => {
// Get buttonGroups from context
const buttonGroups = context?.buttonGroups || context?.data?.buttonGroups || [];
// Generate IDs for each button group and store in ids object
const ids: Record<string, string> = {};
const validatedIds: string[] = [];
buttonGroups.forEach((group, index) => {
const id = generateId('ButtonGroup', validatedIds);
ids[index] = group.id ?? id;
if (!group.id) {
validatedIds.push(id);
}
});
return { ids };
}
},
['building-block/custom-column/View.xml']: {
getData: (generateId: IdGeneratorFunction): { ids: Record<string, string> } => {
return {
ids: {
column: generateId('TableColumn')
}
};
}
}
};
/**
* Generates a unique element ID that is not already used in any view or fragment file.
* Uses an incremental counter for predictable, readable IDs.
*
* @param baseId - The base name for the ID (e.g., 'filterBar', 'chart')
* @param filteredFilesContent - The list of files to check for ID availability
* @param validatedIds - A list of IDs that have already been validated in the current session to avoid duplicates
* @returns A unique ID that is available across all view and fragment files
*/
function generateUniqueElementId(baseId: string, filteredFilesContent: string[], validatedIds: string[] = []): string {
const maxAttempts = 1000;
// Check both in-memory validatedIds and filesystem files
if (!validatedIds.includes(baseId) && isUI5IdUnique(baseId, filteredFilesContent)) {
return baseId;
}
for (let counter = 1; counter < maxAttempts; counter++) {
const candidateId = `${baseId}${counter}`;
// Check both in-memory validatedIds and filesystem files
if (!validatedIds.includes(candidateId) && isUI5IdUnique(candidateId, filteredFilesContent)) {
return candidateId;
}
}
// If we couldn't find an available ID after maxAttempts
throw new Error(`Failed to generate unique ID for base '${baseId}' after ${maxAttempts} attempts`);
}
/**
* Retrieves all view and fragment files in the application.
*
* @param appPath - The root path of the application
* @param fs - The file system object for reading files
* @returns A list of view and fragment files
*/
export async function getFragmentAndViewFiles(appPath: string, fs: Editor): Promise<string[]> {
const files = await findFilesByExtension(
'.xml',
appPath,
['.git', 'node_modules', 'dist', 'annotations', 'localService'],
fs
);
const lookupFiles = ['.fragment.xml', '.view.xml'];
return files.filter((fileName) => lookupFiles.some((lookupFile) => fileName.endsWith(lookupFile)));
}
/**
* Creates an ID generator function for a given base path and editor.
* The generator ensures unique IDs across all fragment and view files in the project.
*
* @param options - Options for creating the ID generator
* @returns A function that generates unique IDs based on a base ID string, or a Promise resolving to such function
*/
export function createIdGenerator(
options: CreateIdGeneratorOptions = {}
): Promise<IdGeneratorFunction> | IdGeneratorFunction {
const { basePath, fsEditor, fileContentCache = [] } = options;
const createGenerator = (fileContents: string[]): IdGeneratorFunction => {
return (baseId: string, validatedIds: string[] = []): string => {
return generateUniqueElementId(baseId, fileContents, validatedIds);
};
};
if (fileContentCache.length > 0) {
return createGenerator(fileContentCache);
}
if (fsEditor && basePath) {
return getFragmentAndViewFiles(basePath, fsEditor).then((filePaths) => {
const fileContents = filePaths.map((path) => fsEditor.read(path).toString());
return createGenerator(fileContents);
});
}
return createGenerator([]);
}
// `noGlob` is supported in `mem-fs-editor` v9,
// but is missing from `@types/mem-fs-editor` (no v9 typings), so we extend the type here.
export const COPY_TEMPLATE_OPTIONS: CopyOptions & { noGlob: boolean } = {
noGlob: true
};
type WriteJsonReplacer = ((key: string, value: any) => any) | Array<string | number>;
type WriteJsonSpace = number | string;
interface ExtendJsonParams {
filepath: string;
content: string;
replacer?: WriteJsonReplacer;
tabInfo?: TabInfo;
}
/**
* Method returns tab info for passed line.
*
* @param line - line with tab spacing
* @returns tab size information
*/
function getLineTabInfo(line: string): TabInfo | undefined {
let tabSize: TabInfo | undefined;
const symbol = line.startsWith(CHAR_TAB) ? CHAR_TAB : CHAR_SPACE;
// get count of tabs
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char !== symbol) {
tabSize = {
size: i,
useTabSymbol: symbol === CHAR_TAB
};
break;
}
}
return tabSize;
}
/**
* Method calculates tab space info for passed file content.
*
* @param content - file content.
* @returns tab size information.
*/
export function detectTabSpacing(content: string): TabInfo | undefined {
let tabSize: TabInfo | undefined;
const tabSymbols = new Set([CHAR_SPACE, CHAR_TAB]);
const lines = content.split(/\r\n|\n/);
const lineWithSpacing = lines.find((line: string): boolean => {
return tabSymbols.has(line[0]);
});
if (lineWithSpacing) {
tabSize = getLineTabInfo(lineWithSpacing);
}
return tabSize;
}
/**
* Method calculates tab spacing parameter for 'JSON.stringify' method.
*
* @param fs - the mem-fs editor instance.
* @param filePath - path to file to read.
* @param tabInfo - External tab configuration.
* @returns tab size information.
*/
export function getJsonSpace(fs: Editor, filePath: string, tabInfo?: TabInfo | undefined): WriteJsonSpace | undefined {
if (!tabInfo) {
// 'tabInfo' was not passed - calculate 'tabInfo' by checking existing content of target file
const content = fs.read(filePath);
tabInfo = detectTabSpacing(content);
}
let space: WriteJsonSpace | undefined;
if (tabInfo) {
// 'tabInfo' exists - it was passed as custom configuration or calculated from target file
if (tabInfo.useTabSymbol) {
// Tab symbol should be used as tab
space = CHAR_TAB.repeat(tabInfo.size || 1);
} else {
// Spaces should be used as tab
space = tabInfo.size;
}
}
return space;
}
/**
* Method extends target JSON file with passed JSOn content.
* Method uses 'fs.extendJSON', but applies additional calculation to reuse existing content tab sizing information.
*
* @param fs - the mem-fs editor instance.
* @param params - options for JSON extend.
*/
export function extendJSON(fs: Editor, params: ExtendJsonParams): void {
const { filepath, content, replacer } = params;
const space: WriteJsonSpace | undefined = getJsonSpace(fs, filepath, params.tabInfo);
// Write json
fs.extendJSON(filepath, JSON.parse(content), replacer, space);
}
/**
* Copies a template file or directory to a target location and applies template interpolation.
* This method wraps `mem-fs-editor`'s `copyTpl` and passes predefined copy options
* (e.g. `noGlob: true`) to prevent glob pattern expansion in source paths.
*
* @param fs - The mem-fs editor instance used to perform the file operations.
* @param from - Source path of the template file or directory.
* @param to - Destination path where the rendered files will be written.
* @param context - Optional template context used for interpolation.
* @param {(baseId: string) => string} generateId - Function to generate unique IDs for the building block elements.
*/
export function copyTpl(
fs: Editor,
from: string,
to: string,
context?: object,
generateId?: (baseId: string) => string
): void {
const configKey = getRelativeTemplateComponentPath(from);
const config = CONFIG[configKey as keyof typeof CONFIG];
if (generateId && config?.getData) {
const additionalContext = config.getData(generateId, context);
context = { ...context, ...additionalContext };
}
fs.copyTpl(from, to, context, undefined, COPY_TEMPLATE_OPTIONS);
}
/**
* Extracts the relative path from the templates directory.
* Works cross-platform by normalizing path separators.
*
* @param absolutePath - Absolute path to a template file or directory
* @returns Relative path from templates directory with forward slashes, or original path if 'templates' not found
*/
export function getRelativeTemplateComponentPath(absolutePath: string): string {
const normalizedPath = normalize(absolutePath);
const templatesMarker = `${sep}templates${sep}`;
const templatesIndex = normalizedPath.indexOf(templatesMarker);
if (templatesIndex === -1) {
return absolutePath;
}
// Extract everything after '/templates/' or '\\templates\\'
const relativePath = normalizedPath.substring(templatesIndex + templatesMarker.length);
// Normalize to forward slashes for consistency
return relativePath.split(sep).join('/');
}