|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the Source EULA. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | +import * as os from 'os'; |
| 6 | +import * as fs from 'fs'; |
| 7 | +import * as path from 'path'; |
| 8 | +import * as vscode from 'vscode'; |
| 9 | +import * as constants from '../constants/constants'; |
| 10 | +import * as LocalizedConstants from '../constants/localizedConstants'; |
| 11 | +// https://github.com/microsoft/vscode-azurefunctions/blob/main/src/vscode-azurefunctions.api.d.ts |
| 12 | +import { AzureFunctionsExtensionApi } from '../../typings/vscode-azurefunctions.api'; |
| 13 | +// https://github.com/microsoft/vscode-azuretools/blob/main/ui/api.d.ts |
| 14 | +import { AzureExtensionApiProvider } from '../../typings/vscode-azuretools.api'; |
| 15 | +import { executeCommand } from '../utils/utils'; |
| 16 | + |
| 17 | +/** |
| 18 | + * Represents the settings in an Azure function project's local.settings.json file |
| 19 | + */ |
| 20 | +export interface ILocalSettingsJson { |
| 21 | + IsEncrypted?: boolean; |
| 22 | + Values?: { [key: string]: string }; |
| 23 | + Host?: { [key: string]: string }; |
| 24 | + ConnectionStrings?: { [key: string]: string }; |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * copied and modified from vscode-azurefunctions extension |
| 29 | + * https://github.com/microsoft/vscode-azurefunctions/blob/main/src/funcConfig/local.settings.ts |
| 30 | + * @param localSettingsPath full path to local.settings.json |
| 31 | + * @returns settings in local.settings.json. If no settings are found, returns default "empty" settings |
| 32 | + */ |
| 33 | +export async function getLocalSettingsJson(localSettingsPath: string): Promise<ILocalSettingsJson> { |
| 34 | + if (await fs.existsSync(localSettingsPath)) { |
| 35 | + const data: string = (fs.readFileSync(localSettingsPath)).toString(); |
| 36 | + try { |
| 37 | + return JSON.parse(data); |
| 38 | + } catch (error) { |
| 39 | + console.log(error); |
| 40 | + throw new Error(constants.failedToParse(error.message)); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return { |
| 45 | + IsEncrypted: false // Include this by default otherwise the func cli assumes settings are encrypted and fails to run |
| 46 | + }; |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Adds a new setting to a project's local.settings.json file |
| 51 | + * modified from setLocalAppSetting code from vscode-azurefunctions extension |
| 52 | + * @param projectFolder full path to project folder |
| 53 | + * @param key Key of the new setting |
| 54 | + * @param value Value of the new setting |
| 55 | + * @returns true if successful adding the new setting, false if unsuccessful |
| 56 | + */ |
| 57 | +export async function setLocalAppSetting(projectFolder: string, key: string, value: string): Promise<boolean> { |
| 58 | + const localSettingsPath: string = path.join(projectFolder, constants.azureFunctionLocalSettingsFileName); |
| 59 | + const settings: ILocalSettingsJson = await getLocalSettingsJson(localSettingsPath); |
| 60 | + |
| 61 | + settings.Values = settings.Values || {}; |
| 62 | + if (settings.Values[key] === value) { |
| 63 | + // don't do anything if it's the same as the existing value |
| 64 | + return true; |
| 65 | + } else if (settings.Values[key]) { |
| 66 | + const result = await vscode.window.showWarningMessage(constants.settingAlreadyExists(key), { modal: true }, constants.yesString); |
| 67 | + if (result !== constants.yesString) { |
| 68 | + // key already exists and user doesn't want to overwrite it |
| 69 | + return false; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + settings.Values[key] = value; |
| 74 | + fs.promises.writeFile(localSettingsPath, JSON.stringify(settings, undefined, 2)); |
| 75 | + |
| 76 | + return true; |
| 77 | +} |
| 78 | + |
| 79 | +export async function getAzureFunctionsExtensionApi(): Promise<AzureFunctionsExtensionApi | undefined> { |
| 80 | + const apiProvider = await vscode.extensions.getExtension(constants.azureFunctionsExtensionName)?.activate() as AzureExtensionApiProvider; |
| 81 | + const azureFunctionApi = apiProvider.getApi<AzureFunctionsExtensionApi>('*'); |
| 82 | + if (azureFunctionApi) { |
| 83 | + return azureFunctionApi; |
| 84 | + } else { |
| 85 | + vscode.window.showErrorMessage(LocalizedConstants.azureFunctionsExtensionNotInstalled); |
| 86 | + return undefined; |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * Overwrites the Azure function methods body to work with the binding |
| 92 | + * @param filePath is the path for the function file (.cs for C# functions) |
| 93 | + */ |
| 94 | +export function overwriteAzureFunctionMethodBody(filePath: string): void { |
| 95 | + let defaultBindedFunctionText = fs.readFileSync(filePath, 'utf-8'); |
| 96 | + // Replace default binding text |
| 97 | + let newValueLines = defaultBindedFunctionText.split(os.EOL); |
| 98 | + const defaultFunctionTextToSkip = new Set(constants.defaultSqlBindingTextLines); |
| 99 | + let replacedValueLines = []; |
| 100 | + for (let defaultLine of newValueLines) { |
| 101 | + // Skipped lines |
| 102 | + if (defaultFunctionTextToSkip.has(defaultLine.trimStart())) { |
| 103 | + continue; |
| 104 | + } else if (defaultLine.trimStart() === constants.defaultBindingResult) { // Result change |
| 105 | + replacedValueLines.push(defaultLine.replace(constants.defaultBindingResult, constants.sqlBindingResult)); |
| 106 | + } else { |
| 107 | + // Normal lines to be included |
| 108 | + replacedValueLines.push(defaultLine); |
| 109 | + } |
| 110 | + } |
| 111 | + defaultBindedFunctionText = replacedValueLines.join(os.EOL); |
| 112 | + fs.writeFileSync(filePath, defaultBindedFunctionText, 'utf-8'); |
| 113 | +} |
| 114 | + |
| 115 | +/** |
| 116 | + * Gets the azure function project for the user to choose from a list of projects files |
| 117 | + * If only one project is found that project is used to add the binding to |
| 118 | + * if no project is found, user is informed there needs to be a C# Azure Functions project |
| 119 | + * @returns the selected project file path |
| 120 | + */ |
| 121 | +export async function getAzureFunctionProject(): Promise<string | undefined> { |
| 122 | + let selectedProjectFile: string | undefined = ''; |
| 123 | + if (vscode.workspace.workspaceFolders === undefined || vscode.workspace.workspaceFolders.length === 0) { |
| 124 | + return selectedProjectFile; |
| 125 | + } else { |
| 126 | + const projectFiles = await getAzureFunctionProjectFiles(); |
| 127 | + if (projectFiles !== undefined) { |
| 128 | + if (projectFiles.length > 1) { |
| 129 | + // select project to add azure function to |
| 130 | + selectedProjectFile = (await vscode.window.showQuickPick(projectFiles, { |
| 131 | + canPickMany: false, |
| 132 | + title: constants.selectProject, |
| 133 | + ignoreFocusOut: true |
| 134 | + })); |
| 135 | + return selectedProjectFile; |
| 136 | + } else if (projectFiles.length === 1) { |
| 137 | + // only one azure function project found |
| 138 | + return projectFiles[0]; |
| 139 | + } |
| 140 | + } |
| 141 | + return undefined; |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +/** |
| 146 | + * Gets the azure function project files based on the host file found in the same folder |
| 147 | + * @returns the azure function project files paths |
| 148 | + */ |
| 149 | +export async function getAzureFunctionProjectFiles(): Promise<string[] | undefined> { |
| 150 | + let projFiles: string[] = []; |
| 151 | + const hostFiles = await getHostFiles(); |
| 152 | + for (let host of hostFiles) { |
| 153 | + let projectFile = await vscode.workspace.findFiles('*.csproj', path.dirname(host)); |
| 154 | + projectFile.filter(file => path.dirname(file.fsPath) === path.dirname(host) ? projFiles.push(file?.fsPath) : projFiles); |
| 155 | + } |
| 156 | + return projFiles.length > 0 ? projFiles : undefined; |
| 157 | +} |
| 158 | + |
| 159 | +/** |
| 160 | + * Gets the host files from the workspace |
| 161 | + * @returns the host file paths |
| 162 | + */ |
| 163 | +export async function getHostFiles(): Promise<string[] | undefined> { |
| 164 | + const hostUris = await vscode.workspace.findFiles('**/host.json'); |
| 165 | + const hostFiles = hostUris.map(uri => uri.fsPath); |
| 166 | + return hostFiles.length > 0 ? hostFiles : undefined; |
| 167 | +} |
| 168 | + |
| 169 | +/** |
| 170 | + * Gets the local.settings.json file path |
| 171 | + * @param projectFile path of the azure function project |
| 172 | + * @returns the local.settings.json file path |
| 173 | + */ |
| 174 | +export async function getSettingsFile(projectFile: string): Promise<string | undefined> { |
| 175 | + return path.join(path.dirname(projectFile), 'local.settings.json'); |
| 176 | +} |
| 177 | + |
| 178 | +/** |
| 179 | + * Retrieves the new function file once the file is created |
| 180 | + * @param projectFile is the path to the project file |
| 181 | + * @returns the function file path once created |
| 182 | + */ |
| 183 | +export function waitForNewFunctionFile(projectFile: string): Promise<string> { |
| 184 | + return new Promise((resolve, reject) => { |
| 185 | + const watcher = vscode.workspace.createFileSystemWatcher(( |
| 186 | + path.dirname(projectFile), '**/*.cs'), false, true, true); |
| 187 | + const timeout = setTimeout(async () => { |
| 188 | + reject(new Error(constants.timeoutError)); |
| 189 | + watcher.dispose(); |
| 190 | + }, 10000); |
| 191 | + watcher.onDidCreate((e) => { |
| 192 | + resolve(e.fsPath); |
| 193 | + watcher.dispose(); |
| 194 | + clearTimeout(timeout); |
| 195 | + }); |
| 196 | + }); |
| 197 | +} |
| 198 | + |
| 199 | +/** |
| 200 | + * Adds the required nuget package to the project |
| 201 | + * @param selectedProjectFile is the users selected project file path |
| 202 | + */ |
| 203 | +export async function addNugetReferenceToProjectFile(selectedProjectFile: string): Promise<void> { |
| 204 | + await executeCommand(`dotnet add ${selectedProjectFile} package ${constants.sqlExtensionPackageName} --prerelease`); |
| 205 | +} |
| 206 | + |
| 207 | +/** |
| 208 | + * Adds the Sql Connection String to the local.settings.json |
| 209 | + * @param connectionString of the SQL Server connection that was chosen by the user |
| 210 | + */ |
| 211 | +export async function addConnectionStringToConfig(connectionString: string, projectFile: string): Promise<void> { |
| 212 | + const settingsFile = await getSettingsFile(projectFile); |
| 213 | + await setLocalAppSetting(path.dirname(settingsFile), constants.sqlConnectionString, connectionString); |
| 214 | +} |
| 215 | + |
0 commit comments