diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/ConvertTo-Json.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/ConvertTo-Json.ps1 deleted file mode 100644 index cf6f9fb1b6cc..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/ConvertTo-Json.ps1 +++ /dev/null @@ -1,124 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -param( - [Parameter(Mandatory = $true)] - $inputObject = $null, - - [Parameter(Mandatory = $false)] - [bool]$compress = $false, - - [Parameter(Mandatory = $false)] - [int]$depth = 1000 -) - -if ($compress) -{ - $jsonText = ConvertTo-Json -Depth $depth -InputObject $inputObject -Compress; -} -else -{ - $jsonText = ConvertTo-Json -Depth $depth -InputObject $inputObject; - - # Re-format the JSON text - [string]$newJsonText = ""; - [int]$indent = 0; - $startQuote = $true; - $semiColon = $false; - for ($i = 0; $i -lt $jsonText.Length; $i++) - { - [char]$ch = $jsonText[$i]; - if ($ch -eq "[") - { - if ($semiColon -ne $true) - { - $newJsonText += " " * $indent; - } - - $newJsonText += $ch; - $indent += 2; - } - elseif ($ch -eq "]") - { - $indent -= 2; - $newJsonText += " " * $indent; - $newJsonText += $ch; - } - elseif ($ch -eq "{") - { - if ($semiColon -ne $true) - { - $newJsonText += " " * $indent; - } - - $newJsonText += $ch; - $indent += 2; - } - elseif ($ch -eq "}") - { - $indent -= 2; - $newJsonText += " " * $indent; - $newJsonText += $ch; - } - elseif ($ch -eq " " -or $ch -eq "`t") - { - # Skip Space Characters - } - elseif ($ch -eq "`"") - { - if ($startQuote -eq $true) - { - if ($semiColon -ne $true) - { - $newJsonText += " " * $indent; - } - - $startQuote = $false; - } - else - { - $startQuote = $true; - } - - $newJsonText += $ch; - } - else - { - $newJsonText += $ch; - } - - # Track Semicolon - if ($ch -eq ":") - { - $semiColon = $true; - } - elseif ($ch -ne " ") - { - $semiColon = $false; - } - } - - $jsonText = $newJsonText.Replace("`r`n`r`n", "`r`n"); -} - -# Change the JSON fields to use lower cases, e.g. {"Say":"Hello World!"} => {"say":"Hello World!"} -$lowerCaseJsonText = $jsonText; -$letterA = [int]([char]'A'); -for ($i = 0; $i -lt 26; $i++) -{ - $ch = [char]($letterA + $i); - $lowerCaseJsonText = $lowerCaseJsonText.Replace("`"" + $ch, "`"" + "$ch".ToLower()); -} - -Write-Output $lowerCaseJsonText; diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Create-ParameterObject.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Create-ParameterObject.ps1 deleted file mode 100644 index 94b944b51ff2..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Create-ParameterObject.ps1 +++ /dev/null @@ -1,137 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -[CmdletBinding(DefaultParameterSetName = "ByTypeInfo")] -param -( - [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ByTypeInfo')] - [System.Type]$TypeInfo = $null, - - [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ByFullTypeNameAndDllPath')] - [string]$TypeFullName = $null, - - [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByFullTypeNameAndDllPath')] - [string]$DllFullPath = $null -) - -function Create-ParameterObjectImpl -{ - param - ( - [Parameter(Mandatory = $true)] - [System.Type]$typeInfo, - - [Parameter(Mandatory = $true)] - [System.Collections.Hashtable]$typeList - ) - - if ([string]::IsNullOrEmpty($typeInfo.FullName) -or $typeList.ContainsKey($typeInfo.FullName)) - { - return $null; - } - - if ($typeInfo.FullName -like "Microsoft.*Azure.Management.*.*" -and (-not ($typeInfo.FullName -like "Microsoft.*Azure.Management.*.SubResource"))) - { - $st = $typeList.Add($typeInfo.FullName, $typeInfo); - } - - if ($typeInfo.FullName -eq 'System.String' -or $typeInfo.FullName -eq 'string') - { - $obj = ''; - } - elseif ($typeInfo.FullName -eq 'System.Uri') - { - $obj = '' -as 'System.Uri'; - } - elseif ($typeInfo.FullName -eq 'System.Boolean') - { - $obj = $false; - } - elseif ($typeInfo.FullName -eq 'System.Int32') - { - $obj = 0; - } - elseif ($typeInfo.FullName -eq 'System.UInt32') - { - $obj = 0; - } - elseif ($typeInfo.FullName -eq 'System.Byte[]') - { - $obj = New-Object -TypeName System.Byte[] -ArgumentList 0; - } - elseif ($typeInfo.FullName -like 'System.Collections.Generic.IList*' -or $typeInfo.FullName -like 'System.Collections.Generic.List*') - { - [System.Type]$itemType = $typeInfo.GetGenericArguments()[0]; - $itemObj = Create-ParameterObjectImpl $itemType $typeList; - - $typeName = "System.Collections.Generic.List[" + $itemType.FullName + "]"; - $listObj = New-Object -TypeName $typeName; - $listObj.Add($itemObj); - - $obj = $listObj; - } - elseif ($typeInfo.FullName -like 'System.Collections.Generic.IDictionary*') - { - # Dictionary in client library always consists of string key & values. - $obj = New-Object 'System.Collections.Generic.Dictionary[string,string]'; - } - elseif ($typeInfo.FullName -like 'System.Nullable*') - { - $obj = $null; - } - else - { - $obj = New-Object $typeInfo.FullName; - - foreach ($item in $typeInfo.GetProperties()) - { - $prop = [System.Reflection.PropertyInfo]$item; - - if (-not ($prop.CanWrite)) - { - continue; - } - - if ($prop.PropertyType.IsGenericType -and $prop.PropertyType.FullName -like 'System.Collections.Generic.*List*') - { - [System.Type]$itemType = $prop.PropertyType.GetGenericArguments()[0]; - $itemObj = Create-ParameterObjectImpl $itemType $typeList; - $listTypeName = "System.Collections.Generic.List[" + $itemType.FullName + "]"; - - $propObjList = New-Object -TypeName $listTypeName; - $st = $propObjList.Add($itemObj); - - $st = $prop.SetValue($obj, $propObjList -as $listTypeName); - } - else - { - $propObj = Create-ParameterObjectImpl $prop.PropertyType $typeList; - $st = $prop.SetValue($obj, $propObj); - } - } - } - - $st = $typeList.Remove($typeInfo.FullName); - - return $obj; -} - -if (($TypeFullName -ne $null) -and ($TypeFullName.Trim() -ne '')) -{ - . "$PSScriptRoot\Import-AssemblyFunction.ps1"; - $dll = Load-AssemblyFile $DllFullPath; - $TypeInfo = $dll.GetType($TypeFullName); -} - -Write-Output (Create-ParameterObjectImpl $TypeInfo @{}); \ No newline at end of file diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Create-ParameterTree.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Create-ParameterTree.ps1 deleted file mode 100644 index 9968751c7ae8..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Create-ParameterTree.ps1 +++ /dev/null @@ -1,194 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -[CmdletBinding(DefaultParameterSetName = "ByTypeInfo")] -param -( - [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ByTypeInfo')] - [System.Type]$TypeInfo = $null, - - [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ByFullTypeNameAndDllPath')] - [string]$TypeFullName = $null, - - [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByFullTypeNameAndDllPath')] - [string]$DllFullPath = $null, - - [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByTypeInfo')] - [Parameter(Mandatory = $true, Position = 2, ParameterSetName = 'ByFullTypeNameAndDllPath')] - [string]$NameSpace, - - [Parameter(Mandatory = $false, Position = 2, ParameterSetName = 'ByTypeInfo')] - [Parameter(Mandatory = $false, Position = 3, ParameterSetName = 'ByFullTypeNameAndDllPath')] - [string]$ParameterName = $null -) - -. "$PSScriptRoot\Import-TypeFunction.ps1"; - -function New-ParameterTreeNode -{ - param ([string]$Name, [System.Type]$TypeInfo, $Parent) - - $node = New-Object PSObject; - $node | Add-Member -Type NoteProperty -Name Name -Value $Name; - $node | Add-Member -Type NoteProperty -Name TypeInfo -Value $TypeInfo; - $node | Add-Member -Type NoteProperty -Name Parent -Value $Parent; - $node | Add-Member -Type NoteProperty -Name IsListItem -Value $false; - $node | Add-Member -Type NoteProperty -Name AllStrings -Value $false; - $node | Add-Member -Type NoteProperty -Name OneStringList -Value $false; - $node | Add-Member -Type NoteProperty -Name OnlySimple -Value $false; - $node | Add-Member -Type NoteProperty -Name Properties -Value @(); - $node | Add-Member -Type NoteProperty -Name SubNodes -Value @(); - $node | Add-Member -Type NoteProperty -Name IsPrimitive -Value $false; - $node | Add-Member -Type NoteProperty -Name IsReference -Value $false; - - return $node; -} - -function Create-ParameterTreeImpl -{ - param( - [Parameter(Mandatory = $false)] - [string]$ParameterName = $null, - - [Parameter(Mandatory = $true)] - [System.Type]$TypeInfo, - - [Parameter(Mandatory = $true)] - [System.Collections.Hashtable]$TypeList, - - [Parameter(Mandatory = $false)] - $Parent = $null, - - [Parameter(Mandatory = $false)] - [int]$Depth = 0 - ) - - if ([string]::IsNullOrEmpty($TypeInfo.FullName)) - { - return $null; - } - - if (-not $TypeInfo.FullName.StartsWith($NameSpace + ".")) - { - $node = New-ParameterTreeNode $ParameterName $TypeInfo $Parent; - return $node; - } - else - { - if ($TypeList.ContainsKey($TypeInfo.FullName)) - { - $treeNode = New-ParameterTreeNode $ParameterName $TypeInfo $Parent; - $treeNode.IsReference = $true; - return $treeNode; - } - else - { - if ($TypeInfo.FullName -like "Microsoft.*Azure.Management.*.*" -and (-not ($typeInfo.FullName -like "Microsoft.*Azure.Management.*.SubResource"))) - { - $TypeList.Add($TypeInfo.FullName, $TypeInfo); - } - - $treeNode = New-ParameterTreeNode $ParameterName $TypeInfo $Parent; - if (Contains-OnlyStringFields $TypeInfo) - { - $treeNode.AllStrings = $true; - } - elseif (Contains-OnlyStringList $TypeInfo) - { - $treeNode.OneStringList = $true; - } - - if (Contains-OnlySimpleFields $TypeInfo $NameSpace) - { - $treeNode.OnlySimple = $true; - } - - $padding = ($Depth.ToString() + (' ' * (4 * ($Depth + 1)))); - if ($Depth -gt 0) - { - Write-Verbose ($padding + "-----------------------------------------------------------"); - } - - if ($treeNode.AllStrings) - { - $annotation = " *"; - } - elseif ($treeNode.OneStringList) - { - $annotation = " ^"; - } - - Write-Verbose ($padding + "[ Node ] " + $treeNode.Name + $annotation); - Write-Verbose ($padding + "[Parent] " + $Parent.Name); - - foreach ($item in $TypeInfo.GetProperties()) - { - $itemProp = [System.Reflection.PropertyInfo]$item; - $can_write = ($itemProp.GetSetMethod() -ne $null) -and $itemProp.CanWrite; - $nodeProp = @{ Name = $itemProp.Name; Type = $itemProp.PropertyType; CanWrite = $can_write}; - $treeNode.Properties += $nodeProp; - - if ($itemProp.PropertyType.FullName.StartsWith($NameSpace + ".")) - { - # Model Class Type - Recursive Call - $subTreeNode = Create-ParameterTreeImpl $itemProp.Name $itemProp.PropertyType $TypeList $treeNode ($Depth + 1); - if ($subTreeNode -ne $null) - { - $treeNode.SubNodes += $subTreeNode; - } - } - elseif ($itemProp.PropertyType.FullName.StartsWith("System.Collections.Generic.IList")) - { - # List Type - $listItemType = $itemProp.PropertyType.GenericTypeArguments[0]; - if ($TypeList.ContainsKey($listItemType.FullName)) - { - $refSuffix = "`'"; - } - Write-Verbose ($padding + '-' + $itemProp.Name + ' : [List] ' + $listItemType.Name + $refSuffix); - - # ListItem is Model Class Type - Recursive Call - $subTreeNode = Create-ParameterTreeImpl $itemProp.Name $listItemType $TypeList $treeNode ($Depth + 1) - if ($subTreeNode -ne $null) - { - $subTreeNode.IsListItem = $true; - $treeNode.SubNodes += $subTreeNode; - } - } - else - { - if ($nodeProp["Type"].IsEquivalentTo([System.Nullable[long]]) -or - $nodeProp["Type"].IsEquivalentTo([System.Nullable[bool]])) - { - $nodeProp["IsPrimitive"] = $true; - } - - # Primitive Type, e.g. int, string, Dictionary, etc. - Write-Verbose ($padding + '-' + $nodeProp["Name"] + " : " + $nodeProp["Type"]); - } - } - - return $treeNode; - } - } -} - -if (($TypeFullName -ne $null) -and ($TypeFullName.Trim() -ne '')) -{ - . "$PSScriptRoot\Import-AssemblyFunction.ps1"; - $dll = Load-AssemblyFile $DllFullPath; - $TypeInfo = $dll.GetType($TypeFullName); -} - -Write-Output (Create-ParameterTreeImpl $ParameterName $TypeInfo @{}); diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-FunctionCommand.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-FunctionCommand.ps1 deleted file mode 100644 index 0faadd218f22..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-FunctionCommand.ps1 +++ /dev/null @@ -1,1439 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -param -( - # VirtualMachine, VirtualMachineScaleSet, etc. - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo, - - [Parameter(Mandatory = $true)] - [string]$ModelClassNameSpace, - - [Parameter(Mandatory = $true)] - [string]$FileOutputFolder, - - [Parameter(Mandatory = $false)] - [string]$FunctionCmdletFlavor = 'None', - - [Parameter(Mandatory = $false)] - [string]$CliOpCommandFlavor = 'Verb', - - [Parameter(Mandatory = $false)] - [System.Reflection.MethodInfo]$FriendMethodInfo = $null, - - [Parameter(Mandatory = $false)] - [System.Reflection.MethodInfo]$PageMethodInfo = $null, - - [Parameter(Mandatory = $false)] - [bool]$CombineGetAndList = $false, - - [Parameter(Mandatory = $false)] - [bool]$CombineGetAndListAll = $false -) - -. "$PSScriptRoot\Import-StringFunction.ps1"; -. "$PSScriptRoot\Import-TypeFunction.ps1"; -. "$PSScriptRoot\Import-WriterFunction.ps1"; - -# Sample: VirtualMachineGetMethod.cs -function Generate-PsFunctionCommandImpl -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo, - - [Parameter(Mandatory = $true)] - [string]$FileOutputFolder, - - [Parameter(Mandatory = $false)] - [System.Reflection.MethodInfo]$FriendMethodInfo = $null - ) - - # e.g. Compute - $componentName = Get-ComponentName $ModelClassNameSpace; - # e.g. CreateOrUpdate, Get, ... - $methodName = ($MethodInfo.Name.Replace('Async', '')); - # e.g. VirtualMachine, System.Void, ... - $returnTypeInfo = $MethodInfo.ReturnType; - $normalizedOutputTypeName = Get-NormalizedTypeName $returnTypeInfo; - $nounPrefix = 'Azure'; - $nounSuffix = 'Method'; - # e.g. VirtualMachines => VirtualMachine - $opSingularName = Get-SingularNoun $OperationName; - # e.g. AzureVirtualMachineGetMethod - $cmdletNoun = $nounPrefix + $opSingularName + $methodName + $nounSuffix; - # e.g. InvokeAzureVirtualMachineGetMethod - $invokeVerb = "Invoke"; - $invokeCmdletName = $invokeVerb + $cmdletNoun; - $invokeParamSetName = $opSingularName + $methodName; - # e.g. Generated/InvokeAzureVirtualMachineGetMethod.cs - $fileNameExt = $invokeParamSetName + $nounSuffix + '.cs'; - $fileFullPath = $FileOutputFolder + '/' + $fileNameExt; - - # The folder and files shall be removed beforehand. - # It will exist, if the target file already exists. - if (Test-Path $fileFullPath) - { - return; - } - - # Common Variables - $indents_8 = ' ' * 8; - $getSetCodeBlock = '{ get; set; }'; - - # Iterate through Param List - $methodParamList = $MethodInfo.GetParameters(); - $positionIndex = 1; - foreach ($methodParam in $methodParamList) - { - # Filter Out Helper Parameters - if (($methodParam.ParameterType.Name -like "I*Operations") -and ($methodParam.Name -eq 'operations')) - { - continue; - } - elseif ($methodParam.ParameterType.Name.EndsWith('CancellationToken')) - { - continue; - } - - # e.g. vmName => VMName, resourceGroup => ResourceGroup, etc. - $paramName = Get-CamelCaseName $methodParam.Name; - $paramTypeName = Get-NormalizedTypeName $methodParam.ParameterType; - $paramCtorCode = Get-ConstructorCode -InputName $paramTypeName; - } - - # Construct Code - $code = ''; - $part1 = Get-InvokeMethodCmdletCode -ComponentName $componentName -OperationName $OperationName -MethodInfo $MethodInfo; - $part2 = Get-ArgumentListCmdletCode -ComponentName $componentName -OperationName $OperationName -MethodInfo $MethodInfo; - - $code += $part1; - $code += $NEW_LINE; - $code += $part2; - - if ($FunctionCmdletFlavor -eq 'Verb') - { - # If the Cmdlet Flavor is 'Verb', generate the Verb-based cmdlet code - $part3 = Get-VerbNounCmdletCode -ComponentName $componentName -OperationName $OperationName -MethodInfo $MethodInfo; - $code += $part3; - } - - # Write Code to File - Write-CmdletCodeFile $fileFullPath $code; - Write-Output $part1; - Write-Output $part2; - Write-Output $part3; -} - -# Get Partial Code for Invoke Method -function Get-InvokeMethodCmdletCode -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$ComponentName, - - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo - ) - - # e.g. CreateOrUpdate, Get, ... - $methodName = ($MethodInfo.Name.Replace('Async', '')); - # e.g. VirtualMachines => VirtualMachine - $opSingularName = Get-SingularNoun $OperationName; - # e.g. InvokeAzureComputeMethodCmdlet - $invoke_cmdlet_class_name = 'InvokeAzure' + $ComponentName + 'MethodCmdlet'; - $invoke_param_set_name = $opSingularName + $methodName; - $method_return_type = $MethodInfo.ReturnType; - $invoke_input_params_name = 'invokeMethodInputParameters'; - - # 1. Start - $code = ""; - $code += " public partial class ${invoke_cmdlet_class_name} : ${ComponentName}AutomationBaseCmdlet" + $NEW_LINE; - $code += " {" + $NEW_LINE; - - # 2. Iterate through Param List - $methodParamList = $MethodInfo.GetParameters(); - [System.Collections.ArrayList]$paramNameList = @(); - [System.Collections.ArrayList]$paramLocalNameList = @(); - [System.Collections.ArrayList]$pruned_params = @(); - foreach ($methodParam in $methodParamList) - { - # Filter Out Helper Parameters - if (($methodParam.ParameterType.Name -like "I*Operations") -and ($methodParam.Name -eq 'operations')) - { - continue; - } - elseif ($methodParam.ParameterType.Name.EndsWith('CancellationToken')) - { - continue; - } - - # e.g. vmName => VMName, resourceGroup => ResourceGroup, etc. - $paramName = Get-CamelCaseName $methodParam.Name; - # Save the parameter's camel name (in upper case) and local name (in lower case). - $paramNameList += $paramName; - $paramLocalNameList += $methodParam.Name; - - # Update Pruned Parameter List - if (-not ($paramName -eq 'ODataQuery')) - { - $st = $pruned_params.Add($methodParam); - } - } - - $invoke_params_join_str = [string]::Join(', ', $paramLocalNameList.ToArray()); - - # 2.1 Dynamic Parameter Assignment - $dynamic_param_assignment_code_lines = @(); - $param_index = 1; - foreach ($pt in $pruned_params) - { - $param_type_full_name = $pt.ParameterType.FullName; - if (($param_type_full_name -like "I*Operations") -and ($param_type_full_name -eq 'operations')) - { - continue; - } - elseif ($param_type_full_name.EndsWith('CancellationToken')) - { - continue; - } - - $is_string_list = Is-ListStringType $pt.ParameterType; - $does_contain_only_strings = Get-StringTypes $pt.ParameterType; - - $param_name = Get-CamelCaseName $pt.Name; - $expose_param_name = $param_name; - - $param_type_full_name = Get-NormalizedTypeName $pt.ParameterType; - - if ($expose_param_name -like '*Parameters') - { - $expose_param_name = $invoke_param_set_name + $expose_param_name; - } - - $expose_param_name = Get-SingularNoun $expose_param_name; - - if (($does_contain_only_strings -eq $null) -or ($does_contain_only_strings.Count -eq 0)) - { - # Complex Class Parameters - $dynamic_param_assignment_code_lines += -@" - var p${param_name} = new RuntimeDefinedParameter(); - p${param_name}.Name = `"${expose_param_name}`"; -"@; - - if ($is_string_list) - { - $dynamic_param_assignment_code_lines += " p${param_name}.ParameterType = typeof(string[]);"; - } - else - { - $dynamic_param_assignment_code_lines += " p${param_name}.ParameterType = typeof($param_type_full_name);"; - } - - $dynamic_param_assignment_code_lines += -@" - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParameters", - Position = $param_index, - Mandatory = false - }); - p${param_name}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${expose_param_name}`", p${param_name}); - -"@; - $param_index += 1; - } - else - { - # String Parameters - foreach ($s in $does_contain_only_strings) - { - $s = Get-SingularNoun $s; - $dynamic_param_assignment_code_lines += -@" - var p${s} = new RuntimeDefinedParameter(); - p${s}.Name = `"${s}`"; - p${s}.ParameterType = typeof(string); - p${s}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParameters", - Position = $param_index, - Mandatory = false - }); - p${s}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${s}`", p${s}); - -"@; - $param_index += 1; - } - } - } - - $param_name = $expose_param_name = 'ArgumentList'; - $param_type_full_name = 'object[]'; - $dynamic_param_assignment_code_lines += -@" - var p${param_name} = new RuntimeDefinedParameter(); - p${param_name}.Name = `"${expose_param_name}`"; - p${param_name}.ParameterType = typeof($param_type_full_name); - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByStaticParameters", - Position = $param_index, - Mandatory = true - }); - p${param_name}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${expose_param_name}`", p${param_name}); - -"@; - - $dynamic_param_assignment_code = [string]::Join($NEW_LINE, $dynamic_param_assignment_code_lines); - - # 2.2 Create Dynamic Parameter Function - $dynamic_param_source_template = -@" - protected object Create${invoke_param_set_name}DynamicParameters() - { - dynamicParameters = new RuntimeDefinedParameterDictionary(); -$dynamic_param_assignment_code - return dynamicParameters; - } -"@; - - $code += $dynamic_param_source_template + $NEW_LINE; - - # 2.3 Execute Method - $position_index = 1; - $indents = ' ' * 8; - $has_properties = $false; - foreach ($pt in $methodParamList) - { - # Filter Out Helper Parameters - if (($pt.ParameterType.Name -like "I*Operations") -and ($pt.Name -eq 'operations')) - { - continue; - } - elseif ($pt.ParameterType.Name.EndsWith('CancellationToken')) - { - continue; - } - - $paramTypeNormalizedName = Get-NormalizedTypeName $pt.ParameterType; - $normalized_param_name = Get-CamelCaseName $pt.Name; - - $has_properties = $true; - $is_string_list = Is-ListStringType $pt.ParameterType; - $does_contain_only_strings = Get-StringTypes $pt.ParameterType; - $only_strings = (($does_contain_only_strings -ne $null) -and ($does_contain_only_strings.Count -ne 0)); - - $param_index = $position_index - 1; - if ($only_strings) - { - # Case 1: the parameter type contains only string types. - $invoke_local_param_definition = $indents + (' ' * 4) + "var " + $pt.Name + " = new ${paramTypeNormalizedName}();" + $NEW_LINE; - - foreach ($param in $does_contain_only_strings) - { - $invoke_local_param_definition += $indents + (' ' * 4) + "var p${param} = (string) ParseParameter(${invoke_input_params_name}[${param_index}]);" + $NEW_LINE; - $invoke_local_param_definition += $indents + (' ' * 4) + $pt.Name + ".${param} = string.IsNullOrEmpty(p${param}) ? null : p${param};" + $NEW_LINE; - $param_index += 1; - $position_index += 1; - } - } - elseif ($is_string_list) - { - # Case 2: the parameter type contains only a list of strings. - $list_of_strings_property = ($pt.ParameterType.GetProperties())[0].Name; - - $invoke_local_param_definition = $indents + (' ' * 4) + "${paramTypeNormalizedName} " + $pt.Name + " = null;"+ $NEW_LINE; - $invoke_local_param_definition += $indents + (' ' * 4) + "if (${invoke_input_params_name}[${param_index}] != null)" + $NEW_LINE; - $invoke_local_param_definition += $indents + (' ' * 4) + "{" + $NEW_LINE; - $invoke_local_param_definition += $indents + (' ' * 8) + "var inputArray${param_index} = Array.ConvertAll((object[]) ParseParameter(${invoke_input_params_name}[${param_index}]), e => e.ToString());" + $NEW_LINE; - if ($paramTypeNormalizedName -like 'System.Collections.Generic.IList*') - { - $invoke_local_param_definition += $indents + (' ' * 8) + $pt.Name + " = inputArray${param_index}.ToList();" + $NEW_LINE; - } - else - { - $invoke_local_param_definition += $indents + (' ' * 8) + $pt.Name + " = new ${paramTypeNormalizedName}();" + $NEW_LINE; - $invoke_local_param_definition += $indents + (' ' * 8) + $pt.Name + ".${list_of_strings_property} = inputArray${param_index}.ToList();" + $NEW_LINE; - } - $invoke_local_param_definition += $indents + (' ' * 4) + "}" + $NEW_LINE; - } - else - { - # Case 3: this is the most general case. - if ($normalized_param_name -eq 'ODataQuery') - { - $paramTypeNormalizedName = "Microsoft.Rest.Azure.OData.ODataQuery<${opSingularName}>"; - } - $invoke_local_param_definition = $indents + (' ' * 4) + "${paramTypeNormalizedName} " + $pt.Name + " = (${paramTypeNormalizedName})ParseParameter(${invoke_input_params_name}[${param_index}]);" + $NEW_LINE; - } - - $invoke_local_param_code_content += $invoke_local_param_definition; - $position_index += 1; - } - - $invoke_cmdlt_source_template = ''; - if ($method_return_type.FullName -eq 'System.Void') - { - $invoke_cmdlt_source_template = -@" - protected void Execute${invoke_param_set_name}Method(object[] ${invoke_input_params_name}) - { -${invoke_local_param_code_content} - ${OperationName}Client.${methodName}(${invoke_params_join_str}); - } -"@; - } - elseif ($PageMethodInfo -ne $null) - { - $invoke_cmdlt_source_template = -@" - protected void Execute${invoke_param_set_name}Method(object[] ${invoke_input_params_name}) - { -${invoke_local_param_code_content} - var result = ${OperationName}Client.${methodName}(${invoke_params_join_str}); - var resultList = result.ToList(); - var nextPageLink = result.NextPageLink; - while (!string.IsNullOrEmpty(nextPageLink)) - { - var pageResult = ${OperationName}Client.${methodName}Next(nextPageLink); - foreach (var pageItem in pageResult) - { - resultList.Add(pageItem); - } - nextPageLink = pageResult.NextPageLink; - } - WriteObject(resultList, true); - } -"@; - } - elseif ($methodName -eq 'Get' -and $ModelClassNameSpace -like "*.Azure.Management.*Model*") - { - # Only for ARM Cmdlets - [System.Collections.ArrayList]$paramLocalNameList2 = @(); - for ($i2 = 0; $i2 -lt $paramLocalNameList.Count - 1; $i2++) - { - $item2 = $paramLocalNameList[$i2]; - - if ($item2 -eq 'vmName' -and $OperationName -eq 'VirtualMachines') - { - continue; - } - - $paramLocalNameList2 += $item2; - } - $invoke_cmdlt_source_template = " protected void Execute${invoke_param_set_name}Method(object[] ${invoke_input_params_name})" + $NEW_LINE; - $invoke_cmdlt_source_template += " {" + $NEW_LINE; - $invoke_cmdlt_source_template += "${invoke_local_param_code_content}" + $NEW_LINE; - $invoke_cmdlt_source_template += " if (" - for ($i2 = 0; $i2 -lt $paramLocalNameList.Count; $i2++) - { - if ($i2 -gt 0) - { - $invoke_cmdlt_source_template += " && "; - } - $invoke_cmdlt_source_template += "!string.IsNullOrEmpty(" + $paramLocalNameList[$i2] + ")" - } - $invoke_cmdlt_source_template += ")" + $NEW_LINE; - $invoke_cmdlt_source_template += " {" + $NEW_LINE; - $invoke_cmdlt_source_template += " var result = ${OperationName}Client.${methodName}(${invoke_params_join_str});" + $NEW_LINE; - $invoke_cmdlt_source_template += " WriteObject(result);" + $NEW_LINE; - $invoke_cmdlt_source_template += " }" + $NEW_LINE; - - if ($CombineGetAndList) - { - $invoke_params_join_str_for_list = [string]::Join(', ', $paramLocalNameList2.ToArray()); - $invoke_cmdlt_source_template += " else if (" - for ($i2 = 0; $i2 -lt $paramLocalNameList2.Count; $i2++) - { - if ($i2 -gt 0) - { - $invoke_cmdlt_source_template += " && "; - } - $invoke_cmdlt_source_template += "!string.IsNullOrEmpty(" + $paramLocalNameList2[$i2] + ")" - } - $invoke_cmdlt_source_template += ")" + $NEW_LINE; - $invoke_cmdlt_source_template += " {" + $NEW_LINE; - $invoke_cmdlt_source_template += " var result = ${OperationName}Client.List(${invoke_params_join_str_for_list});" + $NEW_LINE; - $invoke_cmdlt_source_template += " WriteObject(result);" + $NEW_LINE; - $invoke_cmdlt_source_template += " }" + $NEW_LINE; - } - - if ($CombineGetAndListAll) - { - $invoke_cmdlt_source_template += " else" + $NEW_LINE; - $invoke_cmdlt_source_template += " {" + $NEW_LINE; - $invoke_cmdlt_source_template += " var result = ${OperationName}Client.ListAll();" + $NEW_LINE; - $invoke_cmdlt_source_template += " WriteObject(result);" + $NEW_LINE; - $invoke_cmdlt_source_template += " }" + $NEW_LINE; - } - - $invoke_cmdlt_source_template += " }" + $NEW_LINE; - } - else - { - $invoke_cmdlt_source_template = -@" - protected void Execute${invoke_param_set_name}Method(object[] ${invoke_input_params_name}) - { -${invoke_local_param_code_content} - var result = ${OperationName}Client.${methodName}(${invoke_params_join_str}); - WriteObject(result); - } -"@; - } - - $code += $NEW_LINE; - $code += $invoke_cmdlt_source_template + $NEW_LINE; - - # End - $code += " }" + $NEW_LINE; - - return $code; -} - -# Get Partial Code for Creating New Argument List -function Get-ArgumentListCmdletCode -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$ComponentName, - - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo - ) - - # e.g. CreateOrUpdate, Get, ... - $methodName = ($MethodInfo.Name.Replace('Async', '')); - # e.g. VirtualMachines => VirtualMachine - $opSingularName = Get-SingularNoun $OperationName; - $indents = ' ' * 8; - - # 1. Construct Code - Starting - $code = ""; - $code += " public partial class NewAzure${ComponentName}ArgumentListCmdlet : ${ComponentName}AutomationBaseCmdlet" + $NEW_LINE; - $code += " {" + $NEW_LINE; - $code += " protected PSArgument[] Create" + $opSingularName + $methodName + "Parameters()" + $NEW_LINE; - $code += " {" + $NEW_LINE; - - # 2. Iterate through Param List - $methodParamList = $MethodInfo.GetParameters(); - $paramNameList = @(); - $paramLocalNameList = @(); - $has_properties = $false; - foreach ($methodParam in $methodParamList) - { - # Filter Out Helper Parameters - if (($methodParam.ParameterType.Name -like "I*Operations") -and ($methodParam.Name -eq 'operations')) - { - continue; - } - elseif ($methodParam.ParameterType.Name.EndsWith('CancellationToken')) - { - continue; - } - - $has_properties = $true; - - # e.g. vmName => VMName, resourceGroup => ResourceGroup, etc. - $paramName = Get-CamelCaseName $methodParam.Name; - - # i.e. System.Int32 => int, Microsoft.Azure.Management.Compute.VirtualMachine => VirtualMachine - $paramTypeName = Get-NormalizedTypeName $methodParam.ParameterType; - $paramCtorCode = Get-ConstructorCode -InputName $paramTypeName; - - $isStringList = Is-ListStringType $methodParam.ParameterType; - $strTypeList = Get-StringTypes $methodParam.ParameterType; - $containsOnlyStrings = ($strTypeList -ne $null) -and ($strTypeList.Count -ne 0); - - # Save the parameter's camel name (in upper case) and local name (in lower case). - if (-not $containsOnlyStrings) - { - $paramNameList += $paramName; - $paramLocalNameList += $methodParam.Name; - } - - # 2.1 Construct Code - Local Constructor Initialization - if ($containsOnlyStrings) - { - # Case 2.1.1: the parameter type contains only string types. - foreach ($param in $strTypeList) - { - $code += $indents + (' ' * 4) + "var p${param} = string.Empty;" + $NEW_LINE; - $param_index += 1; - $position_index += 1; - $paramNameList += ${param}; - $paramLocalNameList += "p${param}"; - } - } - elseif ($isStringList) - { - # Case 2.1.2: the parameter type contains only a list of strings. - $code += " var " + $methodParam.Name + " = new string[0];" + $NEW_LINE; - } - elseif ($paramName -eq 'ODataQuery') - { - # Case 2.1.3: ODataQuery. - $paramTypeName = "Microsoft.Rest.Azure.OData.ODataQuery<${opSingularName}>"; - $code += " ${paramTypeName} " + $methodParam.Name + " = new ${paramTypeName}();" + $NEW_LINE; - } - else - { - # Case 2.1.4: Most General Constructor Case - $code += " ${paramTypeName} " + $methodParam.Name + " = ${paramCtorCode};" + $NEW_LINE; - } - } - - # Construct Code - 2.2 Return Argument List - if ($has_properties) - { - $code += $NEW_LINE; - $code += " return ConvertFromObjectsToArguments(" + $NEW_LINE; - $code += " new string[] { `"" + ([string]::Join("`", `"", $paramNameList)) + "`" }," + $NEW_LINE; - $code += " new object[] { " + ([string]::Join(", ", $paramLocalNameList)) + " });" + $NEW_LINE; - } - else - { - $code += " return ConvertFromObjectsToArguments(new string[0], new object[0]);" + $NEW_LINE; - } - - # Construct Code - Ending - $code += " }" + $NEW_LINE; - $code += " }"; - - return $code; -} - -# Get Partial Code for Verb-Noun Cmdlet -function Get-VerbNounCmdletCode -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$ComponentName, - - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo - ) - - # e.g. CreateOrUpdate, Get, ... - $methodName = ($MethodInfo.Name.Replace('Async', '')); - # e.g. VirtualMachines => VirtualMachine - $opSingularName = Get-SingularNoun $OperationName; - $invoke_param_set_name = $opSingularName + $methodName; - if ($FriendMethodInfo -ne $null) - { - $friendMethodName = ($FriendMethodInfo.Name.Replace('Async', '')); - $invoke_param_set_name_for_friend = $opSingularName + $friendMethodName; - } - - # Variables - $return_vals = Get-VerbTermNameAndSuffix $methodName; - $mapped_verb_name = $return_vals[0]; - $mapped_verb_term_suffix = $return_vals[1]; - $shortNounName = Get-ShortNounName $opSingularName; - - $mapped_noun_str = 'AzureRm' + $shortNounName + $mapped_verb_term_suffix; - $verb_cmdlet_name = $mapped_verb_name + $mapped_noun_str; - - # 1. Start - $code = ""; - - # 2. Body - $mapped_noun_str = $mapped_noun_str.Replace("VMSS", "Vmss"); - - # Iterate through Param List - $methodParamList = $MethodInfo.GetParameters(); - $paramNameList = @(); - $paramLocalNameList = @(); - [System.Collections.ArrayList]$pruned_params = @(); - foreach ($methodParam in $methodParamList) - { - # Filter Out Helper Parameters - if (($methodParam.ParameterType.Name -like "I*Operations") -and ($methodParam.Name -eq 'operations')) - { - continue; - } - elseif ($methodParam.ParameterType.Name.EndsWith('CancellationToken')) - { - continue; - } - - # e.g. vmName => VMName, resourceGroup => ResourceGroup, etc. - $paramName = Get-CamelCaseName $methodParam.Name; - # Save the parameter's camel name (in upper case) and local name (in lower case). - $paramNameList += $paramName; - $paramLocalNameList += $methodParam.Name; - - # Update Pruned Parameter List - if (-not ($paramName -eq 'ODataQuery')) - { - $st = $pruned_params.Add($methodParam); - } - } - - $invoke_params_join_str = [string]::Join(', ', $paramLocalNameList); - - # 2.1 Dynamic Parameter Assignment - $dynamic_param_assignment_code_lines = @(); - $param_index = 1; - foreach ($pt in $pruned_params) - { - $param_type_full_name = $pt.ParameterType.FullName; - if (($param_type_full_name -like "I*Operations") -and ($param_type_full_name -eq 'operations')) - { - continue; - } - elseif ($param_type_full_name.EndsWith('CancellationToken')) - { - continue; - } - - $is_string_list = Is-ListStringType $pt.ParameterType; - $does_contain_only_strings = Get-StringTypes $pt.ParameterType; - - $param_name = Get-CamelCaseName $pt.Name; - $expose_param_name = $param_name; - - $param_type_full_name = Get-NormalizedTypeName $pt.ParameterType; - - if ($expose_param_name -like '*Parameters') - { - $expose_param_name = $invoke_param_set_name + $expose_param_name; - } - - $expose_param_name = Get-SingularNoun $expose_param_name; - - if (($does_contain_only_strings -eq $null) -or ($does_contain_only_strings.Count -eq 0)) - { - # Complex Class Parameters - $dynamic_param_assignment_code_lines += -@" - var p${param_name} = new RuntimeDefinedParameter(); - p${param_name}.Name = `"${expose_param_name}`"; -"@; - - if ($is_string_list) - { - $dynamic_param_assignment_code_lines += " p${param_name}.ParameterType = typeof(string[]);"; - } - else - { - $dynamic_param_assignment_code_lines += " p${param_name}.ParameterType = typeof($param_type_full_name);"; - } - - $dynamic_param_assignment_code_lines += -@" - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParameters", - Position = $param_index, - Mandatory = false - }); -"@; - if ($FriendMethodInfo -ne $null) - { - $dynamic_param_assignment_code_lines += -@" - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParametersForFriendMethod", - Position = $param_index, - Mandatory = false - }); -"@; - } - - $dynamic_param_assignment_code_lines += -@" - p${param_name}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${expose_param_name}`", p${param_name}); - -"@; - $param_index += 1; - } - else - { - # String Parameters - foreach ($s in $does_contain_only_strings) - { - $s = Get-SingularNoun $s; - $dynamic_param_assignment_code_lines += -@" - var p${s} = new RuntimeDefinedParameter(); - p${s}.Name = `"${s}`"; - p${s}.ParameterType = typeof(string); - p${s}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParameters", - Position = $param_index, - Mandatory = false - }); -"@; - if ($FriendMethodInfo -ne $null) - { - $dynamic_param_assignment_code_lines += -@" - p${s}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParametersForFriendMethod", - Position = $param_index, - Mandatory = false - }); -"@; - } - $dynamic_param_assignment_code_lines += -@" - p${s}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${s}`", p${s}); - -"@; - $param_index += 1; - } - } - } - - $param_name = $expose_param_name = 'ArgumentList'; - $param_type_full_name = 'object[]'; - $dynamic_param_assignment_code_lines += -@" - var p${param_name} = new RuntimeDefinedParameter(); - p${param_name}.Name = `"${expose_param_name}`"; - p${param_name}.ParameterType = typeof($param_type_full_name); - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByStaticParameters", - Position = $param_index, - Mandatory = true - }); -"@; - if ($FriendMethodInfo -ne $null) - { - $dynamic_param_assignment_code_lines += -@" - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByStaticParametersForFriendMethod", - Position = $param_index, - Mandatory = true - }); -"@; - } - - $dynamic_param_assignment_code_lines += -@" - p${param_name}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${expose_param_name}`", p${param_name}); - -"@; - - $dynamic_param_assignment_code = [string]::Join($NEW_LINE, $dynamic_param_assignment_code_lines); - - if ($FriendMethodInfo -ne $null) - { - $friend_code = ""; - if ($FriendMethodInfo.Name -eq 'PowerOff') - { - $param_name = $expose_param_name = 'StayProvision'; - } - else - { - $param_name = $expose_param_name = $FriendMethodInfo.Name.Replace($methodName, ''); - } - - $param_type_full_name = 'SwitchParameter'; - $static_param_index = $param_index + 1; - $friend_code += -@" - var p${param_name} = new RuntimeDefinedParameter(); - p${param_name}.Name = `"${expose_param_name}`"; - p${param_name}.ParameterType = typeof($param_type_full_name); - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByDynamicParametersForFriendMethod", - Position = $param_index, - Mandatory = true - }); - p${param_name}.Attributes.Add(new ParameterAttribute - { - ParameterSetName = "InvokeByStaticParametersForFriendMethod", - Position = ${static_param_index}, - Mandatory = true - }); - p${param_name}.Attributes.Add(new AllowNullAttribute()); - dynamicParameters.Add(`"${expose_param_name}`", p${param_name}); - -"@; - - $dynamic_param_assignment_code += $NEW_LINE; - $dynamic_param_assignment_code += $friend_code; - } - - $code += -@" - - - [Cmdlet(`"${mapped_verb_name}`", `"${mapped_noun_str}`", DefaultParameterSetName = `"InvokeByDynamicParameters`")] - public partial class $verb_cmdlet_name : ${invoke_cmdlet_class_name} - { - public $verb_cmdlet_name() - { - } - - public override string MethodName { get; set; } - - protected override void ProcessRecord() - { -"@; - if ($FriendMethodInfo -ne $null) - { - $code += $NEW_LINE; - $code += " if (this.ParameterSetName == `"InvokeByDynamicParameters`")" + $NEW_LINE; - $code += " {" + $NEW_LINE; - $code += " this.MethodName = `"$invoke_param_set_name`";" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " else" + $NEW_LINE; - $code += " {" + $NEW_LINE; - $code += " this.MethodName = `"$invoke_param_set_name_for_friend`";" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - else - { - $code += $NEW_LINE; - $code += " this.MethodName = `"$invoke_param_set_name`";" + $NEW_LINE; - } - - $code += -@" - base.ProcessRecord(); - } - - public override object GetDynamicParameters() - { - dynamicParameters = new RuntimeDefinedParameterDictionary(); -$dynamic_param_assignment_code - return dynamicParameters; - } - } -"@; - - # 3. End - $code += ""; - - return $code; -} - -# azure vm get -function Generate-CliFunctionCommandImpl -{ - param - ( - # VirtualMachine, VirtualMachineScaleSet, etc. - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo, - - [Parameter(Mandatory = $true)] - [string]$ModelNameSpace, - - [Parameter(Mandatory = $false)] - [string]$FileOutputFolder = $null - ) - - # Skip Pagination Function - if (CheckIf-PaginationMethod $MethodInfo) - { - return; - } - - $methodParameters = $MethodInfo.GetParameters(); - $methodName = ($MethodInfo.Name.Replace('Async', '')); - - $methodParamNameList = @(); - $methodParamTypeDict = @{}; - $allStringFieldCheck = @{}; - $oneStringListCheck = @{}; - - $componentName = Get-ComponentName $ModelClassNameSpace; - $componentNameInLowerCase = $componentName.ToLower(); - - # 3. CLI Code - # 3.1 Types - foreach ($paramItem in $methodParameters) - { - [System.Type]$paramType = $paramItem.ParameterType; - if (($paramType.Name -like "I*Operations") -and ($paramItem.Name -eq 'operations')) - { - continue; - } - elseif ($paramType.FullName.EndsWith('CancellationToken')) - { - continue; - } - elseif ($paramItem.Name -eq 'odataQuery') - { - continue; - } - elseif ($paramType.IsEquivalentTo([string]) -and $paramItem.Name -eq 'select') - { - continue; - } - else - { - # Record the Normalized Parameter Name, i.e. 'vmName' => 'VMName', 'resourceGroup' => 'ResourceGroup', etc. - $methodParamNameList += (Get-CamelCaseName $paramItem.Name); - $methodParamTypeDict.Add($paramItem.Name, $paramType); - $allStringFields = Contains-OnlyStringFields $paramType; - $allStringFieldCheck.Add($paramItem.Name, $allStringFields); - $oneStringList = Contains-OnlyStringList $paramType; - $oneStringListCheck.Add($paramItem.Name, $oneStringList); - - if ($paramType.Namespace -like $ModelNameSpace) - { - # If the namespace is like 'Microsoft.Azure.Management.*.Models', generate commands for the complex parameter - - # 3.1.1 Create the Parameter Object, and convert it to JSON code text format - $param_object = (. $PSScriptRoot\Create-ParameterObject.ps1 -typeInfo $paramType); - $param_object_comment = (. $PSScriptRoot\ConvertTo-Json.ps1 -inputObject $param_object -compress $true); - $param_object_comment_no_compress = (. $PSScriptRoot\ConvertTo-Json.ps1 -inputObject $param_object); - - # 3.1.2 Create a parameter tree that represents the complext object - $cmdlet_tree = (. $PSScriptRoot\Create-ParameterTree.ps1 -TypeInfo $paramType -NameSpace $ModelNameSpace -ParameterName $paramType.Name); - - # 3.1.3 Generate the parameter command according to the parameter tree - $cmdlet_tree_code = (. $PSScriptRoot\Generate-ParameterCommand.ps1 -CmdletTreeNode $cmdlet_tree -Operation $opShortName -ModelNameSpace $ModelNameSpace -MethodName $methodName -OutputFolder $FileOutputFolder); - } - } - } - - # 3.2 Functions - - # 3.2.1 Compute the CLI Category Name, i.e. VirtualMachineScaleSet => vmss, VirtualMachineScaleSetVM => vmssvm - $cliCategoryName = Get-CliCategoryName $OperationName; - - # 3.2.2 Compute the CLI Operation Name, i.e. VirtualMachineScaleSets => virtualMachineScaleSets, VirtualMachineScaleSetVM => virtualMachineScaleSetVMs - $cliOperationName = Get-CliNormalizedName $OperationName; - - # 3.2.3 Normalize the CLI Method Name, i.e. CreateOrUpdate => createOrUpdate, ListAll => listAll - $cliMethodName = Get-CliNormalizedName $methodName; - $cliCategoryVarName = $cliOperationName + $methodName; - $cliMethodOption = Get-CliOptionName $methodName; - - # 3.2.4 Compute the CLI Command Description, i.e. VirtualMachineScaleSet => virtual machine scale set - $cliOperationDescription = (Get-CliOptionName $OperationName).Replace('-', ' '); - - # 3.2.5 Generate the CLI Command Comment - $cliOperationComment = "/*" + $NEW_LINE; - $cliOperationComment += " " + $OperationName + " " + $methodName + $NEW_LINE; - for ($index = 0; $index -lt $methodParamNameList.Count; $index++) - { - $cli_option_name = Get-CliOptionName $methodParamNameList[$index]; - $cliOperationComment += " --" + (Get-CliOptionName $methodParamNameList[$index]) + $NEW_LINE; - } - - if ($param_object_comment_no_compress -ne $null -and $param_object_comment_no_compress.Trim() -ne '') - { - $cliOperationComment += $BAR_LINE + $NEW_LINE; - $cliOperationComment += $param_object_comment_no_compress + $NEW_LINE; - } - - $cliOperationComment += "*/" + $NEW_LINE; - - # 3.2.6 Generate the CLI Command Code - $code = ""; - $code += $cliOperationComment; - - if ($ModelNameSpace -like "*.WindowsAzure.*") - { - # Use Invoke Category for RDFE APIs - $invoke_category_desc = "Commands to invoke service management operations."; - $invoke_category_code = ".category('invoke').description('${invoke_category_desc}')"; - } - - $code += " var $cliCategoryVarName = cli${invoke_category_code}.category('${cliCategoryName}')" + $NEW_LINE; - - # 3.2.7 Description Text - $desc_text = "Commands to manage your ${cliOperationDescription}."; - $desc_text_lines = Get-SplitTextLines $desc_text 80; - $code += " .description(`$('"; - $code += [string]::Join("'" + $NEW_LINE + " + '", $desc_text_lines); - $code += " '));" + $NEW_LINE; - - # Set Required Parameters - $requireParams = @(); - $requireParamNormalizedNames = @(); - for ($index = 0; $index -lt $methodParamNameList.Count; $index++) - { - # Parameter Declaration - For Each Method Parameter - [string]$optionParamName = $methodParamNameList[$index]; - if ($allStringFieldCheck[$optionParamName]) - { - [System.Type]$optionParamType = $methodParamTypeDict[$optionParamName]; - foreach ($propItem in $optionParamType.GetProperties()) - { - [System.Reflection.PropertyInfo]$propInfoItem = $propItem; - $cli_option_name = Get-CliOptionName $propInfoItem.Name; - $requireParams += $cli_option_name; - $requireParamNormalizedNames += (Get-CliNormalizedName $propInfoItem.Name); - } - } - else - { - $cli_option_name = Get-CliOptionName $optionParamName; - $requireParams += $cli_option_name; - $requireParamNormalizedNames += (Get-CliNormalizedName $optionParamName); - } - } - - $requireParamsString = $null; - $usageParamsString = $null; - $optionParamString = $null; - if ($requireParams.Count -gt 0) - { - $requireParamsJoinStr = "] ["; - $requireParamsString = " [" + ([string]::Join($requireParamsJoinStr, $requireParams)) + "]"; - $usageParamsJoinStr = "> <"; - $usageParamsString = " <" + ([string]::Join($usageParamsJoinStr, $requireParams)) + ">"; - $optionParamString = ([string]::Join(", ", $requireParamNormalizedNames)) + ", "; - } - - if ($xmlDocItems -ne $null) - { - $xmlHelpText = ""; - foreach ($helpItem in $xmlDocItems) - { - $helpSearchStr = "M:${ClientNameSpace}.${OperationName}OperationsExtensions.${methodName}(*)"; - if ($helpItem.name -like $helpSearchStr) - { - $helpLines = $helpItem.summary.Split("`r").Split("`n"); - foreach ($helpLine in $helpLines) - { - $xmlHelpText += (' ' + $helpLine.Trim()); - } - $xmlHelpText = $xmlHelpText.Trim(); - break; - } - } - } - - $code += " ${cliCategoryVarName}.command('${cliMethodOption}${requireParamsString}')" + $NEW_LINE; - #$code += " .description(`$('Commands to manage your $cliOperationDescription by the ${cliMethodOption} method.${xmlHelpText}'))" + $NEW_LINE; - $code += " .description(`$('${xmlHelpText}'))" + $NEW_LINE; - $code += " .usage('[options]${usageParamsString}')" + $NEW_LINE; - for ($index = 0; $index -lt $methodParamNameList.Count; $index++) - { - # Parameter Declaration - For Each Method Parameter - [string]$optionParamName = $methodParamNameList[$index]; - $optionShorthandStr = $null; - if ($allStringFieldCheck[$optionParamName]) - { - [System.Type]$optionParamType = $methodParamTypeDict[$optionParamName]; - foreach ($propItem in $optionParamType.GetProperties()) - { - [System.Reflection.PropertyInfo]$propInfoItem = $propItem; - $cli_option_name = Get-CliOptionName $propInfoItem.Name; - $cli_shorthand_str = Get-CliShorthandName $propInfoItem.Name; - if ($cli_shorthand_str -ne '') - { - $cli_shorthand_str = "-" + $cli_shorthand_str + ", "; - } - $code += " .option('${cli_shorthand_str}--${cli_option_name} <${cli_option_name}>', `$('${cli_option_name}'))" + $NEW_LINE; - } - } - else - { - $cli_option_name = Get-CliOptionName $optionParamName; - $cli_shorthand_str = Get-CliShorthandName $optionParamName; - if ($cli_shorthand_str -ne '') - { - $cli_shorthand_str = "-" + $cli_shorthand_str + ", "; - } - $code += " .option('${cli_shorthand_str}--${cli_option_name} <${cli_option_name}>', `$('${cli_option_name}'))" + $NEW_LINE; - } - } - $code += " .option('--parameter-file ', `$('the input parameter file'))" + $NEW_LINE; - $code += " .option('-s, --subscription ', `$('the subscription identifier'))" + $NEW_LINE; - $code += " .execute(function(${optionParamString}options, _) {" + $NEW_LINE; - for ($index = 0; $index -lt $methodParamNameList.Count; $index++) - { - # Parameter Assignment - For Each Method Parameter - [string]$optionParamName = $methodParamNameList[$index]; - if ($allStringFieldCheck[$optionParamName]) - { - [System.Type]$optionParamType = $methodParamTypeDict[$optionParamName]; - $cli_param_name = Get-CliNormalizedName $optionParamName; - - $code += " var ${cli_param_name}Obj = null;" + $NEW_LINE; - $code += " if (options.parameterFile) {" + $NEW_LINE; - $code += " cli.output.verbose(`'Reading file content from: \`"`' + options.parameterFile + `'\`"`');" + $NEW_LINE; - $code += " var ${cli_param_name}FileContent = fs.readFileSync(options.parameterFile, 'utf8');" + $NEW_LINE; - $code += " ${cli_param_name}Obj = JSON.parse(${cli_param_name}FileContent);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " else {" + $NEW_LINE; - $code += " ${cli_param_name}Obj = {};" + $NEW_LINE; - - foreach ($propItem in $optionParamType.GetProperties()) - { - [System.Reflection.PropertyInfo]$propInfoItem = $propItem; - $cli_op_param_name = Get-CliNormalizedName $propInfoItem.Name; - $code += " cli.output.verbose('${cli_op_param_name} = ' + ${cli_op_param_name});" + $NEW_LINE; - $code += " ${cli_param_name}Obj.${cli_op_param_name} = ${cli_op_param_name};" + $NEW_LINE; - } - - $code += " }" + $NEW_LINE; - $code += " cli.output.verbose('${cli_param_name}Obj = ' + JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - } - else - { - $cli_param_name = Get-CliNormalizedName $optionParamName; - $code += " cli.output.verbose('${cli_param_name} = ' + ${cli_param_name});" + $NEW_LINE; - if ((${cli_param_name} -eq 'Parameters') -or (${cli_param_name} -like '*InstanceIds')) - { - $code += " var ${cli_param_name}Obj = null;" + $NEW_LINE; - $code += " if (options.parameterFile) {" + $NEW_LINE; - $code += " cli.output.verbose(`'Reading file content from: \`"`' + options.parameterFile + `'\`"`');" + $NEW_LINE; - $code += " var fileContent = fs.readFileSync(options.parameterFile, 'utf8');" + $NEW_LINE; - $code += " ${cli_param_name}Obj = JSON.parse(fileContent);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " else {" + $NEW_LINE; - - if ($oneStringListCheck[$optionParamName]) - { - $code += " var ${cli_param_name}ValArr = ${cli_param_name}.split(',');" + $NEW_LINE; - $code += " cli.output.verbose(`'${cli_param_name}ValArr : `' + ${cli_param_name}ValArr);" + $NEW_LINE; - #$code += " ${cli_param_name}Obj = {};" + $NEW_LINE; - #$code += " ${cli_param_name}Obj.instanceIDs = ${cli_param_name}ValArr;" + $NEW_LINE; - $code += " ${cli_param_name}Obj = [];" + $NEW_LINE; - $code += " for (var item in ${cli_param_name}ValArr) {" + $NEW_LINE; - $code += " ${cli_param_name}Obj.push(${cli_param_name}ValArr[item]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - else - { - $code += " ${cli_param_name}Obj = JSON.parse(${cli_param_name});" + $NEW_LINE; - } - - $code += " }" + $NEW_LINE; - $code += " cli.output.verbose('${cli_param_name}Obj = ' + JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - } - } - } - $code += " var subscription = profile.current.getSubscription(options.subscription);" + $NEW_LINE; - - if ($ModelNameSpace.Contains(".WindowsAzure.")) - { - $code += " var ${componentNameInLowerCase}ManagementClient = utils.create${componentName}Client(subscription);" + $NEW_LINE; - } - else - { - $code += " var ${componentNameInLowerCase}ManagementClient = utils.create${componentName}ManagementClient(subscription);" + $NEW_LINE; - } - - if ($cliMethodName -eq 'delete') - { - $cliMethodFuncName = $cliMethodName + 'Method'; - } - else - { - $cliMethodFuncName = $cliMethodName; - } - - $code += " var result = ${componentNameInLowerCase}ManagementClient.${cliOperationName}.${cliMethodFuncName}("; - - for ($index = 0; $index -lt $methodParamNameList.Count; $index++) - { - # Function Call - For Each Method Parameter - $cli_param_name = Get-CliNormalizedName $methodParamNameList[$index]; - if ((${cli_param_name} -eq 'Parameters') -or (${cli_param_name} -like '*InstanceIds')) - { - $code += "${cli_param_name}Obj"; - } - else - { - $code += "${cli_param_name}"; - } - - $code += ", "; - } - - $code += "_);" + $NEW_LINE; - - if ($PageMethodInfo -ne $null) - { - $code += " var nextPageLink = result.nextPageLink;" + $NEW_LINE; - $code += " while (nextPageLink) {" + $NEW_LINE; - $code += " var pageResult = ${componentNameInLowerCase}ManagementClient.${cliOperationName}.${cliMethodFuncName}Next(nextPageLink, _);" + $NEW_LINE; - $code += " pageResult.forEach(function(item) {" + $NEW_LINE; - $code += " result.push(item);" + $NEW_LINE; - $code += " });" + $NEW_LINE; - $code += " nextPageLink = pageResult.nextPageLink;" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += "" + $NEW_LINE; - } - - if ($PageMethodInfo -ne $null -and $methodName -ne 'ListSkus') - { - $code += " if (cli.output.format().json) {" + $NEW_LINE; - $code += " cli.output.json(result);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " else {" + $NEW_LINE; - $code += " cli.output.table(result, function (row, item) {" + $NEW_LINE; - $code += " var rgName = item.id ? utils.parseResourceReferenceUri(item.id).resourceGroupName : null;" + $NEW_LINE; - $code += " row.cell(`$('ResourceGroupName'), rgName);" + $NEW_LINE; - $code += " row.cell(`$('Name'), item.name);" + $NEW_LINE; - $code += " row.cell(`$('ProvisioningState'), item.provisioningState);" + $NEW_LINE; - $code += " row.cell(`$('Location'), item.location);" + $NEW_LINE; - $code += " });" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - else - { - $code += " cli.output.json(result);" + $NEW_LINE; - } - $code += " });" + $NEW_LINE; - - # 3.3 Parameters - for ($index = 0; $index -lt $methodParamNameList.Count; $index++) - { - [string]$optionParamName = $methodParamNameList[$index]; - if ($allStringFieldCheck[$optionParamName]) - { - # Skip all-string parameters that are already handled in the function command. - continue; - } - - $cli_param_name = Get-CliNormalizedName $methodParamNameList[$index]; - if ($cli_param_name -eq 'Parameters') - { - $params_category_name = $cliMethodOption + '-parameters'; - $params_category_var_name = "${cliCategoryVarName}${cliMethodName}Parameters" + $index; - $params_generate_category_name = 'generate'; - $params_generate_category_var_name = "${cliCategoryVarName}${cliMethodName}Generate" + $index; - - # 3.3.1 Parameter Generate Command - $code += " var ${params_category_var_name} = ${cliCategoryVarName}.category('${params_category_name}')" + $NEW_LINE; - $code += " .description(`$('Commands to generate parameter input file for your ${cliOperationDescription}.'));" + $NEW_LINE; - $code += " ${params_category_var_name}.command('generate')" + $NEW_LINE; - $code += " .description(`$('Generate ${cliCategoryVarName} parameter string or files.'))" + $NEW_LINE; - $code += " .usage('[options]')" + $NEW_LINE; - $code += " .option('--parameter-file ', `$('The parameter file path.'))" + $NEW_LINE; - $code += " .execute(function(options, _) {" + $NEW_LINE; - - $output_content = $param_object_comment.Replace("`"", "\`""); - $code += " cli.output.verbose(`'" + $output_content + "`', _);" + $NEW_LINE; - - $file_content = $param_object_comment_no_compress.Replace($NEW_LINE, "\r\n").Replace("`r", "\r").Replace("`n", "\n"); - $file_content = $file_content.Replace("`"", "\`"").Replace(' ', ''); - $code += " var filePath = `'${cliCategoryVarName}_${cliMethodName}.json`';" + $NEW_LINE; - $code += " if (options.parameterFile) {" + $NEW_LINE; - $code += " filePath = options.parameterFile;" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " fs.writeFileSync(filePath, beautify(`'" + $file_content + "`'));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Parameter file output to: `' + filePath);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " });" + $NEW_LINE; - $code += $NEW_LINE; - - # 3.3.2 Parameter Patch Command - $code += " ${params_category_var_name}.command('patch')" + $NEW_LINE; - $code += " .description(`$('Command to patch ${cliCategoryVarName} parameter JSON file.'))" + $NEW_LINE; - $code += " .usage('[options]')" + $NEW_LINE; - $code += " .option('--parameter-file ', `$('The parameter file path.'))" + $NEW_LINE; - $code += " .option('--operation ', `$('The JSON patch operation: add, remove, or replace.'))" + $NEW_LINE; - $code += " .option('--path ', `$('The JSON data path, e.g.: \`"foo/1\`".'))" + $NEW_LINE; - $code += " .option('--value ', `$('The JSON value.'))" + $NEW_LINE; - $code += " .option('--parse', `$('Parse the JSON value to object.'))" + $NEW_LINE; - $code += " .execute(function(options, _) {" + $NEW_LINE; - $code += " cli.output.verbose(options.parameterFile, _);" + $NEW_LINE; - $code += " cli.output.verbose(options.operation);" + $NEW_LINE; - $code += " cli.output.verbose(options.path);" + $NEW_LINE; - $code += " cli.output.verbose(options.value);" + $NEW_LINE; - $code += " cli.output.verbose(options.parse);" + $NEW_LINE; - $code += " if (options.parse) {" + $NEW_LINE; - $code += " options.value = JSON.parse(options.value);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " cli.output.verbose(options.value);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Reading file content from: \`"`' + options.parameterFile + `'\`"`');" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " var fileContent = fs.readFileSync(options.parameterFile, 'utf8');" + $NEW_LINE; - $code += " var ${cli_param_name}Obj = JSON.parse(fileContent);" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object:`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - $code += " if (options.operation == 'add') {" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path, value: options.value}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " else if (options.operation == 'remove') {" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " else if (options.operation == 'replace') {" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path, value: options.value}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " var updatedContent = JSON.stringify(${cli_param_name}Obj);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object (updated):`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " fs.writeFileSync(options.parameterFile, beautify(updatedContent));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Parameter file updated at: `' + options.parameterFile);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " });" + $NEW_LINE; - $code += $NEW_LINE; - - # 3.3.3 Parameter Commands - $code += $cmdlet_tree_code + $NEW_LINE; - - break; - } - } - - return $code; -} - -Generate-PsFunctionCommandImpl $OperationName $MethodInfo $FileOutputFolder $FriendMethodInfo; - -# CLI Function Command Code -$opItem = $cliOperationSettings[$OperationName]; -if ($opItem -contains $MethodInfo.Name) -{ - return $null; -} -Generate-CliFunctionCommandImpl $OperationName $MethodInfo $ModelClassNameSpace $FileOutputFolder; \ No newline at end of file diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-ParameterCommand.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-ParameterCommand.ps1 deleted file mode 100644 index 67b8f5741ef5..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-ParameterCommand.ps1 +++ /dev/null @@ -1,727 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -param( - [Parameter(Mandatory = $true)] - $CmdletTreeNode, - - # VirtualMachine, VirtualMachineScaleSet, etc. - [Parameter(Mandatory = $true)] - [string]$OperationName, - - [Parameter(Mandatory = $false)] - [string]$MethodName = $null, - - [Parameter(Mandatory = $false)] - [string]$ModelNameSpace = $null, - - # CLI commands or PS cmdlets - [Parameter(Mandatory = $false)] - [string]$ToolType = "CLI", - - [Parameter(Mandatory = $false)] - [string]$OutputFolder = $null, - - [Parameter(Mandatory = $false)] - [string]$CmdletNounPrefix = "Azure" -) - -$NEW_LINE = "`r`n"; -. "$PSScriptRoot\Import-StringFunction.ps1"; - -$CLI_HELP_MSG = " There are two sets of commands:\r\n" ` - + " 1) function commands that are used to manage Azure resources in the cloud, and \r\n" ` - + " 2) parameter commands that generate & edit input files for the other set of commands.\r\n" ` - + " For example, \'vmss get/list/stop\' are the function commands that call get, list and stop operations of \r\n" ` - + " virtual machine scale set, whereas \'vmss create-or-update-parameters * generate/set/remove/add\' commands \r\n" ` - + " are used to configure the input parameter file. The \'vmss create-or-update\' command takes a parameter \r\n" ` - + " file as for the VM scale set configuration, and creates it online."; - -function Get-ParameterCommandCategoryDescription -{ - param - ( - # e.g. 'virtual machine scale set' - [Parameter(Mandatory = $true)] - [string]$OperationName, - - # e.g. 'create-or-update-parameters' - [Parameter(Mandatory = $true)] - [string]$FunctionParamName, - - # e.g. 'os-profile' - [Parameter(Mandatory = $true)] - [string]$SubParameterName - ) - - $description = "Commands to set/remove/add ${SubParameterName} "; - $description += "of ${OperationName} in ${FunctionParamName} file."; - - return $description; -} - -function Generate-CliParameterCommandImpl -{ - param( - [Parameter(Mandatory = $true)] - $TreeNode - ) - - if ($TreeNode -eq $null) - { - return $null; - } - - $paramSuffix = $OperationName + $TreeNode.Name; - $cli_method_option_name = Get-CliOptionName $TreeNode.Name; - $cli_op_description = Get-CliOptionName $OperationName; - $category_name = Get-CliCategoryName $OperationName; - $params_category_name = (Get-CliCategoryName $MethodName) + '-parameters'; - $params_category_var_name_prefix = 'parameters'; - $cli_param_name = 'parameters'; - - # 0. Construct Path to Node - $pathToTreeNode = ""; - $parentNode = $TreeNode; - $indexerParamList = @(); - while ($parentNode -ne $null) - { - [string]$nodeName = Get-CliNormalizedName $parentNode.Name.Trim(); - [string]$pathName = $nodeName; - # Skip this for AutoRest, as the parameter names are always matched. - # if ($pathName.ToLower().StartsWith('ip')) - # { - # $pathName = 'iP' + $pathName.Substring(2); - # } - - if ($parentNode.Parent -ne $null) - { - if ($parentNode.IsListItem) - { - if ($nodeName -eq $TreeNode.Name) - { - $indexerName = "index"; - $pathToTreeNode = "/$pathName`' + (options.${indexerName} ? ('/' + options.${indexerName}) : '')"; - } - else - { - $indexerName = "${nodeName}Index"; - $pathToTreeNode = "/$pathName/`' + options.${indexerName} + `'" + $pathToTreeNode; - } - - $indexerParamList += $indexerName; - } - else - { - $pathToTreeNode = "/$pathName" + $pathToTreeNode; - } - } - - $parentNode = $parentNode.Parent; - } - - if ($TreeNode.IsListItem) - { - $pathToTreeNode = "`'${pathToTreeNode}"; - } - else - { - $pathToTreeNode = "`'${pathToTreeNode}`'"; - } - - if ($ModelNameSpace -like "*.WindowsAzure.*") - { - # 0.1 Use Invoke Category for RDFE APIs - $invoke_category_desc = "Commands to invoke service management operations."; - $invoke_category_code = ".category('invoke').description('${invoke_category_desc}')"; - } - - # 0.2 Construct Sample JSON Parameter Body for Help Messages - $paramObject = (. $PSScriptRoot\Create-ParameterObject.ps1 -typeInfo $TreeNode.TypeInfo); - $paramObjText = (. $PSScriptRoot\ConvertTo-Json.ps1 -inputObject $paramObject); - if ($TreeNode.Parent -eq $null) - { - $sampleJsonText = $paramObjText.Replace("`r`n", "\r\n"); - } - else - { - $padding = " "; - $sampleJsonText = $padding + "{\r\n"; - $sampleJsonText += $padding + " ...\r\n"; - $sampleJsonText += $padding + " `"" + (Get-CliNormalizedName $TreeNode.Name) + "`" : "; - $sampleJsonText += ($paramObjText.Replace("`r`n", "\r\n" + $padding + " ")) + "\r\n"; - $sampleJsonText += $padding + " ...\r\n"; - $sampleJsonText += $padding + "}\r\n"; - } - - if ($TreeNode.Properties.Count -gt 0 -or ($TreeNode.IsListItem)) - { - # 1. Parameter Set Command - $params_category_var_name = $params_category_var_name_prefix + $MethodName + $paramSuffix + "0"; - $cat_params_category_var_name = 'cat' + $params_category_var_name; - $params_generate_category_name = 'set'; - $params_generate_category_var_name = $params_generate_category_name + $params_category_var_name; - $code = " //$params_category_name set ${cli_method_option_name}" + $NEW_LINE; - $code += " var ${cat_params_category_var_name} = cli${invoke_category_code}.category('${category_name}');" + $NEW_LINE; - $code += " var ${params_category_var_name} = ${cat_params_category_var_name}.category('${params_category_name}')" + $NEW_LINE; - $code += " .description(`$('Commands to manage parameter for your ${cli_op_description}.'));" + $NEW_LINE; - $code += " var ${params_generate_category_var_name} = ${params_category_var_name}.category('${cli_method_option_name}')" + $NEW_LINE; - $code += " .description(`$('" + (Get-ParameterCommandCategoryDescription $cli_op_description $params_category_name $cli_method_option_name) +"'));" + $NEW_LINE; - $code += " ${params_generate_category_var_name}.command('${params_generate_category_name}')" + $NEW_LINE; - $code += " .description(`$('Set ${cli_method_option_name} in ${params_category_name} string or files, e.g. \r\n${sampleJsonText}\r\n" + $CLI_HELP_MSG + "'))" + $NEW_LINE; - $code += " .usage('[options]')" + $NEW_LINE; - $code += " .option('--parameter-file ', `$('The parameter file path.'))" + $NEW_LINE; - - # 1.1 For List Item - if ($indexerParamList.Count -gt 0) - { - foreach ($indexerParamName in $indexerParamList) - { - $indexerOptionName = Get-CliOptionName $indexerParamName; - $code += " .option('--$indexerOptionName <$indexerOptionName>', `$('Indexer: $indexerOptionName.'))" + $NEW_LINE; - } - - if ($indexerParamList -contains 'index') - { - $code += " .option('--value ', `$('The input string value for the indexed item.'))" + $NEW_LINE; - } - } - $code += " .option('--parse', `$('Parse the input value string to a JSON object.'))" + $NEW_LINE; - - # 1.2 For Each Property, Set the Option - foreach ($propertyItem in $TreeNode.Properties) - { - $code += " .option('--" + (Get-CliOptionName $propertyItem["Name"]); - $code += " <" + (Get-CliNormalizedName $propertyItem["Name"]); - $code += ">', `$('Set the " + (Get-CliOptionName $propertyItem["Name"]); - $code += " value.'))" + $NEW_LINE; - } - - $code += " .execute(function(options, _) {" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(options), _);" + $NEW_LINE; - $code += " if (options.parse && options.value) {" + $NEW_LINE; - $code += " options.value = JSON.parse(options.value);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " cli.output.verbose(options.value);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Reading file content from: \`"`' + options.parameterFile + `'\`"`');" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " var fileContent = fs.readFileSync(options.parameterFile, 'utf8');" + $NEW_LINE; - $code += " var ${cli_param_name}Obj = JSON.parse(fileContent);" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object:`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - - $code += " options.operation = 'replace';" + $NEW_LINE; - $code += " options.path = ${pathToTreeNode};" + $NEW_LINE; - - # 1.3 For List Item - if ($TreeNode.IsListItem) - { - $code += " if (options.value) {" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path, value: options.value}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - - # 1.4 For Each Property, Apply the Change if Any - $isFirstDefinition = $true; - foreach ($propertyItem in $TreeNode.Properties) - { - if ($isFirstDefinition) - { - $isFirstDefinition = $false; - $defTypePrefix = "var "; - } - else - { - $defTypePrefix = ""; - } - - $paramName = (Get-CliNormalizedName $propertyItem["Name"]); - $code += " ${defTypePrefix}paramPath = " + "options.path" + " + `'/`' + " + "`'" + ${paramName} + "`';" + $NEW_LINE; - $code += " cli.output.verbose(`'================================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON Parameters Path:`' + paramPath);" + $NEW_LINE; - $code += " cli.output.verbose(`'================================================`');" + $NEW_LINE; - $code += " if (options.${paramName}) {" + $NEW_LINE; - $code += " if (options.parse && options.${paramName}) {" + $NEW_LINE; - $code += " options.${paramName} = JSON.parse(options.${paramName});" + $NEW_LINE; - $code += " }" + $NEW_LINE; - - if ($propertyItem["IsPrimitive"]) - { - $code += " options.${paramName} = JSON.parse(options.${paramName});" + $NEW_LINE; - } - - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: paramPath, value: options.${paramName}}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - - $code += " var updatedContent = JSON.stringify(${cli_param_name}Obj);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object (updated):`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " fs.writeFileSync(options.parameterFile, beautify(updatedContent));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Parameter file updated at: `' + options.parameterFile);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - - $code += " });" + $NEW_LINE; - $code += "" + $NEW_LINE; - } - - # 2. Parameter Remove Command - $params_category_var_name = $params_category_var_name_prefix + $MethodName + $paramSuffix + "1"; - $cat_params_category_var_name = 'cat' + $params_category_var_name; - $params_generate_category_name = 'remove'; - $params_generate_category_var_name = $params_generate_category_name + $params_category_var_name; - $code += " //$params_category_name ${params_generate_category_name} ${cli_method_option_name}" + $NEW_LINE; - $code += " var ${cat_params_category_var_name} = cli${invoke_category_code}.category('${category_name}');" + $NEW_LINE; - $code += " var ${params_category_var_name} = ${cat_params_category_var_name}.category('${params_category_name}')" + $NEW_LINE; - $code += " .description(`$('Commands to manage parameter for your ${cli_op_description}.'));" + $NEW_LINE; - $code += " var ${params_generate_category_var_name} = ${params_category_var_name}.category('${cli_method_option_name}')" + $NEW_LINE; - $code += " .description(`$('" + (Get-ParameterCommandCategoryDescription $cli_op_description $params_category_name $cli_method_option_name) +"'));" + $NEW_LINE; - $code += " ${params_generate_category_var_name}.command('${params_generate_category_name}')" + $NEW_LINE; - $code += " .description(`$('Remove ${cli_method_option_name} in ${params_category_name} string or files, e.g. \r\n${sampleJsonText}\r\n" + $CLI_HELP_MSG + "'))" + $NEW_LINE; - $code += " .usage('[options]')" + $NEW_LINE; - $code += " .option('--parameter-file ', `$('The parameter file path.'))" + $NEW_LINE; - - # 2.1 For List Item - if ($indexerParamList.Count -gt 0) - { - foreach ($indexerParamName in $indexerParamList) - { - $indexerOptionName = Get-CliOptionName $indexerParamName; - $code += " .option('--$indexerOptionName <$indexerOptionName>', `$('Indexer: $indexerOptionName.'))" + $NEW_LINE; - } - } - - # 2.2 For Each Property, Append the Option for Removal - foreach ($propertyItem in $TreeNode.Properties) - { - $code += " .option('--" + (Get-CliOptionName $propertyItem["Name"]) + "',"; - $code += " `$('Remove the " + (Get-CliOptionName $propertyItem["Name"]); - $code += " value.'))" + $NEW_LINE; - } - - # 2.3 Function Definition - $code += " .execute(function(options, _) {" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(options), _);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Reading file content from: \`"`' + options.parameterFile + `'\`"`');" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " var fileContent = fs.readFileSync(options.parameterFile, 'utf8');" + $NEW_LINE; - $code += " var ${cli_param_name}Obj = JSON.parse(fileContent);" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object:`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - $code += " options.operation = 'remove';" + $NEW_LINE; - $code += " options.path = ${pathToTreeNode};" + $NEW_LINE; - - if ($TreeNode.Properties.Count -gt 0) - { - # 2.3.1 For Any Sub-Item Removal - $code += " var anySubItem = false"; - foreach ($propertyItem in $TreeNode.Properties) - { - $code += " || options." + (Get-CliNormalizedName $propertyItem["Name"]); - } - $code += ";" + $NEW_LINE; - - # 2.3.2 For Removal of the Entire Item - $code += " if (anySubItem) {" + $NEW_LINE; - $code += " var subItemPath = null;" + $NEW_LINE; - foreach ($propertyItem in $TreeNode.Properties) - { - $code += " if (options." + (Get-CliNormalizedName $propertyItem["Name"]) + ") {" + $NEW_LINE; - $code += " subItemPath = options.path + '/" + (Get-CliNormalizedName $propertyItem["Name"]) + "';" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: subItemPath}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - - $code += " }" + $NEW_LINE; - $code += " else {" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - elseif ($indexerParamList.Count -gt 0) - { - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path}]);" + $NEW_LINE; - } - - $code += " " + $NEW_LINE; - $code += " var updatedContent = JSON.stringify(${cli_param_name}Obj);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object (updated):`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " fs.writeFileSync(options.parameterFile, beautify(updatedContent));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Parameter file updated at: `' + options.parameterFile);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " });" + $NEW_LINE; - - # 3. Parameter Add Command - $params_category_var_name = $params_category_var_name_prefix + $MethodName + $paramSuffix + "2"; - $cat_params_category_var_name = 'cat' + $params_category_var_name; - $params_generate_category_name = 'add'; - $params_generate_category_var_name = $params_generate_category_name + $params_category_var_name; - $code += " //$params_category_name ${params_generate_category_name} ${cli_method_option_name}" + $NEW_LINE; - $code += " var ${cat_params_category_var_name} = cli${invoke_category_code}.category('${category_name}');" + $NEW_LINE; - $code += " var ${params_category_var_name} = ${cat_params_category_var_name}.category('${params_category_name}')" + $NEW_LINE; - $code += " .description(`$('Commands to manage the parameter input file for your ${cli_op_description}.'));" + $NEW_LINE; - $code += " var ${params_generate_category_var_name} = ${params_category_var_name}.category('${cli_method_option_name}')" + $NEW_LINE; - $code += " .description(`$('" + (Get-ParameterCommandCategoryDescription $cli_op_description $params_category_name $cli_method_option_name) +"'));" + $NEW_LINE; - $code += " ${params_generate_category_var_name}.command('${params_generate_category_name}')" + $NEW_LINE; - $code += " .description(`$('Add ${cli_method_option_name} in ${params_category_name} string or files, e.g. \r\n${sampleJsonText}\r\n" + $CLI_HELP_MSG + "'))" + $NEW_LINE; - $code += " .usage('[options]')" + $NEW_LINE; - $code += " .option('--parameter-file ', `$('The parameter file path.'))" + $NEW_LINE; - $code += " .option('--key ', `$('The JSON key.'))" + $NEW_LINE; - $code += " .option('--value ', `$('The JSON value.'))" + $NEW_LINE; - $code += " .option('--parse', `$('Parse the input value string to a JSON object.'))" + $NEW_LINE; - - # For Each Property, Add the Option - foreach ($propertyItem in $TreeNode.Properties) - { - $code += " .option('--" + (Get-CliOptionName $propertyItem["Name"]); - $code += " <" + (Get-CliNormalizedName $propertyItem["Name"]); - $code += ">', `$('Add the " + (Get-CliOptionName $propertyItem["Name"]); - $code += " value.'))" + $NEW_LINE; - } - - $code += " .execute(function(options, _) {" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(options), _);" + $NEW_LINE; - $code += " if (options.parse && options.value) {" + $NEW_LINE; - $code += " options.value = JSON.parse(options.value);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - $code += " cli.output.verbose(options.value);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Reading file content from: \`"`' + options.parameterFile + `'\`"`');" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " var fileContent = fs.readFileSync(options.parameterFile, 'utf8');" + $NEW_LINE; - $code += " var ${cli_param_name}Obj = JSON.parse(fileContent);" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object:`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - - $code += " options.operation = 'add';" + $NEW_LINE; - $code += " options.path = ${pathToTreeNode} + `'/`' + options.key;" + $NEW_LINE; - $code += " cli.output.verbose(`'options.path = `' + options.path);" + $NEW_LINE; - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: options.path, value: options.value}]);" + $NEW_LINE; - - # For Each Property, Apply the Change if Any - $isFirstDefinition = $true; - foreach ($propertyItem in $TreeNode.Properties) - { - if ($isFirstDefinition) - { - $isFirstDefinition = $false; - $defTypePrefix = "var "; - } - else - { - $defTypePrefix = ""; - } - - $paramName = (Get-CliNormalizedName $propertyItem["Name"]); - $code += " ${defTypePrefix}paramPath = ${pathToTreeNode} + `'/`' + `'${paramName}`';" + $NEW_LINE; - $code += " cli.output.verbose(`'================================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON Parameters Path:`' + paramPath);" + $NEW_LINE; - $code += " cli.output.verbose(`'================================================`');" + $NEW_LINE; - $code += " if (options.${paramName}) {" + $NEW_LINE; - $code += " if (options.parse && options.${paramName}) {" + $NEW_LINE; - $code += " options.${paramName} = JSON.parse(options.${paramName});" + $NEW_LINE; - $code += " }" + $NEW_LINE; - - if ($propertyItem["IsPrimitive"]) - { - $code += " options.${paramName} = JSON.parse(options.${paramName});" + $NEW_LINE; - } - - $code += " jsonpatch.apply(${cli_param_name}Obj, [{op: options.operation, path: paramPath, value: options.${paramName}}]);" + $NEW_LINE; - $code += " }" + $NEW_LINE; - } - - $code += " var updatedContent = JSON.stringify(${cli_param_name}Obj);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'JSON object (updated):`');" + $NEW_LINE; - $code += " cli.output.verbose(JSON.stringify(${cli_param_name}Obj));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " fs.writeFileSync(options.parameterFile, beautify(updatedContent));" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - $code += " cli.output.verbose(`'Parameter file updated at: `' + options.parameterFile);" + $NEW_LINE; - $code += " cli.output.verbose(`'=====================================`');" + $NEW_LINE; - - $code += " });" + $NEW_LINE; - $code += "" + $NEW_LINE; - - # 4. Recursive Calls for All Sub-Nodes - foreach ($subNode in $TreeNode.SubNodes) - { - if ($null -ne $subNode) - { - $code += Generate-CliParameterCommandImpl $subNode; - } - } - - return $code; -} - -function AddTo-HashTable -{ - param( - [Parameter(Mandatory = $true)] - $hashTable, - [Parameter(Mandatory = $true)] - $newKey, - [Parameter(Mandatory = $true)] - $newValue - ) - - - if ($hashTable[$newKey] -eq $null) - { - $hashTable += @{$newKey =$newValue}; - } - return $hashTable; -} - -function Merge-HashTables -{ - param( - [Parameter(Mandatory = $true)] - $hashTable1, - [Parameter(Mandatory = $true)] - $hashTable2 - ) - - foreach ($key in $hashTable2.Keys) - { - $hashTable1 = AddTo-HashTable $hashTable1 $key $hashTable2.$key; - } - return $hashTable1; -} - -function Generate-PowershellParameterCommandImpl -{ - param( - [Parameter(Mandatory = $true)] - $TreeNode, - - [Parameter(Mandatory = $false)] - [string] $fileOutputFolder = $null - ) - - $powershell_object_name = Get-SingularNoun $OperationName; - - if ($TreeNode -eq $null) - { - return $null; - } - - $paramSuffix = $powershell_object_name + $TreeNode.Name; - $category_name = Get-PowershellCategoryName $powershell_object_name; - - # 0. Construct Path to Node - $pathToTreeNode = @(); - $pathFromRoot =@(); - - $parentNode = $TreeNode; - $indexerParamList = @(); - $type_binding = @{}; - - while ($parentNode -ne $null) - { - if ($type_binding[$parentNode.Name] -eq $null) - { - if ($parentNode.IsListItem) - { - $binding_type = "Array:"+$parentNode.TypeInfo; - } - else - { - $binding_type = $parentNode.TypeInfo; - } - - $type_binding.Add($parentNode.Name, $binding_type); - } - - [string]$nodeName = $parentNode.Name.Trim(); - - if ($parentNode.Parent -ne $null) - { - $pathToTreeNode += $nodeName; - $rootNode = $parentNode.Parent; - } - - $parentNode = $parentNode.Parent; - } - - if (($rootNode.Name -ne $powershell_object_name) -and ($TreeNode.Name -ne $powershell_object_name)) - { - return; - } - - for ($i = $pathToTreeNode.Count - 1; $i -ge 0; $i--) - { - $pathFromRoot += $pathToTreeNode[$i]; - } - - $parameters = @(); - - if ($TreeNode.Properties.Count -gt 0 -or ($TreeNode.IsListItem)) - { - foreach ($propertyItem in $TreeNode.Properties) - { - if (-not ($propertyItem["Type"] -like "*$ModelNameSpace*")) - { - $property_type = Get-ProperTypeName $propertyItem["Type"]; - if ($propertyItem["CanWrite"]) - { - $param_name = Get-SingularNoun $propertyItem["Name"]; - $param = @{Name = $param_name; Type = $property_type; OriginalName = $propertyItem["Name"]; Chain = $pathFromRoot}; - $parameters += $param; - } - } - else - { - Write-Verbose("Skip this property: " + $propertyItem["Name"]); - } - } - - foreach ($subNode in $TreeNode.SubNodes) - { - $nonSingleSubNodeResult = Get-NonSingleComplexDescendant $subNode $pathFromRoot; - $nonSingleSubNode = $nonSingleSubNodeResult["Node"]; - - if (-not $nonSingleSubNode.IsListItem) - { - foreach ($propertyItem in $nonSingleSubNode.Properties) - { - if ($propertyItem["CanWrite"]) - { - $property_type = Get-ProperTypeName $propertyItem["Type"]; - $chain = $nonSingleSubNodeResult["Chain"]; - $chain += $nonSingleSubNode.Name; - $type_binding = AddTo-HashTable $type_binding $nonSingleSubNode.Name $nonSingleSubNode.TypeInfo; - - if ($nonSingleSubNode.OnlySimple) - { - $param_name = Get-SingularNoun ($nonSingleSubNode.Name + $propertyItem["Name"]); - $param = @{Name = $param_name; Type = $property_type; OriginalName = $propertyItem["Name"]; Chain = $chain}; - $parameters += $param; - } - else - { - if ($propertyItem["Type"] -like "*$ModelNameSpace*") - { - - $subsub = Get-SpecificSubNode $nonSingleSubNode $propertyItem["Name"]; - $nonSingleComlexResult = Get-NonSingleComplexDescendant $subsub $chain; - $realsubsub = $nonSingleComlexResult["Node"]; - $chain = $nonSingleComlexResult["Chain"]; - - if ($realsubsub.Properties.Count -eq 1) - { - $parameter = $realsubsub.Properties[0]; - $property_type = $parameter["Type"]; - - if ($realsubsub.IsListItem) - { - $paramterType = "Array:" + $property_type; - $bindingType = "Array:" + $realsubsub.TypeInfo; - } - else - { - $paramterType = $property_type; - $bindingType = $realsubsub.TypeInfo; - } - - $chain += $realsubsub.Name; - $type_binding = AddTo-HashTable $type_binding $realsubsub.Name $bindingType; - - if ($propertyItem["CanWrite"]) - { - $param_name = Get-SingularNoun $propertyItem["Name"]; - $param = @{Name = $param_name; Type = $paramterType; OriginalName = $parameter["Name"]; Chain = $chain}; - $parameters += $param; - } - } - else - { - if ($realsubsub.IsListItem) - { - $property_type = Get-ProperTypeName $realsubsub.TypeInfo; - $paramterType = "Array:" + $property_type; - } - else - { - $property_type = Get-ProperTypeName $realsubsub.TypeInfo; - $paramterType = $property_type; - } - $param_name = Get-SingularNoun $realsubsub.Name; - $param = @{Name = $param_name; Type = $paramterType; OriginalName = $realsubsub.Name; Chain = $chain}; - $parameters += $param; - - $binding = Generate-PowershellParameterCommandImpl $realsubsub $fileOutputFolder; - $type_binding = Merge-HashTables $type_binding $binding; - } - } - else - { - $param_name = Get-SingularNoun $propertyItem["Name"]; - $param = @{Name = $param_name; Type = $property_type; OriginalName = $propertyItem["Name"]; Chain = $chain}; - $parameters += $param; - } - } - } - } - } - elseif ($nonSingleSubNode.Properties.Count -eq 1) - { - $onlyProperty = $nonSingleSubNode.Properties[0]; - $chain = $nonSingleSubNodeResult["Chain"]; - $chain += $nonSingleSubNode.Name; - $type_info = "Array:" + $nonSingleSubNode.TypeInfo; - $type_binding = AddTo-HashTable $type_binding $nonSingleSubNode.Name $type_info; - $property_type = Get-ProperTypeName $onlyProperty["Type"]; - if ($onlyProperty["CanWrite"]) - { - $param_name = Get-SingularNoun ($nonSingleSubNode.Name + $onlyProperty["Name"]); - $param = @{Name = $param_name; Type = "Array:" + $property_type; OriginalName = $onlyProperty["Name"]; Chain = $chain}; - $parameters += $param; - } - } - else - { - $chain = $nonSingleSubNodeResult["Chain"]; - $property_type = Get-ProperTypeName $nonSingleSubNode.TypeInfo; - - $param_name = Get-SingularNoun $nonSingleSubNode.Name; - $param = @{Name = $param_name; Type = "Array:" + $property_type; OriginalName = $nonSingleSubNode.Name; Chain = $chain}; - $parameters += $param; - $binding = Generate-PowershellParameterCommandImpl $nonSingleSubNode $fileOutputFolder; - $type_binding = Merge-HashTables $type_binding $binding; - } - } - - (. $PSScriptRoot\Generate-PowershellParameterCmdlet.ps1 -OutputFolder $OutputFolder -TreeNode $TreeNode -Parameters $parameters -ModelNameSpace $ModelNameSpace -ObjectName $powershell_object_name -TypeBinding $type_binding); - } - - return $type_binding; -} - -$ignore_this_output = Generate-PowershellParameterCommandImpl $CmdletTreeNode $OutputFolder; - -if ($ToolType -eq 'CLI') -{ - Write-Output (Generate-CliParameterCommandImpl $CmdletTreeNode); -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-PowershellParameterCmdlet.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-PowershellParameterCmdlet.ps1 deleted file mode 100644 index ffea727f9a5c..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Generate-PowershellParameterCmdlet.ps1 +++ /dev/null @@ -1,1142 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -param( - [Parameter(Mandatory = $true)] - [string]$OutputFolder, - - [Parameter(Mandatory = $true)] - $TreeNode, - - [Parameter(Mandatory = $true)] - $Parameters, - - [Parameter(Mandatory = $true)] - [string]$ModelNameSpace, - - # VirtualMachine, VirtualMachineScaleSet, etc. - [Parameter(Mandatory = $true)] - [string]$ObjectName, - - [Parameter(Mandatory = $true)] - $TypeBinding -) - -function Does-Contain -{ - param( - [Parameter(Mandatory = $True)] - $arrayOfArray, - [Parameter(Mandatory = $True)] - $element - ) - - foreach($a in $arrayOfArray) - { - $check = Compare-Object -ReferenceObject $a -DifferenceObject $element - - if ($check -eq $null) - { - return $True; - } - } - - return $false; -} - -function Get-ParameterChainSet -{ - - param( - [Parameter(Mandatory = $True)] - $parameters - ) - - $chainSet = @(); - foreach ($p in $parameters) - { - if (-not [System.String]::IsNullOrEmpty($p["Chain"])) - { - if (-not (Does-Contain $chainSet $p["Chain"])) - { - $chainSet += , $p["Chain"]; - } - } - } - return ,$chainSet; -} - -function Get-ArrayType -{ - param( - [Parameter(Mandatory = $True)] - [string] $type - ) - - if ($type.StartsWith("Array:")) - { - $type = $type.Replace("Array:", "") + " []"; - } - if ($type.StartsWith("IList<")) - { - $type = $type.Replace("IList<", "").Replace(">", "") + " []"; - } - return $type; -} - -function Get-ListType -{ - param( - [Parameter(Mandatory = $True)] - [string] $type - ) - - if ($type.StartsWith("Array:")) - { - $type = $type.Replace("Array:", "List<") + ">"; - } - if ($type.StartsWith("IList<")) - { - $type = $type.Replace("IList<", "List<") + ">"; - } - return $type; -} - -function Is-ValueType -{ - param( - [Parameter(Mandatory = $True)] - [string] $type - ) - - if ($type.Equals("bool")) - { - return $True; - } - if ($type.Contains("int") -and $type.EndsWith("?")) - { - return $True; - } - return $false; -} - -function Is-DictionaryType -{ - param( - [Parameter(Mandatory = $True)] - [string] $type - ) - - if ($type.StartsWith("IDictionary") -or $type.StartsWith("Dictionary")) - { - $start = $type.IndexOf("<")+1; - $end = $type.IndexOf(">"); - return $type.Substring($start, $end-$start); - } - return $null; -} - -function Get-AssignCode -{ - param( - [Parameter(Mandatory = $True)] - $parameter, - [Parameter(Mandatory = $false)] - $nullCheck = $True - ) - - $dic = Is-DictionaryType $parameter["Type"]; - $property_name = $parameter["Name"]; - if ($dic -eq $null) - { - $assign_code = "this." + $property_name; - } - else - { - $key_value_pair_type = $dic.Split(","); - $assign_code = "this.${property_name}.Cast().ToDictionary(ht => (" + $key_value_pair_type[0]+ ")ht.Key, ht => (" + $key_value_pair_type[1]+ ")ht.Value)"; - if ($nullCheck) - { - $assign_code = "(this.${property_name} == null) ? null : " + $assign_code; - } - } - return $assign_code; -} - - -function Get-SingleType -{ - param( - [Parameter(Mandatory = $True)] - [string] $type - ) - - if ($type.StartsWith("Array:")) - { - $type = $type.Replace("Array:", ""); - } - if ($type.StartsWith("IList<")) - { - $type = $type.Replace("IList<", "").Replace(">", ""); - } - return $type; -} - - -function Get-SortedUsings -{ - param( - [Parameter(Mandatory = $True)] - $usings_array - ) - - $sorted_usings = $usings_array | Sort-Object -Unique | foreach { "using ${_};" }; - - $text = [string]::Join($NEW_LINE, $sorted_usings); - - return $text; -} - -function Get-SimpleNoun -{ - param( - [Parameter(Mandatory = $True)] - [string] $noun - ) - if ($noun.Equals("VirtualMachineScaleSet")) - { - return "Vmss"; - } - else - { - return $noun; - } -} - -function Get-ArrayParent -{ - param( - [Parameter(Mandatory = $True)] - $chain - ) - - if ($chain -eq $null) - { - return ""; - } - $result = ""; - for ($i = $chain.Length - 1; $i -ge 0 ; $i--) - { - $c = $chain[$i]; - if ($i -eq $chain.Length - 1) - { - $result = $c; - } - else - { - $result = $c + "." + $result; - } - - $t = $TypeBinding[$c]; - - if ($t.ToString().StartsWith("Array:")) - { - return $result; - } - } - return ""; -} - -function Get-ParameterCode -{ - param( - [Parameter(Mandatory = $True)] - $parameter, - - [Parameter(Mandatory = $True)] - [int] $index, - - [Parameter(Mandatory = $false)] - [bool] $make_null = $false - ) - - $p_type = Get-ArrayType $parameter["Type"]; - - if ($make_null -and (Is-ValueType $p_type)) - { - $p_type += "?"; - } - if ((Is-DictionaryType $p_type) -ne $null) - { - $p_type = "Hashtable"; - } - - $p_name = $parameter["Name"]; - - $return_code = -@" - - [Parameter( - Mandatory = false, - Position = $index, - ValueFromPipelineByPropertyName = true)] - public $p_type $p_name { get; set; } - -"@; - - return $return_code; -} - -function Get-PropertyFromChain -{ - param( - [Parameter(Mandatory = $True)] - $array - ) - - $result = $array[0]; - - for ($i = 1; $i -lt $array.Count ; $i++) - { - $result += "." + $array[$i]; - } - - return $result; -} - -function Get-VariableName -{ - param( - [Parameter(Mandatory = $True)] - $array - ) - - $result = "v" + (Get-PropertyFromChain $array); - return $result; -} - -function Get-NewObjectCode -{ - param( - [Parameter(Mandatory = $True)] - $chain, - - [Parameter(Mandatory = $false)] - [int] $left_space = 0 - ) - - $return_string = "`r`n"; - $new_obj = ${ObjectName}; - - for ($i = 0; $i -lt $chain.Count; $i++) - { - $c = $chain[$i]; - $new_obj += "." + $c; - $single_type = Get-SingleType $TypeBinding[$c]; - $type = Get-ListType $TypeBinding[$c]; - - $left_pad = " " * $left_space; - $left_deep_pad = " " * ($left_space + 4); - $right_pad = "`r`n"; - - $return_string += $left_pad + "// ${c}" + $right_pad; - $return_string += $left_pad + "if (this.${new_obj} == null)" + $right_pad; - $return_string += $left_pad + "{" + $right_pad; - $return_string += $left_deep_pad + "this.${new_obj} = new ${type}();" + $right_pad; - $return_string += $left_pad + "}" + $right_pad; - } - return $return_string; -} - -function Write-PowershellCmdlet -{ - param( - [Parameter(Mandatory = $true)] - [string]$cmdlet_verb, - - [Parameter(Mandatory = $true)] - [string]$OutputFolder, - - [Parameter(Mandatory = $true)] - $TreeNode, - - [Parameter(Mandatory = $true)] - $Parameters, - - [Parameter(Mandatory = $true)] - [string]$ModelNameSpace, - - # VirtualMachine, VirtualMachineScaleSet, etc. - [Parameter(Mandatory = $true)] - [string]$ObjectName, - - [Parameter(Mandatory = $true)] - $TypeBinding - ) - - - - $library_namespace = $ModelNameSpace.Substring(0, $ModelNameSpace.LastIndexOf('.')); - - $ps_cmdlet_namespace = ($library_namespace.Replace('.Management.', '.Commands.')); - $ps_generated_cmdlet_namespace = $ps_cmdlet_namespace + '.Automation'; - $ps_generated_model_namespace = $ps_cmdlet_namespace + '.Automation.Models'; - $ps_common_namespace = $ps_cmdlet_namespace.Substring(0, $ps_cmdlet_namespace.LastIndexOf('.')); - - $parameter_cmdlet_usings = @( - 'System', - 'System.Collections', - 'System.Collections.Generic', - 'System.Linq', - 'System.Management.Automation' - ); - - $parameter_cmdlet_usings += $ModelNameSpace; - - $cmdlet_noun = "AzureRm"; - $cmdlet_noun += Get-SimpleNoun $ObjectName; - - if ($TreeNode.Name -ne ${ObjectName}) - { - $cmdlet_noun += Get-SingularNoun $TreeNode.Name; - } - - if ($cmdlet_verb.Equals("New")) - { - $cmdlet_noun += "Config"; - } - - if (($cmdlet_verb.Equals("Add") -or $cmdlet_verb.Equals("Remove")) -and $cmdlet_noun.EndsWith('s')) - { - $cmdlet_noun = $cmdlet_noun.Substring(0, $cmdlet_noun.Length - 1); - } - - $cmdlet_class_name = $cmdlet_verb + $cmdlet_noun + "Command"; - - $cmdlet_class_code = -@" - -namespace ${ps_generated_cmdlet_namespace} -{ - [Cmdlet(`"${cmdlet_verb}`", `"${cmdlet_noun}`")] - [OutputType(typeof(${ObjectName}))] - public class $cmdlet_class_name : $ps_common_namespace.ResourceManager.Common.AzureRMCmdlet - { -"@; - - if ($cmdlet_verb.Equals("New")) - { - for($i = 0; $i -lt $Parameters.Count ; $i++) - { - $cmdlet_class_code += Get-ParameterCode $Parameters[$i] $i; - } - } - else - { - $cmdlet_class_code += -@" - - [Parameter( - Mandatory = false, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] - public ${ObjectName} ${ObjectName} { get; set; } - -"@; - - - for($i = 0; $i -lt $Parameters.Count ; $i++) - { - $j = $i + 1; - if ($cmdlet_verb.Equals("Remove")) - { - $cmdlet_class_code += Get-ParameterCode $Parameters[$i] $j $true; - } - else - { - $cmdlet_class_code += Get-ParameterCode $Parameters[$i] $j; - } - } - } - - if ($TreeNode -eq $null) - { - return $null; - } - - $chain_set = (Get-ParameterChainSet $Parameters); - $object_list = @(); - $cmdlet_complex_parameter_code = ""; - $cmdlet_new_object_code = ""; - $cmdlet_new_single_object_code = @{}; - $cmdlet_add_single_object_code = @{}; - $cmdlet_code_add_body = ""; - - - if ($cmdlet_verb.Equals("New") -and ($TreeNode.Name -eq ${ObjectName})) - { - foreach($chain in $chain_set) - { - $new_obj = $chain[0]; - $var_name = "v" + $new_obj; - - if(-not $object_list.Contains($new_obj)) - { - $object_list += $new_obj; - $type = $TypeBinding[$new_obj]; - - $cmdlet_new_object_code += -@" - - // ${new_obj} - var ${var_name} = new ${type}(); - -"@; - - $cmdlet_complex_parameter_code += -@" - - ${new_obj} = ${var_name}, -"@; - } - - - for ($i = 1; $i -lt $chain.Count; $i++) - { - $c = $chain[$i]; - - $new_obj += "." + $c; - $var_name = "v" + $new_obj; - - if(-not $object_list.Contains($new_obj)) - { - $object_list += $new_obj; - $type = $TypeBinding[$c]; - - $cmdlet_new_object_code += -@" - - // ${c} - ${var_name} = new ${type}(); - -"@; - } - } - } - } - elseif ($cmdlet_verb.Equals("New")) - { - foreach($chain in $chain_set) - { - $is_parent_list = $null; - - $start = $false; - - for ($i = 0; $i -lt $chain.Count; $i++) - { - $c = $chain[$i]; - Write-Verbose ("Chain["+$i + "]: " + $c); - - if ($c -eq $TreeNode.Name) - { - $start = $True; - $new_obj = ""; - } - - if ($start) - { - $new_obj += "." + $c; - - if(-not $object_list.Contains($new_obj)) - { - $object_list += $new_obj; - $single_type = Get-SingleType $TypeBinding[$c]; - $type = Get-ListType $TypeBinding[$c]; - - if ($is_parent_list -ne $null) - { - $cmdlet_code_add_body += -@" - - // ${c} - v${is_parent_list}.${c} = new ${type}(); - -"@; - - } - - if ($TypeBinding[$c].ToString().StartsWith("Array:")) - { - $new_code = "var v${c} = new ${single_type}();"; - - $cmdlet_new_single_object_code.Add($c, $new_code); - } - - } - - if ($TypeBinding[$c].ToString().StartsWith("Array:")) - { - $is_parent_list = $c; - } - - } - } - } - } - elseif ($cmdlet_verb.Equals("Remove")) - { - $remove_object = $null; - foreach($chain in $chain_set) - { - $new_obj = $chain[0]; - $is_parent_list = $null; - - for ($i = 0; $i -lt $chain.Count; $i++) - { - if ($remove_object -eq $null) - { - - $c = $chain[$i]; - $array_parent = Get-ArrayParent $chain; - - if ($i -ne 0) - { - $new_obj += "." + $c; - } - - if(-not $object_list.Contains($new_obj)) - { - $object_list += $new_obj; - $single_type = Get-SingleType $TypeBinding[$c]; - $type = Get-ListType $TypeBinding[$c]; - - $cmdlet_new_object_code += -@" - - // ${c} - if (this.${ObjectName}.${new_obj} == null) - { - WriteObject(this.${ObjectName}); - return; - } - -"@; - } - - if ($TypeBinding[$c].ToString().StartsWith("Array:")) - { - $is_parent_list = $c; - } - - if ($TypeBinding[$c].ToString().StartsWith("Array:") -and $array_parent.StartsWith(${c})) - { - $cmdlet_new_object_code += -@" - var v${c} = this.${ObjectName}.${new_obj}.First - (e => -"@; - - $cmdlet_remove_object_code = -@" - if (v${c} != null) - { - this.${ObjectName}.${new_obj}.Remove(v${c}); - } - - if (this.${ObjectName}.${new_obj}.Count == 0) - { - this.${ObjectName}.${new_obj} = null; - } -"@; - $remove_object = $c; - } - } - } - } - } - elseif ($cmdlet_verb.Equals("Add")) - { - # Set,Add - foreach($chain in $chain_set) - { - $new_obj = $chain[0]; - $is_parent_list = $null; - - for ($i = 0; $i -lt $chain.Count; $i++) - { - $c = $chain[$i]; - - if ($i -ne 0) - { - $new_obj += "." + $c; - } - - if(-not $object_list.Contains($new_obj)) - { - $object_list += $new_obj; - $single_type = Get-SingleType $TypeBinding[$c]; - $type = Get-ListType $TypeBinding[$c]; - - if ($is_parent_list -ne $null) - { - $cmdlet_code_add_body += -@" - - // ${c} - v${is_parent_list}.${c} = new ${type}(); - -"@; - - } - else - { - $cmdlet_new_object_code += -@" - - // ${c} - if (this.${ObjectName}.${new_obj} == null) - { - this.${ObjectName}.${new_obj} = new ${type}(); - } - -"@; - } - - if ($TypeBinding[$c].ToString().StartsWith("Array:")) - { - $new_code = "var v${c} = new ${single_type}();"; - - if ($is_parent_list -eq $null) - { - $add_code = "this.${ObjectName}.${new_obj}.Add(v${c});"; - } - else - { - $add_code = "v${is_parent_list}.${c}.Add(v${c});"; - } - - $cmdlet_new_single_object_code.Add($c, $new_code); - $cmdlet_add_single_object_code.Add($c, $add_code); - } - } - - if ($TypeBinding[$c].ToString().StartsWith("Array:")) - { - $is_parent_list = $c; - } - } - } - } - - # - # New config cmdlet - # - if ($cmdlet_verb.Equals("New") -and ($TreeNode.Name -eq ${ObjectName})) - { - $cmdlet_code_body = -@" - protected override void ProcessRecord() - { -"@; - - $cmdlet_code_body += $cmdlet_new_object_code; - - foreach($p in $Parameters) - { - if (-not [System.String]::IsNullOrEmpty($p["Chain"])) - { - $var_name = Get-VariableName $p["Chain"]; - $property = $p["OriginalName"]; - $thisProperty = $p["Name"]; - $assign = Get-AssignCode $p; - - $cmdlet_code_body += -@" - ${var_name}.${property} = ${assign}; - -"@; - } - } - - $cmdlet_code_body += -@" - - var v${ObjectName} = new ${ObjectName} - { -"@; - - foreach($p in $Parameters) - { - if ([System.String]::IsNullOrEmpty($p["Chain"])) - { - $property = $p["OriginalName"]; - $thisProperty = $p["Name"]; - $assign = Get-AssignCode $p; - - $cmdlet_code_body += -@" - - ${property} = ${assign}, -"@; - } - } - - $cmdlet_code_body += $cmdlet_complex_parameter_code; - $cmdlet_code_body += -@" - - }; - - WriteObject(v${ObjectName}); - } - } -} - -"@; - } - elseif ($cmdlet_verb.Equals("New")) - { - $cmdlet_code_body = -@" - protected override void ProcessRecord() - { -"@; - $cmdlet_code_body += $cmdlet_new_object_code; - - foreach($p in $Parameters) - { - $chain = $p["Chain"]; - $var_name = $chain[$chain.Length - 1]; - $type = $TypeBinding[$var_name]; - $single_type = $type.ToString().Replace("Array:", ""); - - if (-not [System.String]::IsNullOrEmpty($p["Chain"])) - { - $property = $p["OriginalName"]; - $thisProperty = $p["Name"]; - $thisType = $p["Type"]; - $array_parent = Get-ArrayParent $chain; - $assign = Get-AssignCode $p; - - if ($thisType.ToString().StartsWith("Array:") -and ($array_parent -ne $TreeNode.Name)) - { - $new_code = $cmdlet_new_single_object_code[$array_parent]; - $cmdlet_new_single_object_code.Remove($array_parent); - $cmdlet_add_single_object_code.Remove($array_parent); - - $var_name = $chain[$chain.Length - 2] + "." + ${var_name}; - $cmdlet_code_add_body += -@" - - if (this.${thisProperty} != null) - { - foreach (var element in this.${thisProperty}) - { - ${new_code} - v${array_parent}.${property} = element; - } - } - -"@; - } - else - { - $cmdlet_code_add_body += -@" - - v${array_parent}.${property} = ${assign}; -"@; - } - } - } - - foreach ($key in $cmdlet_new_single_object_code.Keys) - { - $new_code = $cmdlet_new_single_object_code[$key]; - $cmdlet_code_body += -@" - - ${new_code} - -"@; - } - - $cmdlet_code_body += $cmdlet_code_add_body; - - $write_object = "v" + $TreeNode.Name; - - $cmdlet_code_body += -@" - - WriteObject($write_object); - } - } -} - -"@; - } - elseif ($cmdlet_verb.Equals("Set")) - { - $cmdlet_code_body = -@" - protected override void ProcessRecord() - { -"@; - - $cmdlet_code_body += $cmdlet_new_object_code; - - foreach($p in $Parameters) - { - if (-not [System.String]::IsNullOrEmpty($p["Chain"])) - { - $my_chain = $p["Chain"]; - $var_name = Get-PropertyFromChain $my_chain; - $property = $p["OriginalName"]; - $assign = Get-AssignCode $p; - - $create_object_code = Get-NewObjectCode $my_chain 16; - $cmdlet_code_body += -@" - - if (${assign} != null) - { -"@ - - $cmdlet_code_body += ${create_object_code}; - - $cmdlet_code_body += -@" - this.${ObjectName}.${var_name}.${property} = ${assign}; - } - -"@; - } - } - - $cmdlet_code_body += -@" - - WriteObject(this.${ObjectName}); - } - } -} - -"@; - } - elseif ($cmdlet_verb.Equals("Remove")) - { - $cmdlet_code_body = -@" - protected override void ProcessRecord() - { -"@; - $cmdlet_code_body += $cmdlet_new_object_code; - - $cmdlet_code_remove_body = ""; - - for($i = 0; $i -lt $Parameters.Count ; $i++) - { - $p = $Parameters[$i]; - $chain = $p["Chain"]; - $var_name = $chain[$chain.Length - 1]; - - if (-not [System.String]::IsNullOrEmpty($p["Chain"])) - { - $property = $p["OriginalName"]; - $thisProperty = $p["Name"]; - $array_parent = Get-ArrayParent $chain; - $assign = Get-AssignCode $p $false; - - if ($array_parent -ne $TreeNode.Name) - { - $middle = $array_parent.TrimStart($TreeNode.Name); - - if ($i -eq 0) - { - $cmdlet_code_remove_body += -@" - - (this.${thisProperty} == null || e${middle}.${property} == ${assign}) - -"@; - } - else - { - - $cmdlet_code_remove_body += -@" - && (this.${thisProperty} == null || e${middle}.${property} == ${assign}) - -"@; - } - } - else - { - if ($i -eq 0) - { - $cmdlet_code_remove_body += -@" - - (this.${thisProperty} == null || e.${property} == ${assign}) - -"@; - } - else - { - $cmdlet_code_remove_body += -@" - && (this.${thisProperty} == null || e.${property} == ${assign}) - -"@; - } - } - } - } - - $cmdlet_code_remove_body += -@" - ); - -$cmdlet_remove_object_code -"@; - - $cmdlet_code_body += $cmdlet_code_remove_body; - - $cmdlet_code_body += -@" - - WriteObject(this.${ObjectName}); - } - } -} - -"@; - } - else - { # "Add" - $cmdlet_code_body = -@" - protected override void ProcessRecord() - { -"@; - $cmdlet_code_body += $cmdlet_new_object_code; - - foreach($p in $Parameters) - { - $chain = $p["Chain"]; - - if (-not [System.String]::IsNullOrEmpty($chain)) - { - $property = $p["OriginalName"]; - $thisProperty = $p["Name"]; - $array_parent = Get-ArrayParent $chain; - $assign = Get-AssignCode $p; - - $cmdlet_code_add_body += -@" - - v${array_parent}.${property} = ${assign}; -"@; - - } - } - - foreach ($key in $cmdlet_new_single_object_code.Keys) - { - $new_code = $cmdlet_new_single_object_code[$key]; - $cmdlet_code_body += -@" - - ${new_code} - -"@; - } - - $cmdlet_code_body += $cmdlet_code_add_body; - - foreach ($key in $cmdlet_add_single_object_code.Keys) - { - $add_code = $cmdlet_add_single_object_code[$key]; - $cmdlet_code_body += -@" - - ${add_code} -"@; - } - - $cmdlet_code_body += -@" - - WriteObject(this.${ObjectName}); - } - } -} - -"@; - } - - $code_usings = Get-SortedUsings $parameter_cmdlet_usings; - - $OutputFolder += "/Config/"; - - if (-not (Test-Path -Path $OutputFolder)) - { - mkdir $OutputFolder -Force; - } - - $fileFullPath = $OutputFolder + $cmdlet_class_name + ".cs"; - $full_code = $code_common_header + "`r`n`r`n" + $code_usings + "`r`n" + $cmdlet_class_code + "`r`n" + $cmdlet_code_body; - - Set-FileContent -Path $fileFullPath -Value $full_code; -} - -# Decide the name of cmdlet verb -if ($TreeNode.Name.Equals($ObjectName)) -{ - $verb = "New"; -} -elseif ($TreeNode.IsListItem) -{ - $parent_node = $TreeNode.Parent; - $add_cmdlet = $True; - while (($parent_node -ne $null) -or ($parent_node.Name -eq $ObjectName)) - { - if ($parent_node.IsListItem) - { - $add_cmdlet = $false; - } - $parent_node = $parent_node.Parent; - } - - if ($add_cmdlet) - { - $verb = "Add"; - } - else - { - $verb = "New"; - } -} -else -{ - $verb = "Set"; -} - -Write-PowershellCmdlet $verb $OutputFolder $TreeNode $Parameters $ModelNameSpace $ObjectName $TypeBinding; - -if ($verb.Equals("Add")) -{ - Write-PowershellCmdlet "Remove" $OutputFolder $TreeNode $Parameters $ModelNameSpace $ObjectName $TypeBinding; -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-AssemblyFunction.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-AssemblyFunction.ps1 deleted file mode 100644 index e75c7be3b996..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-AssemblyFunction.ps1 +++ /dev/null @@ -1,51 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -function Load-AssemblyFile -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$dllPath - ) - - $assembly = [System.Reflection.Assembly]::LoadFrom($dllPath); - $st = [System.Reflection.Assembly]::LoadWithPartialName("System.Collections.Generic"); - return $assembly; -} - -function Get-AzureNameSpace -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$dllPath - ) - - [System.Reflection.Assembly]$assembly = Load-AssemblyFile $dllPath; - - $clientNameSpace = $null; - foreach ($type in $assembly.GetTypes()) - { - [System.Type]$type = $type; - if ($type.Namespace -like "Microsoft.*Azure.Management.*" -and ` - $type.Namespace -notlike "Microsoft.*Azure.Management.*.Model*") - { - $clientNameSpace = $type.Namespace; - break; - } - } - - return $clientNameSpace; -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-CommonVariables.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-CommonVariables.ps1 deleted file mode 100644 index d1ab59e6cc3c..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-CommonVariables.ps1 +++ /dev/null @@ -1,164 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -$VerbosePreference='Continue'; -$ErrorActionPreference = "Stop"; - -$NEW_LINE = "`r`n"; -$BAR_LINE = "============================================="; -$SEC_LINE = "---------------------------------------------"; -$verbs_common_new = "VerbsCommon.New"; -$verbs_lifecycle_invoke = "VerbsLifecycle.Invoke"; - -$common_verb_mapping = -@{ -"CreateOrUpdate" = "New"; -"Get" = "Get"; -"List" = "Get"; -"Delete" = "Remove"; -"Deallocate" = "Stop"; -"PowerOff" = "Stop"; -"Start" = "Start"; -"Restart" = "Restart"; -"Capture" = "Save"; -"Update" = "Update"; -}; - -$common_noun_mapping = -@{ -"VirtualMachine" = "VM"; -"ScaleSet" = "SS"; -}; - -$code_common_usings = @( - 'System', - 'System.Collections.Generic', - 'System.Linq', - 'System.Management.Automation', - 'Microsoft.Azure' -); - -$code_common_header = -@" -// -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// Warning: This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if the -// code is regenerated. -"@; - -. "$PSScriptRoot\Import-AssemblyFunction.ps1"; - -# Load Assembly and get the Azure namespace for the client, -# e.g. Microsoft.Azure.Management.Compute -$clientNameSpace = Get-AzureNameSpace $dllFileFullPath; -$clientModelNameSpace = $clientNameSpace + '.Models'; - -$is_hyak_mode = $clientNameSpace -like "Microsoft.WindowsAzure.*.*"; -$component_name = $clientNameSpace.Substring($clientNameSpace.LastIndexOf('.') + 1); - -# The base cmdlet from which all automation cmdlets derive -[string]$baseCmdletFullName = "Microsoft.Azure.Commands.${component_name}.${component_name}ClientBaseCmdlet"; -if ($clientNameSpace -eq "Microsoft.WindowsAzure.Management.${component_name}") -{ - # Overwrite RDFE base cmdlet name - $baseCmdletFullName = "Microsoft.WindowsAzure.Commands.Utilities.Common.ServiceManagementBaseCmdlet"; -} - -# The property field to access the client wrapper class from the base cmdlet -[string]$baseClientFullName = "${component_name}Client.${component_name}ManagementClient"; -if ($clientNameSpace -eq "Microsoft.WindowsAzure.Management.${component_name}") -{ - # Overwrite RDFE base cmdlet name - $baseClientFullName = "${component_name}Client"; -} - -# Initialize other variables -$all_return_type_names = @(); - -# XML Documentation -if (Test-Path -Path $dllFileFullPath.Replace('.dll', '.xml')) -{ - $xmlFileFullPath = $dllFileFullPath.Replace('.dll', '.xml'); - [xml]$xmlDoc = Get-Content $xmlFileFullPath; - $xmlDocItems = $xmlDoc.SelectNodes('doc/members/*'); -} - -Write-Verbose $BAR_LINE; -Write-Verbose "Input Parameters:"; -Write-Verbose "DLL File = $dllFileFullPath"; -Write-Verbose "XML File = $xmlFileFullPath"; -Write-Verbose "Out Folder = $outFolder"; -Write-Verbose "Config Path = $ConfigPath"; -Write-Verbose "Client NameSpace = $clientNameSpace"; -Write-Verbose "Model NameSpace = $clientModelNameSpace"; -Write-Verbose "Component Name = $component_name"; -Write-Verbose "Base Cmdlet Full Name = $baseCmdletFullName"; -Write-Verbose "Base Client Full Name = $baseClientFullName"; -Write-Verbose "Cmdlet Flavor = $cmdletFlavor"; -Write-Verbose "Operation Name Filter = $operationNameFilter"; -Write-Verbose $BAR_LINE; -Write-Verbose $NEW_LINE; - -$code_common_namespace = ($clientNameSpace.Replace('.Management.', '.Commands.')) + '.Automation'; -$code_model_namespace = ($clientNameSpace.Replace('.Management.', '.Commands.')) + '.Automation.Models'; - -function Get-SortedUsingsCode -{ - $list_of_usings = @() + $code_common_usings + $clientNameSpace + $clientModelNameSpace + $code_model_namespace; - $sorted_usings = $list_of_usings | Sort-Object -Unique | foreach { "using ${_};" }; - $text = [string]::Join($NEW_LINE, $sorted_usings); - return $text; -} - -$code_using_strs = Get-SortedUsingsCode; - -function Get-RomanNumeral -{ - param - ( - [Parameter(Mandatory = $true)] - $number - ) - - if ($number -ge 1000) { return "M" + (Get-RomanNumeral ($number - 1000)); } - if ($number -ge 900) { return "CM" + (Get-RomanNumeral ($number - 900)); } - if ($number -ge 500) { return "D" + (Get-RomanNumeral ($number - 500)); } - if ($number -ge 400) { return "CD" + (Get-RomanNumeral ($number - 400)); } - if ($number -ge 100) { return "C" + (Get-RomanNumeral ($number - 100)); } - if ($number -ge 90) { return "XC" + (Get-RomanNumeral ($number - 90)); } - if ($number -ge 50) { return "L" + (Get-RomanNumeral ($number - 50)); } - if ($number -ge 40) { return "XL" + (Get-RomanNumeral ($number - 40)); } - if ($number -ge 10) { return "X" + (Get-RomanNumeral ($number - 10)); } - if ($number -ge 9) { return "IX" + (Get-RomanNumeral ($number - 9)); } - if ($number -ge 5) { return "V" + (Get-RomanNumeral ($number - 5)); } - if ($number -ge 4) { return "IV" + (Get-RomanNumeral ($number - 4)); } - if ($number -ge 1) { return "I" + (Get-RomanNumeral ($number - 1)); } - return ""; -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-OperationFunction.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-OperationFunction.ps1 deleted file mode 100644 index 549f56216d98..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-OperationFunction.ps1 +++ /dev/null @@ -1,160 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -function Get-HyakOperationShortName -{ - param( - # Sample #1: 'IVirtualMachineOperations' => 'VirtualMachine' - # Sample #2: 'IDeploymentOperations' => 'Deployment' - [Parameter(Mandatory = $true)] - [string]$opFullName, - - [Parameter(Mandatory = $false)] - [string]$prefix = 'I', - - [Parameter(Mandatory = $false)] - [string]$suffix = 'Operations' - ) - - $opShortName = $opFullName; - if ($opFullName.StartsWith($prefix) -and $opShortName.EndsWith($suffix)) - { - $lenOpShortName = ($opShortName.Length - $prefix.Length - $suffix.Length); - $opShortName = $opShortName.Substring($prefix.Length, $lenOpShortName); - } - - return $opShortName; -} - -function Get-AutoRestOperationShortName -{ - param( - # Sample #1: 'VirtualMachineOperationsExtensions' => 'VirtualMachine' - # Sample #2: 'DeploymentOperationsExtensions' => 'Deployment' - [Parameter(Mandatory = $True)] - [string]$opFullName - ) - - $prefix = ''; - $suffix = 'OperationsExtensions'; - $result = Get-HyakOperationShortName $opFullName $prefix $suffix; - - return $result; -} - -function Get-OperationShortName -{ - param( - # Sample #1: 'VirtualMachineOperationsExtensions' => 'VirtualMachine' - # Sample #2: 'DeploymentOperationsExtensions' => 'Deployment' - [Parameter(Mandatory = $true)] - [string]$opFullName, - - # Hyak or AutoRest - [Parameter(Mandatory = $false)] - [bool]$isHyakMode = $false - ) - # $isHyakMode = $isHyakMode -or ($client_library_namespace -like "Microsoft.WindowsAzure.*.*"); - # if ($isHyakMode) - # { - # return Get-AutoRestOperationShortName $opFullName; - # } - # else - # { - # return Get-AutoRestOperationShortName $opFullName; - # } - return Get-AutoRestOperationShortName $opFullName; -} - -function Match-OperationFilter -{ - param( - [Parameter(Mandatory = $true)] - [string]$operation_full_name, - - [Parameter(Mandatory = $true)] - [string[]]$operation_name_filter) - - if ($operation_name_filter -eq $null) - { - return $true; - } - - if ($operation_name_filter -eq '*') - { - return $true; - } - - $op_short_name = Get-AutoRestOperationShortName $operation_full_name; - if ($operation_name_filter -ccontains $op_short_name) - { - return $true; - } - - return $false; -} - -function Get-OperationMethods -{ - param( - [Parameter(Mandatory = $true)] - $operation_type - ) - - $method_binding_flags = [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static -bor [System.Reflection.BindingFlags]::DeclaredOnly; - $methods = $operation_type.GetMethods($method_binding_flags); - return ($methods | Sort-Object -Property Name -Unique); -} - -# Get Filtered Operation Types from all DLL Types -function Get-FilteredOperationTypes -{ - param( - [Parameter(Mandatory = $true)] - $all_assembly_types, - - [Parameter(Mandatory = $true)] - $dll_name, - - [Parameter(Mandatory = $false)] - $operation_name_filter = $null - ) - - $op_types = $all_assembly_types | where { $_.Namespace -eq $dll_name -and $_.Name -like '*OperationsExtensions' }; - - Write-Verbose $BAR_LINE; - Write-Verbose 'List All Operation Types:'; - foreach ($op_type in $op_types) - { - Write-Verbose ('[' + $op_type.Namespace + '] ' + $op_type.Name); - } - - $op_filtered_types = $op_types; - if ($operation_name_filter -ne $null) - { - $op_filtered_types = $op_filtered_types | where { Match-OperationFilter $_.Name $operation_name_filter }; - } - - Write-Verbose $BAR_LINE; - Write-Verbose ('Operation Name Filter : "' + $operation_name_filter + '"'); - Write-Verbose 'Filtered Operation Types : '; - foreach ($op_type in $op_filtered_types) - { - Write-Verbose ('[' + $op_type.Namespace + '] ' + $op_type.Name); - } - - Write-Verbose $BAR_LINE; - - return $op_filtered_types; -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-StringFunction.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-StringFunction.ps1 deleted file mode 100644 index ad11ee48ccc3..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-StringFunction.ps1 +++ /dev/null @@ -1,352 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -function Get-CamelCaseName -{ - param - ( - # Sample: 'vmName' => 'VMName', 'resourceGroup' => 'ResourceGroup', etc. - [Parameter(Mandatory = $true)] - [string]$inputName, - - [Parameter(Mandatory = $false)] - [bool]$upperCase = $true - ) - - if ([string]::IsNullOrEmpty($inputName)) - { - return $inputName; - } - - $prefix = ''; - $suffix = ''; - - if ($inputName.StartsWith('vm')) - { - $prefix = 'vm'; - $suffix = $inputName.Substring($prefix.Length); - } - elseif ($inputName.StartsWith('IP')) - { - $prefix = 'ip'; - $suffix = $inputName.Substring($prefix.Length); - } - elseif ($inputName.StartsWith('DNS')) - { - $prefix = 'dns'; - $suffix = $inputName.Substring($prefix.Length); - } - else - { - $prefix = $inputName.Substring(0, 1); - $suffix = $inputName.Substring(1); - } - - if ($upperCase) - { - $prefix = $prefix.ToUpper(); - } - else - { - $prefix = $prefix.ToLower(); - } - - $outputName = $prefix + $suffix; - - return $outputName; -} - -function Get-CliNormalizedName -{ - # Samples: 'VMName' to 'vmName', - # 'VirtualMachine' => 'virtualMachine', - # 'InstanceIDs' => 'instanceIds', - # 'ResourceGroup' => 'resourceGroup', etc. - param - ( - [Parameter(Mandatory = $True)] - [string]$inName - ) - - $outName = Get-CamelCaseName $inName $false; - - if ($outName.EndsWith('IDs')) - { - $outName = $outName.Substring(0, $outName.Length - 3) + 'Ids'; - } - - return $outName; -} - - -function Get-CliCategoryName -{ - # Sample: 'VirtualMachineScaleSetVM' => 'vmssvm', 'VirtualMachineScaleSet' => 'vmss', etc. - param( - [Parameter(Mandatory = $True)] - [string]$inName - ) - - if ($inName -eq 'VirtualMachineScaleSet') - { - $outName = 'vmss'; - } - elseif ($inName -eq 'VirtualMachineScaleSetVM') - { - $outName = 'vmssvm'; - } - if ($inName -eq 'VirtualMachineScaleSets') - { - $outName = 'vmss'; - } - elseif ($inName -eq 'VirtualMachineScaleSetVMs') - { - $outName = 'vmssvm'; - } - elseif ($inName -eq 'VirtualMachines') - { - $outName = 'vm'; - } - else - { - $outName = Get-CliOptionName $inName; - } - - return $outName; -} - -function Get-PowershellCategoryName -{ - # Sample: 'VirtualMachineScaleSetVM' => 'VmssVm', 'VirtualMachineScaleSet' => 'Vmss', etc. - param( - [Parameter(Mandatory = $True)] - [string]$inName - ) - - if ($inName -eq 'VirtualMachineScaleSet') - { - $outName = 'Vmss'; - } - elseif ($inName -eq 'VirtualMachineScaleSetVM') - { - $outName = 'VmssVm'; - } - else - { - $outName = Get-CliOptionName $inName; - } - - return $outName; -} - - -function Get-CliOptionName -{ - # Sample: 'VMName' to 'vmName', 'VirtualMachine' => 'virtual-machine', 'ResourceGroup' => 'resource-group', etc. - param( - [Parameter(Mandatory = $True)] - [string]$inName - ) - - if ([string]::IsNullOrEmpty($inName)) - { - return $inName; - } - - [string]$varName = Get-CliNormalizedName $inName; - [string]$outName = $null; - - $i = 0; - while ($i -lt $varName.Length) - { - if ($i -eq 0 -or [char]::IsUpper($varName[$i])) - { - if ($i -gt 0) - { - # Sample: "parameter-..." - $outName += '-'; - } - - [string[]]$abbrWords = @('VM', 'IP', 'RM', 'OS', 'NAT', 'IDs', 'DNS'); - $matched = $false; - foreach ($matchedAbbr in $abbrWords) - { - if ($varName.Substring($i) -like ("${matchedAbbr}*")) - { - $matched = $true; - break; - } - } - - if ($matched) - { - $outName += $matchedAbbr.ToLower(); - $i = $i + $matchedAbbr.Length; - } - else - { - $j = $i + 1; - while (($j -lt $varName.Length) -and [char]::IsLower($varName[$j])) - { - $j++; - } - - $outName += $varName.Substring($i, $j - $i).ToLower(); - $i = $j; - } - } - else - { - $i++; - } - } - - return $outName; -} - -function Get-CliShorthandName -{ - # Sample: 'ResourceGroupName' => '-g', 'Name' => '-n', etc. - param( - [Parameter(Mandatory = $True)] - [string]$inName - ) - - if ($inName -eq 'ResourceGroupName') - { - $outName = 'g'; - } - elseif ($inName -eq 'Name') - { - $outName = 'n'; - } - elseif ($inName -eq 'VMName') - { - $outName = 'n'; - } - elseif ($inName -eq 'VMScaleSetName') - { - $outName = 'n'; - } - elseif ($inName -eq 'VirtualMachineScaleSetName') - { - $outName = 'n'; - } - elseif ($inName -eq 'instanceId') - { - $outName = 'd'; - } - elseif ($inName -eq 'vmInstanceIDs') - { - $outName = 'D'; - } - elseif ($inName -eq 'parameters') - { - $outName = 'p'; - } - elseif ($inName -eq 'ExpandExpression') - { - $outName = 'e'; - } - elseif ($inName -eq 'FilterExpression') - { - $outName = 't'; - } - elseif ($inName -eq 'SelectExpression') - { - $outName = 'c'; - } - else - { - $outName = ''; - } - - return $outName; -} - -function Get-SplitTextLines -{ - # Sample: 'A Very Long Text.' => @('A Very ', 'Long Text.'); - param( - [Parameter(Mandatory = $true)] - [string]$text, - - [Parameter(Mandatory = $false)] - [int]$lineWidth - ) - - if ($text -eq '' -or $text -eq $null -or $text.Length -le $lineWidth) - { - return $text; - } - - $lines = @(); - - while ($text.Length -gt $lineWidth) - { - $lines += $text.Substring(0, $lineWidth); - $text = $text.Substring($lineWidth); - } - - if ($text -ne '' -and $text -ne $null) - { - $lines += $text; - } - - return $lines; -} - -function Get-SingularNoun -{ - param( - [Parameter(Mandatory = $true)] - [string]$noun - ) - - if ($noun -eq $null) - { - return $noun; - } - - if ($noun.ToLower().EndsWith("address")) - { - return $noun; - } - - if ($noun.EndsWith("s")) - { - return $noun.Substring(0, $noun.Length - 1); - } - else - { - return $noun; - } -} - -function Get-ComponentName -{ - # Sample: "Microsoft.Azure.Management.Compute" => "Compute"; - param - ( - [Parameter(Mandatory = $true)] - [string]$clientNS - ) - - if ($clientNS.EndsWith('.Model') -or $clientNS.EndsWith('.Models')) - { - $clientNS = $clientNS.Substring(0, $clientNS.LastIndexOf('.')); - } - - return $clientNS.Substring($clientNS.LastIndexOf('.') + 1); -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-TypeFunction.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-TypeFunction.ps1 deleted file mode 100644 index 8604ab8dcd2c..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-TypeFunction.ps1 +++ /dev/null @@ -1,837 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -function Contains-OnlyStringFields -{ - param( - [Parameter(Mandatory = $True)] - [System.Type]$parameterType - ) - - if ($parameterType -eq $null -or $parameterType.BaseType -eq $null) - { - return $false; - } - - if ((-not $parameterType.IsInterface) -and ($parameterType.BaseType -ne $null) -and $parameterType.BaseType.IsEquivalentTo([System.Enum])) - { - return $false; - } - - $result = $true; - - foreach ($propItem in $parameterType.GetProperties()) - { - if (-not ($propItem.PropertyType.IsEquivalentTo([string]))) - { - $result = $false; - } - } - - return $result; -} - -function Contains-OnlyStringList -{ - param( - [Parameter(Mandatory = $True)] - [System.Type]$parameterType - ) - - if ($parameterType -eq $null) - { - return $false; - } - - if ($parameterType.IsEquivalentTo([System.Collections.Generic.IList[string]])) - { - return $true; - } - - if ((-not $parameterType.IsInterface) -and ($parameterType.BaseType -ne $null) -and $parameterType.BaseType.IsEquivalentTo([System.Enum])) - { - return $false; - } - - if ($parameterType.GetProperties().Count -ne 1) - { - return $false; - } - else - { - [System.Reflection.PropertyInfo]$propInfoItem = ($parameterType.GetProperties())[0]; - if ($propInfoItem.PropertyType.FullName.StartsWith("System.Collections.Generic.IList")) - { - [System.Type]$itemType = $propInfoItem.PropertyType.GenericTypeArguments[0]; - if ($itemType.IsEquivalentTo([string])) - { - return $true; - } - } - - return $false; - } -} - -function Contains-OnlySimpleFields -{ - param( - [Parameter(Mandatory = $True)] - [System.Type]$parameterType, - - [Parameter(Mandatory = $True)] - [System.String]$namespace - ) - - if ($parameterType -eq $null) - { - return $false; - } - - if ($parameterType.BaseType.IsEquivalentTo([System.Enum])) - { - return $false; - } - - $result = $true; - - foreach ($propItem in $parameterType.GetProperties()) - { - if ($propItem.PropertyType.Namespace -like "*$namespace*") - { - $result = $false; - } - - if ($propItem.PropertyType.Namespace -like "System.Collections.Generic") - { - if ($propItem.PropertyType -like "*$namespace*") - { - $result = $false; - } - } - } - - return $result; -} - -function Get-SpecificSubNode -{ - param( - [Parameter(Mandatory = $True)] - $TreeNode, - [Parameter(Mandatory = $True)] - [System.String] $typeName - ) - - foreach ($subNode in $TreeNode.SubNodes) - { - if ($subNode.Name -eq $typeName) - { - return $subNode; - } - } - - return $null; -} - -# This function returns the first descendant without a single comlex property. -# The returned node contains either more than one properties or single simple property. -function Get-NonSingleComplexDescendant -{ - param( - [Parameter(Mandatory = $True)] - $TreeNode, - [Parameter(Mandatory = $True)] - $chainArray - ) - - if ($TreeNode.OnlySimple) - { - return @{Node = $TreeNode;Chain = $chainArray}; - } - - if ($TreeNode.Properties.Count -eq 1) - { - $subNode = Get-SpecificSubNode $TreeNode $TreeNode.Properties[0]["Name"] - - $chainArray += $TreeNode.Name; - $result = Get-NonSingleComplexDescendant $subNode $chainArray; - - return @{Node = $result["Node"];Chain = $result["Chain"]}; - } - else - { - return @{Node = $TreeNode;Chain = $chainArray}; - } -} - - -function Get-NormalizedTypeName -{ - param( - # Sample: 'System.String' => 'string', 'System.Boolean' => bool, etc. - [Parameter(Mandatory = $true)] - [System.Reflection.TypeInfo]$parameter_type - ) - - if ($parameter_type.IsGenericType -and $parameter_type.GenericTypeArguments.Count -eq 1) - { - $generic_item_type = $parameter_type.GenericTypeArguments[0]; - if (($generic_item_type.FullName -eq 'System.String') -or ($generic_item_type.Name -eq 'string')) - { - return 'System.Collections.Generic.IList'; - } - } - - [string]$inputName = $parameter_type.FullName; - - if ([string]::IsNullOrEmpty($inputName)) - { - return $inputName; - } - - $outputName = $inputName; - $clientModelNameSpacePrefix = $clientModelNameSpace + '.'; - - if ($inputName -eq 'System.String') - { - $outputName = 'string'; - } - elseif ($inputName -eq 'System.Boolean') - { - $outputName = 'bool'; - } - elseif ($inputName -eq 'System.DateTime') - { - return 'DateTime'; - } - elseif ($inputName -eq 'System.Int32') - { - return 'int'; - } - elseif ($inputName -eq 'System.UInt32') - { - return 'uint'; - } - elseif ($inputName -eq 'System.Char') - { - return 'char'; - } - elseif ($inputName.StartsWith($clientModelNameSpacePrefix)) - { - $outputName = $inputName.Substring($clientModelNameSpacePrefix.Length); - } - - $outputName = $outputName.Replace('+', '.'); - - return $outputName; -} - -function Is-ListStringType -{ - # This function returns $true if the given property info contains only a list of strings. - param( - [Parameter(Mandatory = $true)] - [System.Reflection.TypeInfo]$parameter_type - ) - - if ($parameter_type.IsGenericType -and $parameter_type.GenericTypeArguments.Count -eq 1) - { - $generic_item_type = $parameter_type.GenericTypeArguments[0]; - if ($generic_item_type.FullName -eq 'System.String') - { - return $true; - } - elseif ($generic_item_type.Name -eq 'string') - { - return $true; - } - } - - [System.Reflection.PropertyInfo[]]$property_info_array = $parameter_type.GetProperties(); - if ($property_info_array.Count -eq 1) - { - if ($property_info_array[0].PropertyType.FullName -like '*List*System.String*') - { - return $true; - } - elseif ($property_info_array[0].PropertyType.FullName -eq 'System.String') - { - return $true; - } - - } - - return $false; -} - -function Get-StringTypes -{ - # This function returns an array of string types, if a given property info array contains only string types. - # It returns $null, otherwise. - param( - [Parameter(Mandatory = $True)] - [System.Reflection.TypeInfo]$parameter_type - ) - - if ($parameter_type.IsGenericType) - { - return $null; - } - - [System.Reflection.PropertyInfo[]]$property_info_array = $parameter_type.GetProperties(); - $return_string_array = @(); - foreach ($prop in $property_info_array) - { - if ($prop.PropertyType.FullName -eq "System.String") - { - $return_string_array += $prop.Name; - } - else - { - return $null; - } - } - - return $return_string_array; -} - - -function Get-ConstructorCode -{ - param( - # Sample: 'string' => 'string.Empty', 'HostedServiceCreateParameters' => 'new HostedServiceCreateParameters()', etc. - [Parameter(Mandatory = $True)] - [string]$InputName - ) - - if ([string]::IsNullOrEmpty($InputName)) - { - return 'null'; - } - - if ($InputName -eq 'string') - { - $outputName = 'string.Empty'; - } - else - { - if ($InputName.StartsWith($clientModelNameSpace + ".")) - { - $InputName = $InputName.Replace($clientModelNameSpace + ".", ''); - } - elseif ($InputName.StartsWith('System.Collections.Generic.')) - { - $InputName = $InputName.Replace('System.Collections.Generic.', ''); - } - - $outputName = 'new ' + $InputName + "()"; - } - - return $outputName; -} - -# Sample: ServiceName, DeploymentName -function Is-PipingPropertyName -{ - param( - [Parameter(Mandatory = $True)] - [string]$parameterName - ) - - if ($parameterName.ToLower() -eq 'servicename') - { - return $true; - } - elseif ($parameterName.ToLower() -eq 'deploymentname') - { - return $true; - } - elseif ($parameterName.ToLower() -eq 'rolename') - { - return $true; - } - elseif ($parameterName.ToLower() -eq 'roleinstancename') - { - return $true; - } - elseif ($parameterName.ToLower() -eq 'vmimagename') - { - return $true; - } - elseif ($parameterName.ToLower() -eq 'imagename') - { - return $true; - } - elseif ($parameterName.ToLower() -eq 'diskname') - { - return $true; - } - - return $false; -} - -function Is-PipingPropertyTypeName -{ - param( - [Parameter(Mandatory = $True)] - [string]$parameterTypeName - ) - - if ($parameterTypeName.ToLower() -eq 'string') - { - return $true; - } - elseif ($parameterTypeName.ToLower() -eq 'system.string') - { - return $true; - } - - return $false; -} - -function Get-VerbTermNameAndSuffix -{ - param( - [Parameter(Mandatory = $True)] - [string]$MethodName - ) - - $found = $false; - foreach ($key in $common_verb_mapping.Keys) - { - if ($MethodName.StartsWith($key)) - { - $verb = $common_verb_mapping[$key]; - $suffix = $MethodName.Substring($key.Length); - - if ($MethodName.StartsWith('List')) - { - $suffix += 'List'; - } - elseif ($MethodName.StartsWith('PowerOff')) - { - $suffix += "WithPowerOff"; - } - $found = $true; - break; - } - } - - if (-not $found) - { - $verb = "Set"; - $suffix = $MethodName; - } - - Write-Output $verb; - Write-Output $suffix; -} - -function Get-ShortNounName -{ - param( - [Parameter(Mandatory = $True)] - [string]$inputNoun - ) - - $noun = $inputNoun; - - foreach ($key in $common_noun_mapping.Keys) - { - if ($noun -like ("*${key}*")) - { - $noun = $noun.Replace($key, $common_noun_mapping[$key]); - } - } - - Write-Output $noun; -} - - -function Get-ParameterTypeShortName -{ - param( - [Parameter(Mandatory = $True)] - $parameter_type_info, - - [Parameter(Mandatory = $false)] - $is_list_type = $false - ) - - if (-not $is_list_type) - { - $param_type_full_name = $parameter_type_info.FullName; - $param_type_full_name = $param_type_full_name.Replace('+', '.'); - - $param_type_short_name = $parameter_type_info.Name; - $param_type_short_name = $param_type_short_name.Replace('+', '.'); - } - else - { - $itemType = $parameter_type_info.GetGenericArguments()[0]; - $itemTypeShortName = $itemType.Name; - $itemTypeFullName = $itemType.FullName; - $itemTypeNormalizedShortName = Get-NormalizedTypeName $itemType;; - - $param_type_full_name = "System.Collections.Generic.List<${itemTypeNormalizedShortName}>"; - $param_type_full_name = $param_type_full_name.Replace('+', '.'); - - $param_type_short_name = "${itemTypeShortName}List"; - $param_type_short_name = $param_type_short_name.Replace('+', '.'); - } - - return $param_type_short_name; -} - -function Get-ParameterTypeFullName -{ - param( - [Parameter(Mandatory = $True)] - $parameter_type_info, - - [Parameter(Mandatory = $false)] - $is_list_type = $false - ) - - if (-not $is_list_type) - { - $param_type_full_name = $parameter_type_info.FullName; - $param_type_full_name = $param_type_full_name.Replace('+', '.'); - } - else - { - $itemType = $parameter_type_info.GetGenericArguments()[0]; - $itemTypeShortName = $itemType.Name; - $itemTypeFullName = $itemType.FullName; - $itemTypeNormalizedShortName = Get-NormalizedTypeName $itemType; - - $param_type_full_name = "System.Collections.Generic.List<${itemTypeNormalizedShortName}>"; - $param_type_full_name = $param_type_full_name.Replace('+', '.'); - } - - return $param_type_full_name; -} - - -# Sample: VirtualMachineCreateParameters -function Is-ClientComplexType -{ - param( - [Parameter(Mandatory = $True)] - $type_info - ) - - return ($type_info.Namespace -like "${client_name_space}.Model?") -and (-not $type_info.IsEnum); -} - -# Sample: IList -function Is-ListComplexType -{ - param( - [Parameter(Mandatory = $True)] - $type_info - ) - - if ($type_info.IsGenericType) - { - $args = $list_item_type = $type_info.GetGenericArguments(); - - if ($args.Count -eq 1) - { - $list_item_type = $type_info.GetGenericArguments()[0]; - - if (Is-ClientComplexType $list_item_type) - { - return $true; - } - } - } - - return $false; -} - -# Sample: IList => ConfigurationSet -function Get-ListComplexItemType -{ - param( - [Parameter(Mandatory = $True)] - $type_info - ) - - if ($type_info.IsGenericType) - { - $args = $list_item_type = $type_info.GetGenericArguments(); - - if ($args.Count -eq 1) - { - $list_item_type = $type_info.GetGenericArguments()[0]; - - if (Is-ClientComplexType $list_item_type) - { - return $list_item_type; - } - } - } - - return $null; -} - -# Sample: VirtualMachines.Create(...) => VirtualMachineCreateParameters -function Get-MethodComplexParameter -{ - param( - [Parameter(Mandatory = $True)] - [System.Reflection.MethodInfo]$op_method_info, - - [Parameter(Mandatory = $True)] - [string]$client_name_space - ) - - $method_param_list = $op_method_info.GetParameters(); - $paramsWithoutEnums = $method_param_list | where { -not $_.ParameterType.IsEnum }; - - # Assume that each operation method has only one complext parameter type - $param_info = $paramsWithoutEnums | where { $_.ParameterType.Namespace -like "${client_name_space}.Model?" } | select -First 1; - - return $param_info; -} - -# Sample: VirtualMachineCreateParameters => ConfigurationSet, VMImageInput, ... -function Get-SubComplexParameterListFromType -{ - param( - [Parameter(Mandatory = $True)] - $type_info, - - [Parameter(Mandatory = $True)] - [string]$client_name_space - ) - - $subParamTypeList = @(); - - if (-not (Is-ClientComplexType $type_info)) - { - return $subParamTypeList; - } - - $paramProps = $type_info.GetProperties(); - foreach ($pp in $paramProps) - { - $isClientType = $false; - if (Is-ClientComplexType $pp.PropertyType) - { - $subParamTypeList += $pp.PropertyType; - $isClientType = $true; - } - elseif (Is-ListComplexType $pp.PropertyType) - { - $subParamTypeList += $pp.PropertyType; - $subParamTypeList += Get-ListComplexItemType $pp.PropertyType; - $isClientType = $true; - } - - if ($isClientType) - { - $recursiveSubParamTypeList = Get-SubComplexParameterListFromType $pp.PropertyType $client_name_space; - foreach ($rsType in $recursiveSubParamTypeList) - { - $subParamTypeList += $rsType; - } - } - } - - return $subParamTypeList; -} - -# Sample: VirtualMachineCreateParameters => ConfigurationSet, VMImageInput, ... -function Get-SubComplexParameterList -{ - param( - [Parameter(Mandatory = $True)] - [System.Reflection.ParameterInfo]$param_info, - - [Parameter(Mandatory = $True)] - [string]$client_name_space - ) - - return Get-SubComplexParameterListFromType $param_info.ParameterType $client_name_space; -} - -# Get proper type name -function Get-ProperTypeName -{ - param([System.Type] $itemType) - - if ($itemType.IsGenericType -and ($itemType.Name.StartsWith('IList') -or $itemType.Name.StartsWith('List'))) - { - $typeStr = 'IList<' + $itemType.GenericTypeArguments[0].Name + '>'; - } - elseif ($itemType.IsGenericType -and ($itemType.Name.StartsWith('IDictionary') -or $itemType.Name.StartsWith('Dictionary'))) - { - $typeStr = 'IDictionary<' + $itemType.GenericTypeArguments[0].Name + ',' + $itemType.GenericTypeArguments[1].Name + '>'; - } - elseif ($itemType.IsGenericType -and $itemType.Name.StartsWith('Nullable')) - { - $typeStr = $itemType.GenericTypeArguments[0].Name + '?'; - } - else - { - $typeStr = $itemType.Name; - } - - $typeStr = $typeStr.Replace("System.String", "string"); - $typeStr = $typeStr.Replace("String", "string"); - $typeStr = $typeStr.Replace("System.Boolean", "bool"); - $typeStr = $typeStr.Replace("Boolean", "bool"); - $typeStr = $typeStr.Replace("System.UInt32", "uint"); - $typeStr = $typeStr.Replace("UInt32", "uint"); - $typeStr = $typeStr.Replace("System.Int32", "int"); - $typeStr = $typeStr.Replace("Int32", "int"); - - return $typeStr; -} - -# Check if 2 methods have the same parameter list -function CheckIf-SameParameterList -{ - param - ( - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$methodInfo, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$friendMethodInfo - ) - - if ($methodInfo -eq $null -or $friendMethodInfo -eq $null) - { - return $false; - } - - $myParams = $methodInfo.GetParameters(); - $friendParams = $friendMethodInfo.GetParameters(); - if ($myParams.Count -ne $friendParams.Count) - { - return $false; - } - - for ($i = 0; $i -lt $myParams.Count -and $i -lt $friendParams.Count; $i++) - { - [System.Reflection.ParameterInfo]$paramInfo = $myParams[$i]; - [System.Reflection.ParameterInfo]$friendInfo = $friendParams[$i]; - if ($paramInfo.Name -ne $friendInfo.Name) - { - return $false; - } - elseif (-not $paramInfo.ParameterType.IsEquivalentTo($friendInfo.ParameterType)) - { - return $false; - } - } - - return $true; -} - -# Check if 2 methods are list-page relation -function CheckIf-ListAndPageMethods -{ - param - ( - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$listMethodInfo, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$pageMethodInfo - ) - - if ($listMethodInfo -eq $null -or $pageMethodInfo -eq $null) - { - return $false; - } - - if (-not (($listMethodInfo.Name.Replace('Async', '') + 'Next') -eq $pageMethodInfo.Name.Replace('Async', ''))) - { - return $false; - } - - $pageParams = $pageMethodInfo.GetParameters(); - Write-Verbose ('pageParams = ' + $pageParams); - # Skip the 1st 'operations' parameter, e.g. - # 1. Microsoft.Azure.Management.Compute.IVirtualMachineScaleSetVMsOperations operations - # 2. System.String nextPageLink - if ($pageParams.Count -eq 2) - { - $paramInfo = $pageParams[1]; - if ($paramInfo.ParameterType.IsEquivalentTo([string]) -and $paramInfo.Name -eq 'nextPageLink') - { - return $true; - } - } - - return $false; -} - -# Function Friend Finder -function Find-MatchedMethod -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$searchName, - - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo[]]$methodList, - - [Parameter(Mandatory = $false)] - [System.Reflection.MethodInfo]$paramMatchedMethodInfo - ) - - foreach ($methodInfo in $methodList) - { - if ($methodInfo.Name -eq $searchName) - { - if ($paramMatchedMethodInfo -eq $null) - { - return $methodInfo; - } - elseif (CheckIf-SameParameterList $methodInfo $paramMatchedMethodInfo) - { - return $methodInfo; - } - } - } - - return $null; -} - -function CheckIf-PaginationMethod -{ - param - ( - [Parameter(Mandatory = $true)] - [System.Reflection.MethodInfo]$MethodInfo - ) - - if ($MethodInfo.Name -like "List*Next") - { - $methodParameters = $MethodInfo.GetParameters(); - if ($methodParameters.Count -eq 2 -and $methodParameters[1].ParameterType.IsEquivalentTo([string])) - { - return $true; - } - } - - return $false; -} \ No newline at end of file diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-WriterFunction.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-WriterFunction.ps1 deleted file mode 100644 index 0d60c3dbb800..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Import-WriterFunction.ps1 +++ /dev/null @@ -1,1099 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -function Write-CmdletCodeFile -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$FilePath, - - [Parameter(Mandatory = $true)] - [string]$CodeContent - ) - - # Write Header - $code = ''; - $code += $code_common_header + $NEW_LINE; - $code += $NEW_LINE; - $code += $code_using_strs + $NEW_LINE; - $code += $NEW_LINE; - - # Write Name Space & Starting Bracket - $code += "namespace ${code_common_namespace}" + $NEW_LINE; - $code += "{" + $NEW_LINE; - - # Write Content - $code += $CodeContent + $NEW_LINE; - - # Write Ending Bracket - $code += "}"; - - $st = Set-FileContent -Path $FilePath -Value $code; -} - -function Set-FileContent -{ - param - ( - [Parameter(Mandatory = $true)] - [string]$Path, - - [Parameter(Mandatory = $true)] - $Value - ) - - $iteration = 0; - $maxIteration = 10; - while ($iteration -lt $maxIteration) - { - $iteration = $iteration + 1; - try - { - $iteration = Set-Content -Path $Path -Value $Value -Force; - } - catch - { - if (($_.Exception.Message -like "*Stream was not readable.") ` - -or ($_.Exception.Message -like "The process cannot access the file*")) - { - $fileName = Split-Path $Path -Leaf; - [string]$message = $_.Exception.Message; - [string]$shortMsg = $message.SubString(0, [System.Math]::Min(30, $message.Length)); - Write-Warning "#${iteration}:File=${fileName};Error=${shortMsg}..."; - sleep -Milliseconds 10; - } - else - { - Write-Error $_.Exception.Message; - return; - } - } - - break; - } - - if ($_ -ne $null -and $_.Exception -ne $null) - { - Write-Error $_.Exception.Message; - } -} - - -function Write-PSArgumentFile -{ - param( - [Parameter(Mandatory = $True)] - [string]$file_full_path - ) - - $model_source_code_text = -@" -${code_common_header} - -$code_using_strs - -namespace ${code_model_namespace} -{ - public class PSArgument - { - public string Name { get; set; } - - public Type Type { get; set; } - - public object Value { get; set; } - } -} -"@; - - $st = Set-FileContent -Path $file_full_path -Value $model_source_code_text; -} - -function Write-BaseCmdletFile -{ - # e.g. - # public abstract class ComputeAutomationBaseCmdlet : Microsoft.WindowsAzure.Commands.Utilities.Common.ServiceManagementBaseCmdlet - param( - [Parameter(Mandatory = $True)] - [string]$file_full_path, - - [Parameter(Mandatory = $True)] - $operation_name_list, - - [Parameter(Mandatory = $True)] - $client_class_info - ) - - [System.Reflection.PropertyInfo[]]$propItems = $client_class_info.GetProperties(); - - $operation_get_code = ""; - foreach ($operation_name in $operation_name_list) - { - # Write-Verbose ('Operation Name = ' + $operation_name); - $opShortName = Get-OperationShortName $operation_name; - $opPropName = $opShortName; - foreach ($propItem in $propItems) - { - if ($propItem.PropertyType.Name -eq ('I' + $opShortName + 'Operations')) - { - $opPropName = $propItem.Name; - break; - } - } - - $operation_get_template = -@" - public I${opShortName}Operations ${opShortName}Client - { - get - { - return ${baseClientFullName}.${opPropName}; - } - } -"@; - - if (-not ($operation_get_code -eq "")) - { - $operation_get_code += ($NEW_LINE * 2); - } - - $operation_get_code += $operation_get_template; - } - - $cmdlet_source_code_text = -@" -${code_common_header} - -$code_using_strs - -namespace ${code_common_namespace} -{ - public abstract class ${component_name}AutomationBaseCmdlet : $baseCmdletFullName - { - protected static PSArgument[] ConvertFromObjectsToArguments(string[] names, object[] objects) - { - var arguments = new PSArgument[objects.Length]; - - for (int index = 0; index < objects.Length; index++) - { - arguments[index] = new PSArgument - { - Name = names[index], - Type = objects[index].GetType(), - Value = objects[index] - }; - } - - return arguments; - } - - protected static object[] ConvertFromArgumentsToObjects(object[] arguments) - { - if (arguments == null) - { - return null; - } - - var objects = new object[arguments.Length]; - - for (int index = 0; index < arguments.Length; index++) - { - if (arguments[index] is PSArgument) - { - objects[index] = ((PSArgument)arguments[index]).Value; - } - else - { - objects[index] = arguments[index]; - } - } - - return objects; - } - -${operation_get_code} - } -} -"@; - - $st = Set-FileContent -Path $file_full_path -Value $cmdlet_source_code_text; -} - -# Write Invoke Compute Client Cmdlet -function Write-InvokeCmdletFile -{ - # e.g. - # public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet, IDynamicParameters - - param( - [Parameter(Mandatory = $True)] - [string]$file_full_path, - - [Parameter(Mandatory = $True)] - [string]$invoke_cmdlet_name, - - [Parameter(Mandatory = $True)] - [string]$base_cmdlet_name, - - [Parameter(Mandatory = $True)] - $client_class_info, - - [Parameter(Mandatory = $True)] - $operation_type_list, - - [Parameter(Mandatory = $True)] - $invoke_cmdlet_method_code, - - [Parameter(Mandatory = $True)] - $dynamic_param_method_code - ) - - $indents = " " * 8; - $get_set_block = '{ get; set; }'; - - $cmdlet_verb = "Invoke"; - $cmdlet_verb_code = $verbs_lifecycle_invoke; - - $cmdlet_file_name_suffix = 'Cmdlet' - $cmdlet_class_name = $cmdlet_verb + $invoke_cmdlet_name.Replace($cmdlet_verb, ''); - $cmdlet_noun = $invoke_cmdlet_name.Replace($cmdlet_verb, '').Replace($cmdlet_file_name_suffix, ''); - - $normalized_output_type_name = 'object'; - $all_method_names = @(); - - foreach ($operation_type in $operation_type_list) - { - $op_short_name = Get-OperationShortName $operation_type.Name; - $op_short_name = $op_short_name.Replace('ScaleSets', 'ScaleSet').Replace('ScaleSetVMs', 'ScaleSetVM'); - $operation_method_info_list = Get-OperationMethods $operation_type; - - foreach ($method in $operation_method_info_list) - { - if ($method.Name -like 'Begin*') - { - continue; - } - elseif ($method.Name -like '*Async') - { - continue; - } - - $invoke_param_set_name = $op_short_name + $method.Name.Replace('Async', ''); - $all_method_names += $invoke_param_set_name; - } - } - - $all_method_names_with_quotes = $all_method_names | foreach { "`"" + $_ + "`"" }; - $all_method_names_str = [string]::Join(',' + $NEW_LINE + (' ' * 12), $all_method_names_with_quotes); - $validate_all_method_names_code = -@" - [ValidateSet( - $all_method_names_str - )] -"@; - - $dynamic_param_set_name = "InvokeByDynamicParameters"; - $static_param_set_name = "InvokeByStaticParameters"; - $param_set_code += -@" - [Parameter(Mandatory = true, ParameterSetName = `"$dynamic_param_set_name`", Position = 0)] - [Parameter(Mandatory = true, ParameterSetName = `"$static_param_set_name`", Position = 0)] -$validate_all_method_names_code - public virtual string MethodName $get_set_block - -"@; - - $dynamic_parameters_code = ""; - $operations_code = ""; - foreach ($method_name in $all_method_names) - { - if ($method_name.Contains("ScaleSets")) - { - $method_name = $method_name.Replace("ScaleSets", "ScaleSet"); - } - elseif ($method_name.Contains("ScaleSetVMs")) - { - $method_name = $method_name.Replace("ScaleSetVMs", "ScaleSetVM"); - } - elseif ($method_name.Contains("VirtualMachines")) - { - $method_name = $method_name.Replace("VirtualMachines", "VirtualMachine"); - } - - $operation_code_template = -@" - case `"${method_name}`" : - Execute${method_name}Method(argumentList); - break; -"@; - $operations_code += $operation_code_template + $NEW_LINE; - - - $dynamic_param_code_template = -@" - case `"${method_name}`" : return Create${method_name}DynamicParameters(); -"@; - $dynamic_parameters_code += $dynamic_param_code_template + $NEW_LINE; - } - - $execute_client_action_code = -@" - protected object ParseParameter(object input) - { - if (input is PSObject) - { - return (input as PSObject).BaseObject; - } - else - { - return input; - } - } - - protected override void ProcessRecord() - { - base.ProcessRecord(); - ExecuteClientAction(() => - { - if (ParameterSetName.StartsWith(`"$dynamic_param_set_name`")) - { - argumentList = ConvertDynamicParameters(dynamicParameters); - } - else - { - argumentList = ConvertFromArgumentsToObjects((object[])dynamicParameters[`"ArgumentList`"].Value); - } - - switch (MethodName) - { -${operations_code} default : WriteWarning(`"Cannot find the method by name = `'`" + MethodName + `"`'.`"); break; - } - }); - } -"@; - - # $invoke_cmdlet_method_code_content = ([string]::Join($NEW_LINE, $invoke_cmdlet_method_code)); - # $dynamic_param_method_code_content = ([string]::Join($NEW_LINE, $dynamic_param_method_code)); - - $cmdlet_source_code_text = -@" -${code_common_header} - -$code_using_strs - -namespace ${code_common_namespace} -{ - [Cmdlet(${cmdlet_verb_code}, `"${cmdlet_noun}`", DefaultParameterSetName = `"$dynamic_param_set_name`")] - [OutputType(typeof(${normalized_output_type_name}))] - public partial class $cmdlet_class_name : $base_cmdlet_name, IDynamicParameters - { - protected RuntimeDefinedParameterDictionary dynamicParameters; - protected object[] argumentList; - - protected static object[] ConvertDynamicParameters(RuntimeDefinedParameterDictionary parameters) - { - List paramList = new List(); - - foreach (var param in parameters) - { - paramList.Add(param.Value.Value); - } - - return paramList.ToArray(); - } - -${param_set_code} -${execute_client_action_code} -$invoke_cmdlet_method_code_content - - public virtual object GetDynamicParameters() - { - switch (MethodName) - { -${dynamic_parameters_code} default : break; - } - - return null; - } -$dynamic_param_method_code_content - } -} -"@; - - $st = Set-FileContent -Path $file_full_path -Value $cmdlet_source_code_text; -} - -# Write New Invoke Parameters Cmdlet -function Write-InvokeParameterCmdletFile -{ - param( - [Parameter(Mandatory = $True)] - [string]$file_full_path, - - [Parameter(Mandatory = $True)] - [string]$parameter_cmdlet_name, - - [Parameter(Mandatory = $True)] - [string]$base_cmdlet_name, - - [Parameter(Mandatory = $True)] - $client_class_info, - - [Parameter(Mandatory = $True)] - $operation_type_list, - - [Parameter(Mandatory = $True)] - $parameter_cmdlet_method_code - ) - - $indents = " " * 8; - $get_set_block = '{ get; set; }'; - - $cmdlet_verb = "New"; - $cmdlet_verb_code = $verbs_common_new; - - $cmdlet_file_name_suffix = 'Cmdlet' - $cmdlet_class_name = $cmdlet_verb + $parameter_cmdlet_name.Replace($cmdlet_verb, ''); - $cmdlet_noun = $parameter_cmdlet_name.Replace($cmdlet_verb, '').Replace($cmdlet_file_name_suffix, ''); - - $normalized_output_type_name = 'object'; - $all_method_names = @(); - $all_param_type_names = @(); - $constructor_code_hashmap = @{}; - - foreach ($operation_type in $operation_type_list) - { - $op_short_name = Get-OperationShortName $operation_type.Name; - $operation_method_info_list = Get-OperationMethods $operation_type; - $parameter_type_info_list = @(); - - foreach ($method in $operation_method_info_list) - { - if ($method.Name -like 'Begin*') - { - continue; - } - elseif ($method.Name -like '*Async') - { - continue; - } - - $invoke_param_set_name = $op_short_name + $method.Name.Replace('Async', ''); - $all_method_names += $invoke_param_set_name; - - [System.Reflection.ParameterInfo]$parameter_type_info = (Get-MethodComplexParameter $method $clientNameSpace); - - if (($parameter_type_info -ne $null) -and (($parameter_type_info_list | where { $_.ParameterType.FullName -eq $parameter_type_info.FullName }).Count -eq 0)) - { - $parameter_type_info_list += $parameter_type_info; - - $parameter_type_short_name = Get-ParameterTypeShortName $parameter_type_info.ParameterType; - if (($parameter_type_short_name -like "${op_short_name}*") -and ($parameter_type_short_name.Length -gt $op_short_name.Length)) - { - # Remove the common part between the parameter type name and operation short name, e.g. 'VirtualMachineDisk' - $parameter_type_short_name = $parameter_type_short_name.Substring($op_short_name.Length); - } - $parameter_type_short_name = $op_short_name + $parameter_type_short_name; - - $parameter_type_full_name = Get-ParameterTypeFullName $parameter_type_info.ParameterType; - if (-not($all_param_type_names -contains $parameter_type_short_name)) - { - $all_param_type_names += $parameter_type_short_name; - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_short_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_short_name, (Get-ConstructorCode $parameter_type_full_name)); - } - } - } - } - } - - $all_method_names_with_quotes = $all_method_names | foreach { "`"" + $_ + "`"" }; - $all_method_names_str = [string]::Join(',' + $NEW_LINE + (' ' * 12), $all_method_names_with_quotes); - $validate_all_method_names_code = -@" - [ValidateSet( - $all_method_names_str - )] -"@; - - $param_set_of_create_by_method_name = "CreateParameterListByMethodName"; - - $param_set_code += -@" - [Parameter(ParameterSetName = `"$param_set_of_create_by_method_name`", Mandatory = true, Position = 0)] -$validate_all_method_names_code - public virtual string MethodName $get_set_block - -"@; - - - $operations_code = ""; - foreach ($method_name in $all_method_names) - { - if ($method_name.Contains("ScaleSets")) - { - $singular_method_name = $method_name.Replace("ScaleSets", "ScaleSet"); - } - elseif ($method_name.Contains("ScaleSetVMs")) - { - $singular_method_name = $method_name.Replace("ScaleSetVMs", "ScaleSetVM"); - } - elseif ($method_name.Contains("VirtualMachines")) - { - $singular_method_name = $method_name.Replace("VirtualMachines", "VirtualMachine"); - } - else - { - $singular_method_name = $method_name; - } - - $operation_code_template = -@" - case `"${method_name}`" : WriteObject(Create${singular_method_name}Parameters(), true); break; -"@; - $operations_code += $operation_code_template + $NEW_LINE; - } - - $execute_client_action_code = -@" - protected override void ProcessRecord() - { - base.ProcessRecord(); - ExecuteClientAction(() => - { - if (ParameterSetName == `"CreateParameterListByMethodName`") - { - switch (MethodName) - { -${operations_code} default : WriteWarning(`"Cannot find the method by name = `'`" + MethodName + `"`'.`"); break; - } - } - }); - } -"@; - - # $parameter_cmdlet_method_code_content = ([string]::Join($NEW_LINE, $parameter_cmdlet_method_code)); - - $cmdlet_source_code_text = -@" -${code_common_header} - -$code_using_strs - -namespace ${code_common_namespace} -{ - [Cmdlet(${cmdlet_verb_code}, `"${cmdlet_noun}`", DefaultParameterSetName = `"$param_set_of_create_by_method_name`")] - [OutputType(typeof(${normalized_output_type_name}))] - public partial class $cmdlet_class_name : $base_cmdlet_name - { -${param_set_code} -${execute_client_action_code} -$parameter_cmdlet_method_code_content - } -} -"@; - - $st = Set-FileContent -Path $file_full_path -Value $cmdlet_source_code_text; -} - - -# Write New Parameter Object Cmdlet -function Write-NewParameterObjectCmdletFile -{ - param( - [Parameter(Mandatory = $True)] - [string]$file_full_path, - - [Parameter(Mandatory = $True)] - [string]$new_object_cmdlet_class_name, - - [Parameter(Mandatory = $True)] - [string]$base_cmdlet_name, - - [Parameter(Mandatory = $True)] - $client_class_info, - - [Parameter(Mandatory = $True)] - $operation_type_list, - - [Parameter(Mandatory = $True)] - $parameter_cmdlet_method_code - ) - - $indents = " " * 8; - $get_set_block = '{ get; set; }'; - - $cmdlet_verb = "New"; - $cmdlet_verb_code = $verbs_common_new; - - $cmdlet_file_name_suffix = 'Cmdlet' - $cmdlet_class_name = $cmdlet_verb + $new_object_cmdlet_class_name.Replace($cmdlet_verb, ''); - $cmdlet_noun = $new_object_cmdlet_class_name.Replace($cmdlet_verb, '').Replace($cmdlet_file_name_suffix, ''); - - $normalized_output_type_name = 'object'; - $all_method_names = @(); - $all_param_type_names = @(); - $constructor_code_hashmap = @{}; - $all_param_full_type_names = @(); - - foreach ($operation_type in $operation_type_list) - { - $op_short_name = Get-OperationShortName $operation_type.Name; - $operation_method_info_list = Get-OperationMethods $operation_type; - $parameter_type_info_list = @(); - - foreach ($method in $operation_method_info_list) - { - if ($method.Name -like 'Begin*') - { - continue; - } - elseif ($method.Name -like '*Async') - { - continue; - } - - $invoke_param_set_name = $op_short_name + $method.Name.Replace('Async', ''); - $all_method_names += $invoke_param_set_name; - - [System.Reflection.ParameterInfo]$parameter_type_info = (Get-MethodComplexParameter $method $clientNameSpace); - - if (($parameter_type_info -ne $null) -and (($parameter_type_info_list | where { $_.ParameterType.FullName -eq $parameter_type_info.FullName }).Count -eq 0)) - { - $parameter_type_info_list += $parameter_type_info; - - $parameter_type_short_name = Get-ParameterTypeShortName $parameter_type_info.ParameterType; - if (($parameter_type_short_name -like "${op_short_name}*") -and ($parameter_type_short_name.Length -gt $op_short_name.Length)) - { - # Remove the common part between the parameter type name and operation short name, e.g. 'VirtualMachineDisk' - $parameter_type_short_name = $parameter_type_short_name.Substring($op_short_name.Length); - } - $parameter_type_short_name = $op_short_name + $parameter_type_short_name; - - $parameter_type_full_name = Get-ParameterTypeFullName $parameter_type_info.ParameterType; - if (-not($all_param_type_names -contains $parameter_type_short_name)) - { - $all_param_type_names += $parameter_type_short_name; - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_short_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_short_name, (Get-ConstructorCode $parameter_type_full_name)); - } - } - - if (-not($all_param_full_type_names -contains $parameter_type_full_name)) - { - $all_param_full_type_names += $parameter_type_full_name; - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_full_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_full_name, (Get-ConstructorCode $parameter_type_full_name)); - } - } - - # Run Through the Sub Parameter List - $subParamTypeList = Get-SubComplexParameterList $parameter_type_info $clientNameSpace; - - if ($subParamTypeList.Count -gt 0) - { - foreach ($sp in $subParamTypeList) - { - if (-not $sp.IsGenericType) - { - $parameter_type_short_name = Get-ParameterTypeShortName $sp; - if (($parameter_type_short_name -like "${op_short_name}*") -and ($parameter_type_short_name.Length -gt $op_short_name.Length)) - { - # Remove the common part between the parameter type name and operation short name, e.g. 'VirtualMachineDisk' - $parameter_type_short_name = $parameter_type_short_name.Substring($op_short_name.Length); - } - $parameter_type_short_name = $op_short_name + $parameter_type_short_name; - - $parameter_type_full_name = Get-ParameterTypeFullName $sp; - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_short_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_short_name, (Get-ConstructorCode $parameter_type_full_name)); - } - - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_full_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_full_name, (Get-ConstructorCode $parameter_type_full_name)); - } - } - else - { - $parameter_type_short_name = Get-ParameterTypeShortName $sp $true; - if (($parameter_type_short_name -like "${op_short_name}*") -and ($parameter_type_short_name.Length -gt $op_short_name.Length)) - { - # Remove the common part between the parameter type name and operation short name, e.g. 'VirtualMachineDisk' - $parameter_type_short_name = $parameter_type_short_name.Substring($op_short_name.Length); - } - $parameter_type_short_name = $op_short_name + $parameter_type_short_name; - - $parameter_type_full_name = Get-ParameterTypeFullName $sp $true; - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_short_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_short_name, (Get-ConstructorCode $parameter_type_full_name)); - } - - if (-not $constructor_code_hashmap.ContainsKey($parameter_type_full_name)) - { - $st = $constructor_code_hashmap.Add($parameter_type_full_name, (Get-ConstructorCode $parameter_type_full_name)); - } - } - - if (-not($all_param_type_names -contains $parameter_type_short_name)) - { - $all_param_type_names += $parameter_type_short_name; - } - - if (-not($all_param_full_type_names -contains $parameter_type_full_name)) - { - $all_param_full_type_names += $parameter_type_full_name; - } - } - } - } - } - } - - $all_param_type_names = $all_param_type_names | Sort; - $all_param_type_names_with_quotes = $all_param_type_names | foreach { "`"" + $_ + "`"" }; - $all_param_names_str = [string]::Join(',' + $NEW_LINE + (' ' * 12), $all_param_type_names_with_quotes); - $validate_all_param_names_code = -@" - [ValidateSet( - $all_param_names_str - )] -"@; - - $all_param_full_type_names = $all_param_full_type_names | Sort; - $all_param_full_type_names_with_quotes = $all_param_full_type_names | foreach { "`"" + $_ + "`"" }; - $all_param_full_names_str = [string]::Join(',' + $NEW_LINE + (' ' * 12), $all_param_full_type_names_with_quotes); - $validate_all_param_full_names_code = -@" - [ValidateSet( - $all_param_full_names_str - )] -"@; - - $param_set_of_create_by_type_name = "CreateParameterObjectByFriendlyName"; - $param_set_of_create_by_full_type_name = "CreateParameterObjectByFullName"; - - $param_set_code += -@" - [Parameter(ParameterSetName = `"$param_set_of_create_by_type_name`", Mandatory = true, Position = 0)] -$validate_all_param_names_code - public string FriendlyName $get_set_block - - [Parameter(ParameterSetName = `"$param_set_of_create_by_full_type_name`", Mandatory = true, Position = 0)] -$validate_all_param_full_names_code - public string FullName $get_set_block - -"@; - - - $operations_code = ""; - foreach ($method_name in $all_method_names) - { - - $operation_code_template = -@" - case `"${method_name}`" : WriteObject(Create${method_name}Parameters()); break; -"@; - $operations_code += $operation_code_template + $NEW_LINE; - } - - $type_operations_code = ""; - foreach ($type_name in $all_param_type_names) - { - $constructor_code = $constructor_code_hashmap.Get_Item($type_name); - $type_code_template = -@" - case `"${type_name}`" : WriteObject(${constructor_code}); break; -"@; - $type_operations_code += $type_code_template + $NEW_LINE; - } - - $full_type_operations_code = ""; - foreach ($type_name in $all_param_full_type_names) - { - $constructor_code = $constructor_code_hashmap.Get_Item($type_name); - $full_type_code_template = -@" - case `"${type_name}`" : WriteObject(${constructor_code}); break; -"@; - $full_type_operations_code += $full_type_code_template + $NEW_LINE; - } - - $execute_client_action_code = -@" - protected override void ProcessRecord() - { - base.ProcessRecord(); - ExecuteClientAction(() => - { - if (ParameterSetName == `"$param_set_of_create_by_type_name`") - { - switch (FriendlyName) - { -${type_operations_code} default : WriteWarning(`"Cannot find the type by FriendlyName = `'`" + FriendlyName + `"`'.`"); break; - } - } - else if (ParameterSetName == `"$param_set_of_create_by_full_type_name`") - { - switch (FullName) - { -${full_type_operations_code} default : WriteWarning(`"Cannot find the type by FullName = `'`" + FullName + `"`'.`"); break; - } - } - }); - } -"@; - - # $parameter_cmdlet_method_code_content = ([string]::Join($NEW_LINE, $parameter_cmdlet_method_code)); - - $cmdlet_source_code_text = -@" -${code_common_header} - -$code_using_strs - -namespace ${code_common_namespace} -{ - [Cmdlet(${cmdlet_verb_code}, `"${cmdlet_noun}`", DefaultParameterSetName = `"$param_set_of_create_by_full_type_name`")] - [OutputType(typeof(${normalized_output_type_name}))] - public partial class $new_object_cmdlet_class_name : $base_cmdlet_name - { -${param_set_code} -${execute_client_action_code} -$parameter_cmdlet_method_code_content - } -} -"@; - - $st = Set-FileContent -Path $file_full_path -Value $cmdlet_source_code_text; -} - -# Process the list return type -function Process-ListType -{ - param([Type] $rt, [System.String] $name) - - $result = $null; - - if ($rt -eq $null) - { - return $result; - } - - $xml = '' + $rt.FullName + ''; - $xml += '' + $rt.FullName + '' + [System.Environment]::NewLine; - $xml += '' + [System.Environment]::NewLine; - - $itemLabel = $itemName = $rt.Name; - $xml += "[Newtonsoft.Json.JsonConvert]::SerializeObject(" + "$" + "_, [Newtonsoft.Json.Formatting]::Indented)" + [System.Environment]::NewLine; - $xml += '' + [System.Environment]::NewLine; - $xml = '' + [System.Environment]::NewLine + $xml + '' + [System.Environment]::NewLine; - - # Write-Verbose ("Xml: " + $xml); - - return $xml; -} - -# Process the return type -function Process-ReturnType -{ - param([Type] $rt, [System.Array] $allrt) - - $result = ""; - - if ($rt -eq $null) - { - return @($result, $allrt); - } - - if ($allrt.Contains($rt.Name)) - { - return @($result, $allrt); - } - - $allrt += $rt.Name; - - if ($rt.Name -like '*LongRunning*' -or $rt.Name -like ('*' + $component_name + 'OperationResponse*') -or $rt.Name -like '*AzureOperationResponse*') - { - return @($result, $allrt); - } - - $xml = '' + $rt.FullName + ''; - $xml += '' + $rt.FullName + '' + [System.Environment]::NewLine; - $xml += '' + [System.Environment]::NewLine; - - $props = $rt.GetProperties([System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::Static); - - foreach ($pr1 in $props) - { - $typeStr = Get-ProperTypeName $pr1.PropertyType; - $itemLabel = $itemName = $pr1.Name; - - if ($typeStr -eq 'string' ` - -or $typeStr -eq 'string[]' ` - -or $typeStr -eq 'uint' ` - -or $typeStr -eq 'uint?' ` - -or $typeStr -eq 'int' ` - -or $typeStr -eq 'int?' ` - -or $typeStr -eq 'bool' ` - -or $typeStr -eq 'bool?' ` - -or $typeStr -eq 'DateTime' ` - -or $typeStr -eq 'DateTime?' ` - -or $typeStr -eq 'DateTimeOffset' ` - -or $typeStr -eq 'DateTimeOffset?' ` - -or $typeStr -eq 'HttpStatusCode' ) - { - $xml += "${itemName}" + [System.Environment]::NewLine; - } - elseif ($typeStr.StartsWith('IList') ` - -or $typeStr.StartsWith('IDictionary')) - { - $elementType = $pr1.PropertyType.GenericTypeArguments[0]; - - if (-not $elementType.FullName.Contains("String")) - { - if (-not $allrt.Contains($elementType.Name)) - { - $allrt += $elementType.Name; - $addxml = Process-ListType -rt $pr1.PropertyType.GenericTypeArguments[0] -name ${itemName}; - } - } - - $xml += " if (" + "$" + "_.${itemName} -eq $" + "null) { 0 } else { $" + "_.${itemName}.Count }" + [System.Environment]::NewLine; - $xml += " foreach ($" + "item in $" + "_.${itemName}) { [Newtonsoft.Json.JsonConvert]::SerializeObject(" + "$" + "item, [Newtonsoft.Json.Formatting]::Indented) } " + [System.Environment]::NewLine; - } - else - { - $xml += "[Newtonsoft.Json.JsonConvert]::SerializeObject(" + "$" + "_." + ${itemName} + ", [Newtonsoft.Json.Formatting]::Indented)" + [System.Environment]::NewLine; - } - } - - $xml += '' + [System.Environment]::NewLine; - $xml = '' + [System.Environment]::NewLine + $xml + '' + [System.Environment]::NewLine; - - if (-not [System.String]::IsNullOrEmpty($addxml)) - { - $xml += $addxml; - } - - # Write-Verbose ("Xml: " + $xml); - - return @($xml, $allrt) -} - -# Get proper type name -function Format-XML ([xml]$xml, $indent = 2) -{ - $StringWriter = New-Object System.IO.StringWriter; - $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter; - $xmlWriter.Formatting = "indented"; - $xmlWriter.Indentation = $Indent; - $st = $xml.WriteContentTo($XmlWriter); - $st = $XmlWriter.Flush(); - $st = $StringWriter.Flush(); - Write-Output $StringWriter.ToString(); -} - -function Write-XmlFormatFile -{ - param( - [Parameter(Mandatory = $True)] - $xmlFilePath - ) - - $xmlCommentHeader = '' + [System.Environment]::NewLine; - - $xmlContent = [xml]($xmlCommentHeader + '' + [System.Environment]::NewLine + $formatXml + '' + [System.Environment]::NewLine); - $node = $xmlContent.CreateXmlDeclaration('1.0', 'UTF-8', $null); - $st = $xmlContent.InsertBefore($node, $xmlContent.ChildNodes[0]); - - $formattedXmlContent = Format-XML $xmlContent.OuterXml; - $st = Set-FileContent -Path $xmlFilePath -Value $formattedXmlContent; - # Write-Verbose($formattedXmlContent); -} - -# Sample: NewAzureVirtualMachineCreateParameters.cs -function Write-CLICommandFile -{ - param( - [Parameter(Mandatory = $True)] - [string]$fileOutputFolder, - - [Parameter(Mandatory = $True)] - $commandCodeLines - ) - - $fileFullPath = $fileOutputFolder + '/' + 'cli.js'; - - Write-Verbose "============================================="; - Write-Verbose "Writing CLI Command File: "; - Write-Verbose $fileFullPath; - Write-Verbose "============================================="; - - $codeContent = -@" -/** - * Copyright (c) Microsoft. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Warning: This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if the -// code is regenerated. - -'use strict'; - -var fs = require('fs'); -var jsonpatch = require('fast-json-patch'); - -var profile = require('../../../util/profile'); -var utils = require('../../../util/utils'); - -var $ = utils.getLocaleString; - -function beautify(jsonText) { - var obj = JSON.parse(jsonText); - return JSON.stringify(obj, null, 2); -} - -exports.init = function (cli) { - -$commandCodeLines - -}; -"@; - - $st = Set-FileContent -Path $fileFullPath -Value $codeContent; -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Invoke-CodeGeneration.ps1 b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Invoke-CodeGeneration.ps1 deleted file mode 100644 index 5810fc4d1eb5..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Automation/Invoke-CodeGeneration.ps1 +++ /dev/null @@ -1,437 +0,0 @@ -# ---------------------------------------------------------------------------------- -# -# Copyright Microsoft Corporation -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ---------------------------------------------------------------------------------- - -# This script is to generate a set of operation and parameter cmdlets that -# are mapped from the source client library. -# -# For example, 'ComputeManagementClient.VirtualMachines.Start()' would be -# 'Invoke-AzureVirtualMachineStartMethod'. -# -# It's also possible to map the actual verb from function to cmdlet, e.g. -# the above example would be 'Start-AzureVirtualMachine', but to keep it -# simple and consistent, we would like to use the generic verb. - -[CmdletBinding(DefaultParameterSetName = "ByConfiguration")] -param( - # The path to the client library DLL file, along with all its dependency DLLs, - # e.g. 'x:\y\z\Microsoft.Azure.Management.Compute.dll', - # Note that dependency DLL files must be place at the same folder, for reflection: - # e.g. 'x:\y\z\Newtonsoft.Json.dll', - # 'x:\y\z\...' ... - [Parameter(Mandatory = $true, Position = 0)] - [string]$dllFileFullPath, - - # The target output folder, and the generated files would be organized in - # the sub-folder called 'Generated'. - [Parameter(Mandatory = $true, Position = 1)] - [string]$outFolder, - - # Cmdlet Code Generation Flavor - # 1. Invoke (default) that uses Invoke as the verb, and Operation + Method (e.g. VirtualMachine + Get) - # 2. Verb style that maps the method name to a certain common PS verb (e.g. CreateOrUpdate -> New) - [Parameter(Mandatory = $false, ParameterSetName = "ByParameters", Position = 2)] - [string]$cmdletFlavor = 'Invoke', - - # CLI Command Code Generation Flavor - [Parameter(Mandatory = $false, ParameterSetName = "ByParameters", Position = 3)] - [string]$cliCommandFlavor = 'Verb', - - # The filter of operation name for code generation - # e.g. "VirtualMachineScaleSet","VirtualMachineScaleSetVM" - [Parameter(Mandatory = $false, ParameterSetName = "ByParameters", Position = 4)] - [string[]]$operationNameFilter = $null, - - # Configuration JSON file path, instead of individual input parameters - [Parameter(Mandatory = $false, ParameterSetName = "ByParameters", Position = 5)] - [Parameter(Mandatory = $false, ParameterSetName = "ByConfiguration", Position = 2)] - $ConfigPath = $null -) - -# Read Settings from Config Object -if (-not [string]::IsNullOrEmpty($ConfigPath)) -{ - $lines = Get-Content -Path $ConfigPath; - $configJsonObject = ConvertFrom-Json ([string]::Join('', $lines)); - - $operationSettings = @{}; - $cliOperationSettings = @{}; - if ($configJsonObject.operations -ne $null) - { - # The filter of operation name for code generation - # e.g. "VirtualMachineScaleSet","VirtualMachineScaleSetVM" - $operationNameFilter = @(); - foreach ($operationItem in $configJsonObject.operations) - { - $operationNameFilter += $operationItem.name; - $operationSettings.Add($operationItem.name, @()); - $cliOperationSettings.Add($operationItem.name, @()); - if ($operationItem.methods -ne $null) - { - foreach ($methodItem in $operationItem.methods) - { - # Configure the List of Skipped Methods - if ($methodItem.cmdlet -ne $null -and $methodItem.cmdlet.skip -eq $true) - { - $operationSettings[$operationItem.name] += $methodItem.name; - } - - if ($methodItem.command -ne $null -and $methodItem.command.skip -eq $true) - { - $cliOperationSettings[$operationItem.name] += $methodItem.name; - } - } - } - } - } - - if ($configJsonObject.produces -ne $null) - { - $produces = $configJsonObject.produces; - foreach ($produceItem in $produces) - { - if ($produceItem.name -eq 'PowerShell' -and $produceItem.flavor -ne $null) - { - $cmdletFlavor = $produceItem.flavor; - } - - if ($produceItem.name -eq 'CLI' -and $produceItem.flavor -ne $null) - { - $cliCommandFlavor = $produceItem.flavor; - } - } - } -} - -# Import functions and variables -. "$PSScriptRoot\Import-AssemblyFunction.ps1"; -. "$PSScriptRoot\Import-CommonVariables.ps1"; -. "$PSScriptRoot\Import-StringFunction.ps1"; -. "$PSScriptRoot\Import-TypeFunction.ps1"; -. "$PSScriptRoot\Import-OperationFunction.ps1"; -. "$PSScriptRoot\Import-WriterFunction.ps1"; - -# Code Generation Main Run -$outFolder += '/Generated'; - -if (-not (Test-Path -Path $dllFileFullPath)) -{ - Write-Verbose "DLL file `'$dllFileFullPath`' not found. Exit."; -} -else -{ - $assembly = Load-AssemblyFile $dllFileFullPath; - - # All original types - $types = $assembly.GetTypes(); - $filtered_types = Get-FilteredOperationTypes $types $clientNameSpace $operationNameFilter; - - # Write Base Cmdlet File - $opNameList = ($filtered_types | select -ExpandProperty Name); - if ($opNameList -eq $null) - { - Write-Error "No qualifed operations found. Exit."; - return -1; - } - - $auto_base_cmdlet_name = $component_name + 'AutomationBaseCmdlet'; - $baseCmdletFileFullName = $outFolder + '\' + "$auto_base_cmdlet_name.cs"; - $clientClassType = $types | where { $_.Namespace -eq $clientNameSpace -and $_.Name -eq ('I' + $component_name + 'ManagementClient') }; - Write-BaseCmdletFile $baseCmdletFileFullName $opNameList $clientClassType; - - # PSArgument File - $model_class_out_folder = $outFolder + '\Models'; - if (Test-Path -Path $model_class_out_folder) - { - $st = rmdir -Recurse -Force $model_class_out_folder; - } - $st = mkdir -Force $model_class_out_folder; - $psargument_model_class_file_path = $model_class_out_folder + '\PSArgument.cs'; - Write-PSArgumentFile $psargument_model_class_file_path; - - $invoke_cmdlet_class_name = 'InvokeAzure' + $component_name + 'MethodCmdlet'; - $invoke_cmdlet_file_name = $outFolder + '\' + "$invoke_cmdlet_class_name.cs"; - $parameter_cmdlet_class_name = 'NewAzure' + $component_name + 'ArgumentListCmdlet'; - $parameter_cmdlet_file_name = $outFolder + '\' + "$parameter_cmdlet_class_name.cs"; - $new_object_cmdlet_class_name = 'NewAzure' + $component_name + 'ParameterObjectCmdlet'; - $new_object_cmdlet_file_name = $outFolder + '\' + "$new_object_cmdlet_class_name.cs"; - - [System.Reflection.ParameterInfo[]]$parameter_type_info_list = @(); - $dynamic_param_method_code = @(); - $invoke_cmdlet_method_code = @(); - $parameter_cmdlet_method_code = @(); - $all_return_type_names = @(); - $formatXml = ""; - $cliCommandCodeMainBody = ""; - - # Write Operation Cmdlet Files - $operation_type_count = 0; - $total_operation_type_count = $filtered_types.Count; - foreach ($operation_type in $filtered_types) - { - $operation_type_count++; - $operation_type_count_roman_index = Get-RomanNumeral $operation_type_count; - $operation_nomalized_name = Get-OperationShortName $operation_type.Name; - Write-Verbose ''; - Write-Verbose $BAR_LINE; - Write-Verbose ("Chapter ${operation_type_count_roman_index}. " + $operation_nomalized_name + " (${operation_type_count}/${total_operation_type_count}) "); - Write-Verbose $BAR_LINE; - - $opShortName = Get-OperationShortName $operation_type.Name; - if ($opShortName.EndsWith("ScaleSets")) - { - $opFolderName = $opShortName.Replace('ScaleSets', 'ScaleSet'); - $opOutFolder = $outFolder + '/' + $opFolderName; - } - elseif ($opShortName.EndsWith("ScaleSetVMs")) - { - $opFolderName = $opShortName.Replace('ScaleSetVMs', 'ScaleSetVM'); - $opOutFolder = $outFolder + '/' + $opFolderName; - } - elseif ($opShortName.EndsWith("VirtualMachines")) - { - $opFolderName = $opShortName.Replace('VirtualMachines', 'VirtualMachine'); - $opOutFolder = $outFolder + '/' + $opFolderName; - } - else - { - $opOutFolder = $outFolder + '/' + $opShortName; - } - - if (Test-Path -Path $opOutFolder) - { - $st = rmdir -Recurse -Force $opOutFolder; - } - $st = mkdir -Force $opOutFolder; - - $methods = Get-OperationMethods $operation_type; - if ($methods -eq $null -or $methods.Count -eq 0) - { - Write-Verbose "No methods found. Skip."; - continue; - } - - $SKIP_VERB_NOUN_CMDLET_LIST = $operationSettings[$operation_nomalized_name]; - - $qualified_methods = @(); - $total_method_count = 0; - [System.Collections.Hashtable]$friendMethodDict = @{}; - [System.Collections.Hashtable]$pageMethodDict = @{}; - foreach ($mtItem in $methods) - { - [System.Reflection.MethodInfo]$methodInfo = $mtItem; - if ($methodInfo.Name -like 'Begin*') - { - continue; - } - elseif ($methodInfo.Name -like '*Async') - { - continue; - } - - $methodAnnotationSuffix = ''; - if ($SKIP_VERB_NOUN_CMDLET_LIST -contains $methodInfo.Name) - { - $methodAnnotationSuffix = ' *'; - } - - Write-Verbose ($methodInfo.Name + $methodAnnotationSuffix); - - $qualified_methods += $mtItem; - $total_method_count++; - - # Handle Friend Methods - if (-not $friendMethodDict.ContainsKey($mtItem.Name)) - { - $searchName = $null; - $matchedMethodInfo = $null; - if ($mtItem.Name -eq 'Deallocate') - { - $searchName = 'PowerOff'; - $matchedMethodInfo = $methodInfo; - } - elseif ($mtItem.Name -eq 'Get') - { - $searchName = 'GetInstanceView'; - $matchedMethodInfo = $methodInfo; - } - elseif ($mtItem.Name -eq 'List') - { - $searchName = 'ListAll'; - } - - if ($searchName -ne $null) - { - $methods2 = Get-OperationMethods $operation_type; - $foundMethod = Find-MatchedMethod $searchName $methods2 $matchedMethodInfo; - if ($foundMethod -ne $null) - { - $friendMethodDict.Add($mtItem.Name, $foundMethod); - } - } - } - - # Handle Page Methods - if ($mtItem.Name -like 'List*' -and (-not $pageMethodDict.ContainsKey($mtItem.Name))) - { - $methods2 = Get-OperationMethods $operation_type; - $foundMethod = Find-MatchedMethod ($mtItem.Name + 'Next') $methods2; - $pageMethodDict.Add($mtItem.Name, $foundMethod); - } - } - - $method_count = 0; - foreach ($mtItem in $qualified_methods) - { - [System.Reflection.MethodInfo]$methodInfo = $mtItem; - $method_count++; - $methodAnnotationSuffix = ''; - if ($SKIP_VERB_NOUN_CMDLET_LIST -contains $methodInfo.Name) - { - $methodAnnotationSuffix = ' *'; - } - - # Get Friend Method (if any) - $friendMethodInfo = $null; - if ($friendMethodDict.ContainsKey($methodInfo.Name)) - { - $friendMethodInfo = $friendMethodDict[$methodInfo.Name]; - } - - $friendMethodMessage = ''; - if ($friendMethodInfo -ne $null -and $friendMethodInfo.Name -ne $null) - { - $friendMethodMessage = 'Friend=' + ($friendMethodInfo.Name.Replace('Async', '')) + ''; - } - - # Get Page Method (if any) - $pageMethodInfo = $null; - if ($pageMethodDict.ContainsKey($methodInfo.Name)) - { - $pageMethodInfo = $pageMethodDict[$methodInfo.Name]; - } - - $pageMethodMessage = ''; - if ($pageMethodInfo -ne $null -and $pageMethodInfo.Name -ne $null) - { - $pageMethodMessage = 'Page=' + ($pageMethodInfo.Name.Replace('Async', '')) + ''; - } - - # Combine Get and List/ListAll Methods (if any) - $combineGetAndList = $false; - $combineGetAndListAll = $false; - if ($mtItem.Name -eq 'Get') - { - $methods3 = Get-OperationMethods $operation_type; - $foundMethod1 = Find-MatchedMethod 'List' $methods3; - $foundMethod2 = Find-MatchedMethod 'ListAll' $methods3; - - if ($foundMethod1 -ne $null) - { - $combineGetAndList = $true; - } - - if ($foundMethod2 -ne $null) - { - $combineGetAndListAll = $true; - } - } - - $opCmdletFlavor = $cmdletFlavor; - if ($SKIP_VERB_NOUN_CMDLET_LIST -contains $methodInfo.Name) - { - #Overwrite and skip these method's 'Verb' cmdlet flavor - $opCmdletFlavor = 'None'; - } - - # Output Info for Method Signature - Write-Verbose ""; - Write-Verbose $SEC_LINE; - $methodMessage = "${operation_type_count_roman_index}. ${method_count}/${total_method_count} " + $methodInfo.Name.Replace('Async', '') + $methodAnnotationSuffix; - if (($friendMethodMessage -ne '') -or ($pageMethodMessage -ne '')) - { - $methodMessage += ' {' + $friendMethodMessage; - if ($friendMethodMessage -ne '' -and $pageMethodMessage -ne '') - { - $methodMessage += ', '; - } - $methodMessage += $pageMethodMessage; - $methodMessage += '}'; - } - - Write-Verbose $methodMessage; - foreach ($paramInfoItem in $methodInfo.GetParameters()) - { - [System.Reflection.ParameterInfo]$paramInfo = $paramInfoItem; - if (($paramInfo.ParameterType.Name -like "I*Operations") -and ($paramInfo.Name -eq 'operations')) - { - continue; - } - elseif ($paramInfo.ParameterType.FullName.EndsWith('CancellationToken')) - { - continue; - } - - Write-Verbose ("-" + $paramInfo.Name + " : " + $paramInfo.ParameterType); - } - Write-Verbose $SEC_LINE; - - $outputs = (. $PSScriptRoot\Generate-FunctionCommand.ps1 -OperationName $opShortName ` - -MethodInfo $methodInfo ` - -ModelClassNameSpace $clientModelNameSpace ` - -FileOutputFolder $opOutFolder ` - -FunctionCmdletFlavor $opCmdletFlavor ` - -FriendMethodInfo $friendMethodInfo ` - -PageMethodInfo $pageMethodInfo ` - -CombineGetAndList $combineGetAndList ` - -CombineGetAndListAll $combineGetAndListAll ); - - if ($outputs.Count -ne $null) - { - $dynamic_param_method_code += $outputs[-4]; - $invoke_cmdlet_method_code += $outputs[-3]; - $parameter_cmdlet_method_code += $outputs[-2]; - $cliCommandCodeMainBody += $outputs[-1]; - } - - if ($methodInfo.ReturnType.FullName -ne 'System.Void') - { - $returnTypeResult = Process-ReturnType -rt $methodInfo.ReturnType -allrt $all_return_type_names; - $formatXml += $returnTypeResult[0]; - $all_return_type_names = $returnTypeResult[1]; - } - } - - Write-InvokeCmdletFile $invoke_cmdlet_file_name $invoke_cmdlet_class_name $auto_base_cmdlet_name $clientClassType $filtered_types $invoke_cmdlet_method_code $dynamic_param_method_code; - Write-InvokeParameterCmdletFile $parameter_cmdlet_file_name $parameter_cmdlet_class_name $auto_base_cmdlet_name $clientClassType $filtered_types $parameter_cmdlet_method_code; - Write-NewParameterObjectCmdletFile $new_object_cmdlet_file_name $new_object_cmdlet_class_name $auto_base_cmdlet_name $clientClassType $filtered_types $parameter_cmdlet_method_code; - } - - # XML - $xmlFilePath = $outFolder + '\' + $code_common_namespace + '.format.generated.ps1xml'; - Write-Verbose $BAR_LINE; - Write-Verbose 'Writing XML Format File: '; - Write-Verbose $xmlFilePath; - Write-Verbose $BAR_LINE; - Write-XmlFormatFile $xmlFilePath; - - # CLI - if ($cliCommandFlavor -eq 'Verb') - { - Write-CLICommandFile $outFolder $cliCommandCodeMainBody; - } - - Write-Verbose $BAR_LINE; - Write-Verbose "Finished."; - Write-Verbose $BAR_LINE; -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Commands.ServiceManagement.Preview.csproj b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Commands.ServiceManagement.Preview.csproj index 4b2d1c52b399..c1142adac834 100644 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Commands.ServiceManagement.Preview.csproj +++ b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Commands.ServiceManagement.Preview.csproj @@ -262,23 +262,23 @@ - + %WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe - .\Automation\Invoke-CodeGeneration.ps1 + $(PSGenScriptPath)\Automation\Invoke-CodeGeneration.ps1 $(OutputPath)\Microsoft.WindowsAzure.Management.Compute.dll $(MSBuildProjectDirectory) - $(MSBuildProjectDirectory)\Configuration\RDFE.json + $(PSGenScriptPath)\Configuration\RDFE.json - + %WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe - .\Automation\Invoke-CodeGeneration.ps1 + $(PSGenScriptPath)\Automation\Invoke-CodeGeneration.ps1 $(OutputPath)\Microsoft.Azure.Management.Compute.dll ..\..\..\ResourceManager\Compute\Commands.Compute - $(MSBuildProjectDirectory)\Configuration\Compute.json + $(PSGenScriptPath)\Configuration\Compute.json diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Configuration/Compute.json b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Configuration/Compute.json deleted file mode 100644 index 91e33ac00c92..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Configuration/Compute.json +++ /dev/null @@ -1,134 +0,0 @@ -{ - "info": { - "title": "Microsoft.Azure.Management.Compute", - "version": "11.3.0-prerelease", - "description": "Virtual Machine Scale Sets" - }, - "produces": [ - { - "name": "PowerShell", - "flavor": "Verb" - }, - { - "name": "CLI", - "flavor": "Verb" - } - ], - "operations": [ - { - "name": "VirtualMachineScaleSets", - "methods": [ - { - "name": "Get", - "friends": [ - "GetInstanceView", - "List", - "ListAll" - ] - }, - { - "name": "Deallocate", - "cmdlet": { - "verb": "Stop", - "suffix": "" - }, - "friends": [ - "PowerOff" - ] - }, - { - "name": "PowerOff", - "cmdlet": { - "skip": true - } - }, - { - "name": "GetInstanceView", - "cmdlet": { - "skip": true - } - }, - { - "name": "List", - "cmdlet": { - "skip": true - } - }, - { - "name": "ListNext", - "cmdlet": { - "skip": true - } - }, - { - "name": "ListAll", - "cmdlet": { - "skip": true - } - }, - { - "name": "ListAllNext", - "cmdlet": { - "skip": true - } - }, - { - "name": "ListSkusNext", - "cmdlet": { - "skip": true - } - } - ] - }, - { - "name": "VirtualMachineScaleSetVMs", - "methods": [ - { - "name": "PowerOff", - "cmdlet": { - "skip": true - } - }, - { - "name": "GetInstanceView", - "cmdlet": { - "skip": true - } - }, - { - "name": "List", - "cmdlet": { - "skip": true - } - }, - { - "name": "ListNext", - "cmdlet": { - "skip": true - } - } - ] - }, - { - "name": "VirtualMachines", - "methods": [ - { "name": "Capture", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "CreateOrUpdate", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "Deallocate", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "Delete", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "Generalize", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "Get", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "List", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "ListAll", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "ListAllNext", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "ListAvailableSizes", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "ListAvailableSizesNext", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "ListNext", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "PowerOff", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "Redeploy", "cmdlet": { "skip": true },"command": { "skip": false } }, - { "name": "Restart", "cmdlet": { "skip": true },"command": { "skip": true } }, - { "name": "Start", "cmdlet": { "skip": true },"command": { "skip": true } } - ] - } - ] -} diff --git a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Configuration/RDFE.json b/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Configuration/RDFE.json deleted file mode 100644 index 17c25751f941..000000000000 --- a/src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Configuration/RDFE.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "info": { - "title": "Microsoft.WindowsAzure.Management.Compute", - "version": "12.6.0", - "description": "Microsoft Azure Service Management" - }, - "produces": [ - { - "name": "PowerShell", - "flavor": "Invoke" - }, - { - "name": "CLI", - "flavor": "Verb" - } - ] -}