generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathchange-utils.ts
More file actions
334 lines (299 loc) · 11.9 KB
/
change-utils.ts
File metadata and controls
334 lines (299 loc) · 11.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
import type { Dirent } from 'node:fs';
import path from 'node:path';
import type { Editor } from 'mem-fs-editor';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { DirName, getWebappPath } from '@sap-ux/project-access';
import {
TemplateFileName,
type AnnotationsData,
type ChangeType,
type DescriptorVariant,
type InboundContent,
type ManifestChangeProperties,
type PropertyValueType,
ChangeTypeMap
} from '../types';
import { renderFile } from 'ejs';
import type { KeyUserChangeContent } from '@sap-ux/axios-extension';
export type ChangeMetadata = Pick<DescriptorVariant, 'id' | 'layer' | 'namespace'>;
type InboundChangeData = { filePath: string; changeWithInboundId: InboundChange | undefined };
interface InboundChange extends ManifestChangeProperties {
content: InboundContent;
}
/**
* Writes annotation changes to the specified project path using the provided `mem-fs-editor` instance.
*
* @param {string} projectPath - The root path of the project.
* @param {number} timestamp - The timestamp of the change.
* @param {AnnotationsData} annotation - The annotation data.
* @param {ManifestChangeProperties} change - The annotation data change that will be written.
* @param {Editor} fs - The `mem-fs-editor` instance used for file operations.
* @param {string} templatesPath - The path to the templates used for generating changes.
* @returns {Promise<void>}
*/
export async function writeAnnotationChange(
projectPath: string,
timestamp: number,
annotation: AnnotationsData['annotation'],
change: ManifestChangeProperties | undefined,
fs: Editor,
templatesPath?: string
): Promise<void> {
try {
const webappPath = await getWebappPath(projectPath, fs);
const changesFolderPath = path.join(webappPath, DirName.Changes);
const annotationsFolderPath = path.join(changesFolderPath, DirName.Annotations);
if (change) {
const changeFileName = `${change.fileName}.change`;
const changeFilePath = path.join(changesFolderPath, changeFileName);
writeChangeToFile(changeFilePath, change, fs);
}
if (!annotation.filePath) {
const annotationsTemplate = templatesPath
? path.join(templatesPath, 'changes', TemplateFileName.Annotation)
: path.join(__dirname, '..', '..', 'templates', 'changes', TemplateFileName.Annotation);
const { namespaces, serviceUrl } = annotation;
const schemaNamespace = `local_${timestamp}`;
renderFile(annotationsTemplate, { namespaces, path: serviceUrl, schemaNamespace }, {}, (err, str) => {
if (err) {
throw new Error('Error rendering template: ' + err.message);
}
fs.write(path.join(annotationsFolderPath, annotation.fileName ?? ''), str);
});
} else {
const selectedDir = path.dirname(annotation.filePath);
if (selectedDir !== annotationsFolderPath) {
fs.copy(annotation.filePath, path.join(annotationsFolderPath, annotation.fileName ?? ''));
}
}
} catch (e) {
throw new Error(`Could not write annotation changes. Reason: ${e.message}`);
}
}
/**
* Writes key-user change payloads to the generated adaptation project.
*
* @param projectPath - Project root path.
* @param changes - Key-user changes retrieved from the backend.
* @param fs - Yeoman mem-fs editor.
*/
export async function writeKeyUserChanges(
projectPath: string,
changes: KeyUserChangeContent[] | undefined,
fs: Editor
): Promise<void> {
if (!changes?.length) {
return;
}
for (const entry of changes) {
if (!entry?.content) {
continue;
}
const change = { ...(entry.content as Record<string, unknown>) };
if (!('texts' in change) && entry.texts) {
(change as Record<string, unknown>)['texts'] = entry.texts;
}
if (!change['fileName']) {
continue;
}
await writeChangeToFolder(projectPath, change as any, fs);
}
}
/**
* Writes a given change object to a file within a specified folder in the project's 'changes' directory.
* If an additional subdirectory is specified, the change file is written there.
*
* @param {string} projectPath - The root path of the project.
* @param {ManifestChangeProperties} change - The change data to be written to the file.
* @param {Editor} fs - The `mem-fs-editor` instance used for file operations.
* @param {string} [dir] - An optional subdirectory within the 'changes' directory where the file will be written.
* @returns {Promise<void>}
*/
export async function writeChangeToFolder(
projectPath: string,
change: ManifestChangeProperties,
fs: Editor,
dir = ''
): Promise<void> {
try {
const webappPath = await getWebappPath(projectPath, fs);
let targetFolderPath = path.join(webappPath, DirName.Changes);
if (dir) {
targetFolderPath = path.join(targetFolderPath, dir);
}
const fileName = `${change.fileName}.change`;
const filePath = path.join(targetFolderPath, fileName);
writeChangeToFile(filePath, change, fs);
} catch (e) {
throw new Error(`Could not write change to folder. Reason: ${e.message}`);
}
}
/**
* Writes a given change object to a specific file path. The change data is stringified to JSON format before
* writing. This function is used to directly write changes to a file, without specifying a directory.
*
* @param {string} path - The root path of the project.
* @param {ManifestChangeProperties} change - The change data to be written to the file.
* @param {Editor} fs - The `mem-fs-editor` instance used for file operations.
*/
export function writeChangeToFile(path: string, change: ManifestChangeProperties, fs: Editor): void {
try {
fs.writeJSON(path, change);
} catch (e) {
throw new Error(`Could not write change to file: ${path}. Reason: ${e.message}`);
}
}
/**
* Parses a string into an object.
*
* @param {string} str - The string to be parsed into an object. The string should be in the format of object properties without the surrounding braces.
* @returns {{ [key: string]: string }} An object constructed from the input string.
* @example
* // returns { name: "value" }
* parseStringToObject('"name":"value"');
*/
export function parseStringToObject(str: string): { [key: string]: string } {
return JSON.parse(`{${str}}`);
}
/**
* Attempts to parse a property value as JSON.
*
* @param {string} propertyValue - The property value to be parsed.
* @returns {PropertyValueType} The parsed value if `propertyValue` is valid JSON; otherwise, returns the original `propertyValue`.
* @example
* // Returns the object { key: "value" }
* getParsedPropertyValue('{"key": "value"}');
*
* // Returns the string "nonJSONValue" because it cannot be parsed as JSON
* getParsedPropertyValue('nonJSONValue');
*/
export function getParsedPropertyValue(propertyValue: string): PropertyValueType {
try {
const value = JSON.parse(propertyValue);
return value;
} catch (e) {
return propertyValue as PropertyValueType;
}
}
/**
* Retrieves all change files from a specified project path that match a given change type,
* optionally within a specific subdirectory.
*
* @param {string} projectPath - The base path of the project.
* @param {ChangeType} changeType - The type of changes to filter by, ensuring only changes of this type are returned.
* @param {string} [subDir] - Optional subdirectory within the main changes directory.
* @returns An array of change objects matching the specified change type.
*/
export function getChangesByType(
projectPath: string,
changeType: ChangeType,
subDir?: string
): ManifestChangeProperties[] {
try {
let targetDir = `${projectPath}/webapp/changes`;
if (!existsSync(targetDir)) {
return [];
}
if (subDir) {
targetDir = `${targetDir}/${subDir}`;
if (!existsSync(targetDir)) {
return [];
}
}
const fileNames = readdirSync(targetDir, { withFileTypes: true })
.filter((dirent) => dirent.isFile() && dirent.name.endsWith('.change'))
.map((dirent) => dirent.name);
if (fileNames.length === 0) {
return [];
}
const changeFiles: ManifestChangeProperties[] = fileNames
.map((fileName) => {
const filePath = path.resolve(targetDir, fileName);
const fileContent = readFileSync(filePath, 'utf-8');
const change: ManifestChangeProperties = JSON.parse(fileContent);
return change;
})
.filter((changeFileObject) => changeFileObject.changeType === changeType);
return changeFiles;
} catch (e) {
throw new Error(`Error reading change files: ${e.message}`);
}
}
/**
* Searches for a change file with a specific inbound ID within a project's change directory.
*
* @param {string} projectPath - The root path of the project.
* @param {string} inboundId - The inbound ID to search for within change files.
* @param {Editor} fs - The `mem-fs-editor` instance used for file operations.
* @returns {InboundChangeData} An object containing the file path and the change object with the matching inbound ID.
* @throws {Error} Throws an error if the change file cannot be read or if there's an issue accessing the directory.
*/
export async function findChangeWithInboundId(
projectPath: string,
inboundId: string,
fs: Editor
): Promise<InboundChangeData> {
let changeObj: InboundChange | undefined;
let filePath = '';
const webappPath = await getWebappPath(projectPath, fs);
const pathToInboundChangeFiles = path.join(webappPath, DirName.Changes);
if (!existsSync(pathToInboundChangeFiles)) {
return {
filePath,
changeWithInboundId: changeObj
};
}
try {
const files: Dirent[] = readdirSync(pathToInboundChangeFiles, { withFileTypes: true }).filter(
(dirent) => dirent.isFile() && dirent.name.includes('changeInbound')
);
for (const file of files) {
const pathToFile = path.join(pathToInboundChangeFiles, file.name);
const change: InboundChange = JSON.parse(readFileSync(pathToFile, 'utf-8'));
if (change.content?.inboundId === inboundId) {
changeObj = change;
filePath = pathToFile;
break;
}
}
return {
filePath,
changeWithInboundId: changeObj
};
} catch (e) {
throw new Error(`Could not find change with inbound id '${inboundId}'. Reason: ${e.message}`);
}
}
/**
* Constructs a generic change object based on provided parameters.
*
* @param {DescriptorVariant} variant - The app descriptor variant.
* @param {number} timestamp - The timestamp.
* @param {object} content - The content of the change to be applied.
* @param {ChangeType} changeType - The type of the change.
* @returns - An object representing the change
*/
export function getChange(
{ id, layer, namespace }: ChangeMetadata,
timestamp: number,
content: object,
changeType: ChangeType
): ManifestChangeProperties {
const changeName = ChangeTypeMap[changeType];
if (!changeName) {
throw new Error(`Could not extract the change name from the change type: ${changeType}`);
}
const fileName = `id_${timestamp}_${changeName}`;
return {
fileName,
namespace: path.posix.join(namespace, DirName.Changes),
layer,
fileType: 'change',
creation: new Date(timestamp).toISOString(),
packageName: '$TMP',
reference: id,
support: { generator: '@sap-ux/adp-tooling' },
changeType,
content
};
}