-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathgenerate-command-reference.ps1
More file actions
266 lines (237 loc) · 11.3 KB
/
Copy pathgenerate-command-reference.ps1
File metadata and controls
266 lines (237 loc) · 11.3 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<#
.SYNOPSIS
Generates the MDX files used for the website's "Command Reference" pages.
.NOTES
Uses the latest Pester version unless a specific -PesterVersion is given.
.EXAMPLE
.\generate-command-reference.ps1
.EXAMPLE
.\generate-command-reference.ps1 -PesterVersion 4.10.1
.LINK
https://docusaurus-powershell.netlify.app/docs/faq/ci-cd
#>
[CmdletBinding()]
param (
[string] $PesterVersion,
[string] $PlatyPSVersion,
[string] $DocusaurusVersion,
[switch] $SkipModuleImport,
[ValidateSet('Current','v4','v5')]
[string] $DocsVersion = 'Current'
)
Set-StrictMode -Version Latest
$PSDefaultParameterValues['*:ErrorAction'] = 'Stop'
Write-Host 'Generating MDX files for website Command Reference' -BackgroundColor DarkGreen
# -----------------------------------------------------------------------------
# Install required modules
# -----------------------------------------------------------------------------
$ModuleList = [ordered]@{
'PlatyPS' = $PlatyPSVersion
'Alt3.Docusaurus.PowerShell' = $DocusaurusVersion
'Pester' = $PesterVersion
}
# Can't use the original enumerator here because we may modify the dictionary mid-process
$ModuleList.Keys.Clone() | ForEach-Object {
$ModuleName = $_
$RequestedVersion = $ModuleList.Item($ModuleName)
Write-Host "Requires $ModuleName $RequestedVersion"
if ([String]::IsNullOrEmpty($RequestedVersion)) {
Write-Host "=> Fetching latest stable version of $ModuleName from PSGallery..."
$RequestedVersion = (Find-Module -Name $ModuleName).Version
$ModuleList.Item($ModuleName) = $RequestedVersion
Write-Host "=> PSGallery version is $RequestedVersion"
}
$Installed = Get-Module -ListAvailable $ModuleName
if ($Installed -and ($Installed.Version -contains $RequestedVersion)) {
Write-Host '=> required version already installed'
} else {
if (-not $Installed) {
Write-Host "=> no versions installed: installing $RequestedVersion"
} else {
Write-Host "=> no matching version installed: installing $RequestedVersion"
}
Install-Module $ModuleName -RequiredVersion $RequestedVersion -AllowPrerelease -Force -SkipPublisherCheck -AllowClobber -Scope CurrentUser
}
if (-not $SkipModuleImport) {
Write-Host '=> importing'
# Import doesn't support prerelease-version. Only one x.y.z* version can be installed at any time, so just strip suffix
Import-Module -Name $ModuleName -RequiredVersion ($RequestedVersion -replace '-\w+$') -Force
}
}
# -----------------------------------------------------------------------------
# Use below settings to manipulate the rendered MDX files
# -----------------------------------------------------------------------------
$docusaurusOptions = @{
Module = 'Pester'
DocsFolder = switch ($DocsVersion) {
'Current' { "$PSScriptRoot/docs" }
'v5' { "$PSScriptRoot/versioned_docs/version-v5" }
'v4' { "$PSScriptRoot/versioned_docs/version-v4" }
}
SideBar = 'commands'
EditUrl = 'null' # prevent the `Edit this Page` button from appearing
Exclude = @(
'Get-MockDynamicParameter'
'Invoke-Mock'
'SafeGetCommand'
'Set-DynamicParameterVariable'
)
MetaDescription = 'Help page for the PowerShell Pester "%1" command'
MetaKeywords = @(
'PowerShell'
'Pester'
'Help'
'Documentation'
)
PrependMarkdown = @'
:::info This page was generated
Contributions are welcome in [Pester-repo](https://github.com/pester/pester).
:::
'@
AppendMarkdown = @"
## VERSION
*This page was generated using comment-based help in [Pester $($ModuleList.Pester)](https://github.com/pester/pester).*
"@
}
# -----------------------------------------------------------------------------
# Generate the new MDX files
# -----------------------------------------------------------------------------
Push-Location $PSScriptRoot
Write-Host (Get-Location)
Write-Host 'Removing existing MDX files' -ForegroundColor Magenta
$outputFolder = Join-Path -Path $docusaurusOptions.DocsFolder -ChildPath $docusaurusOptions.Sidebar | Join-Path -ChildPath '*.*'
if (Test-Path -Path $outputFolder) {
Remove-Item -Path $outputFolder
}
Write-Host 'Generating new MDX files' -ForegroundColor Magenta
New-DocusaurusHelp @docusaurusOptions
function Repair-ExampleFences {
<#
Pester's source comment-based help embeds Markdown code fences (```powershell
... ```), including a 'powereshell' typo, inside its .EXAMPLE blocks. PlatyPS
double-wraps these, emitting mismatched fences - a bare ``` opening paired with
a ```powershell "closing" fence, sometimes doubled up. MDX 3 then mispairs the
fences, treating an example's PowerShell '@{ ... }' as a JSX expression, which
breaks the Docusaurus build ("Could not parse expression with acorn").
Normalize fences inside the EXAMPLES section only: collapse runs of adjacent
fence lines and alternate them open/close per example, so each example becomes a
single well-formed ```powershell code block followed by its description. The
SYNTAX and PARAMETERS sections (and their YAML blocks) are left untouched.
#>
param([string] $Content)
$eol = if ($Content -match "`r`n") { "`r`n" } else { "`n" }
$lines = $Content -split "`r?`n"
# Locate the EXAMPLES section: '## EXAMPLES' up to the next H2 heading.
$start = -1
for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match '^##\s+EXAMPLES\s*$') { $start = $i; break }
}
if ($start -lt 0) { return $Content }
$end = $lines.Count
for ($i = $start + 1; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match '^##\s' -and $lines[$i] -notmatch '^###') { $end = $i; break }
}
$result = [System.Collections.Generic.List[string]]::new()
$inCode = $false
$i = 0
while ($i -lt $lines.Count) {
$line = $lines[$i]
# Outside the EXAMPLES section: pass through unchanged.
if ($i -le $start -or $i -ge $end) {
if ($i -eq $end -and $inCode) { $result.Add('```'); $inCode = $false }
$result.Add($line); $i++; continue
}
# A new example heading closes any block left open by the previous one.
if ($line -match '^###\s') {
if ($inCode) { $result.Add('```'); $inCode = $false }
$result.Add($line); $i++; continue
}
# Collapse a run of adjacent fence lines into a single open or close fence.
if ($line -match '^\s{0,3}```') {
$langs = @()
while ($i -lt $end -and $lines[$i] -match '^\s{0,3}```(.*)$') {
$langs += $Matches[1].Trim()
$i++
}
if (-not $inCode) {
$lang = $langs | Where-Object { $_ -ne '' } | Select-Object -First 1
if (-not $lang -or $lang -eq 'powereshell') { $lang = 'powershell' }
$result.Add('```' + $lang)
$inCode = $true
}
else {
$result.Add('```')
$inCode = $false
}
continue
}
$result.Add($line); $i++
}
return ($result -join $eol)
}
function Format-SyntaxCommonParameters {
# After ProgressAction is removed, '[<CommonParameters>]' is collapsed back inline.
# PlatyPS keeps it inline only while the SYNTAX line stays within its wrap width
# (~110 chars, measured from prior generated output) and otherwise wraps it onto its
# own continuation line. Reproduce that so we neither leave overly long lines nor
# dangling orphans. Only lines that still carry content before the token are wrapped;
# lines that are already just ' [<CommonParameters>]' are left untouched.
param([string] $Content, [int] $MaxWidth = 110)
$eol = if ($Content -match "`r`n") { "`r`n" } else { "`n" }
$lines = $Content -split "`r?`n"
$out = [System.Collections.Generic.List[string]]::new()
foreach ($line in $lines) {
if ($line.Length -gt $MaxWidth -and $line -match '\S[ ]\[<CommonParameters>\][ ]*$') {
$head = $line -replace '[ ]*\[<CommonParameters>\][ ]*$', ''
$out.Add($head)
$out.Add(' [<CommonParameters>]')
}
else {
$out.Add($line)
}
}
return ($out -join $eol)
}
# -----------------------------------------------------------------------------
# Post-process the generated MDX:
# * Strip the spurious ProgressAction common parameter that PlatyPS emits on
# PowerShell 7.4+ (https://github.com/PowerShell/platyPS/issues/663). Pester 6
# loads a .NET 8 assembly and therefore requires PowerShell 7.4+, so the docs
# can no longer be generated on an older PowerShell to avoid this.
# * Repair the mismatched code fences PlatyPS emits for .EXAMPLE blocks that
# contain their own Markdown fences (see Repair-ExampleFences) so the MDX
# compiles.
# The '[<CommonParameters>]' SYNTAX entry and the '### CommonParameters' section are
# kept as PlatyPS produces them. Because the ProgressAction token is longer than
# '[<CommonParameters>]' and always sits right before it, removing ProgressAction can
# leave '[<CommonParameters>]' orphaned on a wrapped continuation line. The first
# replacement handles that case by pulling '[<CommonParameters>]' back onto the line
# ProgressAction occupied; the second removes any remaining ProgressAction token,
# whether inline or wrapped onto its own line. Format-SyntaxCommonParameters then wraps
# '[<CommonParameters>]' back onto its own line where the result would exceed PlatyPS's
# syntax wrap width, matching the layout PlatyPS produces without ProgressAction.
# -----------------------------------------------------------------------------
Write-Host 'Post-processing generated MDX files (ProgressAction, example fences)' -ForegroundColor Magenta
$commandsFolder = Join-Path -Path $docusaurusOptions.DocsFolder -ChildPath $docusaurusOptions.Sidebar
Get-ChildItem -Path $commandsFolder -Filter '*.mdx' | ForEach-Object {
$content = Get-Content -LiteralPath $_.FullName -Raw
# Pull '[<CommonParameters>]' back up when removing ProgressAction would orphan it
$updated = $content -replace '[ ]*\[-ProgressAction <ActionPreference>\][ ]*\r?\n[ ]*\[<CommonParameters>\]', ' [<CommonParameters>]'
# Remove any remaining ' [-ProgressAction <ActionPreference>]' from the SYNTAX code-blocks
$updated = $updated -replace '[ ]*(\r?\n[ ]*)?\[-ProgressAction <ActionPreference>\]', ''
# Remove the dedicated '### -ProgressAction' section up to the next '### ' heading
$updated = $updated -replace '(?ms)^### -ProgressAction\r?\n.*?(?=^### )', ''
# Re-wrap '[<CommonParameters>]' onto its own line where the SYNTAX line is too long
$updated = Format-SyntaxCommonParameters -Content $updated
# Fix mismatched code fences inside the EXAMPLES section
$updated = Repair-ExampleFences -Content $updated
if ($updated -ne $content) {
Set-Content -LiteralPath $_.FullName -Value $updated -NoNewline -Encoding utf8
}
}
Write-Host 'Render completed successfully' -BackgroundColor DarkGreen
Pop-Location
if ($ENV:GITHUB_ACTIONS) {
# Output Workflow information
"pester-version=$($ModuleList.Pester))" >> $env:GITHUB_OUTPUT
}