Skip to content
Merged
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
31 changes: 30 additions & 1 deletion powershell/utils/tsp-host.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -66,13 +66,42 @@ 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;
}
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<string | undefined>(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');
Expand Down
Loading