Skip to content

Commit

Permalink
Task: Use a temporary folder (#5299)
Browse files Browse the repository at this point in the history
  • Loading branch information
thewahome authored Sep 3, 2024
1 parent 91bc171 commit ba708a6
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 44 deletions.
19 changes: 9 additions & 10 deletions vscode/microsoft-kiota/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,9 @@ export async function activate(

let languagesInformation = await getLanguageInformation(context);
let availableStateInfo: Partial<GenerateState>;
if(Object.keys(deepLinkParams).length > 0){
if (!deepLinkParams["name"] && openApiTreeProvider.apiTitle ){
deepLinkParams["name"] = getSanitizedString(openApiTreeProvider.apiTitle);
if (Object.keys(deepLinkParams).length > 0) {
if (!deepLinkParams.name && openApiTreeProvider.apiTitle) {
deepLinkParams.name = getSanitizedString(openApiTreeProvider.apiTitle);
}
availableStateInfo = transformToGenerationconfig(deepLinkParams);
} else {
Expand Down Expand Up @@ -212,8 +212,7 @@ export async function activate(
'fx-extension.createprojectfromkiota',
[
pathOfSpec,
pathPluginManifest,
true
pathPluginManifest
]
);
} catch (error) {
Expand Down Expand Up @@ -248,12 +247,12 @@ export async function activate(
) => {
// set deeplink params if exists
if (Object.keys(searchParams).length > 0) {
let errorsArray: string [];
let errorsArray: string[];
[deepLinkParams, errorsArray] = validateDeepLinkQueryParams(searchParams);
reporter.sendTelemetryEvent("DeepLinked searchOrOpenApiDescription", {
"searchParameters": JSON.stringify(searchParams),
"validationErrors": errorsArray.join(", ")
});
reporter.sendTelemetryEvent("DeepLinked searchOrOpenApiDescription", {
"searchParameters": JSON.stringify(searchParams),
"validationErrors": errorsArray.join(", ")
});
}

// proceed to enable loading of openapi description
Expand Down
69 changes: 35 additions & 34 deletions vscode/microsoft-kiota/src/steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as vscode from 'vscode';
import { Disposable, l10n, OpenDialogOptions, QuickInput, QuickInputButton, QuickInputButtons, QuickPickItem, Uri, window, workspace } from 'vscode';
import { allGenerationLanguages, generationLanguageToString, KiotaSearchResultItem, LanguagesInformation, maturityLevelToString } from './kiotaInterop';
import { findAppPackageDirectory, getWorkspaceJsonDirectory } from './util';
import { createTemporaryFolder, isTemporaryDirectory } from './utilities/temporary-folder';

export async function filterSteps(existingFilter: string, filterCallback: (searchQuery: string) => void) {
const state = {} as Partial<BaseStepsState>;
Expand Down Expand Up @@ -116,37 +117,37 @@ export async function searchSteps(searchCallBack: (searchQuery: string) => Thena
return state;
}

export function transformToGenerationconfig(deepLinkParams: Record<string, string|undefined>)
: Partial<GenerateState>
{
export function transformToGenerationconfig(deepLinkParams: Record<string, string | undefined>)
: Partial<GenerateState> {
const generationConfig: Partial<GenerateState> = {};
if (deepLinkParams.kind === "client")
{
generationConfig["generationType"] = "client";
generationConfig["clientClassName"] = deepLinkParams.name;
generationConfig["language"] = deepLinkParams.language;
if (deepLinkParams.kind === "client") {
generationConfig.generationType = "client";
generationConfig.clientClassName = deepLinkParams.name;
generationConfig.language = deepLinkParams.language;
}
else if (deepLinkParams.kind === "plugin")
{
generationConfig["pluginName"] = deepLinkParams.name;
switch(deepLinkParams.type){
else if (deepLinkParams.kind === "plugin") {
generationConfig.pluginName = deepLinkParams.name;
switch (deepLinkParams.type) {
case "apiplugin":
generationConfig["generationType"] = "plugin";
generationConfig["pluginTypes"] = ["ApiPlugin"];
generationConfig.generationType = "plugin";
generationConfig.pluginTypes = ["ApiPlugin"];
break;
case "openai":
generationConfig["generationType"] = "plugin";
generationConfig["pluginTypes"] = ['OpenAI'];
generationConfig.generationType = "plugin";
generationConfig.pluginTypes = ['OpenAI'];
break;
case "apimanifest":
generationConfig["generationType"] = "apimanifest";
generationConfig.generationType = "apimanifest";
break;
}
}
generationConfig.outputPath =
(deepLinkParams.source && deepLinkParams.source?.toLowerCase() === 'ttk')
? createTemporaryFolder()
: undefined;
}
return generationConfig;
}


export async function generateSteps(existingConfiguration: Partial<GenerateState>, languagesInformation?: LanguagesInformation) {
const state = { ...existingConfiguration } as Partial<GenerateState>;
if (existingConfiguration.generationType && existingConfiguration.clientClassName && existingConfiguration.clientNamespaceName && existingConfiguration.outputPath && existingConfiguration.language &&
Expand All @@ -155,7 +156,7 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
return state;
}

if (typeof state.outputPath === 'string') {
if (typeof state.outputPath === 'string' && !isTemporaryDirectory(state.outputPath)) {
state.outputPath = workspace.asRelativePath(state.outputPath);
}
const workspaceOpen = vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0;
Expand Down Expand Up @@ -184,8 +185,8 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
];
}
}
function getNextStepForGenerationType(generationType: string|QuickPickItem) {
switch(generationType) {
function getNextStepForGenerationType(generationType: string | QuickPickItem) {
switch (generationType) {
case 'client':
return inputClientClassName;
case 'plugin':
Expand All @@ -197,30 +198,30 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
}
}
async function inputGenerationType(input: MultiStepInput, state: Partial<GenerateState>) {
if (!state.generationType){
if (!state.generationType) {
const items = [l10n.t('Generate an API client'), l10n.t('Generate a plugin'), l10n.t('Generate an API manifest')];
const option = await input.showQuickPick({
title: l10n.t('What do you want to generate?'),
step: 1,
totalSteps: 1,
placeholder: l10n.t('Select an option'),
items: items.map(x => ({label: x})),
items: items.map(x => ({ label: x })),
validate: validateIsNotEmpty,
shouldResume: shouldResume
});
if(option.label === l10n.t('Generate an API client')) {
if (option.label === l10n.t('Generate an API client')) {
state.generationType = "client";
}
else if(option.label === l10n.t('Generate a plugin')) {
else if (option.label === l10n.t('Generate a plugin')) {
state.generationType = "plugin";
}
else if(option.label === l10n.t('Generate an API manifest')) {
else if (option.label === l10n.t('Generate an API manifest')) {
state.generationType = "apimanifest";
}
}
let nextStep = getNextStepForGenerationType(state.generationType?.toString() || '');
return (input: MultiStepInput) => nextStep(input, state);
}
}
async function inputClientClassName(input: MultiStepInput, state: Partial<GenerateState>) {
if (!state.clientClassName) {
state.clientClassName = await input.showInputBox({
Expand Down Expand Up @@ -312,7 +313,7 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
}
}
async function inputPluginName(input: MultiStepInput, state: Partial<GenerateState>) {
if (!state.pluginName){
if (!state.pluginName) {
state.pluginName = await input.showInputBox({
title: `${l10n.t('Create a new plugin')} - ${l10n.t('plugin name')}`,
step: step++,
Expand All @@ -325,11 +326,11 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
});
}
updateWorkspaceFolder(state.pluginName);
return (input: MultiStepInput) => inputPluginType(input, state);
}
return (input: MultiStepInput) => inputPluginType(input, state);
}
async function inputPluginType(input: MultiStepInput, state: Partial<GenerateState>) {
if (!state.pluginTypes) {
const items = ['API Plugin','Open AI'].map(x => ({ label: x})as QuickPickItem);
const items = ['API Plugin', 'Open AI'].map(x => ({ label: x }) as QuickPickItem);
const pluginTypes = await input.showQuickPick({
title: l10n.t('Choose a plugin type'),
step: step++,
Expand All @@ -344,7 +345,7 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
return (input: MultiStepInput) => inputPluginOutputPath(input, state);
}
async function inputPluginOutputPath(input: MultiStepInput, state: Partial<GenerateState>) {
while (true) {
while (!state.outputPath) {
const selectedOption = await input.showQuickPick({
title: `${l10n.t('Create a new plugin')} - ${l10n.t('output directory')}`,
step: 3,
Expand Down Expand Up @@ -382,7 +383,7 @@ export async function generateSteps(existingConfiguration: Partial<GenerateState
}

async function inputManifestName(input: MultiStepInput, state: Partial<GenerateState>) {
if (!state.pluginName){
if (!state.pluginName) {
state.pluginName = await input.showInputBox({
title: `${l10n.t('Create a new manifest')} - ${l10n.t('manifest name')}`,
step: step++,
Expand Down
33 changes: 33 additions & 0 deletions vscode/microsoft-kiota/src/utilities/temporary-folder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

export function createTemporaryFolder(): string | undefined {
const uniqueFolderIdentifier = `kiota-${Date.now()}`;
const temporaryDirectory = os.tmpdir();
const temporaryDirectoryPath = path.join(temporaryDirectory, uniqueFolderIdentifier);

try {
createFolderInFileSystem(temporaryDirectoryPath);
return path.resolve(temporaryDirectoryPath);
} catch (error) {
return undefined;
}
}

function createFolderInFileSystem(directoryPath: string) {
const exists = fs.existsSync(directoryPath);
if (exists) {
return createTemporaryFolder();
}

try {
fs.mkdirSync(directoryPath);
} catch (err: unknown) {
throw new Error(`Error creating temporary directory: ${(err as Error).message}`);
}
}

export function isTemporaryDirectory(path: string): boolean {
return path.startsWith(os.tmpdir());
}

0 comments on commit ba708a6

Please sign in to comment.