@microsoft.azure/autorest.incubator
Version:
AutoRest incubator project
489 lines • 37.5 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const schema_1 = require("../common/code-model/schema");
const dictionary_1 = require("../common/dictionary");
const text_manipulation_1 = require("../common/text-manipulation");
const access_modifier_1 = require("../csharp/code-dom/access-modifier");
const attribute_1 = require("../csharp/code-dom/attribute");
const class_1 = require("../csharp/code-dom/class");
const constructor_1 = require("../csharp/code-dom/constructor");
const expression_1 = require("../csharp/code-dom/expression");
const field_1 = require("../csharp/code-dom/field");
const method_1 = require("../csharp/code-dom/method");
const dotnet = require("../csharp/code-dom/mscorlib");
const namespace_1 = require("../csharp/code-dom/namespace");
const parameter_1 = require("../csharp/code-dom/parameter");
const property_1 = require("../csharp/code-dom/property");
const case_1 = require("../csharp/code-dom/statements/case");
const catch_1 = require("../csharp/code-dom/statements/catch");
const for_1 = require("../csharp/code-dom/statements/for");
const if_1 = require("../csharp/code-dom/statements/if");
const return_1 = require("../csharp/code-dom/statements/return");
const statement_1 = require("../csharp/code-dom/statements/statement");
const switch_1 = require("../csharp/code-dom/statements/switch");
const try_1 = require("../csharp/code-dom/statements/try");
const using_1 = require("../csharp/code-dom/statements/using");
const ternery_1 = require("../csharp/code-dom/ternery");
const variable_1 = require("../csharp/code-dom/variable");
const clientruntime_1 = require("../csharp/lowlevel-generator/clientruntime");
const method_2 = require("../csharp/lowlevel-generator/operation/method");
const model_cmdlet_1 = require("../powershell/model-cmdlet");
const powershell_declarations_1 = require("./powershell-declarations");
exports.PSCmdlet = new class_1.Class(new namespace_1.Namespace('System.Management.Automation'), 'PSCmdlet');
class CmdletClass extends class_1.Class {
constructor(namespace, operation, state, dropBodyParameter, objectInitializer) {
const variantName = `${operation.noun}_${operation.details.powershell.name}${dropBodyParameter ? 'Expanded' : ''}`;
const name = `${operation.verb}${variantName}`;
super(namespace, name, exports.PSCmdlet);
this.dropBodyParameter = dropBodyParameter ? true : false;
this.apply(objectInitializer);
this.interfaces.push(clientruntime_1.ClientRuntime.IEventListener);
this.state = state;
this.eventListener = new method_2.EventListener(new expression_1.LiteralExpression('this'), true);
// basic stuff
this.addCommonStuff();
this.add(new method_1.Method('BeginProcessing', dotnet.Void, {
override: access_modifier_1.Modifier.Override,
access: access_modifier_1.Access.Protected,
}));
// construct the class
this.addClassAttributes(operation, variantName);
this.addPowershellParameters(operation);
// implement IEventListener
this.implementIEventListener();
// add constructors
this.implementConstructors(operation);
// json serialization
this.implementSerialization(operation);
// processRecord
this.implementProcessRecord(operation);
this.implementProcessRecordAsync(operation);
}
addCommonStuff() {
// pipeline property
this.add(new property_1.Property('Pipeline', clientruntime_1.ClientRuntime.HttpPipeline, { getAccess: access_modifier_1.Access.Private, setAccess: access_modifier_1.Access.Private }));
// client API property (gs01: fill this in correctly)
const clientAPI = new dotnet.LibraryType(this.state.model.details.csharp.namespace, this.state.model.details.csharp.name);
this.add(new property_1.LambdaProperty('Client', clientAPI, new expression_1.LiteralExpression(`${this.state.project.serviceNamespace.moduleClass.declaration}.Instance.ClientAPI`)));
// Cmdlet Parameters for pipeline manipulations.
const prepend = this.add(new property_1.Property('HttpPipelinePrepend', clientruntime_1.ClientRuntime.SendAsyncStep, { attributes: [] }));
prepend.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `DontShow= true`, `HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline"`] }));
prepend.add(new attribute_1.Attribute(powershell_declarations_1.ValidateNotNull));
const append = this.add(new property_1.Property('HttpPipelineAppend', clientruntime_1.ClientRuntime.SendAsyncStep, { attributes: [] }));
append.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `DontShow= true`, `HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline"`] }));
append.add(new attribute_1.Attribute(powershell_declarations_1.ValidateNotNull));
const asjob = this.add(new property_1.Property('AsJob', powershell_declarations_1.SwitchParameter));
asjob.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `DontShow=true`, `HelpMessage = "Run the command as a job"`] }));
const proxyCredential = this.add(new property_1.Property('ProxyCredential', new dotnet.LibraryType('System.Management.Automation', 'PSCredential'), { attributes: [] }));
proxyCredential.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `DontShow= true`, `HelpMessage = "Credentials for a proxy server to use for the remote call"`] }));
proxyCredential.add(new attribute_1.Attribute(powershell_declarations_1.ValidateNotNull));
const useDefaultCreds = this.add(new property_1.Property('ProxyUseDefaultCredentials ', new dotnet.LibraryType('System.Management.Automation', 'SwitchParameter'), { attributes: [] }));
useDefaultCreds.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `DontShow= true`, `HelpMessage = "Use the default credentials for the proxy"`] }));
const proxyUri = this.add(new property_1.Property('Proxy ', dotnet.System.Uri, { attributes: [] }));
proxyUri.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `DontShow= true`, `HelpMessage = "The URI for the proxy server to use"`] }));
if (this.state.project.azure) {
const defaultProfile = this.add(new property_1.Property('DefaultProfile', dotnet.Object));
defaultProfile.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: ['Mandatory = false', `HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure."`] }));
defaultProfile.add(new attribute_1.Attribute(powershell_declarations_1.ValidateNotNull));
defaultProfile.add(new attribute_1.Attribute(powershell_declarations_1.Alias, { parameters: ['"AzureRMContext"', '"AzureCredential"'] }));
}
this.add(new method_1.Method('StopProcessing', dotnet.Void, { access: access_modifier_1.Access.Protected, override: access_modifier_1.Modifier.Override })).add(function* () {
yield `Cancel();`;
yield `base.StopProcessing();`;
});
this.add(new method_1.Method('EndProcessing', dotnet.Void, { access: access_modifier_1.Access.Protected, override: access_modifier_1.Modifier.Override })).add(function* () {
// gs01: remember what you were doing here to make it so these can be parallelized...
yield '';
});
}
isWritableCmdlet(operation) {
switch (operation.callGraph[0].method.toLowerCase()) {
case 'put':
case 'post':
case 'delete':
case 'patch':
return true;
}
return false;
}
implementProcessRecord(operation) {
const $this = this;
const writable = this.isWritableCmdlet(operation);
this.add(new method_1.Method('ProcessRecord', undefined, { access: access_modifier_1.Access.Protected, override: access_modifier_1.Modifier.Override })).add(function* () {
yield $this.eventListener.syncSignal(powershell_declarations_1.Events.CmdletProcessRecordStart);
yield try_1.Try(function* () {
yield `// work`;
const normal = new statement_1.Statements(function* () {
const acr = new variable_1.LocalVariable('asyncCommandRuntime', dotnet.Var, { initializer: powershell_declarations_1.AsyncCommandRuntime.newInstance(dotnet.This, $this.cancellationToken) });
yield using_1.Using(acr.declarationExpression, function* () {
yield `${acr}.Wait( ProcessRecordAsync(),${$this.cancellationToken});`;
});
});
const work = operation.asjob ? function* () {
yield if_1.If(`true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")`, function* () {
// clone the cmdlet instance, since the instance can be reused and overwrite data.
const instance = new variable_1.LocalVariable(`instance`, dotnet.Var, { initializer: `this.Clone()` });
yield instance.declarationStatement;
// create the job (which will set the CommandRuntime of the clone to the AsyncJob itself)
const job = new variable_1.LocalVariable('job', dotnet.Var, { initializer: powershell_declarations_1.AsyncJob.newInstance(instance, 'this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token', 'this._cancellationTokenSource.Cancel') });
yield job.declarationStatement;
// add the job to the repository
yield `JobRepository.Add(${job});`;
// invoke the cmdlet's PRA
const task = new variable_1.LocalVariable(`task`, dotnet.Var, { initializer: `${instance}.ProcessRecordAsync()` });
yield task.declarationStatement;
// have the AsyncJob monitor the lifetime of the Task
yield `${job}.Monitor(${task});`;
// return the job to the user now.
yield `WriteObject(${job});`;
});
yield if_1.Else(normal);
} : normal;
if (writable) {
yield if_1.If(`ShouldProcess($"Call remote '${operation.callGraph[0].details.default.name}' operation")`, work);
}
else {
yield work;
}
});
const aggregateException = new parameter_1.Parameter('aggregateException', dotnet.System.AggregateException);
yield catch_1.Catch(aggregateException, function* () {
yield `// unroll the inner exceptions to get the root cause`;
yield for_1.ForEach('innerException', new expression_1.LiteralExpression(`${aggregateException.use}.Flatten().InnerExceptions`), function* () {
yield $this.eventListener.syncSignal(powershell_declarations_1.Events.CmdletException, new expression_1.LiteralExpression(`$"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}"`));
yield `// Write exception out to error channel.`;
yield `WriteError( new ${powershell_declarations_1.ErrorRecord}(innerException,string.Empty, ${powershell_declarations_1.ErrorCategory('NotSpecified')}, null) );`;
});
});
const exception = new parameter_1.Parameter('exception', dotnet.System.Exception);
yield catch_1.Catch(exception, function* () {
yield $this.eventListener.syncSignal(powershell_declarations_1.Events.CmdletException, new expression_1.LiteralExpression(`$"{${exception.use}.GetType().Name} - {${exception.use}.Message} : {${exception.use}.StackTrace}"`));
yield `// Write exception out to error channel.`;
yield `WriteError( new ${powershell_declarations_1.ErrorRecord}(${exception.use},string.Empty, ${powershell_declarations_1.ErrorCategory('NotSpecified')}, null) );`;
});
});
}
implementProcessRecordAsync(operation) {
const $this = this;
this.add(new method_1.Method('ProcessRecordAsync', dotnet.System.Threading.Tasks.Task(), { access: access_modifier_1.Access.Protected, async: access_modifier_1.Modifier.Async })).add(function* () {
// construct the call to the operation
yield $this.eventListener.signal(powershell_declarations_1.Events.CmdletGetPipeline);
// const pipeline = new LocalVariable('pipeline', dotnet.Var, { initializer: new LiteralExpression(`${$this.state.project.serviceNamespace.moduleClass.declaration}.Instance.CreatePipeline(this.MyInvocation.BoundParameters)`) });
const pipeline = $this.$('Pipeline');
yield pipeline.assign(new expression_1.LiteralExpression(`${$this.state.project.serviceNamespace.moduleClass.declaration}.Instance.CreatePipeline(this.MyInvocation.BoundParameters)`));
yield pipeline.invokeMethod('Prepend', $this.$('HttpPipelinePrepend'));
yield pipeline.invokeMethod('Append', $this.$('HttpPipelineAppend'));
yield `// get the client instance`;
const apiCall = operation.callGraph[0];
// find each parameter to the method, and find out where the value is going to come from.
const operationParameters = dictionary_1.values(apiCall.parameters).linq.select(p => {
return dictionary_1.values($this.properties).linq.where(each => each.metadata.parameterDefinition).linq.first(each => each.metadata.parameterDefinition === p);
}).linq.select(each => each ? each : new expression_1.LiteralExpression('null')).linq.toArray();
// is there a body parameter we should include?
const requestBody = apiCall.requestBody;
if (requestBody) {
// we have a body parameter.
const bodyParameter = dictionary_1.values($this.properties).linq.where(each => each.metadata.parameterDefinition).linq.first(each => each.metadata.parameterDefinition.schema === requestBody.schema);
if (bodyParameter) {
operationParameters.push(bodyParameter);
}
}
// how many inputs is the api expecting
const inputParameters = operationParameters.length;
// create the response handlers
const responses = [...dictionary_1.values(apiCall.responses_new).linq.selectMany(each => each)];
const callbackMethods = dictionary_1.values(responses).linq.toArray().map(each => new expression_1.LiteralExpression(each.details.csharp.name));
// make callback methods
for (const each of dictionary_1.values(responses)) {
const responseParameter = new parameter_1.Parameter('response', new dotnet.LibraryType(clientruntime_1.ClientRuntime, each.details.csharp.type));
const responseMethod = new method_1.Method(`${each.details.csharp.name}`, dotnet.System.Threading.Tasks.Task(), { access: access_modifier_1.Access.Private, parameters: [responseParameter], async: access_modifier_1.Modifier.Async });
responseMethod.add(function* () {
if (each.details.csharp.isErrorResponse) {
// this should write an error to the error channel.
yield `// Error Response : ${each.responseCode} `;
if (each.schema) {
// the schema should be the error information.
const props = schema_1.getAllProperties(each.schema);
const codeProp = dictionary_1.values(props).linq.first(p => p.details.csharp.name === 'Code');
const messageProp = dictionary_1.values(props).linq.first(p => p.details.csharp.name === 'Message');
if (codeProp && messageProp) {
yield `var code = (await response.Result).${codeProp.details.csharp.name};`;
yield `var message = (await response.Result).${messageProp.details.csharp.name};`;
yield `WriteError(new System.Management.Automation.ErrorRecord(new System.Exception($"[{code}] : {message}"), code.ToString(System.Globalization.CultureInfo.InvariantCulture), System.Management.Automation.ErrorCategory.InvalidOperation, new { ${operationParameters.join(',')}}));`;
return;
}
else {
yield new variable_1.LocalVariable('responseMessage', dotnet.Var, { initializer: `response.ResponseMessage as System.Net.Http.HttpResponseMessage` });
// what do we do with the response object?
yield `WriteError(new System.Management.Automation.ErrorRecord(new System.Exception($"The service encountered an unexpected result: {responseMessage.StatusCode}"), responseMessage.StatusCode.ToString(System.Globalization.CultureInfo.InvariantCulture), System.Management.Automation.ErrorCategory.InvalidOperation, new { ${operationParameters.filter(e => expression_1.valueOf(e) !== 'null').join(',')}}));`;
return;
}
}
else {
yield new variable_1.LocalVariable('responseMessage', dotnet.Var, { initializer: `response.ResponseMessage as System.Net.Http.HttpResponseMessage` });
// all we know is that this was an error, and we can't proceed.
yield `WriteError(new System.Management.Automation.ErrorRecord(new System.Exception($"The service encountered an unexpected result: {responseMessage.StatusCode}"), responseMessage.StatusCode.ToString(System.Globalization.CultureInfo.InvariantCulture), System.Management.Automation.ErrorCategory.InvalidOperation, new { ${operationParameters.filter(e => expression_1.valueOf(e) !== 'null').join(',')}}));`;
return;
}
}
yield `// ${each.details.csharp.name} - response for ${each.responseCode} / ${each.mimeTypes.join('/')}`;
if (each.schema) {
const schema = each.schema;
if (apiCall.details.csharp.pageable) {
const pageable = apiCall.details.csharp.pageable;
yield `// response should be returning an array of some kind. +Pageable`;
yield `// ${pageable.responseType} / ${pageable.itemName || '<none>'} / ${pageable.nextLinkName || '<none>'}`;
switch (pageable.responseType) {
// the result is (or works like a x-ms-pageable)
case `pageable`:
case `nested-array`:
const valueProperty = schema.properties[pageable.itemName];
const nextLinkProperty = schema.properties[pageable.nextLinkName];
if (valueProperty && nextLinkProperty) {
// it's pageable!
const result = new variable_1.LocalVariable('result', dotnet.Var, { initializer: new expression_1.LiteralExpression(`await response.Result`) });
yield result.declarationStatement;
// write out the current contents
yield `WriteObject(${result.value}.${valueProperty.details.csharp.name},true);`;
const nextLinkName = `${result.value}.${nextLinkProperty.details.csharp.name}`;
yield (if_1.If(`${nextLinkName} != null`, if_1.If(`response.RequestMessage is System.Net.Http.HttpRequestMessage req `, function* () {
yield `req = req.Clone(new System.Uri( ${nextLinkName} ),Microsoft.Rest.ClientRuntime.Method.Get );`;
yield $this.eventListener.signal(powershell_declarations_1.Events.FollowingNextLink);
yield `await this.${$this.$('Client').invokeMethod(apiCall.details.csharp.name, ...[...operationParameters, ...callbackMethods, dotnet.This, pipeline]).implementation}`;
})));
return;
}
else if (valueProperty) {
// it's just a nested array
yield `WriteObject((await response.Result).${valueProperty.details.csharp.name}, true);`;
return;
}
break;
// it's just an array,
case `array`:
// just write-object(enumerate) with the output
yield `WriteObject(await response.Result, true);`;
return;
}
// ok, let's see if the response type
}
// we expect to get back some data from this call.
yield `// (await response.Result) // should be ${$this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(schema, true, $this.state).declaration}`;
const props = schema_1.getAllProperties(schema);
if (props.length === 1) {
// let's unroll this and write out the single property
yield `WriteObject((await response.Result).${props[0].details.csharp.name});`;
return;
}
// more than one property, let's just return the result object
yield `WriteObject(await response.Result);`;
return;
}
// no return type. Let's just return ... true?
yield `WriteObject(true);`;
});
$this.add(responseMethod);
}
// make the call.
yield $this.eventListener.signal(powershell_declarations_1.Events.CmdletBeforeAPICall);
yield `await this.${$this.$('Client').invokeMethod(apiCall.details.csharp.name, ...[...operationParameters, ...callbackMethods, dotnet.This, pipeline]).implementation}`;
yield $this.eventListener.signal(powershell_declarations_1.Events.CmdletAfterAPICall);
});
}
implementSerialization(operation) {
const $this = this;
// set up the declaration for the toJson method.
const container = new parameter_1.Parameter('container', clientruntime_1.ClientRuntime.JsonObject);
const mode = new parameter_1.Parameter('serializationMode', clientruntime_1.ClientRuntime.SerializationMode);
const toJsonMethod = this.add(new method_1.Method('ToJson', clientruntime_1.ClientRuntime.JsonNode, {
parameters: [container, mode],
}));
toJsonMethod.add(function* () {
yield `// serialization method`;
yield `container = ${container.use} ?? new ${clientruntime_1.ClientRuntime.JsonObject.declaration}();`;
for (const parameter of dictionary_1.values(operation.parameters)) {
const td = $this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(parameter.schema, parameter.required, $this.state);
if (!(parameter.details.default.constantValue)) {
// yield td.getSerializeStatement(KnownMediaType.Json, container.use, parameter.details.powershell.name, parameter.details.powershell.name);
}
}
// yield `bool returnNow = false;`;
// yield `${$this.btj.name}(ref result, ref returnNow);`;
// yield If({ value: `returnNow` }, `return result;`);
// yield `${$this.atj.name}(ref result);`;
yield `return container;`;
});
// create the FromJson method
const node = new parameter_1.Parameter('node', clientruntime_1.ClientRuntime.JsonNode);
const fromJson = this.addMethod(new method_1.Method('FromJson', this, { parameters: [node], static: access_modifier_1.Modifier.Static }));
fromJson.add(function* () {
const json = expression_1.IsDeclaration(node, clientruntime_1.ClientRuntime.JsonObject, 'json');
yield return_1.Return(ternery_1.Ternery(json.check, $this.newInstance(json), dotnet.Null));
});
// from/to json-string
const strJson = new parameter_1.Parameter('jsonText', dotnet.String);
this.add(new method_1.LambdaMethod('FromJsonString', this, new expression_1.LiteralExpression(`string.IsNullOrEmpty(${strJson.value}) ? null : ${fromJson.invoke(new expression_1.LiteralExpression(`Carbon.Json.JsonObject.Parse(${strJson.value})`)).value}`), { parameters: [strJson], static: access_modifier_1.Modifier.Static }));
// clone
const clone = this.add(new method_1.Method('Clone', this));
clone.add(function* () {
const i = new variable_1.LocalVariable('clone', dotnet.Var, {
initializer: fromJson.invoke(new expression_1.LiteralExpression(`this.${toJsonMethod.invoke(dotnet.Null, clientruntime_1.ClientRuntime.SerializationMode.IncludeAll).value}`))
});
yield i.declarationStatement;
yield `${i.value}.HttpPipelinePrepend = this.HttpPipelinePrepend;`;
yield `${i.value}.HttpPipelineAppend = this.HttpPipelineAppend;`;
yield return_1.Return(i);
});
}
implementConstructors(operation) {
const $this = this;
// default constructor
this.add(new constructor_1.Constructor(this));
// deserialization constructor
const deserializerConstructor = this.add(new constructor_1.Constructor(this, { parameters: [new parameter_1.Parameter('json', clientruntime_1.ClientRuntime.JsonObject)], access: access_modifier_1.Access.Internal }));
deserializerConstructor.add(function* () {
yield `// deserialize the contents`;
for (const parameter of dictionary_1.values(operation.parameters)) {
const td = $this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(parameter.schema, parameter.required, $this.state);
const bp = $this.$(parameter.details.powershell.name);
if (!(parameter.details.default.constantValue)) {
// dont' serialize if it's a constant or host parameter.
// yield td.getDeserializePropertyStatement(KnownMediaType.Json, 'json', bp.backingName, parameter.details.powershell.name);
}
}
});
}
implementIEventListener() {
const $this = this;
const cts = this.add(new field_1.InitializedField('_cancellationTokenSource', dotnet.System.Threading.CancellationTokenSource, new expression_1.LiteralExpression(`new ${dotnet.System.Threading.CancellationTokenSource.declaration}()`), { access: access_modifier_1.Access.Private }));
this.cancellationToken = this.add(new property_1.LambdaProperty('Token', dotnet.System.Threading.CancellationToken, new expression_1.LiteralExpression(`${cts.value}.Token`)));
this.add(new property_1.LambdaProperty('Cancel', dotnet.System.Action(), new expression_1.LiteralExpression(`${cts.value}.Cancel`)));
const id = new parameter_1.Parameter('id', dotnet.String);
const token = new parameter_1.Parameter('token', dotnet.System.Threading.CancellationToken);
const messageData = new parameter_1.Parameter('messageData', dotnet.System.Func(clientruntime_1.ClientRuntime.EventData));
this.add(new method_1.Method('Signal', dotnet.System.Threading.Tasks.Task(), { async: access_modifier_1.Modifier.Async, parameters: [id, token, messageData] })).add(function* () {
yield if_1.If(`${token.value}.IsCancellationRequested`, return_1.Return());
yield switch_1.Switch(id, [
case_1.TerminalCase(powershell_declarations_1.Events.Verbose.value, function* () {
yield `WriteVerbose($"{messageData().Message ?? ""}");`;
yield return_1.Return();
}),
case_1.TerminalCase(powershell_declarations_1.Events.Warning.value, function* () {
yield `WriteWarning($"{messageData().Message ?? ""}");`;
yield return_1.Return();
}),
case_1.TerminalCase(powershell_declarations_1.Events.Information.value, function* () {
const data = new variable_1.LocalVariable('data', dotnet.Var, { initializer: new expression_1.LiteralExpression(`${messageData.use}()`) });
yield data.declarationStatement;
yield `WriteInformation(data, new[] { data.Message });`;
yield return_1.Return();
}),
case_1.TerminalCase(powershell_declarations_1.Events.Debug.value, function* () {
yield `WriteDebug($"{messageData().Message ?? ""}");`;
yield return_1.Return();
}),
case_1.TerminalCase(powershell_declarations_1.Events.Error.value, function* () {
yield `WriteError(new System.Management.Automation.ErrorRecord( new System.Exception(messageData().Message), string.Empty, System.Management.Automation.ErrorCategory.NotSpecified, null ) );`;
yield return_1.Return();
}),
]);
if ($this.state.project.azure) {
yield `await ${$this.state.project.serviceNamespace.moduleClass.declaration}.Instance.Signal(${id.value}, ${token.value}, ${messageData.value}, (i,t,m)=> Signal(i,t,()=> Microsoft.Rest.ClientRuntime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Rest.ClientRuntime.EventData ) );`;
yield if_1.If(`${token.value}.IsCancellationRequested`, return_1.Return());
}
yield `WriteDebug($"{id}: {messageData().Message ?? ""}");`;
// any handling of the signal on our side...
});
}
addPowershellParameters(operation) {
for (const parameter of dictionary_1.values(operation.parameters)) {
// these are the parameters that this command expects
// create a single
const td = this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(parameter.schema, parameter.required, this.state);
if (parameter.details.default.constantValue) {
// this parameter has a constant value
// don't give it a parameter attribute
const cmdletParameter = this.add(new property_1.LambdaProperty(parameter.details.powershell.name, td, new expression_1.StringExpression(parameter.details.default.constantValue), {
metadata: {
parameterDefinition: parameter
},
}));
}
else if (parameter.details.default.fromHost) {
// the parameter is expected to be gotten from the host.
const cmdletParameter = this.add(new property_1.BackedProperty(parameter.details.powershell.name, td, {
metadata: {
parameterDefinition: parameter.details.default.originalParam
},
}));
this.$('BeginProcessing').add(cmdletParameter.assignPrivate(new expression_1.LiteralExpression(`${this.state.project.serviceNamespace.moduleClass.declaration}.Instance.GetParameter(this.MyInvocation.BoundParameters, "${parameter.name}") as string`)));
// in the BeginProcessing, we should tell it to go get the value for this property from the common module
}
else if (this.dropBodyParameter && parameter.details.powershell.isBodyParameter) {
// we're supposed to use parameters for the body parameter instead of a big object
const cmdletParameter = this.add(new property_1.BackedProperty(parameter.details.powershell.name, td, {
metadata: {
parameterDefinition: parameter
},
initializer: `new ${parameter.schema.details.csharp.fullname}()`
}));
model_cmdlet_1.addPowershellParameters(this, parameter.schema, cmdletParameter);
}
else {
// regular cmdlet parameter
const cmdletParameter = this.add(new property_1.BackedProperty(parameter.details.powershell.name, td, {
metadata: {
parameterDefinition: parameter
}
}));
if (!parameter.details.powershell.isBodyParameter) {
cmdletParameter.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: [new expression_1.LiteralExpression('Mandatory = true'), new expression_1.LiteralExpression(`HelpMessage = "${text_manipulation_1.escapeString(parameter.details.powershell.description) || 'HELP MESSAGE MISSING'}"`)] }));
}
else {
cmdletParameter.add(new attribute_1.Attribute(powershell_declarations_1.ParameterAttribute, { parameters: [new expression_1.LiteralExpression('Mandatory = true'), new expression_1.LiteralExpression(`HelpMessage = "${text_manipulation_1.escapeString(parameter.details.powershell.description) || 'HELP MESSAGE MISSING'}"`), new expression_1.LiteralExpression('ValueFromPipeline = true')] }));
}
}
}
}
addClassAttributes(operation, variantName) {
if (this.isWritableCmdlet(operation)) {
// add should process
this.add(new attribute_1.Attribute(powershell_declarations_1.CmdletAttribute, { parameters: [powershell_declarations_1.verbEnum(operation.category, operation.verb), new expression_1.StringExpression(variantName), `SupportsShouldProcess = true`] }));
}
else {
this.add(new attribute_1.Attribute(powershell_declarations_1.CmdletAttribute, { parameters: [powershell_declarations_1.verbEnum(operation.category, operation.verb), new expression_1.StringExpression(variantName)] }));
}
const rt = new dictionary_1.Dictionary();
for (const op of dictionary_1.values(operation.callGraph)) {
/* testing
for (const schema of
values(operation.callGraph).linq
.selectMany(httpOperation => items(httpOperation.responses)).linq
.where(each => each.key !== 'default').linq
.select(each => each.value).linq
.selectMany(response => values(response.content)).linq
.distinct(mediaType => mediaType.schema).linq
.selectNonNullable(mediaType => mediaType.schema)) {
console.error(`it is ${schema.details.csharp.name}`);
}
*/
for (const item of dictionary_1.items(op.responses_new).linq.where(each => each.key !== 'default')) {
for (const schema of dictionary_1.values(item.value).linq.selectNonNullable(each => each.schema)) {
const props = schema_1.getAllProperties(schema);
// does the target type just wrap a single output?
const td = props.length !== 1 ?
this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(schema, true, this.state) :
this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(props[0].schema, true, this.state);
if (td) {
if (!rt[td.declaration]) {
rt[td.declaration] = true;
this.add(new attribute_1.Attribute(powershell_declarations_1.OutputTypeAttribute, { parameters: [{ value: `typeof(${td.declaration})` }] }));
}
}
}
}
}
}
}
exports.CmdletClass = CmdletClass;
//# sourceMappingURL=cmdlet-class.js.map