Skip to content
This repository was archived by the owner on Sep 27, 2019. It is now read-only.

Commit 9dd5db7

Browse files
saving changes
2 parents 6f76382 + c3b1ea6 commit 9dd5db7

File tree

1 file changed

+116
-110
lines changed

1 file changed

+116
-110
lines changed

PSSwagger.psm1

Lines changed: 116 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
<#
1+
$Global:parameters = @{}
2+
3+
<#
24
.DESCRIPTION
35
Decodes the swagger spec and generates PowerShell cmdlets.
46
@@ -22,9 +24,9 @@ function Export-CommandFromSwagger
2224
[String] $Path,
2325

2426
[Parameter(Mandatory = $true)]
25-
[String] $ModuleName
2627

27-
)
28+
[String] $ModuleName
29+
)
2830

2931
if ($PSCmdlet.ParameterSetName -eq 'PathParameterSet')
3032
{
@@ -54,6 +56,8 @@ function Export-CommandFromSwagger
5456
$null = New-Item -ItemType Directory $outputDirectory -ErrorAction Stop
5557

5658
$namespace = "Microsoft.PowerShell.$moduleName"
59+
$Global:parameters.Add('namespace', $namespace)
60+
5761
GenerateCsharpCode -swaggerSpecPath $swaggerSpecPath -path $outputDirectory -moduleName $moduleName -nameSpace $namespace
5862
GenerateModuleManifest -path $outputDirectory -moduleName $moduleName -rootModule "$moduleName.psm1"
5963

@@ -62,6 +66,12 @@ function Export-CommandFromSwagger
6266
$cmds = [System.Collections.ObjectModel.Collection[string]]::new()
6367

6468
$jsonObject = ConvertFrom-Json ((Get-Content $swaggerSpecPath) -join [Environment]::NewLine) -ErrorAction Stop
69+
70+
# Populate the global parameters
71+
$null = ProcessGlobalParams -globalParams $jsonObject.parameters -info $jsonObject.info
72+
$null = ProcessDefinitions -definitions $jsonObject.definitions
73+
74+
# Handle the paths
6575
$jsonObject.Paths.PSObject.Properties | % {
6676
$jsonPathObject = $_.Value
6777
$jsonPathObject.psobject.Properties | % {
@@ -97,29 +107,12 @@ function $commandName
97107
[CmdletBinding()]
98108
param($paramblock
99109
)
110+
111+
$body
100112
}
101113
'@
102114

103-
$commandName = ProcessOperationId $jsonPathItemObject.operationId
104-
$description = $jsonPathItemObject.description
105-
$commandHelp = $executionContext.InvokeCommand.ExpandString($helpDescStr)
106-
107-
[string]$paramHelp = ""
108-
$paramblock,$paramHelp = ProcessParameters $jsonPathItemObject.parameters
109-
110-
$executionContext.InvokeCommand.ExpandString($advFnSignature)
111-
112-
}
113-
<#
114-
.DESCRIPTION
115-
Returns a string that can be used in a parameter block.
116-
#>
117-
function ProcessParameters
118-
{
119-
param(
120-
[object[]] $parametersSpec)
121-
122-
$parameterDefString = @'
115+
$parameterDefString = @'
123116
124117
[Parameter(Mandatory = $isParamMandatory)]
125118
[$paramType] $paramName,
@@ -132,34 +125,89 @@ $helpParamStr = @'
132125
133126
'@
134127

135-
$paramBlockToReturn = ""
136-
[string]$tempParamHelp = ""
137-
138-
$parametersSpec | % {
139-
# TODO: What to do with $ref
140-
if ($_.Name)
141-
{
128+
$functionBodyStr = @'
129+
$serviceCredentials = Get-AzCredentials
130+
$subscriptionId = Get-SubscriptionId
131+
132+
$clientName = [$fullModuleName]::new($serviceCredentials, [System.Net.Http.DelegatingHandler[]]::new(0))
133+
$clientName.ApiVersion = $infoVersion
134+
$clientName.SubscriptionId = $subscriptionId
135+
$operationVar = $clientName.$operations.$methodName($requiredParamList)
136+
'@
137+
138+
$commandName = ProcessOperationId $jsonPathItemObject.operationId
139+
$description = $jsonPathItemObject.description
140+
$commandHelp = $executionContext.InvokeCommand.ExpandString($helpDescStr)
141+
142+
[string]$paramHelp = ""
143+
$paramblock = ""
144+
$requiredParamList = ""
145+
$optionalParamList = ""
146+
$body = ""
147+
148+
# Handle the function parameters
149+
#region Function Parameters
150+
151+
$jsonPathItemObject.parameters | ForEach-Object {
152+
if($_.name)
153+
{
142154
$isParamMandatory = '$false'
143155
$paramName = '$' + $_.Name
144156
$paramType = if ($_.type) { $_.type } else { "object" }
145-
if ($_.required) { $isParamMandatory = '$true' }
146-
$paramBlockToReturn += $executionContext.InvokeCommand.ExpandString($parameterDefString)
157+
if ($_.required)
158+
{
159+
$isParamMandatory = '$true'
160+
$requiredParamList += $paramName + ", "
161+
}
162+
else
163+
{
164+
$optionalParamList += $paramName + ", "
165+
}
166+
167+
$paramblock += $executionContext.InvokeCommand.ExpandString($parameterDefString)
147168
if ($_.description)
148169
{
149170
$pDescription = $_.description
150-
#$tempParamHelp += $executionContext.InvokeCommand.ExpandString($helpParamStr)
151-
$tempParamHelp += @"
171+
$paramHelp += @"
152172
153173
.PARAMETER $($_.Name)
154174
$pDescription
155175
156176
"@
157177
}
158-
}
159-
} # $parametersSpec
178+
}
179+
elseif($_.'$ref')
180+
{
181+
}
182+
}# $parametersSpec
183+
184+
$paramblock = $paramBlock.TrimEnd(",")
185+
$requiredParamList = $requiredParamList.TrimEnd(", ")
186+
$optionalParamList = $optionalParamList.TrimEnd(", ")
187+
188+
#endregion Function Parameters
189+
190+
# Handle the function body
191+
#region Function Body
192+
$infoVersion = $Global:parameters['infoVersion']
193+
$modulePostfix = $Global:parameters['infoTitle'] + '.' + $Global:parameters['infoName']
194+
$fullModuleName = $Global:parameters['namespace'] + '.' + $modulePostfix
195+
$clientName = '$' + $modulePostfix.Split('.')[$_.count - 1]
196+
197+
$operationName = $jsonPathItemObject.operationId.Split('_')[0]
198+
$operationType = $jsonPathItemObject.operationId.Split('_')[1]
199+
$operations = $operationName + 'Operations'
200+
$methodName = $operationType + 'WithHttpMessagesAsync'
201+
$operationVar = '$' + $operationName
160202

161-
$paramBlockToReturn.TrimEnd(",")
162-
$tempParamHelp
203+
$serviceCredentials = '$' + 'serviceCredentials'
204+
$subscriptionId = '$' + 'subscriptionId'
205+
206+
$body = $executionContext.InvokeCommand.ExpandString($functionBodyStr)
207+
208+
#endregion Function Body
209+
210+
$executionContext.InvokeCommand.ExpandString($advFnSignature)
163211
}
164212

165213
<#
@@ -197,92 +245,50 @@ function ProcessOperationId
197245
return "$cmdVerb-$cmdNoun"
198246
}
199247

200-
#endregion
201-
202-
#region Module Generation Helpers
203-
204-
function GenerateCsharpCode
248+
function ProcessGlobalParams
205249
{
206250
param(
207-
[Parameter(Mandatory = $true)]
208-
[string] $swaggerSpecPath,
209-
210-
[Parameter(Mandatory = $true)]
211-
[string] $path,
212-
213-
[Parameter(Mandatory = $true)]
214-
[string] $moduleName,
215-
216-
[Parameter(Mandatory = $true)]
217-
[string] $nameSpace
218-
219-
)
220-
221-
Write-Verbose "Generating CSharp Code using AutoRest"
222-
223-
$autoRestExePath = get-command autorest.exe | % source
224-
if (-not $autoRestExePath)
225-
{
226-
throw "Unable to find AutoRest.exe in PATH environment. Ensure the PATH is updated."
227-
}
228-
229-
$outputDirectory = $path
230-
$outAssembly = join-path $outputDirectory azure.csharp.ps.generated.dll
231-
$net45Dir = join-path $outputDirectory "Net45"
232-
$generatedCSharpPath = Join-Path $outputDirectory "Generated.Csharp"
233-
$startUpScriptFile = (join-path $outputDirectory $moduleName) + ".StartupScript.ps1"
234-
$moduleManifestFile = (join-path $outputDirectory $moduleName) + ".psd1"
235-
236-
if (Test-Path $outAssembly)
237-
{
238-
del $outAssembly -Force
239-
}
251+
[PSCustomObject] $globalParams,
252+
[PSCustomObject] $info
253+
)
240254

241-
if (Test-Path $net45Dir)
242-
{
243-
del $net45Dir -Force -Recurse
255+
$globalParams.parameters.PSObject.Properties | % {
256+
$name = removeSpecialChars -strWithSpecialChars $_.name
257+
$Global:parameters.Add($name, $jsonObject.parameters.$name)
244258
}
245259

246-
& $autoRestExePath -input $swaggerSpecPath -CodeGenerator CSharp -OutputDirectory $generatedCSharpPath -NameSpace $nameSpace
247-
if ($LastExitCode)
248-
{
249-
throw "AutoRest resulted in an error"
250-
}
260+
$infoVersion = $info.version
261+
$infoTitle = $info.title
262+
$infoName = $info.'x-ms-code-generation-settings'.name
251263

252-
Write-Verbose "Generating assembly from the CSharp code"
253-
254-
$srcContent = dir $generatedCSharpPath -Filter *.cs -Recurse -Exclude Program.cs,TemporaryGeneratedFile* | ? DirectoryName -notlike '*Azure.Csharp.Generated*' | % { "// File $($_.FullName)"; get-content $_.FullName }
255-
$oneSrc = $srcContent -join "`n"
256-
257-
$refassemlbiles = @("System.dll","System.Core.dll","System.Net.Http.dll",
258-
"System.Net.Http.WebRequest","System.Runtime.Serialization.dll","System.Xml.dll",
259-
"$PSScriptRoot\Generated.Azure.Common.Helpers\Net45\Microsoft.Rest.ClientRuntime.dll",
260-
"$PSScriptRoot\Generated.Azure.Common.Helpers\Net45\Newtonsoft.Json.dll")
261-
262-
Add-Type -TypeDefinition $oneSrc -ReferencedAssemblies $refassemlbiles -OutputAssembly $outAssembly
264+
$Global:parameters.Add('infoVersion', $infoVersion)
265+
$Global:parameters.Add('infoTitle', $infoTitle)
266+
$Global:parameters.Add('infoName', $infoName)
263267
}
264268

265-
function GenerateModuleManifest
269+
function ProcessDefinitions
266270
{
267271
param(
268-
[Parameter(Mandatory = $true)]
269-
[string] $path,
272+
[PSCustomObject] $definitions
273+
)
274+
275+
$definitionList = @{}
276+
$definitions.PSObject.Properties | % {
277+
$name = $_.name
278+
$definitionList.Add($name, $_)
279+
}
270280

271-
[Parameter(Mandatory = $true)]
272-
[string] $moduleName,
281+
$Global:parameters.Add('definitionList', $definitionList)
282+
}
273283

274-
[Parameter(Mandatory = $true)]
275-
[string] $rootModule
276-
)
284+
function removeSpecialChars
285+
{
286+
param([string] $strWithSpecialChars)
277287

278-
$startUpScriptFile = (join-path $path $moduleName) + ".StartupScript.ps1"
279-
$moduleManifestFile = (join-path $path $moduleName) + ".psd1"
280-
281-
@'
282-
Add-Type -LiteralPath "$PSScriptRoot\azure.csharp.ps.generated.dll"
283-
'@ | out-file -Encoding Ascii $startUpScriptFile
288+
$pattern = '[^a-zA-Z]'
289+
$resultStr = $strWithSpecialChars -replace $pattern, ''
284290

285-
New-ModuleManifest -Path $moduleManifestFile -Guid (New-Guid) -Author (whoami) -ScriptsToProcess ($moduleName + ".StartupScript.ps1") -RequiredModules "Generated.Azure.Common.Helpers" -RootModule "$rootModule"
291+
return $resultStr
286292
}
287293

288294
#endregion

0 commit comments

Comments
 (0)