-
Notifications
You must be signed in to change notification settings - Fork 92
/
Profiles.ts
1779 lines (1657 loc) · 75.5 KB
/
Profiles.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This program and the accompanying materials are made available under the terms of the
* Eclipse Public License v2.0 which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Copyright Contributors to the Zowe Project.
*
*/
import * as vscode from "vscode";
import * as zowe from "@zowe/cli";
import * as path from "path";
import {
Gui,
IZoweTree,
IZoweNodeType,
IZoweUSSTreeNode,
IZoweDatasetTreeNode,
IZoweJobTreeNode,
IZoweTreeNode,
PersistenceSchemaEnum,
IProfileValidation,
IValidationSetting,
ValidProfileEnum,
ProfilesCache,
IUrlValidator,
ZoweVsCodeExtension,
getFullPath,
getZoweDir,
} from "@zowe/zowe-explorer-api";
import { errorHandling, FilterDescriptor, FilterItem, readConfigFromDisk } from "./utils/ProfilesUtils";
import { ZoweExplorerApiRegister } from "./ZoweExplorerApiRegister";
import { ZoweExplorerExtender } from "./ZoweExplorerExtender";
import * as globals from "./globals";
import * as nls from "vscode-nls";
import { SettingsConfig } from "./utils/SettingsConfig";
import { ZoweLogger } from "./utils/LoggerUtils";
// Set up localization
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
let InputBoxOptions: vscode.InputBoxOptions;
export class Profiles extends ProfilesCache {
// Processing stops if there are no profiles detected
public static async createInstance(log: zowe.imperative.Logger): Promise<Profiles> {
Profiles.loader = new Profiles(log, vscode.workspace.workspaceFolders?.[0]?.uri.fsPath);
await Profiles.loader.refresh(ZoweExplorerApiRegister.getInstance());
return Profiles.loader;
}
public static getInstance(): Profiles {
ZoweLogger.trace("Profiles.getInstance called.");
return Profiles.loader;
}
protected static loader: Profiles;
public loadedProfile: zowe.imperative.IProfileLoaded;
public validProfile: ValidProfileEnum = ValidProfileEnum.INVALID;
private dsSchema: string = globals.SETTINGS_DS_HISTORY;
private ussSchema: string = globals.SETTINGS_USS_HISTORY;
private jobsSchema: string = globals.SETTINGS_JOBS_HISTORY;
private mProfileInfo: zowe.imperative.ProfileInfo;
private profilesOpCancelled = localize("profiles.operation.cancelled", "Operation Cancelled");
public constructor(log: zowe.imperative.Logger, cwd?: string) {
super(log, cwd);
}
/**
* Initializes the Imperative ProfileInfo API and reads profiles from disk.
* During extension activation the ProfileInfo object is cached, so this
* method can be called multiple times without impacting performance. After
* the extension has activated, the cache expires so that the latest profile
* contents will be loaded.
*/
public async getProfileInfo(): Promise<zowe.imperative.ProfileInfo> {
ZoweLogger.trace("Profiles.getProfileInfo called.");
this.mProfileInfo = await super.getProfileInfo();
return this.mProfileInfo;
}
public async checkCurrentProfile(theProfile: zowe.imperative.IProfileLoaded): Promise<IProfileValidation> {
ZoweLogger.trace("Profiles.checkCurrentProfile called.");
let profileStatus: IProfileValidation;
if (!theProfile.profile.tokenType && (!theProfile.profile.user || !theProfile.profile.password)) {
// The profile will need to be reactivated, so remove it from profilesForValidation
this.profilesForValidation = this.profilesForValidation.filter(
(profile) => profile.status === "unverified" && profile.name !== theProfile.name
);
let values: string[];
try {
values = await Profiles.getInstance().promptCredentials(theProfile);
} catch (error) {
errorHandling(error, theProfile.name, error.message);
return profileStatus;
}
if (values) {
theProfile.profile.user = values[0];
theProfile.profile.password = values[1];
theProfile.profile.base64EncodedAuth = values[2];
// Validate profile
profileStatus = await this.getProfileSetting(theProfile);
} else {
profileStatus = { name: theProfile.name, status: "unverified" };
}
} else {
// Profile should have enough information to allow validation
profileStatus = await this.getProfileSetting(theProfile);
}
switch (profileStatus.status) {
case "unverified":
this.validProfile = ValidProfileEnum.UNVERIFIED;
break;
case "inactive":
this.validProfile = ValidProfileEnum.INVALID;
break;
case "active":
this.validProfile = ValidProfileEnum.VALID;
break;
}
return profileStatus;
}
public async getProfileSetting(theProfile: zowe.imperative.IProfileLoaded): Promise<IProfileValidation> {
ZoweLogger.trace("Profiles.getProfileSetting called.");
let profileStatus: IProfileValidation;
let found: boolean = false;
this.profilesValidationSetting.forEach((instance) => {
if (instance.name === theProfile.name && instance.setting === false) {
profileStatus = {
status: "unverified",
name: instance.name,
};
if (this.profilesForValidation.length > 0) {
this.profilesForValidation.forEach((profile) => {
if (profile.name === theProfile.name && profile.status === "unverified") {
found = true;
}
if (profile.name === theProfile.name && profile.status !== "unverified") {
found = true;
const index = this.profilesForValidation.lastIndexOf(profile);
this.profilesForValidation.splice(index, 1, profileStatus);
}
});
}
if (!found) {
this.profilesForValidation.push(profileStatus);
}
}
});
if (profileStatus === undefined) {
profileStatus = await this.validateProfiles(theProfile);
}
return profileStatus;
}
public disableValidation(node: IZoweNodeType): IZoweNodeType {
ZoweLogger.trace("Profiles.disableValidation called.");
this.disableValidationContext(node);
return node;
}
public disableValidationContext(node: IZoweNodeType): IZoweNodeType {
ZoweLogger.trace("Profiles.disableValidationContext called.");
const theProfile: zowe.imperative.IProfileLoaded = node.getProfile();
this.validationArraySetup(theProfile, false);
if (node.contextValue.includes(`${globals.VALIDATE_SUFFIX}true`)) {
node.contextValue = node.contextValue
.replace(/(_validate=true)/g, "")
.replace(/(_Active)/g, "")
.replace(/(_Inactive)/g, "");
node.contextValue = node.contextValue + `${globals.VALIDATE_SUFFIX}false`;
} else if (node.contextValue.includes(`${globals.VALIDATE_SUFFIX}false`)) {
return node;
} else {
node.contextValue = node.contextValue + `${globals.VALIDATE_SUFFIX}false`;
}
return node;
}
public enableValidation(node: IZoweNodeType): IZoweNodeType {
ZoweLogger.trace("Profiles.enableValidation called.");
this.enableValidationContext(node);
return node;
}
public enableValidationContext(node: IZoweNodeType): IZoweNodeType {
ZoweLogger.trace("Profiles.enableValidationContext called.");
const theProfile: zowe.imperative.IProfileLoaded = node.getProfile();
this.validationArraySetup(theProfile, true);
if (node.contextValue.includes(`${globals.VALIDATE_SUFFIX}false`)) {
node.contextValue = node.contextValue.replace(/(_validate=false)/g, "").replace(/(_Unverified)/g, "");
node.contextValue = node.contextValue + `${globals.VALIDATE_SUFFIX}true`;
} else if (node.contextValue.includes(`${globals.VALIDATE_SUFFIX}true`)) {
return node;
} else {
node.contextValue = node.contextValue + `${globals.VALIDATE_SUFFIX}true`;
}
return node;
}
public validationArraySetup(theProfile: zowe.imperative.IProfileLoaded, validationSetting: boolean): IValidationSetting {
ZoweLogger.trace("Profiles.validationArraySetup called.");
let found: boolean = false;
let profileSetting: IValidationSetting;
if (this.profilesValidationSetting.length > 0) {
this.profilesValidationSetting.forEach((instance) => {
if (instance.name === theProfile.name && instance.setting === validationSetting) {
found = true;
profileSetting = {
name: instance.name,
setting: instance.setting,
};
}
if (instance.name === theProfile.name && instance.setting !== validationSetting) {
found = true;
profileSetting = {
name: instance.name,
setting: validationSetting,
};
const index = this.profilesValidationSetting.lastIndexOf(instance);
this.profilesValidationSetting.splice(index, 1, profileSetting);
}
});
if (!found) {
profileSetting = {
name: theProfile.name,
setting: validationSetting,
};
this.profilesValidationSetting.push(profileSetting);
}
} else {
profileSetting = {
name: theProfile.name,
setting: validationSetting,
};
this.profilesValidationSetting.push(profileSetting);
}
return profileSetting;
}
/**
* Adds a new Profile to the provided treeview by clicking the 'Plus' button and
* selecting which profile you would like to add from the drop-down that appears.
* The profiles that are in the tree view already will not appear in the
* drop-down.
*
* @export
* @param {USSTree} zoweFileProvider - either the USS, MVS, JES tree
*/
public async createZoweSession(zoweFileProvider: IZoweTree<IZoweTreeNode>): Promise<void> {
ZoweLogger.trace("Profiles.createZoweSession called.");
let profileNamesList: string[] = [];
const treeType = zoweFileProvider.getTreeType();
try {
const allProfiles = Profiles.getInstance().allProfiles;
if (allProfiles) {
// Get all profiles and filter to list of the APIs available for current tree explorer
profileNamesList = allProfiles
.map((profile) => profile.name)
.filter((profileName) => {
const profile = Profiles.getInstance().loadNamedProfile(profileName);
const notInSessionNodes = !zoweFileProvider.mSessionNodes?.find(
(sessionNode) => sessionNode.getProfileName() === profileName
);
if (profile) {
if (zoweFileProvider.getTreeType() === PersistenceSchemaEnum.USS) {
const ussProfileTypes = ZoweExplorerApiRegister.getInstance().registeredUssApiTypes();
return ussProfileTypes.includes(profile.type) && notInSessionNodes;
}
if (zoweFileProvider.getTreeType() === PersistenceSchemaEnum.Dataset) {
const mvsProfileTypes = ZoweExplorerApiRegister.getInstance().registeredMvsApiTypes();
return mvsProfileTypes.includes(profile.type) && notInSessionNodes;
}
if (zoweFileProvider.getTreeType() === PersistenceSchemaEnum.Job) {
const jesProfileTypes = ZoweExplorerApiRegister.getInstance().registeredJesApiTypes();
return jesProfileTypes.includes(profile.type) && notInSessionNodes;
}
}
return false;
});
}
} catch (err) {
ZoweLogger.warn(err);
}
// Set Options according to profile management in use
const createNewProfile = "Create a New Connection to z/OS";
const createNewConfig = "Create a New Team Configuration File";
const editConfig = "Edit Team Configuration File";
const createPick = new FilterDescriptor("\uFF0B " + createNewProfile);
const configPick = new FilterDescriptor("\uFF0B " + createNewConfig);
const configEdit = new FilterDescriptor("\u270F " + editConfig);
const items: vscode.QuickPickItem[] = [];
let mProfileInfo: zowe.imperative.ProfileInfo;
try {
mProfileInfo = await this.getProfileInfo();
const profAllAttrs = mProfileInfo.getAllProfiles();
for (const pName of profileNamesList) {
const osLocInfo = mProfileInfo.getOsLocInfo(profAllAttrs.find((p) => p.profName === pName));
items.push(new FilterItem({ text: pName, icon: this.getProfileIcon(osLocInfo)[0] }));
}
} catch (err) {
ZoweLogger.warn(err);
}
const quickpick = Gui.createQuickPick();
let addProfilePlaceholder = "";
switch (zoweFileProvider.getTreeType()) {
case PersistenceSchemaEnum.Dataset:
addProfilePlaceholder = localize(
"createZoweSession.ds.quickPickOption",
'Choose "Create new..." to define or select a profile to add to the DATA SETS Explorer'
);
break;
case PersistenceSchemaEnum.Job:
addProfilePlaceholder = localize(
"createZoweSession.job.quickPickOption",
'Choose "Create new..." to define or select a profile to add to the JOBS Explorer'
);
break;
default:
// Use USS View as default for placeholder text
addProfilePlaceholder = localize(
"createZoweSession.uss.quickPickOption",
'Choose "Create new..." to define or select a profile to add to the USS Explorer'
);
}
if (mProfileInfo && mProfileInfo.usingTeamConfig) {
quickpick.items = [configPick, configEdit, ...items];
} else {
quickpick.items = [createPick, configPick, ...items];
}
quickpick.placeholder = addProfilePlaceholder;
quickpick.ignoreFocusOut = true;
quickpick.show();
const choice = await Gui.resolveQuickPick(quickpick);
quickpick.hide();
const debugMsg = localize("createZoweSession.cancelled", "Profile selection has been cancelled.");
if (!choice) {
ZoweLogger.debug(debugMsg);
Gui.showMessage(debugMsg);
return;
}
if (choice === configPick) {
await this.createZoweSchema(zoweFileProvider);
return;
}
if (choice === configEdit) {
await this.editZoweConfigFile();
return;
}
let chosenProfile: string = "";
if (choice instanceof FilterDescriptor) {
chosenProfile = "";
} else {
// remove any icons from the label
chosenProfile = choice.label.replace(/\$\(.*\)\s/g, "");
}
if (chosenProfile === "") {
let config: zowe.imperative.ProfileInfo;
try {
config = await this.getProfileInfo();
} catch (error) {
ZoweLogger.error(error);
ZoweExplorerExtender.showZoweConfigError(error.message);
}
if (config.usingTeamConfig) {
const profiles = config.getAllProfiles();
const currentProfile = await this.getProfileFromConfig(profiles[0].profName);
const filePath = currentProfile.profLoc.osLoc[0];
await this.openConfigFile(filePath);
return;
} else {
let newprofile: any;
let profileName: string;
if (quickpick.value) {
profileName = quickpick.value;
}
const options = {
placeHolder: localize("createZoweSession.connectionName.placeholder", "Connection Name"),
prompt: localize("createZoweSession.connectionName.prompt", "Enter a name for the connection"),
value: profileName,
};
profileName = await Gui.showInputBox(options);
if (!profileName) {
ZoweLogger.debug(debugMsg);
Gui.showMessage(debugMsg);
return;
}
chosenProfile = profileName.trim();
try {
newprofile = await Profiles.getInstance().createNewConnection(chosenProfile);
} catch (error) {
await errorHandling(error, chosenProfile);
}
if (newprofile) {
try {
await Profiles.getInstance().refresh(ZoweExplorerApiRegister.getInstance());
} catch (error) {
await errorHandling(error, newprofile);
}
ZoweLogger.info(localize("createZoweSession.createNewProfile", "New profile created, {0}.", chosenProfile));
await zoweFileProvider.addSession(newprofile);
await zoweFileProvider.refresh();
}
}
} else if (chosenProfile) {
ZoweLogger.info(localize("createZoweSession.addProfile", "The profile {0} has been added to the {1} tree.", chosenProfile, treeType));
await zoweFileProvider.addSession(chosenProfile);
} else {
ZoweLogger.debug(debugMsg);
}
}
public async editSession(profileLoaded: zowe.imperative.IProfileLoaded, profileName: string): Promise<any | undefined> {
ZoweLogger.trace("Profiles.editSession called.");
if ((await this.getProfileInfo()).usingTeamConfig) {
const currentProfile = await this.getProfileFromConfig(profileLoaded.name);
const filePath = currentProfile.profLoc.osLoc[0];
await this.openConfigFile(filePath);
return;
}
const editSession = this.loadNamedProfile(profileLoaded.name, profileLoaded.type).profile;
const editURL = `${editSession.host as string}:${editSession.port as string}`;
const editUser = editSession.user;
const editPass = editSession.password;
const editrej = editSession.rejectUnauthorized;
let updUser: string;
let updPass: string;
let updRU: boolean;
let updUrl: IUrlValidator | undefined;
let updPort: any;
const schema: {} = this.getSchema(profileLoaded.type);
const schemaArray = Object.keys(schema);
const updSchemaValues: {
[k: string]: any;
} = {};
updSchemaValues.name = profileName;
// Go through array of schema for input values
for (const value of schemaArray) {
switch (value) {
case "host":
updUrl = await this.urlInfo(editURL);
if (updUrl === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
updSchemaValues[value] = updUrl.host;
if (updUrl.port) {
updSchemaValues.port = updUrl.port;
}
break;
case "port":
if (updSchemaValues[value] === undefined) {
updPort = await this.portInfo(value, schema);
if (Number.isNaN(Number(updPort))) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
updSchemaValues[value] = updPort;
break;
}
break;
case "user":
updUser = await this.userInfo(editUser);
if (updUser === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
updSchemaValues[value] = updUser;
break;
case "password":
updPass = await this.passwordInfo(editPass);
if (updPass === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
updSchemaValues[value] = updPass;
break;
case "rejectUnauthorized":
updRU = await this.ruInfo(editrej);
if (updRU === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
updSchemaValues[value] = updRU;
break;
// for extenders that have their own token authentication methods with values in schema
// tokenType & tokenValue does not need to be presented to user as this is collected via login
case "tokenType":
break;
case "tokenValue":
break;
default: {
const response = this.checkType(schema[value].type);
switch (response) {
case "number": {
const updValue = await Gui.showInputBox(this.optionsValue(value, schema, editSession[value]));
if (!Number.isNaN(Number(updValue))) {
updSchemaValues[value] = Number(updValue);
} else {
switch (true) {
case updValue === undefined:
Gui.showMessage(this.profilesOpCancelled);
return undefined;
case "defaultValue" in schema[value].optionDefinition:
updSchemaValues[value] = schema[value].optionDefinition.defaultValue;
break;
default:
updSchemaValues[value] = undefined;
break;
}
}
break;
}
case "boolean": {
const updIsTrue = await this.boolInfo(value, schema);
if (updIsTrue === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
updSchemaValues[value] = updIsTrue;
break;
}
default: {
const updDefValue = await Gui.showInputBox(this.optionsValue(value, schema, editSession[value]));
if (updDefValue === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
if (updDefValue === "") {
break;
}
updSchemaValues[value] = updDefValue;
break;
}
}
}
}
}
try {
const updSession = await zowe.ZosmfSession.createSessCfgFromArgs(updSchemaValues as zowe.imperative.ICommandArguments);
updSchemaValues.base64EncodedAuth = updSession.base64EncodedAuth;
await this.updateProfile({
profile: updSchemaValues,
name: profileName,
type: profileLoaded.type,
});
Gui.showMessage(localize("editSession.success", "Profile was successfully updated"));
return updSchemaValues;
} catch (error) {
await errorHandling(error, profileName);
}
}
public async getProfileType(): Promise<string> {
ZoweLogger.trace("Profiles.getProfileType called.");
let profileType: string;
const profTypes = ZoweExplorerApiRegister.getInstance().registeredApiTypes();
const typeOptions = Array.from(profTypes);
if (typeOptions.length === 1 && typeOptions[0] === "zosmf") {
profileType = typeOptions[0];
} else {
const quickPickTypeOptions: vscode.QuickPickOptions = {
placeHolder: localize("getProfileType.qp.placeholder", "Profile Type"),
ignoreFocusOut: true,
canPickMany: false,
};
profileType = await Gui.showQuickPick(typeOptions, quickPickTypeOptions);
}
return profileType;
}
public async createZoweSchema(_zoweFileProvider: IZoweTree<IZoweTreeNode>): Promise<string> {
ZoweLogger.trace("Profiles.createZoweSchema called.");
try {
let user = false;
let global = true;
let rootPath = getZoweDir();
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders[0]) {
const choice = await this.getConfigLocationPrompt("create");
if (choice === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return;
}
if (choice === "project") {
rootPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
user = true;
global = false;
}
}
// call check for existing and prompt here
const existingFile = await this.checkExistingConfig(rootPath);
if (!existingFile) {
return;
}
if (existingFile.includes("zowe")) {
if (existingFile.includes("user")) {
user = true;
global = false;
} else {
user = false;
global = true;
}
}
const config = await zowe.imperative.Config.load("zowe", {
homeDir: getZoweDir(),
projectDir: getFullPath(rootPath),
});
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders[0]) {
config.api.layers.activate(user, global, rootPath);
}
const impConfig: zowe.imperative.IImperativeConfig = zowe.getImperativeConfig();
const knownCliConfig: zowe.imperative.ICommandProfileTypeConfiguration[] = impConfig.profiles;
// add extenders config info from global variable
globals.EXTENDER_CONFIG.forEach((item) => {
knownCliConfig.push(item);
});
knownCliConfig.push(impConfig.baseProfile);
config.setSchema(zowe.imperative.ConfigSchema.buildSchema(knownCliConfig));
// Note: IConfigBuilderOpts not exported
// const opts: IConfigBuilderOpts = {
const opts: any = {
// getSecureValue: this.promptForProp.bind(this),
populateProperties: true,
};
// Build new config and merge with existing layer
const newConfig: zowe.imperative.IConfig = await zowe.imperative.ConfigBuilder.build(impConfig, opts);
// Create non secure profile if VS Code setting is false
this.createNonSecureProfile(newConfig);
config.api.layers.merge(newConfig);
await config.save(false);
let configName;
if (user) {
configName = config.userConfigName;
} else {
configName = config.configName;
}
await this.openConfigFile(path.join(rootPath, configName));
await this.promptToRefreshForProfiles(rootPath);
return path.join(rootPath, configName);
} catch (err) {
ZoweLogger.error(err);
ZoweExplorerExtender.showZoweConfigError(err.message);
}
}
public async editZoweConfigFile(): Promise<void> {
ZoweLogger.trace("Profiles.editZoweConfigFile called.");
const existingLayers = await this.getConfigLayers();
if (existingLayers.length === 1) {
await this.openConfigFile(existingLayers[0].path);
}
if (existingLayers && existingLayers.length > 1) {
const choice = await this.getConfigLocationPrompt("edit");
switch (choice) {
case "project":
for (const file of existingLayers) {
if (file.user) {
await this.openConfigFile(file.path);
}
}
break;
case "global":
for (const file of existingLayers) {
if (file.global) {
await this.openConfigFile(file.path);
}
}
break;
default:
Gui.showMessage(this.profilesOpCancelled);
return;
}
return;
}
}
public async createNewConnection(profileName: string, requestedProfileType?: string): Promise<string | undefined> {
ZoweLogger.trace("Profiles.createNewConnection called.");
let newUser: string;
let newPass: string;
let newRU: boolean;
let newUrl: IUrlValidator | undefined;
let newPort: any;
const newProfileName = profileName.trim();
if (newProfileName === undefined || newProfileName === "") {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
const profileType = requestedProfileType ? requestedProfileType : await this.getProfileType();
if (profileType === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
const schema: {} = this.getSchema(profileType);
const schemaArray = Object.keys(schema);
const schemaValues: any = {};
schemaValues.name = newProfileName;
// Go through array of schema for input values
for (const value of schemaArray) {
switch (value) {
case "host":
newUrl = await this.urlInfo();
if (newUrl === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
schemaValues[value] = newUrl.host;
if (newUrl.port) {
schemaValues.port = newUrl.port;
}
break;
case "port":
if (schemaValues[value] === undefined) {
newPort = await this.portInfo(value, schema);
if (Number.isNaN(Number(newPort))) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
schemaValues[value] = newPort;
break;
}
break;
case "user":
newUser = await this.userInfo();
if (newUser === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
} else if (newUser === "") {
delete schemaValues[value];
} else {
schemaValues[value] = newUser;
}
break;
case "password":
newPass = await this.passwordInfo();
if (newPass === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
} else if (newPass === "") {
delete schemaValues[value];
} else {
schemaValues[value] = newPass;
}
break;
case "rejectUnauthorized":
newRU = await this.ruInfo();
if (newRU === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
schemaValues[value] = newRU;
break;
// for extenders that have their own token authentication methods with values in schema
// tokenType & tokenValue does not need to be presented to user as this is collected via login
case "tokenType":
break;
case "tokenValue":
break;
default: {
let options: vscode.InputBoxOptions;
const response = this.checkType(schema[value].type);
switch (response) {
case "number": {
options = this.optionsValue(value, schema);
const enteredValue = Number(await Gui.showInputBox(options));
if (!Number.isNaN(Number(enteredValue))) {
if ((value === "encoding" || value === "responseTimeout") && enteredValue === 0) {
delete schemaValues[value];
} else {
schemaValues[value] = Number(enteredValue);
}
} else {
if ("defaultValue" in schema[value].optionDefinition) {
schemaValues[value] = schema[value].optionDefinition.defaultValue;
} else {
delete schemaValues[value];
}
}
break;
}
case "boolean": {
const isTrue = await this.boolInfo(value, schema);
if (isTrue === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
schemaValues[value] = isTrue;
break;
}
default: {
options = this.optionsValue(value, schema);
const defValue = await Gui.showInputBox(options);
if (defValue === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return undefined;
}
if (defValue === "") {
delete schemaValues[value];
} else {
schemaValues[value] = defValue;
}
break;
}
}
}
}
}
try {
for (const profile of this.allProfiles) {
if (profile.name.toLowerCase() === profileName.toLowerCase()) {
Gui.errorMessage(
localize(
"createNewConnection.duplicateProfileName",
"Profile name already exists. Please create a profile using a different name"
)
);
return undefined;
}
}
await this.saveProfile(schemaValues, schemaValues.name, profileType);
Gui.showMessage(localize("createNewConnection.success", "Profile {0} was created.", newProfileName));
// Trigger a ProfilesCache.createConfigInstance with a fresh Config.load
// This shall capture any profiles created (v1 or v2)
await readConfigFromDisk();
return newProfileName;
} catch (error) {
await errorHandling(error, profileName);
ZoweExplorerExtender.showZoweConfigError(error.message);
}
}
public async promptCredentials(profile: string | zowe.imperative.IProfileLoaded, rePrompt?: boolean): Promise<string[]> {
const userInputBoxOptions: vscode.InputBoxOptions = {
placeHolder: localize("promptCredentials.userInputBoxOptions.placeholder", "User Name"),
prompt: localize("promptCredentials.userInputBoxOptions.prompt", "Enter the user name for the connection. Leave blank to not store."),
};
const passwordInputBoxOptions: vscode.InputBoxOptions = {
placeHolder: localize("promptCredentials.passwordInputBoxOptions.placeholder", "Password"),
prompt: localize("promptCredentials.passwordInputBoxOptions.prompt", "Enter the password for the connection. Leave blank to not store."),
};
const promptInfo = await ZoweVsCodeExtension.updateCredentials(
{
sessionName: typeof profile !== "string" ? profile.name : profile,
sessionType: typeof profile !== "string" ? profile.type : undefined,
rePrompt,
secure: (await this.getProfileInfo()).isSecured(),
userInputBoxOptions,
passwordInputBoxOptions,
},
ZoweExplorerApiRegister.getInstance()
);
if (!promptInfo) {
Gui.showMessage(this.profilesOpCancelled);
return; // See https://github.com/zowe/vscode-extension-for-zowe/issues/1827
}
const updSession = promptInfo.profile as zowe.imperative.ISession;
const returnValue = [updSession.user, updSession.password, updSession.base64EncodedAuth];
this.updateProfilesArrays(promptInfo);
return returnValue;
}
public async getDeleteProfile(): Promise<zowe.imperative.IProfileLoaded> {
ZoweLogger.trace("Profiles.getDeleteProfile called.");
const allProfiles: zowe.imperative.IProfileLoaded[] = this.allProfiles;
const profileNamesList = allProfiles.map((temprofile) => {
return temprofile.name;
});
if (!profileNamesList.length) {
Gui.showMessage(localize("getDeleteProfile.noProfiles", "No profiles available"));
return;
}
const quickPickList: vscode.QuickPickOptions = {
placeHolder: localize("getDeleteProfile.qp.placeholder", "Select the profile you want to delete"),
ignoreFocusOut: true,
canPickMany: false,
};
const sesName = await Gui.showQuickPick(profileNamesList, quickPickList);
if (sesName === undefined) {
Gui.showMessage(this.profilesOpCancelled);
return;
}
return allProfiles.find((temprofile) => temprofile.name === sesName);
}
public async deleteProfile(
datasetTree: IZoweTree<IZoweDatasetTreeNode>,
ussTree: IZoweTree<IZoweUSSTreeNode>,
jobsProvider: IZoweTree<IZoweJobTreeNode>,
node?: IZoweNodeType
): Promise<void> {
ZoweLogger.trace("Profiles.deleteProfile called.");
let deletedProfile: zowe.imperative.IProfileLoaded;
if (!node) {
deletedProfile = await this.getDeleteProfile();
} else {
deletedProfile = node.getProfile();
}
if (!deletedProfile) {
return;
}
const deleteLabel = deletedProfile.name;
if ((await this.getProfileInfo()).usingTeamConfig) {
const currentProfile = await this.getProfileFromConfig(deleteLabel);
const filePath = currentProfile.profLoc.osLoc[0];
await this.openConfigFile(filePath);
return;
}
const deleteSuccess = await this.deletePrompt(deletedProfile);
if (!deleteSuccess) {
Gui.showMessage(this.profilesOpCancelled);
return;
}
// Delete from data det file history
const fileHistory: string[] = datasetTree.getFileHistory();
fileHistory
.slice()
.reverse()
.filter((ds) => ds.substring(1, ds.indexOf("]")).trim() === deleteLabel.toUpperCase())
.forEach((ds) => {
datasetTree.removeFileHistory(ds);
});
// Delete from Data Set Favorites
datasetTree.removeFavProfile(deleteLabel, false);
// Delete from Data Set Tree
datasetTree.mSessionNodes.forEach((sessNode) => {
if (sessNode.getProfileName() === deleteLabel) {
datasetTree.deleteSession(sessNode);
sessNode.dirty = true;
datasetTree.refresh();
}
});
// Delete from USS file history
const fileHistoryUSS: string[] = ussTree.getFileHistory();
fileHistoryUSS
.slice()
.reverse()
.filter((uss) => uss.substring(1, uss.indexOf("]")).trim() === deleteLabel.toUpperCase())
.forEach((uss) => {
ussTree.removeFileHistory(uss);
});
// Delete from USS Favorites
ussTree.removeFavProfile(deleteLabel, false);
// Delete from USS Tree
ussTree.mSessionNodes.forEach((sessNode) => {
if (sessNode.getProfileName() === deleteLabel) {
ussTree.deleteSession(sessNode);
sessNode.dirty = true;
ussTree.refresh();
}
});
// Delete from Jobs Favorites
jobsProvider.removeFavProfile(deleteLabel, false);