diff --git a/powershell/utils/tsp-host.ts b/powershell/utils/tsp-host.ts index 5ff5c76c65..4fcdce1e55 100644 --- a/powershell/utils/tsp-host.ts +++ b/powershell/utils/tsp-host.ts @@ -1,5 +1,5 @@ import { Message } from '@autorest/extension-base'; -import { comment } from '@azure-tools/codegen'; +import { comment, safeEval } from '@azure-tools/codegen'; import { writeFileSync, existsSync, mkdirSync } from 'fs'; import { dirname } from 'path'; export interface TspWriteFileOptions { @@ -66,6 +66,8 @@ export class TspHostImpl implements TspHost { if (artifactType === 'binary-file') { writeFileSync(filename, Buffer.from(content, 'base64')); } else { + // Apply `transform` directives. + content = this.applyTransformDirectives(content, filename, artifactType); if (artifactType === 'source-file-csharp' && filename.endsWith('.cs')) { const header = comment('Copyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the MIT License. See License.txt in the project root for license information.\nChanges may cause incorrect behavior and will be lost if the code is regenerated.', '//'); content = header + '\n' + content; @@ -73,6 +75,33 @@ export class TspHostImpl implements TspHost { writeFileSync(filename, content); } } + + private applyTransformDirectives(content: string, filename: string, artifactType?: string): string { + if (!artifactType) { + return content; + } + const directives = this.configurations['directive']; + if (!directives) { + return content; + } + for (const directive of (Array.isArray(directives) ? directives : [directives])) { + if (!directive || !directive.transform) { + continue; + } + const from = directive.from; + const froms = from === undefined ? [] : (Array.isArray(from) ? from : [from]); + if (!froms.includes(artifactType)) { + continue; + } + // A transform may either `return` a new value or reassign `$` in place; fall back to `$` when nothing is returned. + const code = `(() => { let $ = __tsp_content__; const __tsp_ret__ = (() => { ${directive.transform}\n })(); return __tsp_ret__ === undefined ? $ : __tsp_ret__; })()`; + const result = safeEval(code, { __tsp_content__: content, $documentPath: filename }); + if (typeof result === 'string') { + content = result; + } + } + return content; + } UpdateConfigurationFile(filename: string, content: string): void { // Shall not be called throw new Error('Method UpdateConfigurationFile not implemented');