-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathGenerateModules.ps1
More file actions
180 lines (160 loc) · 7.48 KB
/
GenerateModules.ps1
File metadata and controls
180 lines (160 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
[CmdletBinding()]
Param(
[string[]] $ModuleToGenerate = @(),
[ValidateSet("v1.0", "beta")]
$ApiVersion = @("v1.0", "beta"),
[string] $ArtifactsLocation = (Join-Path $PSScriptRoot "..\artifacts\"),
[switch] $SkipGeneration = $false,
[switch] $Build,
[switch] $Test,
[switch] $Pack,
[switch] $EnableSigning,
[switch] $ExcludeExampleTemplates,
[switch] $ExcludeNotesSection,
[switch] $Isolated
)
$ErrorActionPreference = 'Stop'
if ($PSEdition -ne 'Core') {
Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.'
}
if (-not $Isolated) {
Write-Debug 'Creating isolated process...'
$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path
& "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated
return
}
# Module import.
Import-Module PowerShellGet
# Install Powershell-yaml
if (!(Get-Module -Name powershell-yaml -ListAvailable)) {
Install-Module powershell-yaml -Repository PSGallery -Scope CurrentUser -Force
}
$ScriptRoot = $PSScriptRoot
$ModulesSrc = Join-Path $ScriptRoot "..\src\"
$ModuleMappingPath = (Join-Path $PSScriptRoot "..\config\ModulesMapping.jsonc")
$GenerateServiceModulePS1 = Join-Path $ScriptRoot ".\GenerateServiceModule.ps1" -Resolve
if (-not (Test-Path $ArtifactsLocation)) {
New-Item -Path $ArtifactsLocation -Type Directory | Out-Null
}
if (-not (Test-Path $ModuleMappingPath)) {
Write-Error "Module mapping file not be found: $ModuleMappingPath."
}
# Build AutoREST.PowerShell submodule.
Set-Location (Join-Path $ScriptRoot "../autorest.powershell")
rush update --purge
rush build
$RequiredGraphModules = @()
$AuthModuleManifest = Join-Path $ModulesSrc "Authentication" "Authentication" "artifacts" "Microsoft.Graph.Authentication.psd1"
$LoadedAuthModule = Import-Module $AuthModuleManifest -PassThru -ErrorAction SilentlyContinue
if ($null -ne $LoadedAuthModule) {
$RequiredGraphModules += @{ ModuleName = $LoadedAuthModule.Name ; RequiredVersion = $LoadedAuthModule.Version; PreRelease = $LoadedAuthModule.PrivateData.PSData.PreRelease }
}
else {
Write-Warning "Module not found in $AuthModuleManifest."
}
if ($ModuleToGenerate.Count -eq 0) {
[HashTable] $ModuleMapping = Get-Content $ModuleMappingPath | ConvertFrom-Json -AsHashTable
$ModuleToGenerate = $ModuleMapping.Keys
}
#This is to ensure that the autorest temp folder is cleared before generating the modules
$TempPath = [System.IO.Path]::GetTempPath()
# Check if there is any folder with autorest in the name
$AutoRestTempFolder = Get-ChildItem -Path $TempPath -Recurse -Directory | Where-Object { $_.Name -match "autorest" }
# Go through each folder and forcefully delete autorest related files
$AutoRestTempFolder | ForEach-Object {
$AutoRestTempFolder = $_
#Delete files and folders if they exist
if (Test-Path $AutoRestTempFolder.FullName) {
#Check if each file in the folder exists
Get-ChildItem -Path $AutoRestTempFolder.FullName -Recurse | ForEach-Object {
$File = $_
Write-Debug "Removing cached file $File"
if (Test-Path $File.FullName) {
#Remove the file
Remove-Item -Path $File.FullName -Force -confirm:$false
}
}
}
}
$Stopwatch = [system.diagnostics.stopwatch]::StartNew()
$CpuCount = (Get-CimInstance Win32_Processor | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum
$Throttle = [int][math]::Max(1, [math]::Min(4, $CpuCount / 2)) # Use half the CPU count but max 4, min 1
$Results = $ModuleToGenerate | ForEach-Object -Parallel {
$Module = $_
Write-Host -ForegroundColor Green "-------------'Generating $Module'-------------"
$ServiceModuleParams = @{
Module = $Module
ModulesSrc = $using:ModulesSrc
ApiVersion = $using:ApiVersion
SkipGeneration = $using:SkipGeneration
Build = $using:Build
Test = $using:Test
Pack = $using:Pack
EnableSigning = $using:EnableSigning
ExcludeExampleTemplates = $using:ExcludeExampleTemplates
ExcludeNotesSection = $using:ExcludeNotesSection
ArtifactsLocation = $using:ArtifactsLocation
RequiredModules = $using:RequiredGraphModules
}
try {
$Result = & $using:GenerateServiceModulePS1 @ServiceModuleParams
# Check if the script returned an exit code (failure)
if ($null -ne $Result -and $Result -is [int] -and $Result -ne 0) {
Write-Host -ForegroundColor Red "Failed to generate module '$Module' with exit code $Result"
return @{ Module = $Module; Success = $false; ExitCode = $Result; Error = "Generation or build failed" }
}
# Also check $LASTEXITCODE in case the script didn't return but set exit code
if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) {
Write-Host -ForegroundColor Red "Failed to generate module '$Module' with exit code $LASTEXITCODE"
return @{ Module = $Module; Success = $false; ExitCode = $LASTEXITCODE; Error = "Generation or build failed" }
}
function Get-OpenFiles {
param (
[string] $Path
)
$OpenFiles = @()
$Files = Get-ChildItem -Path $Path -Recurse -Directory | Where-Object { $_.Name -match "autorest" }
$Files | ForEach-Object {
$File = $_
try {
$FileStream = $File.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
$FileStream.Close()
}
catch {
$OpenFiles += $File.FullName
}
}
return $OpenFiles
}
#Call a function to check if there are any open files in the temp folder. Recurse through the folder until all files are closed
$OpenFiles = Get-OpenFiles -Path $using:TempPath
if ($OpenFiles.Count -gt 0) {
$OpenFiles = Get-OpenFiles -Path $using:TempPath
}
return @{ Module = $Module; Success = $true; ExitCode = 0; Error = $null }
}
catch {
Write-Host -ForegroundColor Red "Exception while generating module '$Module': $_"
return @{ Module = $Module; Success = $false; ExitCode = -1; Error = $_.Exception.Message }
}
} -ThrottleLimit $Throttle
$stopwatch.Stop()
# Check if any modules failed to generate
$FailedModules = $Results | Where-Object { -not $_.Success }
if ($FailedModules.Count -gt 0) {
Write-Host ""
Write-Host -ForegroundColor Red "========================================="
Write-Host -ForegroundColor Red "Failed to generate the following modules:"
Write-Host -ForegroundColor Red "========================================="
$FailedModules | ForEach-Object {
Write-Host -ForegroundColor Red " - $($_.Module) (Exit Code: $($_.ExitCode)) - $($_.Error)"
}
Write-Host -ForegroundColor Red "========================================="
Write-Host ""
Write-Error "Module generation failed. $($FailedModules.Count) of $($ModuleToGenerate.Count) module(s) failed to generate."
}
else {
Write-Host -ForegroundColor Green "All modules generated successfully in '$($Stopwatch.Elapsed.TotalMinutes)' minutes."
}