-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.ps1
More file actions
297 lines (271 loc) · 10.6 KB
/
build.ps1
File metadata and controls
297 lines (271 loc) · 10.6 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
Builds the website.
.DESCRIPTION
Builds a static site using PowerShell.
.EXAMPLE
./build.ps1
#>param(
[string[]]$FilePath,
[string]$Root = $PSScriptRoot,
[ValidateScript({
$isValid = $_ -is [Management.Automation.CommandInfo] -or
$_ -is [ScriptBlock]
if ($isValid) { return $true }
throw "Must be a Command or ScriptBlock"
})]
[PSObject]
$Layout = $(
if (Test-Path (Join-Path $PSScriptRoot 'layout.ps1')) {
Get-Command (Join-Path $PSScriptRoot 'layout.ps1')
} else {
{"<html><head></head><body>"
@($input; $args) -join [Environment]::NewLine
"</body></html>"}
}
),
[string[]]
$excludeTerms = @("Color-Schemes", ".tests.ps1", ".turtle.ps1", ".websocket.ps1")
)
$PSStyle.OutputRendering = 'ANSI'
#region Common Filters
filter Require {
# What do we require?
$require = $_
# If it is a script
if ($require -is [Management.Automation.ExternalScriptInfo]) {
# get its required modules
$require.ScriptBlock.Ast.ScriptRequirements.RequiredModules.Name |
. $MyInvocation.MyCommand # and pipe to ourself and return
return
}
if ($require -isnot [string]) { return }
$importSplat = @{PassThru=$true;ErrorAction='Ignore';Global=$true}
$isInstalled = Import-Module -Name $require @importSplat
# If they're not installed
if (-not $isInstalled) {
# install them.
Write-Host -ForegroundColor Cyan "Installing $require"
Install-Module -AllowClobber -Force -Name $require -Scope CurrentUser
$isInstalled = Import-Module -Name $require @importSplat
}
}
filter GetScriptParameters {
$in = $_
if ($in -is [ScriptBlock]) {
$function:tempFunction = $in
$invokeCommand = $ExecutionContext.SessionState.InvokeCommand
$in = $invokeCommand.GetCommand('tempFunction', 'Function')
}
if ($in -isnot [Management.Automation.CommandInfo]) { return }
if (-not $args) { return $in.Parameters }
$splat = [Ordered]@{}
:nextParameter foreach ($parameterName in $in.Parameters.Keys) {
$parameter = $in.Parameters[$parameterName]
$potentialType = $parameter.ParameterType
# PowerShell parameters can have aliases, so find all potential names.
$parameterNames = @($parameter.Name;$parameter.Aliases) -ne ''
foreach ($PotentialName in $parameterNames) {
foreach ($arg in $args) {
if ($arg -isnot [Collections.IDictionary]) { continue }
if ($arg[$potentialName] -and
$arg[$potentialName] -as $potentialType) {
if ($potentialType -eq [Collections.IDictionary]) {
if (-not $splat[$parameterName]) {
$splat[$parameterName] = [Ordered]@{}
}
foreach ($key in $arg[$potentialName].Keys) {
$splat[$parameterName][$key] =
$arg[$potentialName][$key]
}
} else {
$splat[$parameterName] = $arg[$potentialName]
}
}
}
}
}
return $splat
}
filter GetScriptMetadata {
$in = $_
$meta = [Ordered]@{}
$help =
if ($in.Source -and $in.ScriptContents -match '\.synopsis') {
Get-Help $in.Source
}
elseif ($in -is [Management.Automation.FunctionInfo]) {
Get-Help $in.Name
}
if ($help -isnot [string]) {
$meta.title = $help.synopsis
$meta.description = $help.description.text -join [Environment]::NewLine
$meta.notes = $help.alertset.alert.text -join [Environment]::NewLine
$meta.help = $help
$meta.examples = @(
foreach ($example in $scriptHelp.examples.example) {
@(
$example.Code
@($example.Remarks.text) -ne ''
) -join ([Environment]::NewLine)
}
)
}
foreach ($attribute in $in.ScriptBlock.Attributes) {
if ($attribute -is [Reflection.AssemblyMetaDataAttribute]) {
$meta[$attribute.Key] = $attribute.Value
}
}
return $meta
}
$mdPipelineBuilder = [Markdig.MarkdownPipelineBuilder]::new()
$mdPipeline = [Markdig.MarkdownExtensions]::UsePipeTables($mdPipelineBuilder).Build()
filter GetMarkdownHTML {
$in = $_
if ($in -is [IO.FileInfo]) {
$in = Get-Content -Raw -LiteralPath $in.FullName
}
$metadata = [Ordered]@{}
if ($in -match '^---') {
$null, $yamlheader, $markdown = $in -split '---', 3
if ($yamlheader) {
require YaYaml
$metadata += ConvertFrom-Yaml $yamlheader -ErrorAction Ignore
}
} else {
$markdown = $in
}
[Markdig.Markdown]::ToHtml("$markdown", $mdPipeline) -replace
'disabled="disabled"' |
Add-Member NoteProperty Metadata $metadata -Force -PassThru
}
#endregion Common Filters
# Push into the script root directory
if ($PSScriptRoot) { Push-Location $PSScriptRoot }
#region Prepare Build
# `$site` holds sitewide information
$Site = [Ordered]@{}
if ($FilePath) {$Site.Path = $FilePath }
elseif ($root){ $Site.Path = $root}
$Site.PSScriptRoot = $Site.Root = if ($Root) { $Root } else { $PSScriptRoot }
$Site.Layout = $Layout
#region Configuration
$excludePattern = @(
@(
foreach ($exclude in $excludeTerms) { [regex]::Escape($exclude) }
'[\\/]_[^\\/]+[\\/]' # always exclude _ directories
) -join '|'
)
$configPs1Path = Join-Path $site.PSScriptRoot config.ps1
if (Test-Path $configPs1Path) {
$configPs1 = Get-command $configPs1Path -CommandType ExternalScript
if ($configPs1) {
$configPs1 | Require
}
. $configPs1Path
}
$Site.Files = Get-ChildItem -Recurse -File -Path $site.Path
#endregion Configuration
#region Build
$buildStart = [DateTime]::Now
Write-Host "Started Building Pages @ $buildStart" -ForegroundColor Cyan
$defaultLayoutParameters = # Get the default layout parameters for the site.
$layoutParameters = $Layout | GetScriptParameters $site
$fileQueue = [Collections.Queue]::new()
foreach ($included in @($site.Files) -notmatch $excludePattern) {
$fileQueue.Enqueue($included)
}
$invokeCommand = $ExecutionContext.SessionState.InvokeCommand
$site.BuildProgress = $buildProgress = [Ordered]@{
Status = 'Building'
Id = Get-Random
}
$originalTotal = $fileQueue.Count
$buildFileCounter = 0
while ($fileQueue.Count) {
$buildFile = $fileQueue.Dequeue()
$output = $null # nullify output (just in case)
$buildProgress.Activity = "$($buildFile.Directory.Name)/$($buildFile.Name) "
$buildProgress.PercentComplete = [Math]::Min(100, (
++$buildFileCounter * 100 / $originalTotal))
:nextFile switch -regex ($buildFile) {
'^' { <# Start of each file name, should always match #> }
{
$_ -match '\.[^\.\\/]+\.ps1$' -or
(
$_.Extension -eq '.ps1' -and (
$_.Name -replace '\.ps1$' -eq $_.Directory.Name
)
)
} { # *.*.ps1 files get run
# after we push into the location and map parameters.
Push-Location $buildFile.Directory.FullName
$scriptFile =
$invokeCommand.Getcommand($buildFile.FullName, 'ExternalScript')
$page = $scriptFile | GetScriptMetadata
$parameters = $scriptFile | GetScriptParameters $site $page
Write-Progress @buildProgress
# Make sure to `dot` the script, so we run in the current context.
$output = . $buildFile.FullName @parameters
# If there is no output, pop out and continue
if (-not $output) {
Pop-Location; continue nextFile
}
# Get the layout parameters after we run, so any changes propagate.
$layoutParameters = $layout | GetScriptParameters $site $page
$outputPath =
if ($buildFile.Name -replace '(?:\.html)?\.ps1$' -eq
$buildFile.Directory.Name) {
$buildFile.FullName -replace "$([Regex]::Escape($buildFile.Name))$",
'index.html'
} else {
$buildFile.FullName -replace '\.ps1$'
}
# If the output is html, and we are not
if ($outputPath -match '\.html?$' -and
-not ($output -match '<html')
) {
$output = $output | # layout the output
. $Layout @layoutParameters
}
# If the output is markdown
if ($outputPath -match '\.(markdown|md)$') {
$output > $outputPath # save it and
$html = $output -join [Environment]::NewLine |
GetMarkdownHTML # get the html,
if ($html.Metadata.Count) {
$layoutParameters = $layout | # and layout the markdown
GetScriptParameters $site $page $html.Metadata
}
$output = $html | . $Layout @layoutParameters
$outputPath = $outputPath -replace '\.(markdown|md)$', '.html'
}
# Write the output and emit the file
if ($output -and $outputPath -ne $buildFile.FullName) {
$output > $outputPath ; Get-Item $outputPath
}
Pop-Location # pop back to where we were
}
'\.(md|markdown)$' {
$html = $buildFile | GetMarkdownHTML # Make our markdown HTML
$page = $html.Metadata # and get any page metadata.
$layoutParameters = $layout | # Get the layout parameters
GetScriptParameters $site $page # from the site and page.
Write-Progress @buildProgress
$output = $html | . $Layout @layoutParameters
$outputPath = ($buildFile.FullName -replace '\.(md|markdown)$', '.html')
if ($output -and $outputPath -ne $buildFile.FullName) {
$output > $outputPath; Get-Item $outputPath
}
}
}
$layoutParameters = $defaultLayoutParameters
}
$buildEnd = [DateTime]::Now
$buildProgress.Status = "Finished Building @ $buildEnd"
$buildProgress.Activity = "in $($buildEnd - $buildStart)"
$buildProgress.Remove('PercentComplete')
Write-Progress @buildProgress -Completed
Write-Host "$($buildProgress.Status) $($buildProgress.Activity)" -ForegroundColor Cyan
#endregion Build
if ($PSScriptRoot) { Pop-Location } # Pop back out.