Skip to content

Rewrite cpUtils and show some examples of how to use it #4620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1486,7 +1486,8 @@
"@microsoft/vscode-azext-azureutils": "^3.4.0",
"@microsoft/vscode-azext-utils": "^3.2.0",
"@microsoft/vscode-azureresources-api": "^2.0.4",
"@microsoft/vscode-container-client": "^0.1.2",
"@microsoft/vscode-container-client": "^0.4.1",
"@microsoft/vscode-processutils": "^0.1.1",
"cross-fetch": "^4.0.0",
"escape-string-regexp": "^4.0.0",
"extract-zip": "^2.0.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { type IActionContext } from '@microsoft/vscode-azext-utils';
import { composeArgs, withArg } from '@microsoft/vscode-processutils';
import * as path from 'path';
import { type Uri } from "vscode";
import { ext } from '../../../extensionVariables';
Expand All @@ -15,5 +16,5 @@ export async function decryptLocalSettings(context: IActionContext, uri?: Uri):
const message: string = localize('selectLocalSettings', 'Select the settings file to decrypt.');
const localSettingsPath: string = uri ? uri.fsPath : await getLocalSettingsFile(context, message);
ext.outputChannel.show(true);
await cpUtils.executeCommand(ext.outputChannel, path.dirname(localSettingsPath), 'func', 'settings', 'decrypt');
await cpUtils.executeCommand(ext.outputChannel, path.dirname(localSettingsPath), 'func', composeArgs(withArg('settings', 'decrypt'))());
}
48 changes: 32 additions & 16 deletions src/commands/createFunction/openAPISteps/OpenAPICreateStep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { AzureWizardExecuteStep, DialogResponses, type IActionContext } from '@microsoft/vscode-azext-utils';
import { composeArgs, withArg, type CommandLineCurryFn } from '@microsoft/vscode-processutils';
import * as path from 'path';
import { ProgressLocation, window, type Uri } from "vscode";
import { ProjectLanguage, packageJsonFileName } from "../../../constants";
Expand All @@ -28,41 +29,56 @@
public async execute(wizardContext: IFunctionWizardContext & IJavaProjectWizardContext & IDotnetFunctionWizardContext): Promise<void> {
const uris: Uri[] = nonNullProp(wizardContext, 'openApiSpecificationFile');
const uri: Uri = uris[0];
const args: string[] = [];

args.push(`--input-file:${cpUtils.wrapArgInQuotes(uri.fsPath)}`);
args.push(`--version:3.0.6320`);
// TODO: Need to work on this...we don't have a good answer for quoting things that are only a substring of a single argument
const generalArgsCurryFn = composeArgs(
withArg(`--input-file:${cpUtils.wrapArgInQuotes(uri.fsPath)}`), // TODO

Check failure on line 35 in src/commands/createFunction/openAPISteps/OpenAPICreateStep.ts

View workflow job for this annotation

GitHub Actions / Build / Build

Unsafe call of an `any` typed value
withArg(`--version:3.0.6320`),
);

let langArgsCurryFn: CommandLineCurryFn;
switch (wizardContext.language) {
case ProjectLanguage.TypeScript:
args.push('--azure-functions-typescript');
args.push('--no-namespace-folders:True');
langArgsCurryFn = composeArgs(
withArg('--azure-functions-typescript'),
withArg('--no-namespace-folders:True'),
);
break;
case ProjectLanguage.CSharp:
args.push(`--namespace:${nonNullProp(wizardContext, 'namespace')}`);
args.push('--azure-functions-csharp');
langArgsCurryFn = composeArgs(
withArg(`--namespace:${nonNullProp(wizardContext, 'namespace')}`),
withArg('--azure-functions-csharp'),
);
break;
case ProjectLanguage.Java:
args.push(`--namespace:${nonNullProp(wizardContext, 'javaPackageName')}`);
args.push('--azure-functions-java');
langArgsCurryFn = composeArgs(
withArg(`--namespace:${nonNullProp(wizardContext, 'javaPackageName')}`),
withArg('--azure-functions-java'),
);
break;
case ProjectLanguage.Python:
args.push('--azure-functions-python');
args.push('--no-namespace-folders:True');
args.push('--no-async');
langArgsCurryFn = composeArgs(
withArg('--azure-functions-python'),
withArg('--no-namespace-folders:True'),
withArg('--no-async'),
);
break;
default:
throw new Error(localize('notSupported', 'Not a supported language. We currently support C#, Java, Python, and Typescript'));
}

args.push('--generate-metadata:false');
args.push(`--output-folder:${cpUtils.wrapArgInQuotes(wizardContext.projectPath)}`);
const args = composeArgs(
generalArgsCurryFn,
langArgsCurryFn,
withArg('--generate-metadata:false'),
withArg(`--output-folder:${cpUtils.wrapArgInQuotes(wizardContext.projectPath)}`), // TODO

Check failure on line 74 in src/commands/createFunction/openAPISteps/OpenAPICreateStep.ts

View workflow job for this annotation

GitHub Actions / Build / Build

Unsafe call of an `any` typed value
)();

ext.outputChannel.appendLog(localize('statutoryWarning', 'Using the plugin could overwrite your custom changes to the functions.\nIf autorest fails, you can run the script on your command-line, or try resetting autorest (autorest --reset) and try again.'));
const title: string = localize('generatingFunctions', 'Generating from OpenAPI...Check [output window](command:{0}) for status.', ext.prefix + '.showOutputChannel');

await window.withProgress({ location: ProgressLocation.Notification, title }, async () => {
await cpUtils.executeCommand(ext.outputChannel, undefined, 'autorest', ...args);
await cpUtils.executeCommand(ext.outputChannel, undefined, 'autorest', args);
});

if (wizardContext.language === ProjectLanguage.TypeScript) {
Expand All @@ -78,7 +94,7 @@

async function validateAutorestInstalled(context: IActionContext): Promise<void> {
try {
await cpUtils.executeCommand(undefined, undefined, 'autorest', '--version');
await cpUtils.executeCommand(undefined, undefined, 'autorest', composeArgs(withArg('--version'))());
} catch (error) {
const message: string = localize('autorestNotFound', 'Failed to find "autorest" | Extension needs AutoRest to generate a function app from an OpenAPI specification. Click "Learn more" for more details on installation steps.');
if (!context.errorHandling.suppressDisplay) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { AzExtFsExtra, DialogResponses, nonNullValueAndProp, type IActionContext } from '@microsoft/vscode-azext-utils';
import { composeArgs, withArg, withNamedArg } from '@microsoft/vscode-processutils';
import * as path from 'path';
import { getMajorVersion, type FuncVersion } from '../../../FuncVersion';
import { ConnectionKey, ProjectLanguage, gitignoreFileName, hostFileName, localSettingsFileName } from '../../../constants';
Expand Down Expand Up @@ -38,9 +39,13 @@ export class DotnetProjectCreateStep extends ProjectCreateStepBase {
// currentely the version created by func init is behind the template version
if (context.containerizedProject) {
const runtime = context.workerRuntime?.capabilities.includes('isolated') ? 'dotnet-isolated' : 'dotnet';
// targetFramework is only supported for dotnet-isolated projects
const targetFramework = runtime === 'dotnet' ? '' : "--target-framework " + nonNullValueAndProp(context.workerRuntime, 'targetFramework');
await cpUtils.executeCommand(ext.outputChannel, context.projectPath, "func", "init", "--worker-runtime", runtime, targetFramework, "--docker");
const args = composeArgs(
withArg('init'),
withNamedArg('--worker-runtime', runtime),
withNamedArg('--target-framework', runtime === 'dotnet' ? undefined : nonNullValueAndProp(context.workerRuntime, 'targetFramework')), // targetFramework is only supported for dotnet-isolated projects // TODO: validate this is doing what I think it's doing
withArg('--docker'),
)();
await cpUtils.executeCommand(ext.outputChannel, context.projectPath, "func", args);
} else {
await this.confirmOverwriteExisting(context, projName);
}
Expand All @@ -52,11 +57,15 @@ export class DotnetProjectCreateStep extends ProjectCreateStepBase {
}
const functionsVersion: string = 'v' + majorVersion;
const projTemplateKey = nonNullProp(context, 'projectTemplateKey');
const args = ['--identity', identity, '--arg:name', cpUtils.wrapArgInQuotes(projectName), '--arg:AzureFunctionsVersion', functionsVersion];
// defaults to net6.0 if there is no targetFramework
args.push('--arg:Framework', cpUtils.wrapArgInQuotes(context.workerRuntime?.targetFramework));

await executeDotnetTemplateCommand(context, version, projTemplateKey, context.projectPath, 'create', ...args);
const args = composeArgs(
withNamedArg('--identity', identity),
withNamedArg('--arg:name', projectName, { shouldQuote: true }),
withNamedArg('--arg:AzureFunctionsVersion', functionsVersion),
withNamedArg('--arg:Framework', context.workerRuntime?.targetFramework, { shouldQuote: true }), // defaults to net6.0 if there is no targetFramework
)();

await executeDotnetTemplateCommand(context, version, projTemplateKey, context.projectPath, 'create', args);

await setLocalAppSetting(context, context.projectPath, ConnectionKey.Storage, '', MismatchBehavior.Overwrite);
}
Expand Down
24 changes: 13 additions & 11 deletions src/templates/dotnet/executeDotnetTemplateCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,29 @@
*--------------------------------------------------------------------------------------------*/

import { type IActionContext } from '@microsoft/vscode-azext-utils';
import { composeArgs, withArg, withNamedArg, withQuotedArg, type CommandLineArgs } from '@microsoft/vscode-processutils';
import * as path from 'path';
import { coerce as semVerCoerce, type SemVer } from 'semver';
import { type FuncVersion } from '../../FuncVersion';
import { ext } from "../../extensionVariables";
import { localize } from '../../localize';
import { cpUtils } from "../../utils/cpUtils";

export async function executeDotnetTemplateCommand(context: IActionContext, version: FuncVersion, projTemplateKey: string, workingDirectory: string | undefined, operation: 'list' | 'create', ...args: string[]): Promise<string> {
export async function executeDotnetTemplateCommand(context: IActionContext, version: FuncVersion, projTemplateKey: string, workingDirectory: string | undefined, operation: 'list' | 'create', additionalArgs?: CommandLineArgs): Promise<string> {
const jsonDllPath: string = ext.context.asAbsolutePath(path.join('resources', 'dotnetJsonCli', 'Microsoft.TemplateEngine.JsonCli.dll'));

const args = composeArgs(
withNamedArg('--roll-forward', 'Major'),
withQuotedArg(jsonDllPath),
withNamedArg('--templateDir', getDotnetTemplateDir(context, version, projTemplateKey), { shouldQuote: true }),
withNamedArg('--operation', operation),
withArg(...(additionalArgs ?? [])),
)();
return await cpUtils.executeCommand(
undefined,
workingDirectory,
'dotnet',
'--roll-forward',
'Major',
cpUtils.wrapArgInQuotes(jsonDllPath),
'--templateDir',
cpUtils.wrapArgInQuotes(getDotnetTemplateDir(context, version, projTemplateKey)),
'--operation',
operation,
...args);
args);
}

export function getDotnetItemTemplatePath(context: IActionContext, version: FuncVersion, projTemplateKey: string): string {
Expand All @@ -50,13 +52,13 @@ async function getFramework(context: IActionContext, workingDirectory: string |
if (!cachedFramework) {
let versions: string = '';
try {
versions += await cpUtils.executeCommand(undefined, workingDirectory, 'dotnet', '--version');
versions += await cpUtils.executeCommand(undefined, workingDirectory, 'dotnet', composeArgs(withArg('--version'))());
} catch {
// ignore
}

try {
versions += await cpUtils.executeCommand(undefined, workingDirectory, 'dotnet', '--list-sdks');
versions += await cpUtils.executeCommand(undefined, workingDirectory, 'dotnet', composeArgs(withArg('--list-sdks'))());
} catch {
// ignore
}
Expand Down
Loading
Loading