forked from benclaussen/NetboxPS
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdeploy.ps1
More file actions
242 lines (175 loc) · 8.32 KB
/
deploy.ps1
File metadata and controls
242 lines (175 loc) · 8.32 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<#
.SYNOPSIS
Concatenate files into single PSM1 and PSD1 files
.DESCRIPTION
Concatenate all ps1 files in the Functions directory, plus the root PSM1,
into a single PSM1 file in the NetboxPS directory.
By default, this script will increment version by 0.0.1
.PARAMETER SkipVersion
Do not increment the version.
.PARAMETER VersionIncrease
Increase the version by a user defined amount
.PARAMETER NewVersion
Override the new version with this version
.PARAMETER Environment
A description of the Environment parameter.
.PARAMETER ResetCurrentEnvironment
A description of the ResetCurrentEnvironment parameter.
.EXAMPLE
Use all defaults and concatenate all files
.\deploy.ps1
.EXAMPLE
Increment the version by 0.2.0. Given version 1.2.0, the resulting version will be 1.4.0
.\deploy.ps1 -VersionIncrease 0.2.0
#>
[CmdletBinding(DefaultParameterSetName = 'IncreaseVersion')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")]
param
(
[Parameter(ParameterSetName = 'SkipVersion')]
[switch]$SkipVersion,
[Parameter(ParameterSetName = 'IncreaseVersion')]
[version]$VersionIncrease = "0.0.1",
[Parameter(ParameterSetName = 'SetVersion')]
[version]$NewVersion,
[ValidateSet('dev', 'development', 'prod', 'production', IgnoreCase = $true)]
[string]$Environment = 'development',
[switch]$ResetCurrentEnvironment
)
Write-Host "Beginning deployment" -ForegroundColor Green
Write-Host "Importing required modules" -ForegroundColor Green
Import-Module "PSScriptAnalyzer", "Microsoft.PowerShell.Utility" -ErrorAction Stop
$ModuleName = 'PowerNetbox'
# Use UTF-8 without BOM on PS Core, UTF-8 (with BOM) on PS Desktop
# PS Core 6+ supports 'utf8NoBOM', PS Desktop only supports 'utf8' (with BOM)
$FileEncoding = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8NoBOM' } else { 'utf8' }
$ConcatenatedFilePath = Join-Path $PSScriptRoot 'concatenated.ps1'
$FunctionPath = Join-Path $PSScriptRoot 'Functions'
$OutputDirectory = Join-Path $PSScriptRoot $ModuleName
$PSD1OutputPath = Join-Path $OutputDirectory "$ModuleName.psd1"
$PSM1OutputPath = Join-Path $OutputDirectory "$ModuleName.psm1"
$SourcePSD1Path = Join-Path $PSScriptRoot "$ModuleName.psd1"
$SourcePSM1Path = Join-Path $PSScriptRoot "$ModuleName.psm1"
$PS1FunctionFiles = Get-ChildItem $FunctionPath -Filter "*.ps1" -Recurse | Sort-Object Name
Write-Host "Removing whitespace from files" -ForegroundColor Green
Invoke-ScriptAnalyzer -Path $FunctionPath -IncludeRule 'PSAvoidTrailingWhitespace' -Recurse -Fix
# Pre-flight check: Detect duplicate function names (case-insensitive)
Write-Host "Checking for duplicate function names" -ForegroundColor Green
$FunctionNames = @{}
$Duplicates = [System.Collections.ArrayList]::new()
foreach ($File in $PS1FunctionFiles) {
# Skip underscore-prefixed files (aliases, classes, argument completers)
if ($File.BaseName -like '_*') {
continue
}
$Content = Get-Content $File.FullName -Raw
# Extract function name using regex
if ($Content -match 'function\s+([\w-]+)\s*[\{\(]') {
$FuncName = $Matches[1]
$FuncNameLower = $FuncName.ToLower()
if ($FunctionNames.ContainsKey($FuncNameLower)) {
[void]$Duplicates.Add([PSCustomObject]@{
FunctionName = $FuncName
File1 = $FunctionNames[$FuncNameLower]
File2 = $File.Name
})
}
else {
$FunctionNames[$FuncNameLower] = $File.Name
}
}
}
if ($Duplicates.Count -gt 0) {
Write-Host "ERROR: Found duplicate function definitions:" -ForegroundColor Red
$Duplicates | ForEach-Object {
Write-Host (" {0}: {1} <-> {2}" -f $_.FunctionName, $_.File1, $_.File2) -ForegroundColor Red
}
throw "Deployment aborted due to duplicate function names. Please resolve conflicts before continuing."
}
Write-Host " No duplicates found ($($FunctionNames.Count) unique functions)" -ForegroundColor Green
Write-Host "Concatenating [$($PS1FunctionFiles.Count)] PS1 files from $FunctionPath"
"" | Out-File -FilePath $ConcatenatedFilePath -Encoding $FileEncoding
$Counter = 0
foreach ($File in $PS1FunctionFiles) {
$Counter++
try {
Write-Host (" Adding file {0:D2}/{1:D2}: $($File.Name)" -f $Counter, $PS1FunctionFiles.Count)
"`n#region File $($File.Name)`n" | Out-File -FilePath $ConcatenatedFilePath -Encoding $FileEncoding -Append -ErrorAction Stop
Get-Content $File.FullName -Encoding UTF8 -ErrorAction Stop | Out-File -FilePath $ConcatenatedFilePath -Encoding $FileEncoding -Append -ErrorAction Stop
"`n#endregion" | Out-File -FilePath $ConcatenatedFilePath -Encoding $FileEncoding -Append -ErrorAction Stop
} catch {
Write-Host "FAILED TO WRITE CONCATENATED FILE: $($_.Exception.Message): $($_.TargetObject)" -ForegroundColor Red
return
}
}
"" | Out-File -FilePath $ConcatenatedFilePath -Encoding $FileEncoding -Append
Write-Host " Adding psm1"
Get-Content $SourcePSM1Path -Encoding UTF8 | Out-File -FilePath $ConcatenatedFilePath -Encoding $FileEncoding -Append
$PSDManifest = Import-PowerShellDataFile -Path $SourcePSD1Path
# Get the version from the PSD1
[version]$CurrentVersion = $PSDManifest.ModuleVersion
$UpdateModuleManifestSplat = @{
Path = $SourcePSD1Path
ErrorAction = 'Stop'
}
if ($Environment -ilike 'dev*') {
Write-Host "Exporting all functions for development (including internal helpers)"
# Exclude underscore-prefixed files (aliases, classes, argument completers - not functions)
$DevFunctions = $PS1FunctionFiles.BaseName | Where-Object { $_ -notlike '_*' }
$UpdateModuleManifestSplat['FunctionsToExport'] = $DevFunctions
} else {
# Production: Only export public functions (those with '-' in the name)
# Internal helpers like BuildNewURI, InvokeNetboxRequest are kept private
$PublicFunctions = $PS1FunctionFiles.BaseName | Where-Object { $_ -like '*-*' }
Write-Host "Exporting $($PublicFunctions.Count) public functions (hiding internal helpers)"
$UpdateModuleManifestSplat['FunctionsToExport'] = $PublicFunctions
}
Write-Host "Comparing versions"
switch ($PSCmdlet.ParameterSetName) {
"SkipVersion" {
# Dont do anything with the PSD
Write-Host " Skipping version update, maintaining version [$CurrentVersion]"
break
}
"IncreaseVersion" {
# Calculate the new version
[version]$NewVersion = "{0}.{1}.{2}" -f ($CurrentVersion.Major + $VersionIncrease.Major), ($CurrentVersion.Minor + $VersionIncrease.Minor), ($CurrentVersion.Build + $VersionIncrease.Build)
Write-Host " Updating version from [$CurrentVersion] to [$NewVersion]"
# Replace the version number in the content
$UpdateModuleManifestSplat['ModuleVersion'] = $NewVersion
break
}
"SetVersion" {
Write-Host " Updating version from [$CurrentVersion] to [$NewVersion]"
# Replace the version number in the content
$UpdateModuleManifestSplat['ModuleVersion'] = $NewVersion
break
}
}
Write-Host "Updating Module Manifest"
Update-ModuleManifest @UpdateModuleManifestSplat
Write-Host " Removing trailing whitespaces from psd1"
Invoke-ScriptAnalyzer -Path $UpdateModuleManifestSplat.Path -IncludeRule 'PSAvoidTrailingWhitespace' -Fix
if (-not (Test-Path $OutputDirectory)) {
try {
Write-Warning "Creating output directory [$OutputDirectory]"
$null = New-Item -Path $OutputDirectory -ItemType Directory -Force
} catch {
throw "Failed to create output directory [$OutputDirectory]: $($_.Exception.Message)"
}
}
Write-Host " Copying psd1"
Copy-Item -Path $SourcePSD1Path -Destination $PSD1OutputPath -Force
Write-Host " Copying psm1"
Copy-Item -Path $ConcatenatedFilePath -Destination $PSM1OutputPath -Force
Write-Host "Deployment complete" -ForegroundColor Green
if ($ResetCurrentEnvironment) {
Write-Warning "Running commands to reset current environment"
if (Get-Module 'PowerNetbox') {
Remove-Module PowerNetbox -Force
}
Write-Host " Reimporting module"
Import-Module $PSM1OutputPath, $PSD1OutputPath -Force -ErrorAction Stop
Write-Host "Reset complete" -ForegroundColor Green
}