From 259ccdb2ee98a1966312c2b4929e8e4cc359b978 Mon Sep 17 00:00:00 2001 From: Hunter Werlla Date: Tue, 10 Nov 2020 13:31:34 -0800 Subject: [PATCH] Merge together template registry and template registry manager (#1391) - Merge together template registry and template registry manager - Move template registry to ext as it's global like telemetry, etc where we register one instance at start then use it until deactivation - This is a replacement for the existing singleton --- ...nager.test.ts => templateRegistry.test.ts} | 19 ++- src/lambda/local/debugConfiguration.ts | 5 +- src/lambda/wizards/samDeployWizard.ts | 4 +- src/shared/cloudformation/activation.ts | 12 +- src/shared/cloudformation/templateRegistry.ts | 127 +++++++++++++++--- .../cloudformation/templateRegistryManager.ts | 120 ----------------- src/shared/debug/launchConfiguration.ts | 2 - src/shared/extensionGlobals.ts | 2 + .../awsSamDebugConfigurationValidator.ts | 9 +- src/shared/sam/debugger/awsSamDebugger.ts | 11 +- .../commands/addSamDebugConfiguration.ts | 5 +- src/test/globalSetup.test.ts | 6 +- .../lambda/commands/createNewSamApp.test.ts | 11 +- src/test/lambda/config/templates.test.ts | 9 +- .../shared/debug/launchConfiguration.test.ts | 15 +-- .../awsSamDebugConfigurationValidator.test.ts | 17 ++- .../debugger/samDebugConfigProvider.test.ts | 59 ++++---- 17 files changed, 200 insertions(+), 233 deletions(-) rename src/integrationTest/cloudformation/{templateRegistryManager.test.ts => templateRegistry.test.ts} (85%) delete mode 100644 src/shared/cloudformation/templateRegistryManager.ts diff --git a/src/integrationTest/cloudformation/templateRegistryManager.test.ts b/src/integrationTest/cloudformation/templateRegistry.test.ts similarity index 85% rename from src/integrationTest/cloudformation/templateRegistryManager.test.ts rename to src/integrationTest/cloudformation/templateRegistry.test.ts index 704f12a0f0d..ecd4c96a932 100644 --- a/src/integrationTest/cloudformation/templateRegistryManager.test.ts +++ b/src/integrationTest/cloudformation/templateRegistry.test.ts @@ -7,7 +7,6 @@ import * as path from 'path' import * as fs from 'fs-extra' import { CloudFormationTemplateRegistry } from '../../shared/cloudformation/templateRegistry' -import { CloudFormationTemplateRegistryManager } from '../../shared/cloudformation/templateRegistryManager' import { makeSampleSamTemplateYaml, strToYamlFile } from '../../test/shared/cloudformation/cloudformationTestUtils' import { getTestWorkspaceFolder } from '../integrationTestsUtilities' @@ -15,9 +14,8 @@ import { getTestWorkspaceFolder } from '../integrationTestsUtilities' * Note: these tests are pretty shallow right now. They do not test the following: * * Adding/removing workspace folders */ -describe('CloudFormation Template Registry Manager', async () => { +describe('CloudFormation Template Registry', async () => { let registry: CloudFormationTemplateRegistry - let manager: CloudFormationTemplateRegistryManager let workspaceDir: string let testDir: string let testDirNested: string @@ -32,11 +30,10 @@ describe('CloudFormation Template Registry Manager', async () => { testDirNested = path.join(testDir, 'nested') await fs.mkdirp(testDirNested) registry = new CloudFormationTemplateRegistry() - manager = new CloudFormationTemplateRegistryManager(registry) }) afterEach(async () => { - manager.dispose() + registry.dispose() await fs.remove(testDir) dir++ }) @@ -45,13 +42,13 @@ describe('CloudFormation Template Registry Manager', async () => { await strToYamlFile(makeSampleSamTemplateYaml(true), path.join(testDir, 'test.yaml')) await strToYamlFile(makeSampleSamTemplateYaml(false), path.join(testDirNested, 'test.yml')) - await manager.addTemplateGlob('**/test.{yaml,yml}') + await registry.addTemplateGlob('**/test.{yaml,yml}') await registryHasTargetNumberOfFiles(registry, 2) }) it('adds dynamically-added template files with yaml and yml extensions at various nesting levels', async () => { - await manager.addTemplateGlob('**/test.{yaml,yml}') + await registry.addTemplateGlob('**/test.{yaml,yml}') await strToYamlFile(makeSampleSamTemplateYaml(false), path.join(testDir, 'test.yml')) await strToYamlFile(makeSampleSamTemplateYaml(true), path.join(testDirNested, 'test.yaml')) @@ -60,8 +57,8 @@ describe('CloudFormation Template Registry Manager', async () => { }) it('Ignores templates matching excluded patterns', async () => { - await manager.addTemplateGlob('**/test.{yaml,yml}') - await manager.addExcludedPattern(/.*nested.*/) + await registry.addTemplateGlob('**/test.{yaml,yml}') + await registry.addExcludedPattern(/.*nested.*/) await strToYamlFile(makeSampleSamTemplateYaml(false), path.join(testDir, 'test.yml')) await strToYamlFile(makeSampleSamTemplateYaml(true), path.join(testDirNested, 'test.yaml')) @@ -73,7 +70,7 @@ describe('CloudFormation Template Registry Manager', async () => { const filepath = path.join(testDir, 'changeMe.yml') await strToYamlFile(makeSampleSamTemplateYaml(false), filepath) - await manager.addTemplateGlob('**/changeMe.yml') + await registry.addTemplateGlob('**/changeMe.yml') await registryHasTargetNumberOfFiles(registry, 1) @@ -85,7 +82,7 @@ describe('CloudFormation Template Registry Manager', async () => { }) it('can handle deleted files', async () => { - await manager.addTemplateGlob('**/deleteMe.yml') + await registry.addTemplateGlob('**/deleteMe.yml') // Specifically creating the file after the watcher is added // Otherwise, it seems the file is deleted before the file watcher realizes the file exists diff --git a/src/lambda/local/debugConfiguration.ts b/src/lambda/local/debugConfiguration.ts index 720fd080627..b5e4c084daa 100644 --- a/src/lambda/local/debugConfiguration.ts +++ b/src/lambda/local/debugConfiguration.ts @@ -6,7 +6,6 @@ import * as path from 'path' import * as vscode from 'vscode' import { CloudFormation } from '../../shared/cloudformation/cloudformation' -import { CloudFormationTemplateRegistry } from '../../shared/cloudformation/templateRegistry' import { AwsSamDebuggerConfiguration, AWS_SAM_DEBUG_TARGET_TYPES, @@ -18,6 +17,7 @@ import { localize } from '../../shared/utilities/vsCodeUtils' import { tryGetAbsolutePath } from '../../shared/utilities/workspaceUtils' import { RuntimeFamily } from '../models/samLambdaRuntime' import { SamLaunchRequestArgs } from '../../shared/sam/debugger/awsSamDebugger' +import { ext } from '../../shared/extensionGlobals' export const DOTNET_CORE_DEBUGGER_PATH = '/tmp/lambci_debug_files/vsdbg' @@ -155,9 +155,8 @@ export function getTemplate( return undefined } const templateInvoke = config.invokeTarget as TemplateTargetProperties - const cftRegistry = CloudFormationTemplateRegistry.getRegistry() const fullPath = tryGetAbsolutePath(folder, templateInvoke.templatePath) - const cfnTemplate = cftRegistry.getRegisteredTemplate(fullPath)?.template + const cfnTemplate = ext.templateRegistry.getRegisteredTemplate(fullPath)?.template return cfnTemplate } diff --git a/src/lambda/wizards/samDeployWizard.ts b/src/lambda/wizards/samDeployWizard.ts index a76ce2e4ef0..b0006fe5742 100644 --- a/src/lambda/wizards/samDeployWizard.ts +++ b/src/lambda/wizards/samDeployWizard.ts @@ -29,7 +29,6 @@ import { } from '../../shared/wizards/multiStepWizard' import { configureParameterOverrides } from '../config/configureParameterOverrides' import { getOverriddenParameters, getParameters } from '../utilities/parameterUtils' -import { CloudFormationTemplateRegistry } from '../../shared/cloudformation/templateRegistry' import { ext } from '../../shared/extensionGlobals' export interface SamDeployWizardResponse { @@ -620,8 +619,7 @@ function validateStackName(value: string): string | undefined { } async function getTemplateChoices(...workspaceFolders: vscode.Uri[]): Promise { - const cfnRegistry = CloudFormationTemplateRegistry.getRegistry() - const templateUris = cfnRegistry.registeredTemplates.map(o => vscode.Uri.file(o.path)) + const templateUris = ext.templateRegistry.registeredTemplates.map(o => vscode.Uri.file(o.path)) const uriToLabel: Map = new Map() const labelCounts: Map = new Map() diff --git a/src/shared/cloudformation/activation.ts b/src/shared/cloudformation/activation.ts index e62a9626199..dd6c731042f 100644 --- a/src/shared/cloudformation/activation.ts +++ b/src/shared/cloudformation/activation.ts @@ -8,7 +8,7 @@ import { getLogger } from '../logger' import { localize } from '../utilities/vsCodeUtils' import { CloudFormationTemplateRegistry } from './templateRegistry' -import { CloudFormationTemplateRegistryManager } from './templateRegistryManager' +import { ext } from '../extensionGlobals' export const TEMPLATE_FILE_GLOB_PATTERN = '**/template.{yaml,yml}' @@ -28,11 +28,11 @@ export const TEMPLATE_FILE_EXCLUDE_PATTERN = /.*[/\\]\.aws-sam([/\\].*|$)/ */ export async function activate(extensionContext: vscode.ExtensionContext): Promise { try { - const registry = CloudFormationTemplateRegistry.getRegistry() - const manager = new CloudFormationTemplateRegistryManager(registry) - await manager.addExcludedPattern(TEMPLATE_FILE_EXCLUDE_PATTERN) - await manager.addTemplateGlob(TEMPLATE_FILE_GLOB_PATTERN) - extensionContext.subscriptions.push(manager) + const registry = new CloudFormationTemplateRegistry() + await registry.addExcludedPattern(TEMPLATE_FILE_EXCLUDE_PATTERN) + await registry.addTemplateGlob(TEMPLATE_FILE_GLOB_PATTERN) + extensionContext.subscriptions.push(registry) + ext.templateRegistry = registry } catch (e) { vscode.window.showErrorMessage( localize( diff --git a/src/shared/cloudformation/templateRegistry.ts b/src/shared/cloudformation/templateRegistry.ts index 042af506d38..fc441025963 100644 --- a/src/shared/cloudformation/templateRegistry.ts +++ b/src/shared/cloudformation/templateRegistry.ts @@ -4,31 +4,66 @@ */ import * as vscode from 'vscode' -import * as path_ from 'path' import { getLogger } from '../logger/logger' import { CloudFormation } from './cloudformation' import * as pathutils from '../utilities/pathUtils' +import * as path from 'path' import { isInDirectory } from '../filesystemUtilities' import { dotNetRuntimes } from '../../lambda/models/samLambdaRuntime' import { getLambdaDetails } from '../../lambda/utils' +import { ext } from '../extensionGlobals' export interface TemplateDatum { path: string template: CloudFormation.Template } -export class CloudFormationTemplateRegistry { - private static INSTANCE: CloudFormationTemplateRegistry | undefined - private readonly templateRegistryData: Map +export class CloudFormationTemplateRegistry implements vscode.Disposable { + private readonly disposables: vscode.Disposable[] = [] + private _isDisposed: boolean = false + private readonly globs: vscode.GlobPattern[] = [] + private readonly excludedFilePatterns: RegExp[] = [] + private readonly templateRegistryData: Map = new Map< + string, + CloudFormation.Template + >() public constructor() { - this.templateRegistryData = new Map() + this.disposables.push( + vscode.workspace.onDidChangeWorkspaceFolders(async () => { + await this.rebuildRegistry() + }) + ) } - private assertAbsolute(path: string) { - if (!path_.isAbsolute(path)) { - throw Error(`CloudFormationTemplateRegistry: path is relative: ${path}`) + /** + * Adds a glob pattern to use for lookups and resets the registry to use it. + * Added templates cannot be removed without restarting the extension. + * Throws an error if this manager has already been disposed. + * @param glob vscode.GlobPattern to be used for lookups + */ + public async addTemplateGlob(glob: vscode.GlobPattern): Promise { + if (this._isDisposed) { + throw new Error('Manager has already been disposed!') + } + this.globs.push(glob) + + const watcher = vscode.workspace.createFileSystemWatcher(glob) + this.addWatcher(watcher) + + await this.rebuildRegistry() + } + + /** + * Adds a regex pattern to ignore paths containing the pattern + */ + public async addExcludedPattern(pattern: RegExp): Promise { + if (this._isDisposed) { + throw new Error('Manager has already been disposed!') } + this.excludedFilePatterns.push(pattern) + + await this.rebuildRegistry() } /** @@ -36,6 +71,13 @@ export class CloudFormationTemplateRegistry { * @param templateUri vscode.Uri containing the template to load in */ public async addTemplateToRegistry(templateUri: vscode.Uri, quiet?: boolean): Promise { + const excluded = this.excludedFilePatterns.find(pattern => templateUri.fsPath.match(pattern)) + if (excluded) { + getLogger().verbose( + `Manager did not add template ${templateUri.fsPath} matching excluded pattern ${excluded}` + ) + return + } const pathAsString = pathutils.normalize(templateUri.fsPath) this.assertAbsolute(pathAsString) try { @@ -91,6 +133,35 @@ export class CloudFormationTemplateRegistry { this.templateRegistryData.delete(pathAsString) } + /** + * Disposes CloudFormationTemplateRegistryManager and marks as disposed. + */ + public dispose(): void { + if (!this._isDisposed) { + while (this.disposables.length > 0) { + const disposable = this.disposables.pop() + if (disposable) { + disposable.dispose() + } + } + this._isDisposed = true + } + } + + /** + * Rebuilds registry using current glob and exclusion patterns. + * All functionality is currently internal to class, but can be made public if we want a manual "refresh" button + */ + private async rebuildRegistry(): Promise { + this.reset() + for (const glob of this.globs) { + const templateUris = await vscode.workspace.findFiles(glob) + for (const template of templateUris) { + await this.addTemplateToRegistry(template, true) + } + } + } + /** * Removes all templates from the registry. */ @@ -99,15 +170,31 @@ export class CloudFormationTemplateRegistry { } /** - * Returns the CloudFormationTemplateRegistry singleton. - * If the singleton doesn't exist, creates it. + * Sets watcher functionality and adds to this.disposables + * @param watcher vscode.FileSystemWatcher */ - public static getRegistry(): CloudFormationTemplateRegistry { - if (!CloudFormationTemplateRegistry.INSTANCE) { - CloudFormationTemplateRegistry.INSTANCE = new CloudFormationTemplateRegistry() - } + private addWatcher(watcher: vscode.FileSystemWatcher): void { + this.disposables.push( + watcher, + watcher.onDidChange(async uri => { + getLogger().verbose(`Manager detected a change to template file: ${uri.fsPath}`) + await this.addTemplateToRegistry(uri) + }), + watcher.onDidCreate(async uri => { + getLogger().verbose(`Manager detected a new template file: ${uri.fsPath}`) + await this.addTemplateToRegistry(uri) + }), + watcher.onDidDelete(async uri => { + getLogger().verbose(`Manager detected a deleted template file: ${uri.fsPath}`) + this.removeTemplateFromRegistry(uri) + }) + ) + } - return CloudFormationTemplateRegistry.INSTANCE + private assertAbsolute(p: string) { + if (!path.isAbsolute(p)) { + throw Error(`CloudFormationTemplateRegistry: path is relative: ${p}`) + } } } @@ -121,7 +208,7 @@ export class CloudFormationTemplateRegistry { export function getResourcesForHandler( filepath: string, handler: string, - unfilteredTemplates: TemplateDatum[] = CloudFormationTemplateRegistry.getRegistry().registeredTemplates + unfilteredTemplates: TemplateDatum[] = ext.templateRegistry.registeredTemplates ): { templateDatum: TemplateDatum; name: string; resourceData: CloudFormation.Resource }[] { // TODO: Array.flat and Array.flatMap not introduced until >= Node11.x -- migrate when VS Code updates Node ver const o = unfilteredTemplates.map(templateDatum => { @@ -150,9 +237,9 @@ export function getResourcesForHandlerFromTemplateDatum( templateDatum: TemplateDatum ): { name: string; resourceData: CloudFormation.Resource }[] { const matchingResources: { name: string; resourceData: CloudFormation.Resource }[] = [] - const templateDirname = path_.dirname(templateDatum.path) + const templateDirname = path.dirname(templateDatum.path) // template isn't a parent or sibling of file - if (!isInDirectory(templateDirname, path_.dirname(filepath))) { + if (!isInDirectory(templateDirname, path.dirname(filepath))) { return [] } @@ -191,7 +278,7 @@ export function getResourcesForHandlerFromTemplateDatum( if ( handler === registeredHandler && isInDirectory( - pathutils.normalize(path_.join(templateDirname, registeredCodeUri)), + pathutils.normalize(path.join(templateDirname, registeredCodeUri)), pathutils.normalize(filepath) ) ) { @@ -210,7 +297,7 @@ export function getResourcesForHandlerFromTemplateDatum( if ( pathutils.normalize(filepath) === pathutils.normalize( - path_.join(templateDirname, registeredCodeUri, parsedLambda.fileName) + path.join(templateDirname, registeredCodeUri, parsedLambda.fileName) ) && functionName === parsedLambda.functionName ) { diff --git a/src/shared/cloudformation/templateRegistryManager.ts b/src/shared/cloudformation/templateRegistryManager.ts deleted file mode 100644 index f32d0a99129..00000000000 --- a/src/shared/cloudformation/templateRegistryManager.ts +++ /dev/null @@ -1,120 +0,0 @@ -/*! - * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -import * as vscode from 'vscode' -import { getLogger } from '../logger/logger' -import { CloudFormationTemplateRegistry } from './templateRegistry' - -export class CloudFormationTemplateRegistryManager implements vscode.Disposable { - private readonly disposables: vscode.Disposable[] = [] - private _isDisposed: boolean = false - private readonly globs: vscode.GlobPattern[] = [] - private readonly excludedFilePatterns: RegExp[] = [] - - public constructor(private readonly registry: CloudFormationTemplateRegistry) { - this.disposables.push( - vscode.workspace.onDidChangeWorkspaceFolders(async () => { - await this.rebuildRegistry() - }) - ) - } - - /** - * Adds a glob pattern to use for lookups and resets the registry to use it. - * Added templates cannot be removed without restarting the extension. - * Throws an error if this manager has already been disposed. - * @param glob vscode.GlobPattern to be used for lookups - */ - public async addTemplateGlob(glob: vscode.GlobPattern): Promise { - if (this._isDisposed) { - throw new Error('Manager has already been disposed!') - } - this.globs.push(glob) - - const watcher = vscode.workspace.createFileSystemWatcher(glob) - this.addWatcher(watcher) - - await this.rebuildRegistry() - } - - /** - * Adds a regex pattern to ignore paths containing the pattern - */ - public async addExcludedPattern(pattern: RegExp): Promise { - if (this._isDisposed) { - throw new Error('Manager has already been disposed!') - } - this.excludedFilePatterns.push(pattern) - - await this.rebuildRegistry() - } - - /** - * Disposes CloudFormationTemplateRegistryManager and marks as disposed. - */ - public dispose(): void { - if (!this._isDisposed) { - this.disposeDisposables() - this._isDisposed = true - } - } - - private async addTemplateToRegistry(templateUri: vscode.Uri, quiet?: boolean): Promise { - const excluded = this.excludedFilePatterns.find(pattern => templateUri.fsPath.match(pattern)) - if (excluded) { - getLogger().verbose(`Manager did not add template ${templateUri.fsPath} matching excluded pattern ${excluded}`) - return - } - await this.registry.addTemplateToRegistry(templateUri, quiet) - } - - /** - * Rebuilds registry using current glob and exclusion patterns. - * All functionality is currently internal to class, but can be made public if we want a manual "refresh" button - */ - private async rebuildRegistry(): Promise { - this.registry.reset() - for (const glob of this.globs) { - const templateUris = await vscode.workspace.findFiles(glob) - for (const template of templateUris) { - await this.addTemplateToRegistry(template, true) - } - } - } - - /** - * Disposes disposables without marking class as disposed. Also empties this.disposables. - */ - private disposeDisposables(): void { - while (this.disposables.length > 0) { - const disposable = this.disposables.pop() - if (disposable) { - disposable.dispose() - } - } - } - - /** - * Sets watcher functionality and adds to this.disposables - * @param watcher vscode.FileSystemWatcher - */ - private addWatcher(watcher: vscode.FileSystemWatcher): void { - this.disposables.push( - watcher, - watcher.onDidChange(async uri => { - getLogger().verbose(`Manager detected a change to template file: ${uri.fsPath}`) - await this.addTemplateToRegistry(uri) - }), - watcher.onDidCreate(async uri => { - getLogger().verbose(`Manager detected a new template file: ${uri.fsPath}`) - await this.addTemplateToRegistry(uri) - }), - watcher.onDidDelete(async uri => { - getLogger().verbose(`Manager detected a deleted template file: ${uri.fsPath}`) - this.registry.removeTemplateFromRegistry(uri) - }) - ) - } -} diff --git a/src/shared/debug/launchConfiguration.ts b/src/shared/debug/launchConfiguration.ts index c741d92c552..f21b22d9ebf 100644 --- a/src/shared/debug/launchConfiguration.ts +++ b/src/shared/debug/launchConfiguration.ts @@ -6,7 +6,6 @@ import * as _ from 'lodash' import * as path from 'path' import * as vscode from 'vscode' -import { CloudFormationTemplateRegistry } from '../cloudformation/templateRegistry' import { AwsSamDebuggerConfiguration, CodeTargetProperties, @@ -46,7 +45,6 @@ export class LaunchConfiguration { public readonly scopedResource: vscode.Uri, private readonly configSource: DebugConfigurationSource = new DefaultDebugConfigSource(scopedResource), private readonly samValidator: AwsSamDebugConfigurationValidator = new DefaultAwsSamDebugConfigurationValidator( - CloudFormationTemplateRegistry.getRegistry(), vscode.workspace.getWorkspaceFolder(scopedResource) ) ) { diff --git a/src/shared/extensionGlobals.ts b/src/shared/extensionGlobals.ts index dec52bb5ffc..4157f117428 100644 --- a/src/shared/extensionGlobals.ts +++ b/src/shared/extensionGlobals.ts @@ -7,6 +7,7 @@ import { ExtensionContext, OutputChannel, Uri } from 'vscode' import { AWSClientBuilder } from './awsClientBuilder' import { AWSContextCommands } from './awsContextCommands' import { ToolkitClientBuilder } from './clients/toolkitClientBuilder' +import { CloudFormationTemplateRegistry } from './cloudformation/templateRegistry' import { TelemetryService } from './telemetry/telemetryService' /** @@ -20,6 +21,7 @@ export namespace ext { export let sdkClientBuilder: AWSClientBuilder export let toolkitClientBuilder: ToolkitClientBuilder export let telemetry: TelemetryService + export let templateRegistry: CloudFormationTemplateRegistry export namespace iconPaths { export const dark: IconPaths = makeIconPathsObject() diff --git a/src/shared/sam/debugger/awsSamDebugConfigurationValidator.ts b/src/shared/sam/debugger/awsSamDebugConfigurationValidator.ts index 0d610b6a1c4..d68c636da07 100644 --- a/src/shared/sam/debugger/awsSamDebugConfigurationValidator.ts +++ b/src/shared/sam/debugger/awsSamDebugConfigurationValidator.ts @@ -7,7 +7,6 @@ import * as vscode from 'vscode' import * as fs from 'fs' import { samLambdaRuntimes } from '../../../lambda/models/samLambdaRuntime' import { CloudFormation } from '../../cloudformation/cloudformation' -import { CloudFormationTemplateRegistry } from '../../cloudformation/templateRegistry' import { localize } from '../../utilities/vsCodeUtils' import { AWS_SAM_DEBUG_REQUEST_TYPES, @@ -19,6 +18,7 @@ import { API_TARGET_TYPE, } from './awsSamDebugConfiguration' import { tryGetAbsolutePath } from '../../utilities/workspaceUtils' +import { ext } from '../../extensionGlobals' export interface ValidationResult { isValid: boolean @@ -30,10 +30,7 @@ export interface AwsSamDebugConfigurationValidator { } export class DefaultAwsSamDebugConfigurationValidator implements AwsSamDebugConfigurationValidator { - public constructor( - private readonly cftRegistry = CloudFormationTemplateRegistry.getRegistry(), - private readonly workspaceFolder: vscode.WorkspaceFolder | undefined - ) {} + public constructor(private readonly workspaceFolder: vscode.WorkspaceFolder | undefined) {} /** * Validates debug configuration properties. @@ -67,7 +64,7 @@ export class DefaultAwsSamDebugConfigurationValidator implements AwsSamDebugConf const fullpath = tryGetAbsolutePath(this.workspaceFolder, config.invokeTarget.templatePath) // Normalize to absolute path for use in the runner. config.invokeTarget.templatePath = fullpath - cfnTemplate = this.cftRegistry.getRegisteredTemplate(fullpath)?.template + cfnTemplate = ext.templateRegistry.getRegisteredTemplate(fullpath)?.template } rv = this.validateTemplateConfig(config, config.invokeTarget.templatePath, cfnTemplate) } else if (config.invokeTarget.target === CODE_TARGET_TYPE) { diff --git a/src/shared/sam/debugger/awsSamDebugger.ts b/src/shared/sam/debugger/awsSamDebugger.ts index 0c5565fc237..40cc8f03e57 100644 --- a/src/shared/sam/debugger/awsSamDebugger.ts +++ b/src/shared/sam/debugger/awsSamDebugger.ts @@ -17,7 +17,6 @@ import { getTemplate, } from '../../../lambda/local/debugConfiguration' import { getDefaultRuntime, getFamily, getRuntimeFamily, RuntimeFamily } from '../../../lambda/models/samLambdaRuntime' -import { CloudFormationTemplateRegistry } from '../../cloudformation/templateRegistry' import { Timeout } from '../../utilities/timeoutUtils' import { ChannelLogger } from '../../utilities/vsCodeUtils' import * as csharpDebug from './csharpSamDebug' @@ -48,6 +47,7 @@ import { notifyUserInvalidCredentials } from '../../../credentials/credentialsUt import { Credentials } from 'aws-sdk/lib/credentials' import { CloudFormation } from '../../cloudformation/cloudformation' import { getSamCliContext, getSamCliVersion } from '../cli/samCliContext' +import { ext } from '../../extensionGlobals' const localize = nls.loadMessageBundle() @@ -165,12 +165,11 @@ export class SamDebugConfigProvider implements vscode.DebugConfigurationProvider if (token?.isCancellationRequested) { return undefined } - const cftRegistry = CloudFormationTemplateRegistry.getRegistry() const configs: AwsSamDebuggerConfiguration[] = [] if (folder) { const folderPath = folder.uri.fsPath - const templates = cftRegistry.registeredTemplates + const templates = ext.templateRegistry.registeredTemplates for (const templateDatum of templates) { if (isInDirectory(folderPath, templateDatum.path)) { @@ -276,15 +275,11 @@ export class SamDebugConfigProvider implements vscode.DebugConfigurationProvider ) return undefined } - const cftRegistry = CloudFormationTemplateRegistry.getRegistry() // If "request" field is missing this means launch.json does not exist. // User/vscode expects us to dynamically decide defaults if possible. const hasLaunchJson = !!config.request - const configValidator: AwsSamDebugConfigurationValidator = new DefaultAwsSamDebugConfigurationValidator( - cftRegistry, - folder - ) + const configValidator: AwsSamDebugConfigurationValidator = new DefaultAwsSamDebugConfigurationValidator(folder) if (!hasLaunchJson) { vscode.window diff --git a/src/shared/sam/debugger/commands/addSamDebugConfiguration.ts b/src/shared/sam/debugger/commands/addSamDebugConfiguration.ts index 49759706df2..476e78761f8 100644 --- a/src/shared/sam/debugger/commands/addSamDebugConfiguration.ts +++ b/src/shared/sam/debugger/commands/addSamDebugConfiguration.ts @@ -8,7 +8,6 @@ import * as vscode from 'vscode' import { Runtime } from 'aws-sdk/clients/lambda' import { getExistingConfiguration } from '../../../../lambda/config/templates' import { createRuntimeQuickPick, getDefaultRuntime, RuntimeFamily } from '../../../../lambda/models/samLambdaRuntime' -import { CloudFormationTemplateRegistry } from '../../../cloudformation/templateRegistry' import { LaunchConfiguration } from '../../../debug/launchConfiguration' import * as picker from '../../../ui/picker' import { localize } from '../../../utilities/vsCodeUtils' @@ -22,6 +21,7 @@ import { TEMPLATE_TARGET_TYPE, } from '../awsSamDebugConfiguration' import { CloudFormation } from '../../../cloudformation/cloudformation' +import { ext } from '../../../extensionGlobals' /** * Holds information required to create a launch config @@ -53,8 +53,7 @@ export async function addSamDebugConfiguration( let preloadedConfig = undefined if (workspaceFolder) { - const registry = CloudFormationTemplateRegistry.getRegistry() - const templateDatum = registry.getRegisteredTemplate(rootUri.fsPath) + const templateDatum = ext.templateRegistry.getRegisteredTemplate(rootUri.fsPath) if (templateDatum) { const resource = templateDatum.template.Resources![resourceName] if (resource && resource.Properties) { diff --git a/src/test/globalSetup.test.ts b/src/test/globalSetup.test.ts index 985df5402b1..2cc494cfe9c 100644 --- a/src/test/globalSetup.test.ts +++ b/src/test/globalSetup.test.ts @@ -9,6 +9,7 @@ import * as assert from 'assert' import { appendFileSync, mkdirpSync, remove } from 'fs-extra' import { join } from 'path' +import { CloudFormationTemplateRegistry } from '../shared/cloudformation/templateRegistry' import { ext } from '../shared/extensionGlobals' import { getLogger } from '../shared/logger' import { setLogger } from '../shared/logger/logger' @@ -42,14 +43,15 @@ before(async () => { } const service = new DefaultTelemetryService(mockContext, mockAws, mockPublisher) ext.telemetry = service + ext.templateRegistry = new CloudFormationTemplateRegistry() }) -beforeEach(async function() { +beforeEach(async function () { // Set every test up so that TestLogger is the logger used by toolkit code testLogger = setupTestLogger() }) -afterEach(async function() { +afterEach(async function () { // Prevent other tests from using the same TestLogger instance // tslint:disable-next-line: no-unsafe-any, no-invalid-this teardownTestLogger(this.currentTest?.fullTitle() as string) diff --git a/src/test/lambda/commands/createNewSamApp.test.ts b/src/test/lambda/commands/createNewSamApp.test.ts index b5fcc68e142..993978d368a 100644 --- a/src/test/lambda/commands/createNewSamApp.test.ts +++ b/src/test/lambda/commands/createNewSamApp.test.ts @@ -15,13 +15,12 @@ import { LaunchConfiguration } from '../../../shared/debug/launchConfiguration' import { anything, capture, instance, mock, when } from 'ts-mockito' import { makeSampleSamTemplateYaml } from '../../shared/cloudformation/cloudformationTestUtils' import { makeTemporaryToolkitFolder } from '../../../shared/filesystemUtilities' -import { CloudFormationTemplateRegistry } from '../../../shared/cloudformation/templateRegistry' import { ExtContext } from '../../../shared/extensions' import { TemplateTargetProperties } from '../../../shared/sam/debugger/awsSamDebugConfiguration' +import { ext } from '../../../shared/extensionGlobals' -describe('addInitialLaunchConfiguration', function() { +describe('addInitialLaunchConfiguration', function () { let mockLaunchConfiguration: LaunchConfiguration - let registry: CloudFormationTemplateRegistry let tempFolder: string let tempTemplate: vscode.Uri let fakeWorkspaceFolder: vscode.WorkspaceFolder @@ -32,7 +31,6 @@ describe('addInitialLaunchConfiguration', function() { fakeContext = await FakeExtensionContext.getFakeExtContext() tempFolder = await makeTemporaryToolkitFolder() tempTemplate = vscode.Uri.file(path.join(tempFolder, 'test.yaml')) - registry = CloudFormationTemplateRegistry.getRegistry() fakeWorkspaceFolder = { uri: vscode.Uri.file(tempFolder), @@ -56,6 +54,7 @@ describe('addInitialLaunchConfiguration', function() { afterEach(async () => { await fs.remove(tempFolder) + ext.templateRegistry.reset() }) it('produces and returns initial launch configurations', async () => { @@ -63,7 +62,7 @@ describe('addInitialLaunchConfiguration', function() { testutil.toFile(makeSampleSamTemplateYaml(true), tempTemplate.fsPath) - await registry.addTemplateToRegistry(tempTemplate) + await ext.templateRegistry.addTemplateToRegistry(tempTemplate) const launchConfigs = await addInitialLaunchConfiguration( fakeContext, fakeWorkspaceFolder, @@ -97,7 +96,7 @@ describe('addInitialLaunchConfiguration', function() { testutil.toFile(makeSampleSamTemplateYaml(true), tempTemplate.fsPath) - await registry.addTemplateToRegistry(tempTemplate) + await ext.templateRegistry.addTemplateToRegistry(tempTemplate) const launchConfigs = await addInitialLaunchConfiguration( fakeContext, fakeWorkspaceFolder, diff --git a/src/test/lambda/config/templates.test.ts b/src/test/lambda/config/templates.test.ts index 2eb63f98772..df28fd3f6cf 100644 --- a/src/test/lambda/config/templates.test.ts +++ b/src/test/lambda/config/templates.test.ts @@ -6,6 +6,7 @@ import * as assert from 'assert' import { mkdir, remove, writeFile } from 'fs-extra' import * as path from 'path' +import { ext } from '../../../shared/extensionGlobals' import * as vscode from 'vscode' import { getExistingConfiguration, @@ -14,7 +15,6 @@ import { LoadTemplatesConfigContext, TemplatesConfigPopulator, } from '../../../lambda/config/templates' -import { CloudFormationTemplateRegistry } from '../../../shared/cloudformation/templateRegistry' import { makeTemporaryToolkitFolder } from '../../../shared/filesystemUtilities' import { makeSampleSamTemplateYaml } from '../../shared/cloudformation/cloudformationTestUtils' @@ -764,7 +764,6 @@ describe('TemplatesConfigPopulator', async () => { }) describe('getExistingConfiguration', async () => { - let registry: CloudFormationTemplateRegistry let tempFolder: string let tempTemplateFile: vscode.Uri let tempConfigFile: string @@ -775,7 +774,6 @@ describe('getExistingConfiguration', async () => { beforeEach(async () => { tempFolder = await makeTemporaryToolkitFolder() tempTemplateFile = vscode.Uri.file(path.join(tempFolder, 'test.yaml')) - registry = new CloudFormationTemplateRegistry() fakeWorkspaceFolder = { uri: vscode.Uri.file(tempFolder), name: 'workspaceFolderMimic', @@ -788,6 +786,7 @@ describe('getExistingConfiguration', async () => { afterEach(async () => { await remove(tempFolder) + ext.templateRegistry.reset() }) it("returns undefined if the legacy config file doesn't exist", async () => { @@ -798,7 +797,7 @@ describe('getExistingConfiguration', async () => { it('returns undefined if the legacy config file is not valid JSON', async () => { await writeFile(tempTemplateFile.fsPath, makeSampleSamTemplateYaml(true, { handler: matchedHandler }), 'utf8') await writeFile(tempConfigFile, makeSampleSamTemplateYaml(true, { handler: matchedHandler }), 'utf8') - await registry.addTemplateToRegistry(tempTemplateFile) + await ext.templateRegistry.addTemplateToRegistry(tempTemplateFile) const val = await getExistingConfiguration(fakeWorkspaceFolder, matchedHandler, tempTemplateFile) assert.strictEqual(val, undefined) }) @@ -819,7 +818,7 @@ describe('getExistingConfiguration', async () => { }, } await writeFile(tempConfigFile, JSON.stringify(configData), 'utf8') - await registry.addTemplateToRegistry(tempTemplateFile) + await ext.templateRegistry.addTemplateToRegistry(tempTemplateFile) const val = await getExistingConfiguration(fakeWorkspaceFolder, matchedHandler, tempTemplateFile) assert.ok(val) if (val) { diff --git a/src/test/shared/debug/launchConfiguration.test.ts b/src/test/shared/debug/launchConfiguration.test.ts index fb234827fb1..33228bfb0c0 100644 --- a/src/test/shared/debug/launchConfiguration.test.ts +++ b/src/test/shared/debug/launchConfiguration.test.ts @@ -17,9 +17,8 @@ import { AwsSamDebuggerConfiguration } from '../../../shared/sam/debugger/awsSam import { AwsSamDebugConfigurationValidator } from '../../../shared/sam/debugger/awsSamDebugConfigurationValidator' import * as pathutils from '../../../shared/utilities/pathUtils' import * as testutil from '../../testUtil' -import { CloudFormationTemplateRegistry } from '../../../shared/cloudformation/templateRegistry' -import { CloudFormationTemplateRegistryManager } from '../../../shared/cloudformation/templateRegistryManager' import { TEMPLATE_FILE_GLOB_PATTERN } from '../../../shared/cloudformation/activation' +import { ext } from '../../../shared/extensionGlobals' const samDebugConfiguration: AwsSamDebuggerConfiguration = { type: 'aws-sam', @@ -93,6 +92,7 @@ const templateUri = vscode.Uri.file('/template.yaml') describe('LaunchConfiguration', () => { let mockConfigSource: DebugConfigurationSource let mockSamValidator: AwsSamDebugConfigurationValidator + /** Test workspace. */ const workspace = vscode.workspace.workspaceFolders![0] const testLaunchJson = vscode.Uri.file(path.join(workspace.uri.fsPath, '.vscode/launch.json')) @@ -105,12 +105,7 @@ describe('LaunchConfiguration', () => { const templateUriCsharp = vscode.Uri.file(path.join(workspace.uri.fsPath, 'csharp2.1-plain-sam-app/template.yaml')) beforeEach(async () => { - // Ensure that template.yaml file(s) in src/testFixtures/ is tracked by - // our inotify thing. - const registry = CloudFormationTemplateRegistry.getRegistry() - // TODO: can registry and registry-manager be combined? - const manager = new CloudFormationTemplateRegistryManager(registry) - await manager.addTemplateGlob(TEMPLATE_FILE_GLOB_PATTERN) + await ext.templateRegistry.addTemplateGlob(TEMPLATE_FILE_GLOB_PATTERN) // TODO: remove mocks in favor of testing src/testFixtures/ data. mockConfigSource = mock() @@ -119,6 +114,10 @@ describe('LaunchConfiguration', () => { when(mockSamValidator.validate(deepEqual(samDebugConfiguration))).thenReturn({ isValid: true }) }) + afterEach(() => { + ext.templateRegistry.reset() + }) + it('getConfigsMappedToTemplates(type=api)', async () => { const actual = getConfigsMappedToTemplates(new LaunchConfiguration(templateUriJsPlainApp), 'api') assert.deepStrictEqual(actual.size, 0) diff --git a/src/test/shared/sam/debugger/awsSamDebugConfigurationValidator.test.ts b/src/test/shared/sam/debugger/awsSamDebugConfigurationValidator.test.ts index 4153110adb6..fa4372fd9ce 100644 --- a/src/test/shared/sam/debugger/awsSamDebugConfigurationValidator.test.ts +++ b/src/test/shared/sam/debugger/awsSamDebugConfigurationValidator.test.ts @@ -15,6 +15,7 @@ import { } from '../../../../shared/sam/debugger/awsSamDebugConfiguration' import { DefaultAwsSamDebugConfigurationValidator } from '../../../../shared/sam/debugger/awsSamDebugConfigurationValidator' import { createBaseTemplate } from '../../cloudformation/cloudformationTestUtils' +import { ext } from '../../../../shared/extensionGlobals' function createTemplateConfig(): AwsSamDebuggerConfiguration { return { @@ -77,10 +78,22 @@ describe('DefaultAwsSamDebugConfigurationValidator', () => { let validator: DefaultAwsSamDebugConfigurationValidator + let savedRegistry: CloudFormationTemplateRegistry + + before(() => { + savedRegistry = ext.templateRegistry + }) + + after(() => { + ext.templateRegistry = savedRegistry + }) + beforeEach(() => { when(mockRegistry.getRegisteredTemplate('/')).thenReturn(templateData) - validator = new DefaultAwsSamDebugConfigurationValidator(instance(mockRegistry), instance(mockFolder)) + ext.templateRegistry = mockRegistry + + validator = new DefaultAwsSamDebugConfigurationValidator(instance(mockFolder)) }) it('returns invalid when resolving debug configurations with an invalid request type', () => { @@ -101,7 +114,7 @@ describe('DefaultAwsSamDebugConfigurationValidator', () => { const mockEmptyRegistry: CloudFormationTemplateRegistry = mock() when(mockEmptyRegistry.getRegisteredTemplate('/')).thenReturn(undefined) - validator = new DefaultAwsSamDebugConfigurationValidator(instance(mockEmptyRegistry), instance(mockFolder)) + validator = new DefaultAwsSamDebugConfigurationValidator(instance(mockFolder)) const result = validator.validate(templateConfig) assert.strictEqual(result.isValid, false) diff --git a/src/test/shared/sam/debugger/samDebugConfigProvider.test.ts b/src/test/shared/sam/debugger/samDebugConfigProvider.test.ts index f466c6170aa..578c59f9219 100644 --- a/src/test/shared/sam/debugger/samDebugConfigProvider.test.ts +++ b/src/test/shared/sam/debugger/samDebugConfigProvider.test.ts @@ -44,6 +44,7 @@ import { Credentials } from 'aws-sdk' import { ExtContext } from '../../../../shared/extensions' import { CredentialsProvider } from '../../../../credentials/providers/credentialsProvider' import { mkdir, remove } from 'fs-extra' +import { ext } from '../../../../shared/extensionGlobals' /** * Asserts the contents of a "launch config" (the result of `makeConfig()` or @@ -99,7 +100,6 @@ function assertEqualLaunchConfigs(actual: SamLaunchRequestArgs, expected: SamLau describe('SamDebugConfigurationProvider', async () => { let debugConfigProvider: SamDebugConfigProvider - let registry: CloudFormationTemplateRegistry let tempFolder: string let tempFolderSimilarName: string | undefined let tempFile: vscode.Uri @@ -111,7 +111,6 @@ describe('SamDebugConfigurationProvider', async () => { beforeEach(async () => { fakeContext = await FakeExtensionContext.getFakeExtContext() - registry = CloudFormationTemplateRegistry.getRegistry() debugConfigProvider = new SamDebugConfigProvider(fakeContext) sandbox = sinon.createSandbox() @@ -126,6 +125,7 @@ describe('SamDebugConfigurationProvider', async () => { if (tempFolderSimilarName) { await remove(tempFolderSimilarName) } + ext.templateRegistry.reset() sandbox.restore() }) @@ -138,7 +138,7 @@ describe('SamDebugConfigurationProvider', async () => { // Malformed template.yaml: testutil.toFile('bogus', tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) assert.deepStrictEqual(await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder), []) }) @@ -146,14 +146,14 @@ describe('SamDebugConfigurationProvider', async () => { const bigYamlStr = `${makeSampleSamTemplateYaml(true)}\nTestResource2:\n . Type: AWS::Serverless::Api` testutil.toFile(bigYamlStr, tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const provided = await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder) assert.strictEqual(provided!.length, 1) }) it('returns one item if a template with one resource is in the workspace', async () => { testutil.toFile(makeSampleSamTemplateYaml(true), tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const provided = await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder) assert.notStrictEqual(provided, undefined) assert.strictEqual(provided!.length, 1) @@ -169,7 +169,7 @@ describe('SamDebugConfigurationProvider', async () => { resourceName: resources[0], })}\n${makeSampleYamlResource({ resourceName: resources[1] })}` testutil.toFile(bigYamlStr, tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const provided = await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder) assert.notStrictEqual(provided, undefined) if (provided) { @@ -195,9 +195,9 @@ describe('SamDebugConfigurationProvider', async () => { testutil.toFile(makeSampleSamTemplateYaml(true, { resourceName: resources[1] }), nestedYaml.fsPath) testutil.toFile(makeSampleSamTemplateYaml(true, { resourceName: badResourceName }), similarNameYaml.fsPath) - await registry.addTemplateToRegistry(tempFile) - await registry.addTemplateToRegistry(nestedYaml) - await registry.addTemplateToRegistry(similarNameYaml) + await ext.templateRegistry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(nestedYaml) + await ext.templateRegistry.addTemplateToRegistry(similarNameYaml) const provided = await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder) assert.notStrictEqual(provided, undefined) @@ -220,7 +220,7 @@ describe('SamDebugConfigurationProvider', async () => { console.log(bigYamlStr) testutil.toFile(bigYamlStr, tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const provided = await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder) assert.strictEqual(provided!.length, 2) assert.strictEqual(provided![1].invokeTarget.target, API_TARGET_TYPE) @@ -236,7 +236,7 @@ describe('SamDebugConfigurationProvider', async () => { console.log(bigYamlStr) testutil.toFile(bigYamlStr, tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const provided = await debugConfigProvider.provideDebugConfigurations(fakeWorkspaceFolder) assert.strictEqual(provided!.length, 1) }) @@ -246,7 +246,7 @@ describe('SamDebugConfigurationProvider', async () => { it('failure modes', async () => { const config = await getConfig( debugConfigProvider, - registry, + ext.templateRegistry, 'testFixtures/workspaceFolder/csharp2.1-plain-sam-app/' ) @@ -334,7 +334,7 @@ describe('SamDebugConfigurationProvider', async () => { }) it("returns undefined when resolving template debug configurations with a template that doesn't have the set resource", async () => { - await createAndRegisterYaml({}, tempFile, registry) + await createAndRegisterYaml({}, tempFile, ext.templateRegistry) const resolved = await debugConfigProvider.makeConfig( undefined, createFakeConfig({ templatePath: tempFile.fsPath }) @@ -343,7 +343,11 @@ describe('SamDebugConfigurationProvider', async () => { }) it('returns undefined when resolving template debug configurations with a resource that has an invalid runtime in template', async () => { - await createAndRegisterYaml({ resourceName, runtime: 'moreLikeRanOutOfTime' }, tempFile, registry) + await createAndRegisterYaml( + { resourceName, runtime: 'moreLikeRanOutOfTime' }, + tempFile, + ext.templateRegistry + ) const resolved = await debugConfigProvider.makeConfig( undefined, createFakeConfig({ @@ -359,7 +363,7 @@ describe('SamDebugConfigurationProvider', async () => { makeSampleSamTemplateYaml(true, { resourceName, runtime: 'moreLikeRanOutOfTime' }), tempFile.fsPath ) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const resolved = await debugConfigProvider.makeConfig(undefined, { type: AWS_SAM_DEBUG_TYPE, name: 'whats in a name', @@ -386,7 +390,7 @@ describe('SamDebugConfigurationProvider', async () => { it('supports workspace-relative template path ("./foo.yaml")', async () => { testutil.toFile(makeSampleSamTemplateYaml(true, { runtime: 'nodejs12.x' }), tempFile.fsPath) // Register with *full* path. - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) // Simulates launch.json: // "invokeTarget": { // "target": "./test.yaml", @@ -559,7 +563,7 @@ describe('SamDebugConfigurationProvider', async () => { }, } const templatePath = vscode.Uri.file(path.join(appDir, 'template.yaml')) - await registry.addTemplateToRegistry(templatePath) + await ext.templateRegistry.addTemplateToRegistry(templatePath) const actual = (await debugConfigProvider.makeConfig(folder, input))! const expected: SamLaunchRequestArgs = { @@ -804,7 +808,7 @@ describe('SamDebugConfigurationProvider', async () => { }, } const templatePath = vscode.Uri.file(path.join(appDir, 'template.yaml')) - await registry.addTemplateToRegistry(templatePath) + await ext.templateRegistry.addTemplateToRegistry(templatePath) const actual = (await debugConfigProvider.makeConfig(folder, input))! as DotNetCoreDebugConfiguration const codeRoot = `${appDir}/src/HelloWorld` const expectedCodeRoot = (actual.baseBuildDir ?? 'fail') + '/input' @@ -1084,7 +1088,7 @@ Outputs: }, } const templatePath = vscode.Uri.file(path.join(appDir, 'python3.7-plain-sam-app/template.yaml')) - await registry.addTemplateToRegistry(templatePath) + await ext.templateRegistry.addTemplateToRegistry(templatePath) // Invoke with noDebug=false (the default). const actual = (await debugConfigProvider.makeConfig(folder, input))! @@ -1266,7 +1270,7 @@ Outputs: }), tempFile.fsPath ) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const actual = (await debugConfigProvider.makeConfig(folder, input))! const tempDir = path.dirname(actual.codeRoot) @@ -1409,7 +1413,7 @@ Resources: }), tempFile.fsPath ) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) const actual = (await debugConfigProviderMockCredentials.makeConfig(folder, input))! const tempDir = path.dirname(actual.codeRoot) @@ -1662,18 +1666,17 @@ describe('createApiAwsSamDebugConfig', () => { }) describe('debugConfiguration', () => { - let registry: CloudFormationTemplateRegistry let tempFolder: string let tempFile: vscode.Uri beforeEach(async () => { tempFolder = await makeTemporaryToolkitFolder() tempFile = vscode.Uri.file(path.join(tempFolder, 'test.yaml')) - registry = CloudFormationTemplateRegistry.getRegistry() }) afterEach(async () => { await remove(tempFolder) + ext.templateRegistry.reset() }) it('getCodeRoot(), getHandlerName() with invokeTarget=code', async () => { @@ -1734,13 +1737,13 @@ describe('debugConfiguration', () => { // Template with relative path: testutil.toFile(makeSampleSamTemplateYaml(true, { codeUri: relativePath }), tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) assert.strictEqual(debugConfiguration.getCodeRoot(folder, config), fullPath) assert.strictEqual(debugConfiguration.getHandlerName(folder, config), 'handler') // Template with absolute path: testutil.toFile(makeSampleSamTemplateYaml(true, { codeUri: fullPath }), tempFile.fsPath) - await registry.addTemplateToRegistry(tempFile) + await ext.templateRegistry.addTemplateToRegistry(tempFile) assert.strictEqual(debugConfiguration.getCodeRoot(folder, config), fullPath) // Template with refs that don't override: @@ -1759,7 +1762,7 @@ describe('debugConfiguration', () => { }, }) testutil.toFile(makeSampleSamTemplateYaml(true, { codeUri: fullPath }, paramStr), tempFileRefs.fsPath) - await registry.addTemplateToRegistry(tempFileRefs) + await ext.templateRegistry.addTemplateToRegistry(tempFileRefs) assert.strictEqual(debugConfiguration.getCodeRoot(folder, fileRefsConfig), fullPath) assert.strictEqual(debugConfiguration.getHandlerName(folder, fileRefsConfig), 'handler') @@ -1786,7 +1789,7 @@ describe('debugConfiguration', () => { ), tempFileDefaultRefs.fsPath ) - await registry.addTemplateToRegistry(tempFileDefaultRefs) + await ext.templateRegistry.addTemplateToRegistry(tempFileDefaultRefs) assert.strictEqual(debugConfiguration.getCodeRoot(folder, fileDefaultRefsConfig), fullPath) assert.strictEqual(debugConfiguration.getHandlerName(folder, fileDefaultRefsConfig), 'thisWillOverride') @@ -1808,7 +1811,7 @@ describe('debugConfiguration', () => { makeSampleSamTemplateYaml(true, { codeUri: fullPath, handler: '!Ref override' }, paramStrNoDefaultOverride), tempFileOverrideRef.fsPath ) - await registry.addTemplateToRegistry(tempFileOverrideRef) + await ext.templateRegistry.addTemplateToRegistry(tempFileOverrideRef) assert.strictEqual(debugConfiguration.getCodeRoot(folder, fileOverrideRefConfig), fullPath) assert.strictEqual(debugConfiguration.getHandlerName(folder, fileOverrideRefConfig), 'override') })