-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathgenerate-command-reference.ps1
More file actions
297 lines (253 loc) · 11.2 KB
/
Copy pathgenerate-command-reference.ps1
File metadata and controls
297 lines (253 loc) · 11.2 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
<#
.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
Update current (latest) docs using latest Pester version
.EXAMPLE
.\generate-command-reference.ps1 -PesterVersion 6.0.0
Update current (latest) docs using Pester 6.0.0 explicitly
.EXAMPLE
.\generate-command-reference.ps1 -PesterVersion 5.9.0 -DocsVersion v5
Update versioned docs for v5 using explicit version 5.9.0
.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 Command Reference-section of website' -BackgroundColor DarkGreen
# -----------------------------------------------------------------------------
# Install required modules
# -----------------------------------------------------------------------------
$ModuleList = [ordered]@{
'Microsoft.PowerShell.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
}
}
Write-Host 'Pre-processing CommandHelp-objects' -ForegroundColor Magenta
$commandHelp = & {
# Workaround: Strict mode breaks PlatyPS (https://github.com/PowerShell/platyPS/issues/800)
Set-StrictMode -Off
New-CommandHelp -CommandInfo (Get-Command -Module Pester -CommandType Cmdlet, Function | Where-Object Version -eq $ModuleList.Pester)
}
$commandHelp | ForEach-Object {
# Customize the description metadata for each command to include the synopsis
# Synopsis is guaranteed by Help.Tests.ps1 in pester/pester-repo, but checking due to platyPS bugs.
if ($_.Synopsis -notmatch '^\{\{ Fill in') {
$_.Metadata['description'] = "Help for Pester command '$($_.Title)'. $($_.Synopsis -replace '\s+', ' ')"
} else {
$_.Metadata['description'] = "Help for Pester command '$($_.Title)'."
}
# Fix Commands navbar link for v4. This is first command in v4 docs
if ($DocsVersion -eq 'v4' -and $_.Title -eq 'Add-AssertionOperator') {
$_.Metadata['id'] = 'Add-ShouldOperator' # Override id to have common docId for all versions
$_.Metadata['slug'] = $_.Title # Override slug so url still matches v4 name
}
}
# -----------------------------------------------------------------------------
# Use below settings to manipulate the rendered MDX files
# -----------------------------------------------------------------------------
$contributeUrl = switch ($DocsVersion) {
'Current' { 'https://github.com/pester/pester' }
'v5' { 'https://github.com/pester/Pester/tree/rel/5.x.x' }
'v4' { 'https://github.com/pester/Pester/tree/rel/4.x.x' }
}
$docusaurusOptions = @{
CommandHelp = $commandHelp
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' # v4 only
'Invoke-Mock' # v4 only
'SafeGetCommand' # v4 only
'Set-DynamicParameterVariable' # v4 only
)
MetaKeywords = @(
'PowerShell'
'Pester'
'Help'
'Documentation'
)
PrependMarkdown = @"
:::info This page was generated
Contributions are welcome in [Pester$(if ($DocsVersion -ne 'Current') { " $DocsVersion" })-repo]($contributeUrl).
:::
"@
AppendMarkdown = @"
## VERSION
*This page was generated using comment-based help in [Pester $($ModuleList.Pester)]($contributeUrl).*
"@
}
# -----------------------------------------------------------------------------
# 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 {
<#
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) { $lang = 'powershell' }
$result.Add('```' + $lang)
$inCode = $true
}
else {
$result.Add('```')
$inCode = $false
}
continue
}
$result.Add($line); $i++
}
return ($result -join $eol)
}
function Repair-RelatedLinks {
<#
A .LINK block that holds more than one entry is rendered as a single link
with an empty url, for example
- [Invoke-Pester
https://kevinmarquette.github.io/2017-03-17-...]()
Invoke-Gherkin in Pester 4.10.1 writes its help that way. Split such a link
into one entry per line, and expand a bare command name to its pester.dev url
so it matches the urls the other .LINK entries already use.
#>
param([string] $Content)
$eol = if ($Content -match "`r`n") { "`r`n" } else { "`n" }
[regex]::Replace(
$Content,
'(?m)^-[ ]\[([\s\S]*?)\]\(\)[ ]*$',
{
param($m)
$entries = $m.Groups[1].Value -split "`r?`n" |
ForEach-Object { $_.Trim() } |
Where-Object { $_ }
($entries | ForEach-Object {
$target = if ($_ -match '^https?://') { $_ }
elseif ($DocsVersion -like 'v*') { "https://pester.dev/docs/$DocsVersion/commands/$_" }
else { "https://pester.dev/docs/commands/$_" }
"- [$target]($target)"
}) -join $eol
}
)
}
# -----------------------------------------------------------------------------
# Post-process the generated MDX:
# * Repair the mismatched code fences PlatyPS emits for .EXAMPLE blocks that
# contain their own Markdown fences (see Repair-ExampleFences) so the MDX
# compiles.
# * Split multi-entry .LINK blocks in v4 that render as one link with an empty url
# (see Repair-RelatedLinks) so the links are not dead.
# -----------------------------------------------------------------------------
Write-Host 'Post-processing generated MDX files' -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
# Fix mismatched code fences inside the EXAMPLES section
# TODO: Remove? Not really needed. Only fixed two earlier typos in pester/pester repo.
$updated = Repair-ExampleFences -Content $content
if ($DocsVersion -eq 'v4' -and $_.BaseName -eq 'Invoke-Gherkin') {
# Fix RELATED LINKS in Invoke-Gherkin. For every other version, fix source.
# Remove if 4.10.2 is ever released
$updated = Repair-RelatedLinks -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
}