Skip to content

Instantly share code, notes, and snippets.

@t1m0thyj
Last active May 11, 2022 10:58
Show Gist options
  • Save t1m0thyj/0e34ab16be875669a2b3ca273724bc5e to your computer and use it in GitHub Desktop.
Save t1m0thyj/0e34ab16be875669a2b3ca273724bc5e to your computer and use it in GitHub Desktop.
Example of how to load default Zowe CLI profile in VS Code extension
import { IProfArgAttrs, IProfile, ProfileInfo } from "@zowe/imperative";
import { trueCasePathSync } from "true-case-path";
import { window, workspace } from "vscode";
/**
* Load properties for the default Zowe CLI profile of a given type.
* @param profileType The type of profile (e.g., "zosmf")
* @returns Profile object with property names and values defined
*/
async function getDefaultProfile(profileType: string): Promise<IProfile> {
const profInfo = new ProfileInfo("zowe", {
// Require Keytar which is a dependency for loading secure credentials from OS vault.
// See https://code.visualstudio.com/api/advanced-topics/remote-extensions#persisting-secrets
// for the `getNodeModule` code which loads the Keytar module bundled with VS Code.
requireKeytar: () => getNodeModule("keytar")
});
// Find the root path of the active VS Code workspace and look for team config there.
// On Windows, the drive casing must be fixed to normalize the path.
const rootPath = workspace.workspaceFolders[0].uri.fsPath;
await profInfo.readProfilesFromDisk({ projectDir: trueCasePathSync(rootPath) });
const profAttrs = profInfo.getDefaultProfile(profileType);
const profile: IProfile = {};
if (profAttrs != null) { // Default profile exists
const mergedArgs = profInfo.mergeArgsForProfile(profAttrs);
for (const arg of mergedArgs.knownArgs) {
profile[arg.argName] = arg.secure ? profInfo.loadSecureArg(arg) : arg.argValue;
}
} else { // Default profile does not exist
const mergedArgs = profInfo.mergeArgsForProfileType(profileType);
const promptForValue = async (arg: IProfArgAttrs) => {
let response: string;
switch (arg.dataType) {
case "string":
case "number":
// Show an input box in VS Code to prompt the user for a string or number
response = await window.showInputBox({
prompt: `Enter a ${arg.dataType} value for "${arg.argName}"`,
value: arg.argValue?.toString(),
password: arg.secure
});
if (response != null) {
profile[arg.argName] = (arg.dataType === "number") ? parseInt(response, 10) : response;
}
case "boolean":
// Show a "quick pick" in VS Code to prompt the user for a boolean value
response = await window.showQuickPick(arg.argValue ? ["True", "False"] : ["False", "True"], {
placeHolder: `Select a boolean value for "${arg.argName}"`
});
if (response != null) {
profile[arg.argName] = response === "True";
}
}
};
for (const arg of mergedArgs.missingArgs) {
await promptForValue(arg);
}
}
return profile;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment