diff --git a/PSSwagger/PSSwagger.Azure.Helpers/PSSwagger.Azure.Helpers.psd1 b/PSSwagger/PSSwagger.Azure.Helpers/PSSwagger.Azure.Helpers.psd1 deleted file mode 100644 index 0b469bb..0000000 --- a/PSSwagger/PSSwagger.Azure.Helpers/PSSwagger.Azure.Helpers.psd1 +++ /dev/null @@ -1,39 +0,0 @@ -@{ -RootModule = 'PSSwagger.Azure.Helpers.psm1' -ModuleVersion = '0.1.0' -GUID = '2a66628c-b4b8-4fb7-9188-c1dd4164cfbf' -Author = 'Microsoft Corporation' -CompanyName = 'Microsoft Corporation' -Copyright = '(c) Microsoft Corporation. All rights reserved.' -Description = 'PowerShell module with Azure common helper functions' -RequiredModules = @('PSSwagger.Common.Helpers') -FunctionsToExport = @('Get-AzDelegatingHandler', - 'Get-AzServiceCredential', - 'Get-AzSubscriptionId', - 'Get-AzResourceManagerUrl', - 'Add-AzSRmEnvironment', - 'Remove-AzSRmEnvironment', - 'Initialize-PSSwaggerDependencies') -CmdletsToExport = '' -VariablesToExport = '' -AliasesToExport = '' - -PrivateData = @{ - PSData = @{ - Tags = @('Azure', - 'Swagger', - 'PSEdition_Desktop', - 'PSEdition_Core', - 'Linux', - 'Mac') - ProjectUri = 'https://github.com/PowerShell/PSSwagger' - LicenseUri = 'https://github.com/PowerShell/PSSwagger/blob/master/LICENSE' - ReleaseNotes = @' -- Initial development release -'@ - } -} - - -} - diff --git a/PSSwagger/PSSwagger.Azure.Helpers/PSSwagger.Azure.Helpers.psm1 b/PSSwagger/PSSwagger.Azure.Helpers/PSSwagger.Azure.Helpers.psm1 deleted file mode 100644 index 4bd366d..0000000 --- a/PSSwagger/PSSwagger.Azure.Helpers/PSSwagger.Azure.Helpers.psm1 +++ /dev/null @@ -1,141 +0,0 @@ -######################################################################################### -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# Licensed under the MIT license. -# -# PSSwagger.Azure.Helpers Module -# -######################################################################################### -Microsoft.PowerShell.Core\Set-StrictMode -Version Latest - -if ((Get-Variable -Name PSEdition -ErrorAction Ignore) -and ('Core' -eq $PSEdition)) { - . (Join-Path -Path "$PSScriptRoot" -ChildPath "Test-CoreRequirements.ps1") - $moduleName = 'AzureRM.Profile.NetCore.Preview' -} else { - . (Join-Path -Path "$PSScriptRoot" -ChildPath "Test-FullRequirements.ps1") - $moduleName = 'AzureRM.Profile' -} - -function Get-AzServiceCredential -{ - [CmdletBinding()] - param() - - $AzureContext = & "$moduleName\Get-AzureRmContext" -ErrorAction Stop - $authenticationFactory = New-Object -TypeName Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory - if ((Get-Variable -Name PSEdition -ErrorAction Ignore) -and ('Core' -eq $PSEdition)) { - [Action[string]]$stringAction = {param($s)} - $serviceCredentials = $authenticationFactory.GetServiceClientCredentials($AzureContext, $stringAction) - } else { - $serviceCredentials = $authenticationFactory.GetServiceClientCredentials($AzureContext) - } - - $serviceCredentials -} - -function Get-AzDelegatingHandler -{ - [CmdletBinding()] - param() - - New-Object -TypeName System.Net.Http.DelegatingHandler[] 0 -} - -function Get-AzSubscriptionId -{ - [CmdletBinding()] - param() - - $AzureContext = & "$moduleName\Get-AzureRmContext" -ErrorAction Stop - if(Get-Member -InputObject $AzureContext.Subscription -Name SubscriptionId) - { - return $AzureContext.Subscription.SubscriptionId - } - else - { - return $AzureContext.Subscription.Id - } -} - -function Get-AzResourceManagerUrl -{ - [CmdletBinding()] - param() - - $AzureContext = & "$moduleName\Get-AzureRmContext" -ErrorAction Stop - $AzureContext.Environment.ResourceManagerUrl -} - -function Add-AzSRmEnvironment -{ - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string] - $Name, - - [Parameter(Mandatory = $true)] - [string] - $UserName, - - [Parameter(Mandatory = $true)] - [string] - $AzureStackDomain - ) - - $AadTenantId = $UserName.split('@')[-1] - $Graphendpoint = "https://graph.$azureStackDomain" - if ($AadTenantId -like '*.onmicrosoft.com') - { - $Graphendpoint = "https://graph.windows.net/" - } - - $Endpoints = Microsoft.PowerShell.Utility\Invoke-RestMethod -Method Get -Uri "https://api.$azureStackDomain/metadata/endpoints?api-version=1.0" - $ActiveDirectoryServiceEndpointResourceId = $Endpoints.authentication.audiences[0] - - # Add the Microsoft Azure Stack environment - & "$moduleName\Add-AzureRmEnvironment" -Name $Name ` - -ActiveDirectoryEndpoint "https://login.windows.net/$AadTenantId/" ` - -ActiveDirectoryServiceEndpointResourceId $ActiveDirectoryServiceEndpointResourceId ` - -ResourceManagerEndpoint "https://api.$azureStackDomain/" ` - -GalleryEndpoint "https://gallery.$azureStackDomain/" ` - -GraphEndpoint $Graphendpoint -} - -function Remove-AzSRmEnvironment -{ - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string] - $Name - ) - - & "$moduleName\Remove-AzureRmEnvironment" @PSBoundParameters -} - -<# -.DESCRIPTION - Manually initialize PSSwagger's external dependencies. Use this function with -AcceptBootstrap for silent execution scenarios. - -.PARAMETER AllUsers - Install dependencies in PSSwagger's global package cache. - -.PARAMETER AcceptBootstrap - Automatically consent to downloading missing packages. If not specified, an interactive prompt will be appear. -#> -function Initialize-PSSwaggerDependencies { - [CmdletBinding()] - param( - [Parameter(Mandatory=$false)] - [switch] - $AllUsers, - - [Parameter(Mandatory=$false)] - [switch] - $AcceptBootstrap - ) - - PSSwagger.Common.Helpers\Initialize-PSSwaggerDependencies -Azure @PSBoundParameters -} \ No newline at end of file diff --git a/PSSwagger/PSSwagger.Azure.Helpers/Test-CoreRequirements.ps1 b/PSSwagger/PSSwagger.Azure.Helpers/Test-CoreRequirements.ps1 deleted file mode 100644 index 4d03574..0000000 --- a/PSSwagger/PSSwagger.Azure.Helpers/Test-CoreRequirements.ps1 +++ /dev/null @@ -1 +0,0 @@ -#Requires -Modules AzureRM.Profile.NetCore.Preview \ No newline at end of file diff --git a/PSSwagger/PSSwagger.Azure.Helpers/Test-FullRequirements.ps1 b/PSSwagger/PSSwagger.Azure.Helpers/Test-FullRequirements.ps1 deleted file mode 100644 index e9c3d67..0000000 --- a/PSSwagger/PSSwagger.Azure.Helpers/Test-FullRequirements.ps1 +++ /dev/null @@ -1 +0,0 @@ -#Requires -Modules AzureRM.Profile \ No newline at end of file diff --git a/PSSwagger/PSSwagger.Resources.psd1 b/PSSwagger/PSSwagger.Resources.psd1 index 334c69f..5b3b8f5 100644 --- a/PSSwagger/PSSwagger.Resources.psd1 +++ b/PSSwagger/PSSwagger.Resources.psd1 @@ -25,6 +25,7 @@ ConvertFrom-StringData @' SamePropertyName=Same property name '{0}' is defined in a definition '{1}' with AllOf inheritance. DataTypeNotImplemented=Please get an implementation of '{0}' for '{1}' AutoRestNotInPath=Unable to find AutoRest in PATH environment. Ensure the PATH is updated. + CscExeNotInPath=Unable to find CSC.exe in PATH environment. Ensure the PATH is updated with CSC.exe location. AutoRestError=AutoRest resulted in an error SwaggerParamsMissing=No parameters in the Swagger SwaggerDefinitionsMissing=No definitions in the Swagger diff --git a/PSSwagger/PSSwagger.psm1 b/PSSwagger/PSSwagger.psm1 index bcaf2c6..de057bd 100644 --- a/PSSwagger/PSSwagger.psm1 +++ b/PSSwagger/PSSwagger.psm1 @@ -587,7 +587,12 @@ function ConvertTo-CsharpCode $autoRestExePath = "AutoRest" if (-not (get-command -name $autoRestExePath)) { - throw $LocalizedData.AutoRestNotInPath + throw $LocalizedData.AutoRestNotInPath + } + + if (-not (Get-OperatingSystemInfo).IsCore -and + (-not (Get-Command -Name 'Csc.Exe' -ErrorAction Ignore))) { + throw $LocalizedData.CscExeNotInPath } $outputDirectory = $SwaggerMetaDict['outputDirectory'] @@ -718,7 +723,7 @@ function ConvertTo-CsharpCode -CliXmlTmpPath $cliXmlTmpPath" $success = & "powershell" -command "& {$command}" - + $codeReflectionResult = Import-CliXml -Path $cliXmlTmpPath if ($codeReflectionResult.ContainsKey('VerboseMessages') -and $codeReflectionResult.VerboseMessages -and ($codeReflectionResult.VerboseMessages.Count -gt 0)) { $verboseMessages = $codeReflectionResult.VerboseMessages -Join [Environment]::NewLine @@ -773,8 +778,7 @@ function ConvertTo-CsharpCode } $dependencies = Get-PSSwaggerExternalDependencies -Azure:$codeCreatedByAzureGenerator -Framework 'netstandard1' $microsoftRestClientRuntimeAzureRequiredVersion = if ($dependencies.ContainsKey('Microsoft.Rest.ClientRuntime.Azure')) { $dependencies['Microsoft.Rest.ClientRuntime.Azure'].RequiredVersion } else { '' } - $command = "Import-Module '$PSScriptRoot\PSSwaggerUtility'; - Add-PSSwaggerClientType -OutputAssemblyName '$outAssembly' `` + $command = "PSSwaggerUtility\Add-PSSwaggerClientType -OutputAssemblyName '$outAssembly' `` -ClrPath '$clrPath' `` -CSharpFiles $allCSharpFilesArrayString `` -MicrosoftRestClientRuntimeAzureRequiredVersion '$microsoftRestClientRuntimeAzureRequiredVersion' `` diff --git a/PSSwagger/PSSwaggerUtility/PSSwaggerUtility.psm1 b/PSSwagger/PSSwaggerUtility/PSSwaggerUtility.psm1 index f2634e2..31b55c4 100644 --- a/PSSwagger/PSSwaggerUtility/PSSwaggerUtility.psm1 +++ b/PSSwagger/PSSwaggerUtility/PSSwaggerUtility.psm1 @@ -467,7 +467,7 @@ function Add-PSSwaggerClientType { $preprocessorDirectives = @() if ((Get-OperatingSystemInfo).IsCore) { # Base framework references - $preprocessorDirectives = @('#define DNXCORE50','#define PORTABLE') + $preprocessorDirectives = @('#define DNXCORE50','#define PORTABLE') $systemRefs = @('System.dll', 'System.Core.dll', 'System.Net.Http.dll', @@ -496,44 +496,57 @@ function Add-PSSwaggerClientType { # Get dependencies for AutoRest SDK $externalReferences = Get-PSSwaggerExternalDependencies -Framework $externalReferencesFramework -Azure:$CodeCreatedByAzureGenerator -RequiredVersionMap $requiredVersionMap - # Ensure output directory exists - if (-not (Test-Path -Path $clrPath -PathType Container)) { - $null = New-Item -Path $clrPath -ItemType Directory -Force + $AddClientTypeHelperParams = @{ + Path = $CSharpFiles | ForEach-Object { $_.FullName } + AllUsers = $AllUsers + BootstrapConsent = $BootstrapConsent + PackageDependencies = $externalReferences + PreprocessorDirectives = $PreprocessorDirectives } + if ($OutputAssemblyName) { + $AddClientTypeHelperParams['OutputDirectory'] = $clrPath + $AddClientTypeHelperParams['OutputAssemblyName'] = $OutputAssemblyName + $AddClientTypeHelperParams['TestBuild'] = $TestBuild + $AddClientTypeHelperParams['SymbolPath'] = $SymbolPath + } + $HelperResult = Add-PSSwaggerClientTypeHelper @AddClientTypeHelperParams - $addTypeParamsResult = Get-PSSwaggerAddTypeParameters -Path ($CSharpFiles | ForEach-Object { $_.FullName }) -OutputDirectory $clrPath -OutputAssemblyName $OutputAssemblyName ` - -AllUsers:$AllUsers -BootstrapConsent:$BootstrapConsent -TestBuild:$TestBuild -SymbolPath $SymbolPath -PackageDependencies $externalReferences ` - -FileReferences $systemRefs -PreprocessorDirectives $preprocessorDirectives - - if ($addTypeParamsResult['ResolvedPackageReferences']) { - # Copy package references when precompiling - foreach ($extraRef in $addTypeParamsResult['ResolvedPackageReferences']) { - $null = Copy-Item -Path $extraRef -Destination (Join-Path -Path $ClrPath -ChildPath (Split-Path -Path $extraRef -Leaf)) -Force - Add-Type -Path $extraRef -ErrorAction Ignore - } + $CompilerHelperParams = @{ + ReferencedAssemblies = $systemRefs + $HelperResult['ResolvedPackageReferences'] + SourceCodeFilePath = $HelperResult['SourceCodeFilePath'] + OutputAssembly = $HelperResult['OutputAssembly'] + TestBuild = $TestBuild } - if ($addTypeParamsResult['SourceFileName']) { - # A source code file is expected to exist - # Emit the created source code - $addTypeParamsResult['SourceCode'] | Out-File -FilePath $addTypeParamsResult['SourceFileName'] + if ((Get-OperatingSystemInfo).IsCore) { + $addTypeParams = Get-AddTypeParameters @CompilerHelperParams + Add-Type @addTypeParams + } + else { + $CscArgumentList = Get-CscParameters @CompilerHelperParams + $output = & 'Csc.exe' $CscArgumentList + if ($output) { + Write-Error -ErrorId 'SOURCE_CODE_ERROR' -Message ($output | Out-String) + return $false + } } - # Execute Add-Type - $addTypeParams = $addTypeParamsResult['Params'] - Add-Type @addTypeParams - # Copy the PDB to the symbol path if specified - if ($addTypeParamsResult['OutputAssemblyPath']) { - # Verify result of Add-Type - $outputAssemblyItem = Get-Item -Path $addTypeParamsResult['OutputAssemblyPath'] - if ((-not (Test-Path -Path $addTypeParamsResult['OutputAssemblyPath'])) -or ($outputAssemblyItem.Length -eq 0kb)) { + if ($HelperResult['OutputAssembly']) { + # Verify result of assembly compilation + $outputAssemblyItem = Get-Item -Path $HelperResult['OutputAssembly'] + if ((-not (Test-Path -Path $HelperResult['OutputAssembly'])) -or ($outputAssemblyItem.Length -eq 0kb)) { return $false } - $OutputPdbName = "$($outputAssemblyItem.BaseName).pdb" - if ($SymbolPath -and (Test-Path -Path (Join-Path -Path $ClrPath -ChildPath $OutputPdbName))) { - $null = Copy-Item -Path (Join-Path -Path $ClrPath -ChildPath $OutputPdbName) -Destination (Join-Path -Path $SymbolPath -ChildPath $OutputPdbName) + if(-not $OutputAssemblyName) { + Add-Type -Path $outputAssemblyItem + } + else { + $OutputPdbName = "$($outputAssemblyItem.BaseName).pdb" + if ($SymbolPath -and (Test-Path -Path (Join-Path -Path $ClrPath -ChildPath $OutputPdbName))) { + $null = Copy-Item -Path (Join-Path -Path $ClrPath -ChildPath $OutputPdbName) -Destination (Join-Path -Path $SymbolPath -ChildPath $OutputPdbName) + } } } @@ -542,7 +555,7 @@ function Add-PSSwaggerClientType { <# .DESCRIPTION - Compiles AutoRest generated C# code using the framework of the current PowerShell process. + Helper function to validate and install the required package dependencies. Also prepares the source code for compilation. .PARAMETER Path All *.Code.ps1 C# files to compile. @@ -568,90 +581,101 @@ function Add-PSSwaggerClientType { .PARAMETER PackageDependencies Map of package dependencies to add as referenced assemblies but don't exist on disk. -.PARAMETER FileReferences - Compilation references that exist on disk. - .PARAMETER PreprocessorDirectives Preprocessor directives to add to the top of the combined source code file. -.NOTES - This function will be deprecated when we move away from Add-Type compilation. #> -function Get-PSSwaggerAddTypeParameters { +function Add-PSSwaggerClientTypeHelper { [CmdletBinding()] param( - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [string[]] $Path, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [AllowEmptyString()] [string] $OutputDirectory, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [AllowEmptyString()] [string] $OutputAssemblyName, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [switch] $AllUsers, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [switch] $BootstrapConsent, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [switch] $TestBuild, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [string] $SymbolPath, - - [Parameter(Mandatory=$false)] - [ValidateSet("ConsoleApplication","Library")] - [string] - $OutputType = 'Library', - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [hashtable] $PackageDependencies, - - [Parameter(Mandatory=$false)] - [string[]] - $FileReferences, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [string[]] $PreprocessorDirectives ) $resultObj = @{ - # The add type parameters to use - Params = $null # Full path to resolved package reference assemblies ResolvedPackageReferences = @() + # The expected output assembly full path - OutputAssemblyPath = $null + OutputAssembly = $null + # The actual source to be emitted - SourceCode = $null + SourceCode = $null + # The file name the returned params expect to exist, if required - SourceFileName = $null + SourceCodeFilePath = $null + } + + if (-not $OutputDirectory -or -not $SymbolPath) { + $TempOutputPath = Join-Path -Path (Get-XDGDirectory -DirectoryType Cache) -ChildPath ([Guid]::NewGuid().Guid) + $null = New-Item -Path $TempOutputPath -ItemType Directory -Force + } + + if (-not $SymbolPath) { + $SymbolPath = $TempOutputPath + } + + if (-not $OutputDirectory) { + $OutputDirectory = $TempOutputPath + } + elseif (-not (Test-Path -Path $OutputDirectory -PathType Container)) { + $null = New-Item -Path $OutputDirectory -ItemType Directory -Force + } + + if (-not $OutputAssemblyName) { + $OutputAssemblyName = [Guid]::NewGuid().Guid + '.dll' } # Resolve package dependencies - $extraRefs = @() if ($PackageDependencies) { foreach ($entry in ($PackageDependencies.GetEnumerator() | Sort-Object { $_.Value.LoadOrder })) { $reference = $entry.Value $resolvedRef = Get-PSSwaggerDependency -PackageName $reference.PackageName ` - -RequiredVersion $reference.RequiredVersion ` - -References $reference.References ` - -Framework $reference.Framework ` - -AllUsers:$AllUsers -Install -BootstrapConsent:$BootstrapConsent - $extraRefs += $resolvedRef + -RequiredVersion $reference.RequiredVersion ` + -References $reference.References ` + -Framework $reference.Framework ` + -AllUsers:$AllUsers ` + -Install ` + -BootstrapConsent:$BootstrapConsent $resultObj['ResolvedPackageReferences'] += $resolvedRef + + # Copy package references to OutputDirectory + $null = Copy-Item -Path $resolvedRef -Destination (Join-Path -Path $OutputDirectory -ChildPath (Split-Path -Path $resolvedRef -Leaf)) -Force + Add-Type -Path $resolvedRef -ErrorAction Ignore } } @@ -660,38 +684,61 @@ function Get-PSSwaggerAddTypeParameters { $srcContent += $Path | ForEach-Object { "// File $_"; Remove-AuthenticodeSignatureBlock -Path $_ } if ($PreprocessorDirectives) { foreach ($preprocessorDirective in $PreprocessorDirectives) { - $srcContent = ,$preprocessorDirective + $srcContent + $srcContent = , $preprocessorDirective + $srcContent } } $oneSrc = $srcContent -join "`n" $resultObj['SourceCode'] = $oneSrc - if ($SymbolPath) { - if ($OutputAssemblyName) { - $OutputAssemblyBaseName = [System.IO.Path]::GetFileNameWithoutExtension("$OutputAssemblyName") - $resultObj['SourceFileName'] = Join-Path -Path $SymbolPath -ChildPath "Generated.$OutputAssemblyBaseName.cs" - } else { - $resultObj['SourceFileName'] = Join-Path -Path $SymbolPath -ChildPath "Generated.cs" - } - $addTypeParams = @{ - Path = $resultObj['SourceFileName'] - WarningAction = 'Ignore' - } - } else { - $addTypeParams = @{ - TypeDefinition = $oneSrc - Language = "CSharp" - WarningAction = 'Ignore' - } + $OutputAssemblyBaseName = [System.IO.Path]::GetFileNameWithoutExtension("$OutputAssemblyName") + $SourceCodeFilePath = Join-Path -Path $SymbolPath -ChildPath "Generated.$OutputAssemblyBaseName.cs" + $resultObj['SourceCodeFilePath'] = $SourceCodeFilePath + Out-File -InputObject $oneSrc -FilePath $SourceCodeFilePath + + $resultObj['OutputAssembly'] = Join-Path -Path $OutputDirectory -ChildPath $OutputAssemblyName + + return $resultObj +} + +function Get-AddTypeParameters { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] + $SourceCodeFilePath, + + [Parameter(Mandatory = $false)] + [string[]] + $ReferencedAssemblies, + + [Parameter(Mandatory = $false)] + [ValidateSet("ConsoleApplication", "Library")] + [string] + $OutputType = 'Library', + + [Parameter(Mandatory = $false)] + [switch] + $TestBuild, + + [Parameter(Mandatory = $false)] + [string] + $OutputAssembly + ) + + $AddTypeParams = @{ + WarningAction = 'Ignore' } if (-not (Get-OperatingSystemInfo).IsCore) { + $AddTypeParams['Path'] = $SourceCodeFilePath $compilerParameters = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters + $compilerParameters.WarningLevel = 3 $compilerParameters.CompilerOptions = '/debug:full' if ($TestBuild) { $compilerParameters.IncludeDebugInformation = $true - } else { + } + else { $compilerParameters.CompilerOptions += ' /optimize+' } @@ -699,35 +746,82 @@ function Get-PSSwaggerAddTypeParameters { $compilerParameters.GenerateExecutable = $true } - $compilerParameters.WarningLevel = 3 - foreach ($ref in ($FileReferences + $extraRefs)) { - $null = $compilerParameters.ReferencedAssemblies.Add($ref) - } - $addTypeParams['CompilerParameters'] = $compilerParameters - } else { - $addTypeParams['ReferencedAssemblies'] = ($FileReferences + $extraRefs) - if ($OutputType -eq 'ConsoleApplication') { - $addTypeParams['ReferencedAssemblies'] = $OutputType + $ReferencedAssemblies | ForEach-Object { + $null = $compilerParameters.ReferencedAssemblies.Add($_) } + $AddTypeParams['CompilerParameters'] = $compilerParameters + } + else { + $AddTypeParams['TypeDefinition'] = Get-Content -Path $SourceCodeFilePath -Raw + $AddTypeParams['ReferencedAssemblies'] = $ReferencedAssemblies + $AddTypeParams['OutputType'] = $OutputType + $AddTypeParams['Language'] = 'CSharp' } - $OutputPdbName = '' - if ($OutputAssemblyName) { - $OutputAssembly = Join-Path -Path $OutputDirectory -ChildPath $OutputAssemblyName - $resultObj['OutputAssemblyPath'] = $OutputAssembly - if ($addTypeParams.ContainsKey('CompilerParameters')) { - $addTypeParams['CompilerParameters'].OutputAssembly = $OutputAssembly - } else { - $addTypeParams['OutputAssembly'] = $OutputAssembly + if ($OutputAssembly) { + if ($AddTypeParams.ContainsKey('CompilerParameters')) { + $AddTypeParams['CompilerParameters'].OutputAssembly = $OutputAssembly } - } else { - if ($addTypeParams.ContainsKey('CompilerParameters')) { - $addTypeParams['CompilerParameters'].GenerateInMemory = $true + else { + $AddTypeParams['OutputAssembly'] = $OutputAssembly + } + } + else { + if ($AddTypeParams.ContainsKey('CompilerParameters')) { + $AddTypeParams['CompilerParameters'].GenerateInMemory = $true } } - $resultObj['Params'] = $addTypeParams - return $resultObj + return $AddTypeParams +} +function Get-CscParameters { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] + $SourceCodeFilePath, + + [Parameter(Mandatory = $false)] + [ValidateSet('Exe', 'Library')] + [string] + $TargetType = 'Library', + + [Parameter(Mandatory = $false)] + [string[]] + $ReferencedAssemblies, + + [Parameter(Mandatory = $false)] + [string[]] + $ConditionalCompilationSymbol, + + [Parameter(Mandatory = $false)] + [switch] + $TestBuild, + + [Parameter(Mandatory = $false)] + [string] + $OutputAssembly + ) + + $CscParameter = @( + $SourceCodeFilePath + '/nologo', + '/langversion:latest', + '/checked', + '/warn:3', + '/debug:full', + '/platform:anycpu', + "/target:$TargetType" + ) + + $ReferencedAssemblies | ForEach-Object { $CscParameter += "/reference:$_" } + if (-not $TestBuild) { $CscParameter += '/optimize+' } + if ($OutputAssembly) { $CscParameter += "/out:$OutputAssembly" } + if ($ConditionalCompilationSymbol) { + $ConditionalCompilationSymbol | ForEach-Object { $CscParameter += "/define:$_" } + } + + return $CscParameter } <# diff --git a/README.md b/README.md index 948da70..32dcdac 100644 --- a/README.md +++ b/README.md @@ -52,17 +52,29 @@ NOTE: In the short term, for best performance, the operation IDs in your Open AP git clone https://github.com/PowerShell/PSSwagger.git ``` -2. Ensure you AutoRest version 0.17.3 installed - ```powershell - Install-Package -Name AutoRest -Source https://www.nuget.org/api/v2 -RequiredVersion 0.17.3 -Scope CurrentUser - ``` - -3. Ensure AutoRest.exe is in $env:Path - ```powershell - $package = Get-Package -Name AutoRest -RequiredVersion 0.17.3 - $env:path += ";$(Split-Path $package.Source -Parent)\tools" - Get-Command -Name AutoRest - ``` +2. Ensure AutoRest is installed and available in $env:PATH + - Install AutoRest version 0.17.3 + ```powershell + Install-Package -Name AutoRest -Source https://www.nuget.org/api/v2 -RequiredVersion 0.17.3 -Scope CurrentUser + ``` + - Add AutoRest.exe path to $env:Path + ```powershell + $package = Get-Package -Name AutoRest -RequiredVersion 0.17.3 + $env:path += ";$(Split-Path $package.Source -Parent)\tools" + Get-Command -Name AutoRest + ``` + +3. Ensure CSC.exe is installed and available in $env:PATH + - If CSC.exe is not installed already, install Microsoft.Net.Compilers package + ```powershell + Install-Package -Name Microsoft.Net.Compilers -Source https://www.nuget.org/api/v2 -Scope CurrentUser + ``` + - Add CSC.exe path to $env:Path + ```powershell + $package = Get-Package -Name Microsoft.Net.Compilers + $env:path += ";$(Split-Path $package.Source -Parent)\tools" + Get-Command -Name CSC.exe + ``` 4. If you plan on pre-compiling the generated assembly, ensure you have the module AzureRM.Profile or AzureRM.NetCore.Preview available to PackageManagement if you are on PowerShell or PowerShell Core, respectively. diff --git a/Tests/run-tests.ps1 b/Tests/run-tests.ps1 index 8edcc20..83b396b 100644 --- a/Tests/run-tests.ps1 +++ b/Tests/run-tests.ps1 @@ -98,6 +98,11 @@ $autoRestModule = Test-Package -packageName "AutoRest" -packageSourceName $nuget $autoRestInstallPath = Split-Path -Path $autoRestModule.Source $executeTestsCommand += ";`$env:Path+=`";$autoRestInstallPath\tools`"" +# Set up Microsoft.Net.Compilers +$MicrosoftNetCompilers = Test-Package -PackageName Microsoft.Net.Compilers -PackageSourceName $nugetPackageSource.Name +$MicrosoftNetCompilersInstallPath = Split-Path -Path $MicrosoftNetCompilers.Source +$executeTestsCommand += ";`$env:Path+=`";$MicrosoftNetCompilersInstallPath\tools`"" + # AzureRM.Profile requirement $azureRmProfile = Get-Module -Name AzureRM.Profile -ListAvailable | Select-Object -First 1 -ErrorAction Ignore if (-not $azureRmProfile) {