generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathcap.ts
815 lines (772 loc) · 30.3 KB
/
cap.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import { spawn } from 'child_process';
import { basename, dirname, join, normalize, relative, sep, resolve } from 'path';
import type { Logger } from '@sap-ux/logger';
import type { Editor } from 'mem-fs-editor';
import { FileName } from '../constants';
import type {
CapCustomPaths,
CapProjectType,
CdsEnvironment,
csn,
LinkedModel,
Package,
ServiceDefinitions,
ServiceInfo,
CdsVersionInfo
} from '../types';
import {
deleteDirectory,
deleteFile,
fileExists,
readDirectory,
readFile,
readJSON,
updatePackageJSON,
writeFile
} from '../file';
import { loadModuleFromProject } from './module-loader';
import { findCapProjectRoot } from './search';
interface CdsFacade {
env: { for: (mode: string, path: string) => CdsEnvironment };
linked: (model: csn) => LinkedModel;
load: (paths: string | string[], options?: { root?: string }) => Promise<csn>;
compile: {
to: {
serviceinfo: (model: csn, options?: { root?: string }) => ServiceInfo[];
edmx: (model: csn, options?: { service?: string; version?: 'v2' | 'v4' }) => Promise<string>;
};
};
resolve: ResolveWithCache;
root: string; // cds.root
version: string; // cds.version
home: string; // cds.home
}
interface ResolveWithCache {
(files: string | string[], options?: { skipModelCache: boolean }): string[];
cache: Record<string, { cached: Record<string, string[]>; paths: string[] }>;
}
/**
* Returns true if the project is a CAP Node.js project.
*
* @param packageJson - the parsed package.json object
* @returns - true if the project is a CAP Node.js project
*/
export function isCapNodeJsProject(packageJson: Package): boolean {
return !!(packageJson.cds ?? packageJson.dependencies?.['@sap/cds']);
}
/**
* Returns true if the project is a CAP Java project.
*
* @param projectRoot - the root path of the project
* @param [capCustomPaths] - optional, relative CAP paths like app, db, srv
* @param memFs - optional mem-fs-editor instance
* @returns - true if the project is a CAP project
*/
export async function isCapJavaProject(
projectRoot: string,
capCustomPaths?: CapCustomPaths,
memFs?: Editor
): Promise<boolean> {
const srv = capCustomPaths?.srv ?? (await getCapCustomPaths(projectRoot)).srv;
return fileExists(join(projectRoot, srv, 'src', 'main', 'resources', FileName.CapJavaApplicationYaml), memFs);
}
/**
* Checks if there are files in the `srv` folder, using node fs or mem-fs.
*
* @param {string} srvFolderPath - The path to the `srv` folder to check for files.
* @param {Editor} [memFs] - An optional `mem-fs-editor` instance. If provided, the function checks files within the in-memory file system.
* @returns {Promise<boolean>} - Resolves to `true` if files are found in the `srv` folder; otherwise, `false`.
*/
async function checkFilesInSrvFolder(srvFolderPath: string, memFs?: Editor): Promise<boolean> {
if (!memFs) {
return await fileExists(srvFolderPath);
}
// Load the srv folder and its files into mem-fs
// This is necessary as mem-fs operates in-memory and doesn't automatically include files from disk.
// By loading the files, we ensure they are available within mem-fs.
if (await fileExists(srvFolderPath)) {
const fileSystemFiles = await readDirectory(srvFolderPath);
for (const file of fileSystemFiles) {
const filePath = join(srvFolderPath, file);
if (await fileExists(filePath)) {
const fileContent = await readFile(filePath);
memFs.write(filePath, fileContent);
}
}
}
// Dump the mem-fs state
const memFsDump = memFs.dump();
const memFsFiles = Object.keys(memFsDump).filter((filePath) => {
const normalisedFilePath = resolve(filePath);
const normalisedSrvPath = resolve(srvFolderPath);
return normalisedFilePath.startsWith(normalisedSrvPath);
});
return memFsFiles.length > 0;
}
/**
* Returns the CAP project type, undefined if it is not a CAP project.
*
* @param projectRoot - root of the project, where the package.json resides.
* @param memFs - optional mem-fs-editor instance
* @returns - CAPJava for Java based CAP projects; CAPNodejs for node.js based CAP projects; undefined if it is no CAP project
*/
export async function getCapProjectType(projectRoot: string, memFs?: Editor): Promise<CapProjectType | undefined> {
const capCustomPaths = await getCapCustomPaths(projectRoot);
if (!(await checkFilesInSrvFolder(join(projectRoot, capCustomPaths.srv), memFs))) {
return undefined;
}
if (await isCapJavaProject(projectRoot, capCustomPaths, memFs)) {
return 'CAPJava';
}
let packageJson;
try {
packageJson = await readJSON<Package>(join(projectRoot, FileName.Package), memFs);
} catch {
// Ignore errors while reading the package.json file
}
if (packageJson && isCapNodeJsProject(packageJson)) {
return 'CAPNodejs';
}
return undefined;
}
/**
* Returns true if the project is either a CAP Node.js or a CAP Java project.
*
* @param projectRoot - the root path of the project
* @returns - true if the project is a CAP project
*/
export async function isCapProject(projectRoot: string): Promise<boolean> {
return !!(await getCapProjectType(projectRoot));
}
/**
* Get CAP CDS project custom paths for project root.
*
* @param capProjectPath - project root of cap project
* @returns - paths to app, db, and srv for CAP project
*/
export async function getCapCustomPaths(capProjectPath: string): Promise<CapCustomPaths> {
const result: CapCustomPaths = {
app: 'app/',
db: 'db/',
srv: 'srv/'
};
try {
const cdsCustomPaths = await getCapEnvironment(capProjectPath);
if (cdsCustomPaths.folders) {
result.app = cdsCustomPaths.folders.app;
result.db = cdsCustomPaths.folders.db;
result.srv = cdsCustomPaths.folders.srv;
}
} catch (error) {
// In case of issues, fall back to the defaults
}
return result;
}
/**
* Return the CAP model and all services. The cds.root will be set to the provided project root path.
*
* @param projectRoot - CAP project root where package.json resides or object specifying project root and optional logger to log additional info
* @returns {Promise<{ model: csn; services: ServiceInfo[]; cdsVersionInfo: CdsVersionInfo }>} - CAP Model and Services
*/
export async function getCapModelAndServices(
projectRoot: string | { projectRoot: string; logger?: Logger; pathSelection?: Set<'app' | 'srv' | 'db'> }
): Promise<{ model: csn; services: ServiceInfo[]; cdsVersionInfo: CdsVersionInfo }> {
let _projectRoot: string;
let _logger: Logger | undefined;
let _pathSelection: Set<string> | undefined;
const defaultPathSelection = new Set(['app', 'srv', 'db']);
if (typeof projectRoot === 'object') {
_projectRoot = projectRoot.projectRoot;
_logger = projectRoot.logger;
_pathSelection = projectRoot.pathSelection ? projectRoot.pathSelection : defaultPathSelection;
} else {
_pathSelection = defaultPathSelection;
_projectRoot = projectRoot;
}
const cds = await loadCdsModuleFromProject(_projectRoot, true);
const capProjectPaths = await getCapCustomPaths(_projectRoot);
const modelPaths: string[] = [];
_pathSelection?.forEach((path: string) => {
modelPaths.push(join(_projectRoot, capProjectPaths[path as keyof CapCustomPaths]));
});
const model = await cds.load(modelPaths, { root: _projectRoot });
_logger?.info(`@sap-ux/project-access:getCapModelAndServices - Using 'cds.home': ${cds.home}`);
_logger?.info(`@sap-ux/project-access:getCapModelAndServices - Using 'cds.version': ${cds.version}`);
_logger?.info(`@sap-ux/project-access:getCapModelAndServices - Using 'cds.root': ${cds.root}`);
_logger?.info(`@sap-ux/project-access:getCapModelAndServices - Using 'projectRoot': ${_projectRoot}`);
let services = cds.compile.to.serviceinfo(model, { root: _projectRoot }) ?? [];
if (services.map) {
services = services.map((value) => {
const { endpoints, urlPath } = value;
const odataEndpoint = endpoints?.find((endpoint) => endpoint.kind === 'odata');
const endpointPath = odataEndpoint?.path ?? urlPath;
return {
name: value.name,
urlPath: uniformUrl(endpointPath),
runtime: value.runtime
};
});
}
return {
model,
services,
cdsVersionInfo: {
home: cds.home,
version: cds.version,
root: cds.root
}
};
}
/**
* Returns a list of cds file paths (layers). By default return list of all, but you can also restrict it to one envRoot.
*
* @param projectRoot - root of the project, where the package.json is
* @param [ignoreErrors] - optionally, default is false; if set to true the thrown error will be checked for CDS file paths in model and returned
* @param [envRoot] - optionally, the root folder or CDS file to get the layer files
* @returns - array of strings containing cds file paths
*/
export async function getCdsFiles(
projectRoot: string,
ignoreErrors = false,
envRoot?: string | string[]
): Promise<string[]> {
let cdsFiles: string[] = [];
try {
let csn;
envRoot ??= await getCdsRoots(projectRoot);
try {
const cds = await loadCdsModuleFromProject(projectRoot);
csn = await cds.load(envRoot, { root: projectRoot });
cdsFiles = [...(csn['$sources'] ?? [])];
} catch (e) {
if (ignoreErrors && e.model?.sources && typeof e.model.sources === 'object') {
cdsFiles.push(...extractCdsFilesFromMessage(e.model.sources));
} else {
throw e;
}
}
} catch (error) {
throw Error(
`Error while retrieving the list of cds files for project ${projectRoot}, envRoot ${envRoot}. Error was: ${error}`
);
}
return cdsFiles;
}
/**
* Returns a list of filepaths to CDS files in root folders. Same what is done if you execute cds.resolve('*') on command line in a project.
*
* @param projectRoot - root of the project, where the package.json is
* @param [clearCache] - optionally, clear the cache, default false
* @returns - array of root paths
*/
export async function getCdsRoots(projectRoot: string, clearCache = false): Promise<string[]> {
const roots = [];
const capCustomPaths = await getCapCustomPaths(projectRoot);
const cdsEnvRoots = [capCustomPaths.db, capCustomPaths.srv, capCustomPaths.app, 'schema', 'services'];
// clear cache is enforced to also resolve newly created cds file at design time
const cds = await loadCdsModuleFromProject(projectRoot);
if (clearCache) {
clearCdsResolveCache(cds);
}
for (const cdsEnvRoot of cdsEnvRoots) {
const resolvedRoots =
cds.resolve(join(projectRoot, cdsEnvRoot), {
skipModelCache: true
}) || [];
for (const resolvedRoot of resolvedRoots) {
roots.push(resolvedRoot);
}
}
return roots;
}
/**
* Return a list of services in a CAP project.
*
* @param projectRoot - root of the CAP project, where the package.json is
* @param ignoreErrors - in case loading the cds model throws an error, try to use the model from the exception object
* @returns - array of service definitions
*/
export async function getCdsServices(projectRoot: string, ignoreErrors = true): Promise<ServiceDefinitions[]> {
let cdsServices: ServiceDefinitions[] = [];
try {
const cds = await loadCdsModuleFromProject(projectRoot);
const roots: string[] = await getCdsRoots(projectRoot);
let model;
try {
model = await cds.load(roots, { root: projectRoot });
} catch (e) {
if (ignoreErrors && e.model) {
model = e.model;
} else {
throw e;
}
}
const linked = cds.linked(model);
if (Array.isArray(linked.services)) {
cdsServices = linked.services;
} else {
Object.keys(linked.services).forEach((service) => {
cdsServices.push(linked.services[service] as ServiceDefinitions);
});
}
} catch (error) {
throw Error(`Error while resolving cds roots for '${projectRoot}'. ${error}`);
}
return cdsServices;
}
/**
* When an error occurs while trying to read cds files, the error object contains the source file
* information. This function extracts this file paths.
*
* @param sources - map containing the file name
* @returns - array of strings containing cds file paths
*/
function extractCdsFilesFromMessage(sources: Record<string, { filename?: string }>): string[] {
const cdsFiles: string[] = [];
for (const source in sources) {
let filename = sources[source].filename;
if (typeof filename === 'string' && !filename.startsWith(sep)) {
filename = join(sep, filename);
}
if (filename) {
cdsFiles.push(filename);
}
}
return cdsFiles;
}
/**
* Remove rogue '\\' - cds windows if needed.
* Replaces all backslashes with forward slashes, removes double slashes, and trailing slashes.
*
* @param url - url to uniform
* @returns - uniform url
*/
function uniformUrl(url: string): string {
return url
.replace(/\\/g, '/')
.replace(/\/\//g, '/')
.replace(/(?:^\/)/g, '');
}
/**
* Return the EDMX string of a CAP service.
*
* @param root - CAP project root where package.json resides
* @param uri - service path, e.g 'incident/'
* @param version - optional OData version v2 or v4
* @returns - string containing the edmx
*/
export async function readCapServiceMetadataEdmx(
root: string,
uri: string,
version: 'v2' | 'v4' = 'v4'
): Promise<string> {
try {
const { model, services } = await getCapModelAndServices(root);
const service = findServiceByUri(services, uri);
if (!service) {
throw Error(`Service for uri: '${uri}' not found. Available services: ${JSON.stringify(services)}`);
}
const cds = await loadCdsModuleFromProject(root);
const edmx = cds.compile.to.edmx(model, { service: service.name, version });
return edmx;
} catch (error) {
throw Error(
`Error while reading CAP service metadata. Path: '${root}', service uri: '${uri}', error: '${error.toString()}'}`
);
}
}
/**
* Find a service in a list of services ignoring leading and trailing slashes.
*
* @param services - list of services from cds.compile.to['serviceinfo'](model)
* @param uri - search uri (usually from data source in manifest.json)
* @returns - name and uri of the service, undefined if service not found
*/
function findServiceByUri(
services: { name: string; urlPath: string }[],
uri: string
): { name: string; urlPath: string } | undefined {
const searchUri = uniformUrl(uri).replace(/(?:^\/)|(?:\/$)/g, '');
return services.find((srv) => srv.urlPath.replace(/(?:^\/)|(?:\/$)/g, '') === searchUri);
}
/**
* Get CAP CDS project environment config for project root.
*
* @param capProjectPath - project root of a CAP project
* @returns - environment config for a CAP project
*/
export async function getCapEnvironment(capProjectPath: string): Promise<CdsEnvironment> {
const cds = await loadCdsModuleFromProject(capProjectPath);
return cds.env.for('cds', capProjectPath);
}
/**
* To fix issues when switching different cds versions dynamically, we need to set global.cds, see end of function loadCdsModuleFromProject()
*/
declare const global: {
cds: CdsFacade;
};
/**
* Load CAP CDS module. First attempt loads @sap/cds for a project based on its root.
* Second attempt loads @sap/cds from global installed @sap/cds-dk.
* Throws error if module could not be loaded or strict mode is true and there is a version mismatch.
*
* @param capProjectPath - project root of a CAP project
* @param [strict] - optional, when set true an error is thrown, if global loaded cds version does not match the cds version from package.json dependency. Default is false.
* @returns - CAP CDS module for a CAP project
*/
async function loadCdsModuleFromProject(capProjectPath: string, strict: boolean = false): Promise<CdsFacade> {
let module: CdsFacade | { default: CdsFacade } | undefined;
let loadProjectError;
let loadError;
try {
// First approach, load @sap/cds from project
module = await loadModuleFromProject<CdsFacade | { default: CdsFacade }>(capProjectPath, '@sap/cds');
} catch (error) {
loadProjectError = error;
}
if (!module) {
try {
// Second approach, load @sap/cds from @sap/cds-dk
module = await loadGlobalCdsModule();
} catch (error) {
loadError = error;
}
}
if (!module) {
throw Error(
`Could not load cds module. Attempt to load module @sap/cds from project threw error '${loadProjectError}', attempt to load module @sap/cds from @sap/cds-dk threw error '${loadError}'`
);
}
const cds = 'default' in module ? module.default : module;
// In case strict is true and there was a fallback to global cds installation for a project that has a cds dependency, check if major versions match
if (strict && loadProjectError) {
const cdsDependencyVersion = await getCdsVersionFromPackageJson(join(capProjectPath, FileName.Package));
if (typeof cdsDependencyVersion === 'string') {
const globalCdsVersion = cds.version;
if (getMajorVersion(cdsDependencyVersion) !== getMajorVersion(globalCdsVersion)) {
const error = new Error(
`The @sap/cds major version (${cdsDependencyVersion}) specified in your CAP project is different to the @sap/cds version you have installed globally (${globalCdsVersion}). Please run 'npm install' on your CAP project to ensure that the correct CDS version is loaded.`
) as Error & { code: string };
error.code = 'CDS_VERSION_MISMATCH';
throw error;
}
}
}
// Fix when switching cds versions dynamically
if (global) {
global.cds = cds;
}
// correct cds.env for current project root. Especially needed CAP Java projects loading cds dependency from jar file
cds.env = cds.env.for('cds', capProjectPath) as typeof cds.env;
return cds;
}
/**
* Method to clear CAP CDS module cache for passed project path.
*
* @param projectRoot root of a CAP project.
* @returns True if cache cleared successfully.
*/
export async function clearCdsModuleCache(projectRoot: string): Promise<boolean> {
let result = false;
try {
const cds = await loadCdsModuleFromProject(projectRoot);
if (cds) {
clearCdsResolveCache(cds);
result = true;
}
} catch (e) {
// ignore exception
}
return result;
}
/**
* Method to clear CAP CDS module cache for passed cds module.
*
* @param cds CAP CDS module
*/
function clearCdsResolveCache(cds: CdsFacade): void {
cds.resolve.cache = {};
}
/**
* Get absolute path to a resource.
*
* @param projectRoot - project root of a CAP project
* @param relativeUri - relative resource path.
* @returns {string} - absolute path.
*/
export const toAbsoluteUri = (projectRoot: string, relativeUri: string): string => join(projectRoot, relativeUri);
/**
* Converts to referenced uri to be used in using statements.
*
* @param projectRoot - project root of a CAP project
* @param relativeUriFrom - relative uri of from directory
* @param relativeUriTo - relative uri of to directory
* @returns {Promise<string>} - reference uri
*/
export const toReferenceUri = async (
projectRoot: string,
relativeUriFrom: string,
relativeUriTo: string
): Promise<string> => {
let relativeUri = '';
const indexNodeModules = relativeUriTo.lastIndexOf('node_modules');
if (indexNodeModules >= 0) {
// extract module name from fileUri - e.g. '@sap/cds/common' from '../../node_modules/@sap/cds/common.cds'
const indexLastDot = relativeUriTo.lastIndexOf('.');
if (indexLastDot > indexNodeModules + 13) {
relativeUri = relativeUriTo.slice(indexNodeModules + 13, indexLastDot);
} else {
relativeUri = relativeUriTo.slice(indexNodeModules + 13);
}
} else if (relativeUriTo.startsWith('../') || relativeUriTo.startsWith('..\\')) {
// file outside current project (e.g. mono repo)
const result = await getPackageNameInFolder(projectRoot, relativeUriTo);
if (result.packageName) {
relativeUri = result.packageName + relativeUriTo.slice(result.packageFolder.length);
}
}
if (!relativeUri) {
// build relative path
const fromDir = dirname(toAbsoluteUri(projectRoot, relativeUriFrom));
relativeUri = relative(fromDir, toAbsoluteUri(projectRoot, relativeUriTo));
if (!relativeUri.startsWith('.')) {
relativeUri = './' + relativeUri;
}
}
// remove file extension
const fileExtension = relativeUri.lastIndexOf('.') > 0 ? relativeUri.slice(relativeUri.lastIndexOf('.') + 1) : '';
if (['CDS', 'JSON'].includes(fileExtension.toUpperCase())) {
relativeUri = relativeUri.slice(0, relativeUri.length - fileExtension.length - 1);
}
// always use '/' instead of platform specific separator
return relativeUri.split(sep).join('/');
};
/**
* Gets package name from the folder.
*
* @param baseUri - base uri of the cap project
* @param relativeUri - relative uri to the resource folder
* @returns {Promise<{ packageName: string; packageFolder: string }>} - package name and folder
*/
async function getPackageNameInFolder(
baseUri: string,
relativeUri: string
): Promise<{ packageName: string; packageFolder: string }> {
const refUriParts = relativeUri.split(sep);
const result = { packageName: '', packageFolder: relativeUri };
for (let i = refUriParts.length - 1; i >= 0 && !result.packageName; i--) {
const currentFolder = refUriParts.slice(0, i).join(sep);
result.packageName = await readPackageNameForFolder(baseUri, currentFolder);
if (result.packageName) {
result.packageFolder = currentFolder;
}
}
return result;
}
/**
* Reads package name from package json of the folder.
*
* @param baseUri - base uri of the cap project
* @param relativeUri - relative uri to the resource folder
* @returns {Promise<string>} - package name
*/
async function readPackageNameForFolder(baseUri: string, relativeUri: string): Promise<string> {
let packageName = '';
try {
const path = normalize(baseUri + '/' + relativeUri + '/' + 'package.json');
const content = await readFile(path);
if (content) {
const parsed = JSON.parse(content);
packageName = parsed.name;
}
} catch (e) {
packageName = '';
}
return packageName;
}
// Cache for request to load global cds. Cache the promise to avoid starting multiple identical requests in parallel.
let globalCdsModulePromise: Promise<CdsFacade> | undefined;
/**
* Try to load global installation of @sap/cds, usually child of @sap/cds-dk.
*
* @returns - module @sap/cds from global installed @sap/cds-dk
*/
async function loadGlobalCdsModule(): Promise<CdsFacade> {
globalCdsModulePromise =
globalCdsModulePromise ??
new Promise<CdsFacade>((resolve, reject) => {
return getCdsVersionInfo().then((versions) => {
if (versions.home) {
resolve(loadModuleFromProject<CdsFacade>(versions.home, '@sap/cds'));
} else {
reject(
new Error(
'Can not find global installation of module @sap/cds, which should be part of @sap/cds-dk'
)
);
}
}, reject);
});
return globalCdsModulePromise;
}
/**
* Clear cache of request to load global cds module.
*/
export function clearGlobalCdsModulePromiseCache(): void {
globalCdsModulePromise = undefined;
}
/**
* Get cds information, which includes versions and also the home path of cds module.
*
* @param [cwd] - optional folder in which cds --version should be executed
* @returns - result of call 'cds --version'
*/
async function getCdsVersionInfo(cwd?: string): Promise<Record<string, string>> {
return new Promise((resolve, reject) => {
let out = '';
const cdsVersionInfo = spawn('cds', ['--version'], { cwd, shell: true });
cdsVersionInfo.stdout.on('data', (data) => {
out += data.toString();
});
cdsVersionInfo.on('close', () => {
if (out) {
const versions: Record<string, string> = {};
for (const line of out.split('\n').filter((v) => v)) {
const [key, value] = line.split(': ');
versions[key] = value;
}
resolve(versions);
} else {
reject(new Error('Module path not found'));
}
});
cdsVersionInfo.on('error', (error) => {
reject(error);
});
});
}
/**
* Read the version string of the @sap/cds module from the package.json file.
*
* @param packageJsonPath - path to package.json
* @returns - version of @sap/cds from package.json or undefined
*/
async function getCdsVersionFromPackageJson(packageJsonPath: string): Promise<string | undefined> {
let version: string | undefined;
try {
if (await fileExists(packageJsonPath)) {
const packageJson = await readJSON<Package>(packageJsonPath);
version = packageJson?.dependencies?.['@sap/cds'];
}
} catch {
// If we can't read or parse the package.json we return undefined
}
return version;
}
/**
* Get major version from version string.
*
* @param versionString - version string
* @returns - major version as number
*/
function getMajorVersion(versionString: string): number {
return parseInt(/\d+/.exec(versionString.split('.')[0])?.[0] ?? '0', 10);
}
/**
* Method resolves cap service name for passed project root and service uri.
*
* @param projectRoot - project root
* @param datasourceUri - service uri
* @returns - found cap service name
*/
export async function getCapServiceName(projectRoot: string, datasourceUri: string): Promise<string> {
const services = (await getCapModelAndServices(projectRoot)).services;
const service = findServiceByUri(services, datasourceUri);
if (!service?.name) {
const errorMessage = `Service for uri: '${datasourceUri}' not found. Available services: ${JSON.stringify(
services
)}`;
throw Error(errorMessage);
}
return service.name;
}
/**
* Method cleans up cds files after deletion of passed appName.
*
* @param cdsFilePaths - cds files to cleanup
* @param appName - CAP application name
* @param memFs - optional mem-fs-editor instance
* @param logger - function to log messages (optional)
*/
async function cleanupCdsFiles(
cdsFilePaths: string[],
appName: string,
memFs?: Editor,
logger?: Logger
): Promise<void> {
const usingEntry = `using from './${appName}/annotations';`;
for (const cdsFilePath of cdsFilePaths) {
if (await fileExists(cdsFilePath, memFs)) {
try {
let cdsFile = await readFile(cdsFilePath, memFs);
if (cdsFile.indexOf(usingEntry) !== -1) {
logger?.info(`Removing using statement for './${appName}/annotations' from '${cdsFilePath}'.`);
cdsFile = cdsFile.replace(usingEntry, '');
if (cdsFile.replace(/\n/g, '').trim() === '') {
logger?.info(`File '${cdsFilePath}' is now empty, removing it.`);
await deleteFile(cdsFilePath, memFs);
} else {
await writeFile(cdsFilePath, cdsFile, memFs);
}
}
} catch (error) {
logger?.error(`Could not modify file '${cdsFilePath}'. Skipping this file.`);
}
}
}
}
/**
* Delete application from CAP project.
*
* @param appPath - path to the application in a CAP project
* @param [memFs] - optional mem-fs-editor instance
* @param [logger] - function to log messages (optional)
*/
export async function deleteCapApp(appPath: string, memFs?: Editor, logger?: Logger): Promise<void> {
const appName = basename(appPath);
const projectRoot = await findCapProjectRoot(appPath);
if (!projectRoot) {
const message = `Project root was not found for CAP application with path '${appPath}'`;
logger?.error(message);
throw Error(message);
}
const packageJsonPath = join(projectRoot, FileName.Package);
const packageJson = await readJSON<Package>(packageJsonPath, memFs);
const cdsFilePaths = [join(dirname(appPath), FileName.ServiceCds), join(dirname(appPath), FileName.IndexCds)];
logger?.info(`Deleting app '${appName}' from CAP project '${projectRoot}'.`);
// Update `sapux` array if presented in package.json
if (Array.isArray(packageJson.sapux)) {
const posixAppPath = appPath.replace(/\\/g, '/');
packageJson.sapux = packageJson.sapux.filter((a) => !posixAppPath.endsWith(a.replace(/\\/g, '/')));
if (packageJson.sapux.length === 0) {
logger?.info(
`This was the last app in this CAP project. Deleting property 'sapux' from '${packageJsonPath}'.`
);
delete packageJson.sapux;
}
}
if (packageJson.scripts?.[`watch-${appName}`]) {
delete packageJson.scripts[`watch-${appName}`];
}
await updatePackageJSON(packageJsonPath, packageJson, memFs);
logger?.info(`File '${packageJsonPath}' updated.`);
await deleteDirectory(appPath, memFs);
logger?.info(`Directory '${appPath}' deleted.`);
// Cleanup app/service.cds and app/index.cds files
await cleanupCdsFiles(cdsFilePaths, appName, memFs, logger);
// Check if app folder is now empty
if ((await readDirectory(dirname(appPath))).length === 0) {
logger?.info(`Directory '${dirname(appPath)}' is now empty. Deleting it.`);
await deleteDirectory(dirname(appPath), memFs);
}
}