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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$siteRoot = $PSScriptRoot
$configPath = $null
$localArchive = $null
$remoteArchive = $null
$remoteArchiveMayExist = $false
$deploymentSucceeded = $false
$failureMessage = $null
$locationPushed = $false
$nativeCommands = @{}
$sshOptions = @("-o", "ConnectTimeout=10")
function Get-NativeCommandPath {
param(
[Parameter(Mandatory)]
[string]$Name
)
$command = Get-Command -Name $Name -CommandType Application -ErrorAction Stop
return $command.Source
}
function Invoke-CheckedNativeCommand {
param(
[Parameter(Mandatory)]
[string]$Command,
[Parameter()]
[string[]]$Arguments = @(),
[Parameter(Mandatory)]
[string]$Operation
)
& $Command @Arguments
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
throw "$Operation failed with exit code $exitCode."
}
}
function Invoke-CheckedSshScript {
param(
[Parameter(Mandatory)]
[string]$Command,
[Parameter(Mandatory)]
[string[]]$Options,
[Parameter(Mandatory)]
[string]$Target,
[Parameter(Mandatory)]
[string]$Script
)
$Script | & $Command @Options $Target "sh -s"
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
throw "Remote release activation failed with exit code $exitCode."
}
}
try {
if ($args.Count -gt 0) {
throw "deploy.ps1 does not accept arguments. Edit deploy.config.psd1 instead."
}
if ([string]::IsNullOrWhiteSpace($siteRoot)) {
throw "Unable to determine the site root. Run deploy.ps1 from a saved file."
}
$siteRoot = (Resolve-Path -LiteralPath $siteRoot).Path
if (-not (Test-Path -LiteralPath (Join-Path $siteRoot "zola.toml") -PathType Leaf)) {
throw "zola.toml was not found next to deploy.ps1."
}
$configPath = Join-Path $siteRoot "deploy.config.psd1"
if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
throw (
"deploy.config.psd1 was not found. " +
"Copy deploy.config.example.psd1 and enter the local deployment settings."
)
}
$deployConfig = Import-PowerShellDataFile -LiteralPath $configPath
if ($deployConfig -isnot [System.Collections.IDictionary]) {
throw "deploy.config.psd1 must contain a PowerShell data hashtable."
}
$requiredConfigKeys = @(
"DeployHost",
"DeployUser",
"RemoteBase",
"IdentityFile",
"SiteUrl"
)
foreach ($key in $requiredConfigKeys) {
if (-not $deployConfig.Contains($key)) {
throw "deploy.config.psd1 is missing the required key: $key"
}
}
$DeployHost = ([string]$deployConfig["DeployHost"]).Trim()
$DeployUser = ([string]$deployConfig["DeployUser"]).Trim()
$RemoteBase = ([string]$deployConfig["RemoteBase"]).Trim()
$IdentityFile = ([string]$deployConfig["IdentityFile"]).Trim()
$siteUrl = ([string]$deployConfig["SiteUrl"]).Trim()
if ($DeployHost -notmatch '^[A-Za-z0-9._-]+$') {
throw "DeployHost contains unsupported characters."
}
if ($DeployUser -notmatch '^[A-Za-z_][A-Za-z0-9_-]*$') {
throw "DeployUser contains unsupported characters."
}
$RemoteBase = $RemoteBase.TrimEnd('/')
if (
$RemoteBase.Length -le 1 -or
$RemoteBase -notmatch '^/[A-Za-z0-9._/-]+$' -or
$RemoteBase -match '(^|/)\.\.?(/|$)' -or
$RemoteBase.Contains('//')
) {
throw "RemoteBase must be a normalized absolute Unix path other than '/'."
}
if (-not $RemoteBase.StartsWith('/srv/www/', [System.StringComparison]::Ordinal)) {
throw "RemoteBase must be located below /srv/www/."
}
$parsedSiteUrl = $null
if (
-not [System.Uri]::TryCreate(
$siteUrl,
[System.UriKind]::Absolute,
[ref]$parsedSiteUrl
) -or
$parsedSiteUrl.Scheme -ne "https"
) {
throw "SiteUrl must be an absolute HTTPS URL."
}
if (-not [string]::IsNullOrWhiteSpace($IdentityFile)) {
$identityCandidate = $IdentityFile
if (-not [System.IO.Path]::IsPathRooted($identityCandidate)) {
$identityCandidate = Join-Path $siteRoot $identityCandidate
}
$identityPath = (Resolve-Path -LiteralPath $identityCandidate -ErrorAction Stop).Path
if (-not (Test-Path -LiteralPath $identityPath -PathType Leaf)) {
throw "IdentityFile must point to a file."
}
$sshOptions += @("-i", $identityPath)
}
foreach ($name in @("zola", "tar", "ssh", "scp")) {
$nativeCommands[$name] = Get-NativeCommandPath -Name $name
}
Push-Location -LiteralPath $siteRoot
$locationPushed = $true
Write-Host "[1/6] Checking site..."
Invoke-CheckedNativeCommand `
-Command $nativeCommands["zola"] `
-Arguments @("check") `
-Operation "zola check"
Write-Host "[2/6] Building site..."
Invoke-CheckedNativeCommand `
-Command $nativeCommands["zola"] `
-Arguments @("build") `
-Operation "zola build"
$publicDir = Join-Path $siteRoot "public"
$publicIndex = Join-Path $publicDir "index.html"
if (-not (Test-Path -LiteralPath $publicIndex -PathType Leaf)) {
throw "Build validation failed: public/index.html was not generated."
}
$resolvedPublicDir = (Resolve-Path -LiteralPath $publicDir).Path
$siteRootPrefix = $siteRoot.TrimEnd(
[System.IO.Path]::DirectorySeparatorChar,
[System.IO.Path]::AltDirectorySeparatorChar
) + [System.IO.Path]::DirectorySeparatorChar
if (-not $resolvedPublicDir.StartsWith(
$siteRootPrefix,
[System.StringComparison]::OrdinalIgnoreCase
)) {
throw "Resolved public directory is outside the site root."
}
$releaseId = Get-Date -Format "yyyyMMdd-HHmmss"
$archiveNonce = [System.Guid]::NewGuid().ToString("N")
$archiveName = "takashi-2521-$releaseId-$archiveNonce.tar.gz"
$localArchive = Join-Path ([System.IO.Path]::GetTempPath()) $archiveName
$remoteArchive = "/tmp/$archiveName"
$remoteTarget = "$DeployUser@$DeployHost"
Write-Host "[3/6] Creating archive..."
Invoke-CheckedNativeCommand `
-Command $nativeCommands["tar"] `
-Arguments @("-czf", $localArchive, "-C", $resolvedPublicDir, ".") `
-Operation "tar archive creation"
if (
-not (Test-Path -LiteralPath $localArchive -PathType Leaf) -or
(Get-Item -LiteralPath $localArchive).Length -le 0
) {
throw "Archive validation failed: the local archive is missing or empty."
}
Write-Host "[4/6] Uploading release..."
$scpArguments = @($sshOptions) + @(
$localArchive,
"${remoteTarget}:$remoteArchive"
)
$remoteArchiveMayExist = $true
Invoke-CheckedNativeCommand `
-Command $nativeCommands["scp"] `
-Arguments $scpArguments `
-Operation "SCP upload"
$remoteScript = @'
set -eu
umask 022
base='__REMOTE_BASE__'
release_id='__RELEASE_ID__'
archive='__REMOTE_ARCHIVE__'
release="$base/releases/$release_id"
new_link="$base/current.new"
release_created=0
fail() {
echo "Remote deployment failed: $*" >&2
exit 1
}
cleanup() {
status=$?
trap - 0
rm -f -- "$archive" || true
rm -f -- "$new_link" || true
if [ "$status" -ne 0 ] && [ "$release_created" -eq 1 ]; then
rm -rf -- "$release" || true
fi
exit "$status"
}
trap cleanup 0
[ -d "$base" ] || fail "remote base does not exist: $base"
[ -d "$base/releases" ] || fail "releases directory does not exist: $base/releases"
[ -L "$base/current" ] || fail "current is not a symbolic link: $base/current"
[ -f "$archive" ] || fail "uploaded archive does not exist: $archive"
if [ -e "$release" ] || [ -L "$release" ]; then
echo "Release already exists: $release_id" >&2
exit 1
fi
if [ -e "$new_link" ] || [ -L "$new_link" ]; then
rm -f -- "$new_link" || fail "could not remove stale symlink: $new_link"
fi
mkdir -- "$release" || fail "could not create release directory: $release"
release_created=1
tar -xzf "$archive" -C "$release" || fail "could not extract archive into: $release"
[ -f "$release/index.html" ] || fail "new release has no index.html: $release/index.html"
ln -s "releases/$release_id" "$new_link" || fail "could not create temporary symlink: $new_link"
mv -Tf "$new_link" "$base/current" || fail "could not atomically replace current symlink"
release_created=0
'@
$remoteScript = $remoteScript.Replace("__REMOTE_BASE__", $RemoteBase)
$remoteScript = $remoteScript.Replace("__RELEASE_ID__", $releaseId)
$remoteScript = $remoteScript.Replace("__REMOTE_ARCHIVE__", $remoteArchive)
Write-Host "[5/6] Switching release..."
Invoke-CheckedSshScript `
-Command $nativeCommands["ssh"] `
-Options $sshOptions `
-Target $remoteTarget `
-Script $remoteScript
$deploymentSucceeded = $true
}
catch {
$failureMessage = $_.Exception.Message
}
finally {
if ($locationPushed) {
Pop-Location
}
if ($null -ne $localArchive -and (Test-Path -LiteralPath $localArchive)) {
Remove-Item -LiteralPath $localArchive -Force -ErrorAction SilentlyContinue
}
if (
$remoteArchiveMayExist -and
-not $deploymentSucceeded -and
$null -ne $remoteArchive
) {
$cleanupCommand = "rm -f -- '$remoteArchive'"
$cleanupSshOptions = @($sshOptions) + @("-o", "BatchMode=yes")
& $nativeCommands["ssh"] @cleanupSshOptions $remoteTarget $cleanupCommand 2>$null | Out-Null
}
}
if (-not $deploymentSucceeded) {
[System.Console]::Error.WriteLine("Deployment failed: $failureMessage")
exit 1
}
Write-Host "[6/6] Done."
Write-Host ""
Write-Host "Release: $releaseId"
Write-Host "URL: $siteUrl"
exit 0
|