forked from redhat-developer/vscode-openshift-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateComponentLoader.ts
More file actions
674 lines (637 loc) · 28.3 KB
/
createComponentLoader.ts
File metadata and controls
674 lines (637 loc) · 28.3 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
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
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import * as fse from 'fs-extra';
import * as fs from 'fs/promises';
import * as JSYAML from 'js-yaml';
import * as path from 'path';
import * as tmp from 'tmp';
import { promisify } from 'util';
import * as vscode from 'vscode';
import { extensions, Uri, ViewColumn, WebviewPanel, window } from 'vscode';
import { AnalyzeResponse, ComponentTypeDescription } from '../../odo/componentType';
import { Endpoint } from '../../odo/componentTypeDescription';
import { Odo } from '../../odo/odoWrapper';
import { ComponentTypesView } from '../../registriesView';
import sendTelemetry from '../../telemetry';
import { ExtensionID } from '../../util/constants';
import { DevfileConverter } from '../../util/devfileConverter';
import { selectWorkspaceFolder } from '../../util/workspace';
import {
getDevfileCapabilities,
getDevfileRegistries,
getDevfileTags,
isValidProjectFolder,
validateName,
validatePortNumber
} from '../common-ext/createComponentHelpers';
import { loadWebviewHtml, validateGitURL } from '../common-ext/utils';
import { Devfile, DevfileRegistry, TemplateProjectIdentifier } from '../common/devfile';
import { DevfileV1 } from '../../util/devfileV1Type';
interface CloneProcess {
status: boolean;
error: string | undefined;
}
type Message = {
action: string;
data: any;
};
let tmpFolder: Uri;
export default class CreateComponentLoader {
static panel: WebviewPanel;
static initFromRootFolderPath: string;
static get extensionPath() {
return extensions.getExtension(ExtensionID).extensionPath;
}
static async loadView(title: string, folderPath?: string): Promise<WebviewPanel> {
if (CreateComponentLoader.panel) {
CreateComponentLoader.panel.reveal();
return;
}
const localResourceRoot = Uri.file(
path.join(CreateComponentLoader.extensionPath, 'out', 'createComponentViewer'),
);
const panel = window.createWebviewPanel('createComponentView', title, ViewColumn.One, {
enableScripts: true,
localResourceRoots: [localResourceRoot],
retainContextWhenHidden: true,
});
const messageHandlerDisposable = panel.webview.onDidReceiveMessage(
CreateComponentLoader.messageHandler,
);
const colorThemeDisposable = vscode.window.onDidChangeActiveColorTheme(async function (
colorTheme: vscode.ColorTheme,
) {
await panel.webview.postMessage({ action: 'setTheme', themeValue: colorTheme.kind });
});
const registriesSubscription = ComponentTypesView.instance.subject.subscribe(() => {
sendUpdatedRegistries();
});
const capabiliiesySubscription = ComponentTypesView.instance.subject.subscribe(() => {
sendUpdatedCapabilities();
});
const tagsSubscription = ComponentTypesView.instance.subject.subscribe(() => {
sendUpdatedTags();
});
panel.onDidDispose(() => {
void sendTelemetry('newComponentClosed');
tagsSubscription.unsubscribe();
capabiliiesySubscription.unsubscribe();
registriesSubscription.unsubscribe();
colorThemeDisposable.dispose();
messageHandlerDisposable.dispose();
CreateComponentLoader.panel = undefined;
if (tmpFolder) {
void fs.rm(tmpFolder.fsPath, { force: true, recursive: true });
}
});
panel.iconPath = Uri.file(
path.join(CreateComponentLoader.extensionPath, 'images/context/cluster-node.png'),
);
panel.webview.html = await loadWebviewHtml('createComponentViewer', panel);
CreateComponentLoader.panel = panel;
CreateComponentLoader.initFromRootFolderPath = folderPath;
return panel;
}
/**
* Respond to messages from the webview.
*/
static async messageHandler(message: Message) {
switch (message.action) {
/**
* The panel has successfully loaded. Send the kind of the current color theme to update the theme.
*/
case 'init': {
void CreateComponentLoader.panel.webview.postMessage({
action: 'setTheme',
themeValue: vscode.window.activeColorTheme.kind,
});
void CreateComponentLoader.panel.webview.postMessage({
action: 'initFromRootFolder',
rootFolder: CreateComponentLoader.initFromRootFolderPath,
});
break;
}
/**
* The panel requested the list of devfile registries with their devfiles. Respond with this list.
*/
case 'getDevfileRegistries': {
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileRegistries',
data: getDevfileRegistries(),
});
break;
}
/**
* The panel requested the list of devfile capabilities. Respond with this list.
*/
case 'getDevfileCapabilities': {
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileCapabilities',
data: getDevfileCapabilities(),
});
break;
}
/**
* The panel requested the list of devfile tags. Respond with this list.
*/
case 'getDevfileTags': {
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileTags',
data: getDevfileTags(),
});
break;
}
/**
* The panel requested the list of workspace folders. Respond with this list.
*/
case 'getWorkspaceFolders': {
if (vscode.workspace.workspaceFolders !== undefined) {
const workspaceFolderUris: Uri[] = vscode.workspace.workspaceFolders.map(
(wsFolder) => wsFolder.uri,
);
const filteredWorkspaceUris: Uri[] = [];
for (const workspaceFolderUri of workspaceFolderUris) {
const hasDevfile = await isDevfileExists(workspaceFolderUri);
if (!hasDevfile) {
filteredWorkspaceUris.push(workspaceFolderUri);
}
}
const filteredWorkspacePaths = filteredWorkspaceUris.map(uri => uri.fsPath);
void CreateComponentLoader.panel.webview.postMessage({
action: 'workspaceFolders',
data: filteredWorkspacePaths,
});
}
break;
}
/**
* The panel requested to validate the entered component name. Respond with error status and message.
*/
case 'validateComponentName': {
const validationMessage = validateName(message.data);
void CreateComponentLoader.panel.webview.postMessage({
action: 'validatedComponentName',
data: validationMessage,
});
break;
}
/**
* The panel requested to validate the entered port number. Respond with error status and message.
*/
case 'validatePortNumber': {
const validationMessage = validatePortNumber(message.data);
void CreateComponentLoader.panel.webview.postMessage({
action: 'validatePortNumber',
data: validationMessage,
});
break;
}
/**
* The panel requested to select a project folder.
*/
case 'selectProjectFolder': {
const workspaceUri: Uri = await selectWorkspaceFolder(true);
const workspaceFolderUris: Uri[] = vscode.workspace.workspaceFolders
? vscode.workspace.workspaceFolders.map((wsFolder) => wsFolder.uri)
: [];
workspaceFolderUris.push(workspaceUri);
const workspacePaths = workspaceFolderUris.map(uri => uri.fsPath);
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileExists',
data: await isDevfileExists(workspaceUri),
});
void CreateComponentLoader.panel.webview.postMessage({
action: 'workspaceFolders',
data: workspacePaths,
});
void CreateComponentLoader.panel.webview.postMessage({
action: 'selectedProjectFolder',
data: workspaceUri.fsPath,
});
break;
}
/**
* The panel request to select a project folder from the
* 'template project' workflow
*/
case 'selectProjectFolderNewProject': {
const workspaceUri: vscode.Uri = await selectWorkspaceFolder(true);
void CreateComponentLoader.panel.webview.postMessage({
action: 'selectedProjectFolder',
data: workspaceUri.fsPath,
});
break;
}
/**
* The panel requested to get the receommended devfile given the selected project.
*/
case 'getRecommendedDevfile': {
await CreateComponentLoader.panel.webview.postMessage({
action: 'devfileExists',
data: await isDevfileExists(Uri.file(message.data)),
});
void CreateComponentLoader.getRecommendedDevfile(Uri.file(message.data));
break;
}
case 'isValidProjectFolder': {
const { folder, componentName } = message.data;
const validationResult = await isValidProjectFolder(folder, componentName);
void CreateComponentLoader.panel.webview.postMessage({
action: 'isValidProjectFolder',
data: validationResult,
});
break;
}
/**
* The panel requested to get the receommended devfile given the selected project.
*/
case 'getRecommendedDevfileFromGit': {
tmpFolder = Uri.parse(await promisify(tmp.dir)());
void CreateComponentLoader.panel.webview.postMessage({
action: 'cloneStart',
});
const cloneProcess: CloneProcess = await clone(
message.data.url,
tmpFolder.fsPath,
message.data.branch,
);
if (!cloneProcess.status && cloneProcess.error) {
void CreateComponentLoader.panel.webview.postMessage({
action: 'cloneFailed',
});
} else {
const isGirDevfileExists = await isDevfileExists(tmpFolder);
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileExists',
data: isGirDevfileExists,
});
if (isGirDevfileExists) {
// Use the Devfile existing in Gir-repo
void CreateComponentLoader.getExistingDevfile(tmpFolder);
} else {
// Use recommended Devfile
void CreateComponentLoader.getRecommendedDevfile(tmpFolder);
}
}
break;
}
/**
* The panel requested to create component from local codebase or git repo.
*/
case 'createComponent': {
const componentName: string = message.data.componentName;
const portNumber: number = message.data.portNumber;
let componentFolder: string = '';
try {
if (message.data.isFromTemplateProject) {
// from template project
const { projectFolder } = message.data;
const templateProject: TemplateProjectIdentifier =
message.data.templateProject;
componentFolder = path.join(projectFolder, componentName);
await fs.mkdir(componentFolder);
await Odo.Instance.createComponentFromTemplateProject(
componentFolder,
componentName,
portNumber,
templateProject.devfileId,
templateProject.registryName,
templateProject.templateProjectName,
);
await sendTelemetry('newComponentCreated', {
strategy: 'fromTemplateProject',
// eslint-disable-next-line camelcase
component_type: templateProject.devfileId,
// eslint-disable-next-line camelcase
starter_project: templateProject.templateProjectName,
});
} else {
let strategy: string;
// from local codebase or existing git repo
if (message.data.path) {
// path of project in local codebase
strategy = 'fromLocalCodebase';
componentFolder = message.data.path;
} else if (message.data.gitDestinationPath) {
// move the cloned git repo to selected project path
strategy = 'fromGitRepo';
componentFolder = path.join(
message.data.gitDestinationPath,
componentName,
);
await fs.mkdir(componentFolder);
await fse.copy(tmpFolder.fsPath, componentFolder);
}
const devfileType = getDevfileType(message.data.devfileDisplayName);
const componentFolderUri = Uri.file(componentFolder);
if (!await isDevfileExists(componentFolderUri)) {
await Odo.Instance.createComponentFromLocation(
devfileType,
componentName,
portNumber,
Uri.file(componentFolder),
);
} else {
// Update component devfile with component's selected name
await CreateComponentLoader.updateDevfileWithComponentName(componentFolderUri, componentName);
}
await sendTelemetry('newComponentCreated', {
strategy,
// eslint-disable-next-line camelcase
component_type: devfileType,
});
}
CreateComponentLoader.panel.dispose();
if (
message.data.addToWorkspace &&
!vscode.workspace.workspaceFolders?.some(
(workspaceFolder) => workspaceFolder.uri.fsPath === componentFolder,
)
) {
vscode.workspace.updateWorkspaceFolders(
vscode.workspace.workspaceFolders
? vscode.workspace.workspaceFolders.length
: 0,
null,
{ uri: Uri.file(componentFolder) },
);
}
void vscode.commands.executeCommand('openshift.componentsView.refresh');
void vscode.window.showInformationMessage('Component has been successfully created. You can now run `Start Dev` from the components view.');
} catch (err) {
await sendTelemetry('newComponentCreationFailed', {
error: JSON.stringify(err),
});
void vscode.window.showErrorMessage(err);
void CreateComponentLoader.panel.webview.postMessage({
action: 'createComponentFailed',
data: err.message,
});
}
break;
}
/**
* The panel requested to validate the git repository URL.
*/
case 'validateGitURL': {
const response = validateGitURL(message);
void CreateComponentLoader.panel?.webview.postMessage({
action: message.action,
data: {
isValid: !response.error,
helpText: response.helpText
}
});
break;
}
/**
* The panel requested to validate a folder path.
*/
case 'validateFolderPath': {
await validateFolderPath(message.data);
break;
}
/**
* The git import workflow was cancelled, delete the cloned git repo in the temp directory.
*/
case 'deleteClonedRepo': {
await fs.rm(tmpFolder.fsPath, { force: true, recursive: true });
break;
}
/**
* Send a telemetry message
*/
case 'sendTelemetry': {
const actionName: string = message.data.actionName;
const properties: {[key: string]: string} = message.data.properties;
void sendTelemetry(actionName, properties);
break;
}
default:
void window.showErrorMessage(`Unexpected message from webview: '${message.action}'`);
break;
}
}
static async updateDevfileWithComponentName(ucomponentFolderUri: vscode.Uri, componentName: string): Promise<void> {
const devFilePath = path.join(ucomponentFolderUri.fsPath, 'devfile.yaml');
const file = await fs.readFile(devFilePath, 'utf8');
const devfile = JSYAML.load(file.toString()) as any;
if (devfile?.metadata?.name !== componentName) {
devfile.metadata.name = componentName;
await fs.unlink(devFilePath);
const yaml = JSYAML.dump(devfile, { sortKeys: true });
await fs.writeFile(devFilePath, yaml.toString(), 'utf-8');
}
}
static async getExistingDevfile(uri: Uri): Promise<void> {
let rawDevfile: any;
let supportsDebug = false; // Initial value
let supportsDeploy = false; // Initial value
try {
void CreateComponentLoader.panel.webview.postMessage({
action: 'getRecommendedDevfileStart'
});
const componentDescription = await Odo.Instance.describeComponent(uri.fsPath);
if (componentDescription) {
rawDevfile = componentDescription.devfileData.devfile;
supportsDebug = componentDescription.devfileData.supportedOdoFeatures.debug;
supportsDeploy = componentDescription.devfileData.supportedOdoFeatures.deploy;
}
} catch (Error) {
// Will try reading the raw devfile
} finally {
if (!rawDevfile) {
//Try reading the raw devfile
const devFileYamlPath = path.join(tmpFolder.fsPath, 'devfile.yaml');
const file = await fs.readFile(devFileYamlPath, 'utf8');
rawDevfile = JSYAML.load(file.toString());
}
void CreateComponentLoader.panel.webview.postMessage({
action: 'getRecommendedDevfile'
});
const devfile: Devfile = {
description: rawDevfile.metadata.description,
name: rawDevfile.metadata.displayName ? rawDevfile.metadata.displayName : rawDevfile.metadata.name,
id: rawDevfile.metadata.name,
starterProjects: rawDevfile.starterProjects,
tags: [],
yaml: JSYAML.dump(rawDevfile),
supportsDebug,
supportsDeploy,
} as Devfile;
void CreateComponentLoader.panel.webview.postMessage({
action: 'recommendedDevfile',
data: {
devfile,
},
});
}
}
static async getRecommendedDevfile(uri: Uri): Promise<void> {
let analyzeRes: AnalyzeResponse[] = [];
let compDescriptions: ComponentTypeDescription[] = [];
try {
void CreateComponentLoader.panel.webview.postMessage({
action: 'getRecommendedDevfileStart'
});
analyzeRes = await Odo.Instance.analyze(uri.fsPath);
compDescriptions = getCompDescription(analyzeRes);
} catch (error) {
if (error.message.toLowerCase().indexOf('failed to parse the devfile') !== -1) {
const actions: Array<string> = ['Yes', 'Cancel'];
const devfileRegenerate = await vscode.window.showInformationMessage(
'We have detected that the repo contains configuration based on devfile v1. The extension does not support devfile v1, will you be okay to regenerate a new devfile v2?',
...actions,
);
if (devfileRegenerate === 'Yes') {
try {
const devFileV1Path = path.join(uri.fsPath, 'devfile.yaml');
const file = await fs.readFile(devFileV1Path, 'utf8');
const devfileV1 = JSYAML.load(file.toString()) as DevfileV1;
await fs.unlink(devFileV1Path);
analyzeRes = await Odo.Instance.analyze(uri.fsPath);
compDescriptions = getCompDescription(analyzeRes);
const endPoints = getEndPoints(compDescriptions[0]);
const devfileV2 = DevfileConverter.getInstance().devfileV1toDevfileV2(
devfileV1,
endPoints,
);
const yaml = JSYAML.dump(devfileV2, { sortKeys: true });
await fs.writeFile(devFileV1Path, yaml.toString(), 'utf-8');
await CreateComponentLoader.panel?.webview.postMessage({
action: 'devfileRegenerated',
});
} catch (e) {
void vscode.window.showErrorMessage(
'Failed to parse devfile v1, Unable to proceed the component creation',
);
}
} else {
void vscode.window.showErrorMessage(
'Devfile version not supported, Unable to proceed the component creation',
);
}
}
} finally {
void CreateComponentLoader.panel.webview.postMessage({
action: 'getRecommendedDevfile'
});
const devfileRegistry: DevfileRegistry[] = getDevfileRegistries();
const allDevfiles: Devfile[] = devfileRegistry.flatMap((registry) => registry.devfiles);
const devfile: Devfile | undefined =
compDescriptions.length !== 0
? allDevfiles.find(
(devfile) => devfile.name === compDescriptions[0].displayName,
)
: undefined;
if (devfile) {
devfile.port = compDescriptions[0].devfileData.devfile.components[0].container?.endpoints[0].targetPort;
}
void CreateComponentLoader.panel.webview.postMessage({
action: 'recommendedDevfile',
data: {
devfile,
},
});
}
}
}
function getCompDescription(devfiles: AnalyzeResponse[]): ComponentTypeDescription[] {
const compDescriptions = ComponentTypesView.instance.getCompDescriptions();
if (devfiles.length === 0) {
return Array.from(compDescriptions);
}
return Array.from(compDescriptions).filter(({ name, version, registry }) =>
devfiles.some(
(res) =>
res.devfile === name &&
res.devfileVersion === version &&
res.devfileRegistry === registry.name,
),
);
}
function getDevfileType(devfileDisplayName: string): string {
const compDescriptions: Set<ComponentTypeDescription> =
ComponentTypesView.instance.getCompDescriptions();
const devfileDescription: ComponentTypeDescription = Array.from(compDescriptions).find(
(description) => description.displayName === devfileDisplayName,
);
return devfileDescription ? devfileDescription.name : devfileDisplayName;
}
function getEndPoints(compDescription: ComponentTypeDescription): Endpoint[] {
return compDescription.devfileData.devfile.components[0].container.endpoints;
}
async function isDevfileExists(uri: vscode.Uri): Promise<boolean> {
if ((await fs.stat(uri.fsPath)).isDirectory()) {
const devFileYamlPath = path.join(uri.fsPath, 'devfile.yaml');
try {
await fs.access(devFileYamlPath);
return true;
} catch {
return false;
}
}
}
function clone(url: string, location: string, branch?: string): Promise<CloneProcess> {
const gitExtension = vscode.extensions.getExtension('vscode.git').exports;
const git = gitExtension.getAPI(1).git.path;
let command = `${git} clone ${url} ${location}`;
command = branch ? `${command} --branch ${branch}` : command;
void CreateComponentLoader.panel.webview.postMessage({
action: 'cloneExecution'
});
// run 'git clone url location' as external process and return location
return new Promise((resolve, reject) =>
cp.exec(command, (error: cp.ExecException) => {
error
? resolve({ status: false, error: error.message })
: resolve({ status: true, error: undefined });
}),
);
}
async function validateFolderPath(path: string) {
let isValid = true;
let helpText = '';
if ((await fs.stat(path)).isDirectory()) {
try {
await fs.access(path);
} catch {
isValid = false;
helpText = 'Please enter a valid directory path.';
}
await CreateComponentLoader.panel?.webview.postMessage({
action: 'validatedFolderPath',
data: {
isValid,
helpText,
},
});
}
}
function sendUpdatedRegistries() {
if (CreateComponentLoader.panel) {
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileRegistries',
data: getDevfileRegistries(),
});
}
}
function sendUpdatedCapabilities() {
if (CreateComponentLoader.panel) {
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileCapabilities',
data: getDevfileCapabilities(),
});
}
}
function sendUpdatedTags() {
if (CreateComponentLoader.panel) {
void CreateComponentLoader.panel.webview.postMessage({
action: 'devfileTags',
data: getDevfileTags(),
});
}
}