Skip to content
This repository was archived by the owner on Sep 27, 2019. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions PSSwagger/GeneratedHelpers.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,16 @@ function Get-AzSubscriptionId
param()

$AzureContext = & "Get-AzureRmContext" -ErrorAction Stop
if(Get-Member -InputObject $AzureContext.Subscription -Name SubscriptionId)
if($AzureContext)
{
return $AzureContext.Subscription.SubscriptionId
}
else
{
return $AzureContext.Subscription.Id
if(Get-Member -InputObject $AzureContext.Subscription -Name SubscriptionId)
{
return $AzureContext.Subscription.SubscriptionId
}
else
{
return $AzureContext.Subscription.Id
}
}
}

Expand Down
110 changes: 110 additions & 0 deletions PSSwagger/New-ServiceClient.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
Microsoft.PowerShell.Core\Set-StrictMode -Version Latest
Copy link
Contributor

@brywang-msft brywang-msft Sep 11, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason why you don't want to add to GeneratedHelpers? #Closed

Copy link
Contributor Author

@bmanikm bmanikm Sep 11, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Module owner can just replace this file during the mock testing. #Closed


<#
.DESCRIPTION
Creates Service Client object.

.PARAMETER FullClientTypeName
Client type full name.

.PARAMETER AddHttpClientHandler
Switch to determine whether the client type constructor expects the HttpClientHandler object.

.PARAMETER Credential
Credential is required for for creating the HttpClientHandler object.

.PARAMETER AuthenticationCommand
Command that should return a Microsoft.Rest.ServiceClientCredentials object that implements custom authentication logic.

.PARAMETER AuthenticationCommandArgumentList
Arguments to the AuthenticationCommand, if any.

.PARAMETER HostOverrideCommand
Command should return a custom hostname string.
Overrides the default host in the specification.

.PARAMETER SubscriptionIdCommand
Custom command get SubscriptionId value.

.PARAMETER GlobalParameterHashtable
Global parameters to be set on client object.
#>
function New-ServiceClient {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]
$FullClientTypeName,

[Parameter(Mandatory = $false)]
[switch]
$AddHttpClientHandler,

[Parameter(Mandatory = $false)]
[pscredential]
$Credential,

[Parameter(Mandatory = $true)]
[string]
$AuthenticationCommand,

[Parameter(Mandatory = $false)]
[Object[]]
$AuthenticationCommandArgumentList,

[Parameter(Mandatory = $false)]
[string]
$HostOverrideCommand,

[Parameter(Mandatory = $false)]
[string]
$SubscriptionIdCommand,

[Parameter(Mandatory = $false)]
[PSCustomObject]
$GlobalParameterHashtable
)

$ClientArgumentList = @()
$InvokeCommand_parameters = @{
ScriptBlock = [scriptblock]::Create($AuthenticationCommand)
}
if ($AuthenticationCommandArgumentList) {
$InvokeCommand_parameters['ArgumentList'] = $AuthenticationCommandArgumentList
}
$ClientArgumentList += Invoke-Command @InvokeCommand_parameters

if ($AddHttpClientHandler) {
$httpClientHandler = New-HttpClientHandler -Credential $Credential
$ClientArgumentList += $httpClientHandler
}

$delegatingHandler = New-Object -TypeName System.Net.Http.DelegatingHandler[] -ArgumentList 0
$ClientArgumentList += $delegatingHandler

$Client = New-Object -TypeName $FullClientTypeName -ArgumentList $ClientArgumentList

if ($HostOverrideCommand) {
$Client.BaseUri = Invoke-Command -ScriptBlock [scriptblock]::Create($HostOverrideCommand)
}

if ($GlobalParameterHashtable) {
$GlobalParameterHashtable.GetEnumerator() | ForEach-Object {
if (Get-Member -InputObject $Client -Name $_.Key -MemberType Property) {
if ((-not $_.Value) -and ($_.Key -eq 'SubscriptionId')) {
if($SubscriptionIdCommand) {
$Client.SubscriptionId = Invoke-Command -ScriptBlock [scriptblock]::Create($SubscriptionIdCommand)
}
else {
$Client.SubscriptionId = Get-AzSubscriptionId
}
}
else {
$Client."$($_.Key)" = $_.Value
}
}
}
}

return $Client
}
74 changes: 43 additions & 31 deletions PSSwagger/PSSwagger.Constants.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ $DynamicAssemblyGenerationCode
`$allDllsPath = Join-Path -Path `$ClrPath -ChildPath '*.dll'
Get-ChildItem -Path `$allDllsPath -File | ForEach-Object { Add-Type -Path `$_.FullName -ErrorAction SilentlyContinue }

. (Join-Path -Path `$PSScriptRoot -ChildPath 'New-ServiceClient.ps1')
. (Join-Path -Path `$PSScriptRoot -ChildPath 'GeneratedHelpers.ps1')

`$allPs1FilesPath = Join-Path -Path `$PSScriptRoot -ChildPath '$GeneratedCommandsName' | Join-Path -ChildPath '*.ps1'
Expand Down Expand Up @@ -157,11 +158,49 @@ $constructFlattenedParameter = @'
$functionBodyStr = @'

`$ErrorActionPreference = 'Stop'
$securityBlock

$clientName = New-Object -TypeName $FullClientTypeName -ArgumentList $clientArgumentList$apiVersion
$overrideBaseUriBlock
$GlobalParameterBlock
`$NewServiceClient_params = @{
FullClientTypeName = '$FullClientTypeName'
}
$(
if($AuthenticationCommand){
"
`$NewServiceClient_params['AuthenticationCommand'] = @'
$AuthenticationCommand
`'@ "
if($AuthenticationCommandArgumentName){
"
`$NewServiceClient_params['AuthenticationCommandArgumentList'] = `$$AuthenticationCommandArgumentName"
}
}
if($AddHttpClientHandler){
"
`$NewServiceClient_params['AddHttpClientHandler'] = `$true
`$NewServiceClient_params['Credential'] = `$Credential"
}
if($hostOverrideCommand){
"
`$NewServiceClient_params['HostOverrideCommand'] = @'
$hostOverrideCommand
`'@"
}
if($GlobalParameters) {
'
$GlobalParameterHashtable = @{} '

foreach($parameter in $GlobalParameters) {
"
`$GlobalParameterHashtable['$parameter'] = `$null
if(`$PSBoundParameters.ContainsKey('$parameter')) {
`$GlobalParameterHashtable['$parameter'] = `$PSBoundParameters['$parameter']
}
"
}
"
`$NewServiceClient_params['GlobalParameterHashtable'] = `$GlobalParameterHashtable "
}
)
$clientName = New-ServiceClient @NewServiceClient_params
$oDataExpressionBlock
$parameterGroupsExpressionBlock
$flattenedParametersBlock
Expand All @@ -174,16 +213,6 @@ $functionBodyStr = @'
}
'@

$clientArgumentListNoHandler = "`$serviceCredentials,`$delegatingHandler"
$clientArgumentListHttpClientHandler = "`$serviceCredentials,`$httpClientHandler,`$delegatingHandler"

$securityBlockStr = @'
`$serviceCredentials = $authFunctionCall
$azSubscriptionIdBlock
$httpClientHandlerCall
`$delegatingHandler = New-Object -TypeName System.Net.Http.DelegatingHandler[] 0
'@

$parameterSetBasedMethodStrIfCase = @'
if ('$operationId' -eq `$PsCmdlet.ParameterSetName) {
$additionalConditionStart$methodBlock$additionalConditionEnd
Expand Down Expand Up @@ -428,23 +457,6 @@ $createObjectStr = @'
return `$Object
'@

$ApiVersionStr = @'

if(Get-Member -InputObject $clientName -Name 'ApiVersion' -MemberType Property)
{
$clientName.ApiVersion = "$infoVersion"
}
'@

$GlobalParameterBlockStr = @'
if(Get-Member -InputObject `$clientName -Name '$globalParameterName' -MemberType Property)
{
`$clientName.$globalParameterName = $globalParameterValue
}
'@

$HostOverrideBlock = '`$ResourceManagerUrl = $hostOverrideCommand`n $clientName.BaseUri = `$ResourceManagerUrl'

$GeneratedCommandsName = 'Generated.PowerShell.Commands'

$FormatViewDefinitionStr = @'
Expand Down
3 changes: 2 additions & 1 deletion PSSwagger/PSSwagger.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -612,9 +612,10 @@ function New-PSSwaggerModule
-PSHeaderComment $PSHeaderComment

$CopyFilesMap = [ordered]@{
'GeneratedHelpers.ps1' = 'GeneratedHelpers.ps1'
'GeneratedHelpers.ps1' = 'GeneratedHelpers.ps1'
'Test-CoreRequirements.ps1' = 'Test-CoreRequirements.ps1'
'Test-FullRequirements.ps1' = 'Test-FullRequirements.ps1'
'New-ServiceClient.ps1' = 'New-ServiceClient.ps1'
}

if (-not $AssemblyFileName) {
Expand Down
67 changes: 34 additions & 33 deletions PSSwagger/Paths.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ function New-SwaggerPath
$parametersToAdd = @{}
$flattenedParametersOnPSCmdlet = @{}
$parameterHitCount = @{}
$globalParameterBlock = ''
$globalParameters = @()
$x_ms_pageableObject = $null
foreach ($parameterSetDetail in $parameterSetDetails) {
if ($parameterSetDetail.ContainsKey('x-ms-pageable') -and $parameterSetDetail.'x-ms-pageable' -and (-not $isNextPageOperation)) {
Expand Down Expand Up @@ -505,7 +505,7 @@ function New-SwaggerPath
$globalParameterValue = $parameterDetails.ConstantValue
}

$globalParameterBlock += [Environment]::NewLine + $executionContext.InvokeCommand.ExpandString($GlobalParameterBlockStr)
$globalParameters += $globalParameterName
}
}

Expand Down Expand Up @@ -609,24 +609,24 @@ function New-SwaggerPath
}

# Process security section
$azSubscriptionIdBlock = ""
$authFunctionCall = ""
$overrideBaseUriBlock = ""
$httpClientHandlerCall = ""
$SubscriptionIdCommand = ""
$AuthenticationCommand = ""
$AuthenticationCommandArgumentName = ''
$hostOverrideCommand = ''
$AddHttpClientHandler = $false
$securityParametersToAdd = @()
$PowerShellCodeGen = $SwaggerMetaDict['PowerShellCodeGen']
if (($PowerShellCodeGen['ServiceType'] -eq 'azure') -or ($PowerShellCodeGen['ServiceType'] -eq 'azure_stack')) {
$azSubscriptionIdBlock = "`$subscriptionId = Get-AzSubscriptionId"
$SubscriptionIdCommand = 'Get-AzSubscriptionId'
}
if ($PowerShellCodeGen['CustomAuthCommand']) {
$authFunctionCall = $PowerShellCodeGen['CustomAuthCommand']
$AuthenticationCommand = $PowerShellCodeGen['CustomAuthCommand']
}
if ($PowerShellCodeGen['HostOverrideCommand']) {
$hostOverrideCommand = $PowerShellCodeGen['HostOverrideCommand']
$overrideBaseUriBlock = $executionContext.InvokeCommand.ExpandString($HostOverrideBlock)
}
# If the auth function hasn't been set by metadata, try to discover it from the security and securityDefinition objects in the spec
if (-not $authFunctionCall) {
if (-not $AuthenticationCommand) {
if ($FunctionDetails.ContainsKey('Security')) {
# For now, just take the first security object
if ($FunctionDetails.Security.Count -gt 1) {
Expand Down Expand Up @@ -674,11 +674,12 @@ function New-SwaggerPath
}
# If the service is specified to not issue authentication challenges, we can't rely on HttpClientHandler
if ($PowerShellCodeGen['NoAuthChallenge'] -and ($PowerShellCodeGen['NoAuthChallenge'] -eq $true)) {
$authFunctionCall = 'Get-AutoRestCredential -Credential $Credential'
$AuthenticationCommand = 'param([pscredential]$Credential) Get-AutoRestCredential -Credential $Credential'
$AuthenticationCommandArgumentName = 'Credential'
} else {
# Use an empty service client credentials object because we're using HttpClientHandler instead
$authFunctionCall = 'Get-AutoRestCredential'
$httpClientHandlerCall = '$httpClientHandler = New-HttpClientHandler -Credential $Credential'
$AuthenticationCommand = 'Get-AutoRestCredential'
$AddHttpClientHandler = $true
}
} elseif ($type -eq 'apiKey') {
if (-not (Get-Member -InputObject $securityDefinition -Name 'name')) {
Expand Down Expand Up @@ -712,22 +713,18 @@ function New-SwaggerPath
Parameter = $credentialParameter
IsConflictingWithOperationParameter = $false
}
$authFunctionCall = "Get-AutoRestCredential -APIKey `$APIKey -Location '$in' -Name '$name'"
$AuthenticationCommand = "param([string]`$APIKey) Get-AutoRestCredential -APIKey `$APIKey -Location '$in' -Name '$name'"
$AuthenticationCommandArgumentName = 'APIKey'
} else {
Write-Warning -Message ($LocalizedData.UnsupportedAuthenticationType -f ($type))
}
}
}
}

if (-not $authFunctionCall) {
if (-not $AuthenticationCommand) {
# At this point, there was no supported security object or overridden auth function, so assume no auth
$authFunctionCall = 'Get-AutoRestCredential'
}

$clientArgumentList = $clientArgumentListNoHandler
if ($httpClientHandlerCall) {
$clientArgumentList = $clientArgumentListHttpClientHandler
$AuthenticationCommand = 'Get-AutoRestCredential'
}

$nonUniqueParameterSets = @()
Expand Down Expand Up @@ -961,18 +958,22 @@ function New-SwaggerPath
}

$functionBodyParams = @{
ParameterSetDetails = $parameterSetDetails
ODataExpressionBlock = $oDataExpressionBlock
ParameterGroupsExpressionBlock = $parameterGroupsExpressionBlock
GlobalParameterBlock = $GlobalParameterBlock
SwaggerDict = $SwaggerDict
SwaggerMetaDict = $SwaggerMetaDict
SecurityBlock = $executionContext.InvokeCommand.ExpandString($securityBlockStr)
OverrideBaseUriBlock = $overrideBaseUriBlock
ClientArgumentList = $clientArgumentList
FlattenedParametersOnPSCmdlet = $flattenedParametersOnPSCmdlet
}

ParameterSetDetails = $parameterSetDetails
ODataExpressionBlock = $oDataExpressionBlock
ParameterGroupsExpressionBlock = $parameterGroupsExpressionBlock
SwaggerDict = $SwaggerDict
SwaggerMetaDict = $SwaggerMetaDict
AddHttpClientHandler = $AddHttpClientHandler
HostOverrideCommand = $hostOverrideCommand
AuthenticationCommand = $AuthenticationCommand
AuthenticationCommandArgumentName = $AuthenticationCommandArgumentName
SubscriptionIdCommand = $SubscriptionIdCommand
FlattenedParametersOnPSCmdlet = $flattenedParametersOnPSCmdlet
}
if($globalParameters) {
$functionBodyParams['GlobalParameters'] = $globalParameters
}

$pathGenerationPhaseResult = Get-PathFunctionBody @functionBodyParams
$bodyObject = $pathGenerationPhaseResult.BodyObject

Expand Down
Loading