# Copyright (c) 2022 SurrealDB Ltd. <# .SYNOPSIS Installs `surreal`, the SurrealDB command line, and the database with it. .DESCRIPTION The Windows counterpart of install.sh, with the same options. irm https://download.surrealdb.com/cli/launcher/install.ps1 | iex & ([scriptblock]::Create((irm https://download.surrealdb.com/cli/launcher/install.ps1))) -Version 3.3.2 & ([scriptblock]::Create((irm https://download.surrealdb.com/cli/launcher/install.ps1))) -With cloud,lsp & ([scriptblock]::Create((irm https://download.surrealdb.com/cli/launcher/install.ps1))) -NoDb C:\tools `irm | iex` cannot pass options, so the database switch is also an environment variable: SURREAL_CLI_INSTALL_DB=1 installs the database and SURREAL_CLI_INSTALL_DB=0 does not. -Db and -NoDb win over it. The launcher goes where the database's Windows installer has always put `surreal.exe`: `Program Files\SurrealDB` from an elevated shell, otherwise `%LOCALAPPDATA%\SurrealDB`, added to the user's PATH. The database is installed by the launcher as a component and pinned, so `surreal db start` works from then on with no network at all. A release named with -Version is pinned whatever was pinned before; one a channel names is pinned unless a later one is. SURREAL_CLI_DOWNLOAD_ROOT replaces the download host, for mirrors. The host must publish the launcher under `cli/launcher/` as well as the database at its root; this script installs nothing without it. The launcher is published as the database is: `cli/launcher/latest.txt` names a release, and `cli/launcher/v/surreal-v.windows-amd64.exe` is it. A `surreal` that comes before the install directory on PATH, such as an older standalone database, would shadow the launcher, so the script warns when it finds one. Every download is checked against the SHA-256 published beside it, and nothing is installed if a check fails. Connections use TLS 1.2 or later. .PARAMETER InstallDir Where to put `surreal.exe`, instead of the database installer's usual place. A directory named here is not added to PATH. .PARAMETER Version The database release to install and pin. Only with the database. .PARAMETER Nightly The latest nightly database. Only with the database. .PARAMETER Beta The latest beta database. Only with the database. .PARAMETER Alpha The latest alpha database. Only with the database. .PARAMETER Db Install the database. The default, for now; ask for it to keep getting it after the default changes. .PARAMETER NoDb Do not install the database: it installs on first use. Nothing is fetched from the database's download location. .PARAMETER With Further components to install: memory, cloud, ext, kit, lsp. .PARAMETER Minimal Another name for -NoDb, kept for scripts that use it. -With still applies. .PARAMETER Interactive Ask where to install when the install directory is not writable. #> [CmdletBinding(PositionalBinding = $false)] param( [Parameter(Position = 0)] [string] $InstallDir = '', # Aliases spelled out: PowerShell would otherwise find `-v` ambiguous with # -Verbose, `-n` with -NoDb and `-i` with -InstallDir. An exact alias wins. [Alias('v')] [string] $Version = '', [Alias('n')] [switch] $Nightly, [Alias('b')] [switch] $Beta, [Alias('a')] [switch] $Alpha, [switch] $Db, [switch] $NoDb, # An array, because `-With cloud,lsp` unquoted is two strings. [string[]] $With = @(), [switch] $Minimal, [Alias('i')] [switch] $Interactive ) Set-StrictMode -Version 3.0 $ErrorActionPreference = 'Stop' # Invoke-WebRequest's progress bar slows Windows PowerShell downloads by an # order of magnitude; this script draws none anyway. $ProgressPreference = 'SilentlyContinue' # Whether the database is installed when nothing says. The one place the # default lives: when it flips, a script that passed -Db or set # SURREAL_CLI_INSTALL_DB=1 keeps getting the database, and one that passed # -NoDb or set it to 0 never downloads it. $DbByDefault = $true # The most an asset download keeps. Releases are tens of megabytes; the cap is # far above any, and stops a host that never ends its response from filling # the disk. The launcher holds its own downloads to the same. $AssetLimit = 1073741824 # A pointer or a digest is a few bytes. $SmallLimit = 65536 # Run from a file, failure is exit code 1. Run by `iex` or as a script block, # `exit` would close the caller's own PowerShell window, so the script sets # $LASTEXITCODE and returns instead. # $PSCommandPath is inherited by a scriptblock that runs inside another .ps1, # so it cannot say whether this installer was loaded from a file. The # invocation's own command has a path only when it is a file. # Strict mode throws on a missing property, and a scriptblock's command may # have no `Path`, so the property is looked for before it is read. $RunFromFile = $false if ($MyInvocation.MyCommand -and $MyInvocation.MyCommand.PSObject.Properties['Path']) { $RunFromFile = [bool] $MyInvocation.MyCommand.Path } function Fail([string] $Message) { throw $Message } # A release spelling as the launcher reads it: `v3.3.2` is `3.3.2`, `stable` is # `latest`, surrounding whitespace is no part of it, and a major is a number, # so `02` is `2`. Kept in step with `normalise_spec` in install.sh and # `Spec::parse` in `src/spec.rs`, and compared case-sensitively, # as both of those read it. function ConvertTo-Spec([string] $Spec) { $value = $Spec.Trim() if ($value.StartsWith('v', [StringComparison]::Ordinal)) { $value = $value.Substring(1) } if ($value -ceq 'stable') { return 'latest' } if ($value -match '^[0-9]+$') { return $value.TrimStart('0').PadLeft(1, '0') } $value } function Read-Option { param( [string] $Version, [switch] $Nightly, [switch] $Beta, [switch] $Alpha, [switch] $Db, [switch] $NoDb, [string[]] $With, [switch] $Minimal ) $channels = @() if ($Nightly) { $channels += 'nightly' } if ($Beta) { $channels += 'beta' } if ($Alpha) { $channels += 'alpha' } if ($channels.Count -gt 1) { Fail 'choose one of -Nightly, -Beta and -Alpha' } $channel = if ($channels.Count -eq 1) { $channels[0] } else { '' } if ($channel -and $Version) { Fail 'choose either -Version or a channel' } $components = @($With | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) if ($Db -and $NoDb) { Fail 'choose either -Db or -NoDb' } # `-Minimal` is another name for `-NoDb`, and like install.sh it still takes # `-With`. PowerShell switches have no order, so `-Minimal` with `-Db` is a # conflict rather than a last-one-wins. if ($Minimal -and $Db) { Fail 'choose either -Db or -Minimal' } # A switch on the command line wins over the environment, so an explicit # switch never reads SURREAL_CLI_INSTALL_DB at all: an invalid value there # must not stop a run that already said what it wants, as install.sh does. $installDb = $DbByDefault $explicit = $Db -or $NoDb -or $Minimal $fromEnv = $env:SURREAL_CLI_INSTALL_DB if (-not $explicit -and $fromEnv) { switch ($fromEnv) { '1' { $installDb = $true } '0' { $installDb = $false } default { Fail 'SURREAL_CLI_INSTALL_DB must be 1, to install the database, or 0, not to' } } } if ($Db) { $installDb = $true } if ($NoDb -or $Minimal) { $installDb = $false } # A release, or the database named in -With, asks for the database, so with # no switch and no variable it holds whatever the default becomes, as it # does in install.sh. $withDb = [bool] ($components | Where-Object { $_ -ceq 'db' -or $_ -clike 'db@*' }) if (-not $explicit -and -not $fromEnv -and ($channel -or $Version -or $withDb)) { $installDb = $true } if (-not $installDb -and ($channel -or $Version)) { $why = if ($Minimal) { '-Minimal' } elseif ($NoDb) { '-NoDb' } else { 'SURREAL_CLI_INSTALL_DB=0' } Fail "$why installs no database, so it takes no database version" } # `-With db` against an explicit opt-out is a conflict, refused before # anything is downloaded. Against the default it implied the database above. if (-not $installDb -and $withDb) { Fail "-With installs the database, which this run turns off; drop one of them" } # Every database selector in -With must name the same release: two cannot # both be installed as the pinned one. $withSpec = '' foreach ($component in $components) { if ($component -cnotlike 'db@*') { continue } $here = ConvertTo-Spec $component.Substring(3) if ($withSpec -and $here -cne $withSpec) { Fail "-With names two database releases, db@$withSpec and $component; drop one of them" } $withSpec = $here } # A `db@` in -With names a database release, so it cannot sit beside a # channel, and beside -Version only when they name the same release. # Refused, not guessed, as install.sh does, with the spellings compared as # the launcher reads them. if ($withSpec -and $channel -and $withSpec -cne $channel) { Fail "-With db@$withSpec names a database release, which -$channel would replace; drop one of them" } if ($withSpec -and $Version -and (ConvertTo-Spec $Version) -cne $withSpec) { Fail "-With db@$withSpec and -Version $Version name different database releases; drop one of them" } [pscustomobject]@{ Channel = $channel Version = $Version Components = $components InstallDb = $installDb WithSpec = $withSpec } } # The download root is printed in progress and in every error about a request, # so it may hold nothing that is a secret: it is an http or https URL naming a # host, with no user name or password, no query, no fragment. The message # names the variable, never its value. function Get-DownloadRoot { $root = if ($env:SURREAL_CLI_DOWNLOAD_ROOT) { $env:SURREAL_CLI_DOWNLOAD_ROOT } else { 'https://download.surrealdb.com' } $root = $root.TrimEnd('/') $notUrl = 'SURREAL_CLI_DOWNLOAD_ROOT is not an http or https URL naming a host, such as https://download.example.com' $uri = $null if (-not [Uri]::TryCreate($root, [UriKind]::Absolute, [ref] $uri)) { Fail $notUrl } if ($uri.Scheme -ne 'http' -and $uri.Scheme -ne 'https') { Fail $notUrl } if (-not $uri.Host) { Fail $notUrl } if ($uri.UserInfo) { Fail 'SURREAL_CLI_DOWNLOAD_ROOT carries a user name or password, which would be printed wherever the download host is named; set it to the mirror''s address alone' } if ($root.Contains('?') -or $root.Contains('#')) { Fail 'SURREAL_CLI_DOWNLOAD_ROOT carries a query or fragment, which would be printed wherever the download host is named; set it to the mirror''s address alone' } $root } function Get-Platform { if ($PSVersionTable.PSEdition -eq 'Core' -and -not $IsWindows) { Fail 'this installer is for Windows; on macOS and Linux use install.sh' } # A 32-bit PowerShell on 64-bit Windows reports x86 in the first and the # machine's architecture in the second. $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } switch ($arch) { 'AMD64' { return 'windows-amd64' } # No arm64 build is published. Windows 11 on Arm runs the amd64 one. 'ARM64' { return 'windows-amd64' } default { Fail "unsupported CPU architecture: $arch" } } } function Initialize-Tls12 { # TLS 1.2 or later, never the 1.0 or 1.1 an older Windows PowerShell # offers by default. Windows PowerShell's HttpClient takes the protocols # from ServicePointManager; PowerShell 7's takes them from its handler. if ($PSVersionTable.PSEdition -ne 'Core') { Add-Type -AssemblyName System.Net.Http [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } } function Get-HttpClient { $handler = New-Object System.Net.Http.HttpClientHandler $handler.AllowAutoRedirect = $true if ($PSVersionTable.PSEdition -eq 'Core') { $protocols = [System.Security.Authentication.SslProtocols]::Tls12 # PowerShell 6's .NET has no TLS 1.3. if ([Enum]::GetNames([System.Security.Authentication.SslProtocols]) -contains 'Tls13') { $protocols = $protocols -bor [System.Security.Authentication.SslProtocols]::Tls13 } $handler.SslProtocols = $protocols } $client = New-Object System.Net.Http.HttpClient($handler) # Deadlines are kept below, per step, so one setting cannot cut a slow but # moving download short. $client.Timeout = [System.Threading.Timeout]::InfiniteTimeSpan $client.DefaultRequestHeaders.UserAgent.ParseAdd('surreal-cli-install-ps1') $client } # Wait for a task, at most $Milliseconds; $false when the deadline passes. A # task that failed throws, which Save-Url reports as a failed download. function Wait-Task($Task, [long] $Milliseconds) { $Task.Wait([int] [Math]::Max(0, $Milliseconds)) } # Save-Url # # 'ok', 'absent' (a 403 or 404: not published here), 'oversize' or 'failed'. # An asset has no overall budget, so a slow # connection can finish a large transfer, but one that takes a minute to # connect, or stalls for a minute once connected, fails. A pointer or a digest # must arrive whole within its total, so a host that accepts the connection # and never answers fails the install rather than hanging it. function Save-Url([string] $Url, [string] $OutFile, [long] $Limit, [int] $TotalSeconds, [int] $StallSeconds) { $client = Get-HttpClient $clock = [System.Diagnostics.Stopwatch]::StartNew() $remaining = { $stall = $StallSeconds * 1000 if ($TotalSeconds -gt 0) { [Math]::Min($stall, $TotalSeconds * 1000 - $clock.ElapsedMilliseconds) } else { $stall } } $response = $null $stream = $null $file = $null try { $send = $client.GetAsync($Url, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead) if (-not (Wait-Task $send (& $remaining))) { return 'failed' } $response = $send.Result if (-not $response.IsSuccessStatusCode) { # The CDN answers a missing key with 403 and some hosts with 404. $code = [int] $response.StatusCode if ($code -eq 403 -or $code -eq 404) { return 'absent' } return 'failed' } $declared = $response.Content.Headers.ContentLength if ($null -ne $declared -and $declared -gt $Limit) { return 'oversize' } $read = $response.Content.ReadAsStreamAsync() if (-not (Wait-Task $read (& $remaining))) { return 'failed' } $stream = $read.Result $file = [System.IO.File]::Create($OutFile) $buffer = New-Object byte[] 65536 $total = 0L while ($true) { $chunk = $stream.ReadAsync($buffer, 0, $buffer.Length) if (-not (Wait-Task $chunk (& $remaining))) { return 'failed' } $n = $chunk.Result if ($n -eq 0) { break } $total += $n if ($total -gt $Limit) { return 'oversize' } $file.Write($buffer, 0, $n) } 'ok' } catch { 'failed' } finally { if ($file) { $file.Dispose() } if ($stream) { $stream.Dispose() } if ($response) { $response.Dispose() } $client.Dispose() } } function Save-Small([string] $Url, [string] $OutFile) { (Save-Url $Url $OutFile $SmallLimit 30 30) -eq 'ok' } # Save-Verified # # The digest is fetched first: a release that is only half published costs # one small request, and a missing digest can never read as a pass. function Save-Verified([string] $Base, [string] $Extension, [string] $OutFile) { $digestFile = Join-Path $Work 'digest' if (-not (Save-Small "$Base.txt" $digestFile)) { Fail "could not fetch $Base.txt within 30 seconds" } $expected = ([System.IO.File]::ReadAllText($digestFile).Trim() -split '\s+')[0].ToLowerInvariant() if ($expected -notmatch '^[0-9a-f]{64}$') { Fail "$Base.txt does not hold a SHA-256 digest" } switch (Save-Url "$Base.$Extension" $OutFile $AssetLimit 0 60) { 'ok' {} 'oversize' { Fail "$Base.$Extension is larger than any release, past $AssetLimit bytes. Nothing was installed." } default { Fail "could not fetch $Base.$Extension" } } $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $OutFile).Hash.ToLowerInvariant() if ($actual -ne $expected) { Fail "$Base.$Extension did not arrive intact (expected $expected, got $actual). Nothing was installed." } } # Run a program with a deadline, returning its stdout, or $null if it exits # non-zero or is still running at the deadline, when it is killed: a binary # that never answers must fail the install, not hang it. function Invoke-Bounded([string] $File, [string[]] $Arguments, [int] $Seconds, [hashtable] $Environment = @{}) { $info = New-Object System.Diagnostics.ProcessStartInfo $info.FileName = $File # Every argument here is a fixed word, so none needs quoting. $info.Arguments = $Arguments -join ' ' $info.UseShellExecute = $false $info.CreateNoWindow = $true $info.RedirectStandardInput = $true $info.RedirectStandardOutput = $true $info.RedirectStandardError = $true foreach ($name in $Environment.Keys) { $info.EnvironmentVariables[$name] = $Environment[$name] } try { $process = [System.Diagnostics.Process]::Start($info) } catch { return $null } $process.StandardInput.Close() $stdout = $process.StandardOutput.ReadToEndAsync() $null = $process.StandardError.ReadToEndAsync() if (-not $process.WaitForExit($Seconds * 1000)) { # The process is the launcher, which runs the database as its own child. # Killing the launcher alone leaves the database running, holding the # pipes this function is reading, so the tree is ended first. taskkill # ships with Windows; Kill is the fallback if it cannot run. try { $null = & taskkill.exe /T /F /PID $process.Id 2>&1 } catch { Write-Verbose "could not end the process tree: $_" } try { $process.Kill() } catch { Write-Verbose "could not stop the child: $_" } return $null } $process.WaitForExit() if ($process.ExitCode -ne 0) { return $null } $stdout.Result } # Whether a directory can be written to, judged by writing to it: an ACL or a # read-only share says no only when it is tried. function Test-Writable([string] $Dir) { try { $null = New-Item -ItemType Directory -Force -Path $Dir $probe = Join-Path $Dir ".surreal-install-$([guid]::NewGuid().ToString('N'))" [System.IO.File]::WriteAllText($probe, '') Remove-Item -LiteralPath $probe -Force $true } catch { $false } } function Expand-Home([string] $Path) { if ($Path -eq '~') { return $HOME } if ($Path.StartsWith('~\') -or $Path.StartsWith('~/')) { return (Join-Path $HOME ($Path.Substring(2))) } $Path } # Warn, on one line, when the `surreal` that comes first on PATH is not the # one just installed. An older standalone database installed as `surreal.exe` # is the usual one, and it would take every command meant for the launcher as # its own. Nothing is said when none is on PATH: the closing message already # says how to put the install directory there. function Write-Shadowed([string] $Installed) { $first = Get-Command surreal -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $first -or -not $first.Path) { return } $found = [System.IO.Path]::GetFullPath($first.Path) if ([string]::Equals($found, $Installed, [StringComparison]::OrdinalIgnoreCase)) { return } [Console]::Error.WriteLine("Warning: $found comes first on your PATH, so 'surreal' runs it rather than $Installed; remove it, since an older standalone database there would shadow the launcher.") } function Install-Surreal { param( [string] $InstallDir, [string] $Version, [switch] $Nightly, [switch] $Beta, [switch] $Alpha, [switch] $Db, [switch] $NoDb, [string[]] $With, [switch] $Minimal, [switch] $Interactive ) $options = Read-Option -Version $Version -Nightly:$Nightly -Beta:$Beta -Alpha:$Alpha ` -Db:$Db -NoDb:$NoDb -With $With -Minimal:$Minimal $root = Get-DownloadRoot $platform = Get-Platform Initialize-Tls12 $script:Work = Join-Path ([System.IO.Path]::GetTempPath()) "surreal-install-$([guid]::NewGuid().ToString('N'))" $null = New-Item -ItemType Directory -Path $Work Write-Information -InformationAction Continue '' Write-Information -InformationAction Continue ' .d8888b. 888 8888888b. 888888b.' Write-Information -InformationAction Continue 'd88P Y88b 888 888 ''Y88b 888 ''88b' Write-Information -InformationAction Continue 'Y88b. 888 888 888 888 .88P' Write-Information -InformationAction Continue ' ''Y888b. 888 888 888d888 888d888 .d88b. 8888b. 888 888 888 8888888K.' Write-Information -InformationAction Continue ' ''Y88b. 888 888 888P'' 888P'' d8P Y8b ''88b 888 888 888 888 ''Y88b' Write-Information -InformationAction Continue ' ''888 888 888 888 888 88888888 .d888888 888 888 888 888 888' Write-Information -InformationAction Continue 'Y88b d88P Y88b 888 888 888 Y8b. 888 888 888 888 .d88P 888 d88P' Write-Information -InformationAction Continue ' ''Y8888P'' ''Y88888 888 888 ''Y8888 ''Y888888 888 8888888P'' 8888888P''' Write-Information -InformationAction Continue '' # The launcher Write-Information -InformationAction Continue 'Fetching the latest surreal launcher...' $latestFile = Join-Path $Work 'latest' # `latest.txt` names a stable launcher. Until one exists a pre-release is all # there is, and it is named by `beta.txt` or `alpha.txt` alone, so fall back # to those in the order the release channels offer them. $pointer = $null foreach ($channel in 'latest', 'beta', 'alpha') { $result = Save-Url "$root/cli/launcher/$channel.txt" $latestFile $SmallLimit 30 30 if ($result -eq 'ok') { $pointer = $channel; break } # Only an absent pointer moves on. A timeout or a server error would # otherwise install a pre-release while a stable launcher may exist. if ($result -ne 'absent') { Fail "could not fetch cli/launcher/$channel.txt within 30 seconds, so nothing was installed" } } if (-not $pointer) { Fail "cli/launcher publishes no latest, beta or alpha launcher at $root, so nothing was installed" } # The pointer's own value names the published directory and asset, build # metadata included, so it is kept whole. Only the comparison below drops # the `+...`: the binary reports the release without it. $launcher = 'v' + ([System.IO.File]::ReadAllText($latestFile) -replace '\s', '').TrimStart('v') if ($launcher -notmatch '^v[0-9]+\.[0-9]+\.[0-9]+') { Fail "$root/cli/launcher/$pointer.txt does not name a version" } Write-Information -InformationAction Continue "Installing surreal $launcher for $platform..." # On Windows the executable is published as it is, not in an archive, so # there is nothing to unpack once the digest has been checked. It is named # for the executable, as every product is: `surreal-v`. $new = Join-Path $Work 'surreal.exe' Save-Verified "$root/cli/launcher/$launcher/surreal-$launcher.$platform" 'exe' $new $said = Invoke-Bounded $new @('--version') 30 if ($null -eq $said) { Fail 'the downloaded launcher does not run on this machine, or did not answer within 30 seconds' } # The checksum proves the file arrived as published; only the binary's own # version proves it is the release the pointer names. Build metadata # (`+...`) names the same release. $reported = '' foreach ($word in ($said -split '\s+')) { if ($word -match '^v?([0-9]+\.[0-9]+\.[0-9]+[^+\s]*)') { $reported = $Matches[1]; break } } $named = ($launcher.Substring(1) -split '\+')[0] if ($reported -ne $named) { $shown = if ($reported) { $reported } else { 'no version' } Fail "the downloaded launcher reports $shown, but cli/launcher/$pointer.txt names $named, so nothing was installed" } # The database, through the launcher still in the temporary directory. An # existing `surreal.exe` - perhaps the database itself, from the previous # installer - is replaced only once this has worked, so a failed download # leaves the machine as it was. if ($options.InstallDb) { # A `db@spec` in -With names the release to pin, so it is installed # here, pinned, rather than latest followed by the -With loop, which # installs without pinning. It is the same rule install.sh applies. $spec = if ($options.Version) { $options.Version } elseif ($options.WithSpec) { $options.WithSpec } elseif ($options.Channel) { $options.Channel } else { 'latest' } Write-Information -InformationAction Continue "Installing the database (db@$spec)..." & $new install "db@$spec" --pin --no-input if ($LASTEXITCODE -ne 0) { Fail 'could not install the database' } # The exit criterion of a fresh install: the database runs with the # network forbidden. if ($null -eq (Invoke-Bounded $new @('db', '--version') 30 @{ SURREAL_CLI_OFFLINE = '1' })) { Fail 'the database was installed but does not run offline' } } # Where it goes: where the database's own Windows installer has always put # `surreal.exe`, so the launcher takes its place rather than sitting # beside it. That is `Program Files\SurrealDB` when it is writable, which # takes an elevated shell, and `%LOCALAPPDATA%\SurrealDB` otherwise. $programFiles = if ($env:ProgramFiles) { $env:ProgramFiles } else { 'C:\Program Files' } $system = Join-Path $programFiles 'SurrealDB' $user = Join-Path $env:LOCALAPPDATA 'SurrealDB' $default = if (Test-Writable $system) { $system } else { $user } $loc = if ($InstallDir) { Expand-Home $InstallDir } else { $default } if (-not (Test-Writable $loc)) { if ($Interactive) { Write-Information -InformationAction Continue '' $answer = Read-Host "Where would you like to install 'surreal' [$user]?" $loc = if ($answer) { Expand-Home $answer } else { $user } } else { $loc = $user } if (-not (Test-Writable $loc)) { Fail "could not create $loc" } } $loc = (Resolve-Path -LiteralPath $loc).ProviderPath $target = Join-Path $loc 'surreal.exe' $isDefault = [string]::Equals($loc.TrimEnd('\'), $system.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase) -or [string]::Equals($loc.TrimEnd('\'), $user.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase) # Staged beside the target and renamed over it, so an existing `surreal.exe` # is replaced whole or not at all. Windows will not overwrite a running # `surreal.exe` but will rename it, so the old one is parked first, as # `.surreal.old.`: the name `surreal upgrade cli` parks under, and # clears once nothing is running it. $staged = Join-Path $loc '.surreal.new.exe' $parked = $null try { Copy-Item -LiteralPath $new -Destination $staged -Force if (Test-Path -LiteralPath $target) { $parked = Join-Path $loc ".surreal.old.$([System.IO.Path]::GetRandomFileName())" Move-Item -LiteralPath $target -Destination $parked } Move-Item -LiteralPath $staged -Destination $target } catch { if ($parked -and -not (Test-Path -LiteralPath $target)) { Move-Item -LiteralPath $parked -Destination $target -ErrorAction SilentlyContinue } Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue Fail "could not install 'surreal' into ${loc}: $_" } Write-Shadowed $target # Anything else asked for if ($options.Components.Count -gt 0) { $failed = @() foreach ($component in $options.Components) { # The database was installed and pinned above. Naming it again would # fetch it again, and a bare `db` is `latest`, a remote lookup. if ($component -ceq 'db' -or $component -clike 'db@*') { continue } Write-Information -InformationAction Continue "Installing $component..." & $target install $component --no-input if ($LASTEXITCODE -ne 0) { $failed += $component } } if ($failed.Count -gt 0) { $ready = if ($options.InstallDb) { "'surreal' and the database are ready." } else { "'surreal' is ready." } [Console]::Error.WriteLine('') [Console]::Error.WriteLine("Warning: not installed: $($failed -join ' '). $ready") } } # A component that failed is advisory, and the launcher itself is installed, # so the install succeeded. The native command's status would otherwise stay # in $LASTEXITCODE for a caller of `irm | iex` or a script block to read. $global:LASTEXITCODE = 0 Write-Information -InformationAction Continue '' Write-Information -InformationAction Continue 'SurrealDB successfully installed in:' Write-Information -InformationAction Continue " $target" Write-Information -InformationAction Continue '' # A default location goes on the user's PATH, as the database's installer # always did, unless it is already there; this session's PATH gets it too. # A directory someone chose is theirs to add. $userPath = [Environment]::GetEnvironmentVariable('Path', 'User') $inUserPath = @("$userPath" -split ';' | Where-Object { $_ } | ForEach-Object { $_.TrimEnd('\') }) -contains $loc.TrimEnd('\') if ($isDefault -and -not $inUserPath) { $joined = if ($userPath) { $userPath.TrimEnd(';') + ';' + $loc } else { $loc } [Environment]::SetEnvironmentVariable('Path', $joined, 'User') $env:PATH = $env:PATH.TrimEnd(';') + ';' + $loc } $onPath = @($env:PATH -split ';' | Where-Object { $_ } | ForEach-Object { $_.TrimEnd('\') }) -contains $loc.TrimEnd('\') if (-not $onPath) { Write-Information -InformationAction Continue 'To ensure that surreal is in your PATH run:' Write-Information -InformationAction Continue " [Environment]::SetEnvironmentVariable('Path', `"$loc;`" + [Environment]::GetEnvironmentVariable('Path', 'User'), 'User')" Write-Information -InformationAction Continue 'and open a new terminal.' Write-Information -InformationAction Continue '' } if (-not $options.InstallDb) { Write-Information -InformationAction Continue 'The database was not installed (-NoDb); it installs on first use. To install it now run:' Write-Information -InformationAction Continue ' surreal install db' } Write-Information -InformationAction Continue 'To see what is installed run:' Write-Information -InformationAction Continue ' surreal list' Write-Information -InformationAction Continue 'To start an in-memory database server run:' Write-Information -InformationAction Continue ' surreal db start --log debug --user root --pass root memory' Write-Information -InformationAction Continue 'For help with getting started visit:' Write-Information -InformationAction Continue ' https://surrealdb.com/docs' Write-Information -InformationAction Continue '' } $Work = $null try { Install-Surreal -InstallDir $InstallDir -Version $Version -Nightly:$Nightly -Beta:$Beta ` -Alpha:$Alpha -Db:$Db -NoDb:$NoDb -With $With -Minimal:$Minimal -Interactive:$Interactive } catch { [Console]::Error.WriteLine("Error: $($_.Exception.Message)") if ($RunFromFile) { exit 1 } $global:LASTEXITCODE = 1 return } finally { if ($Work -and (Test-Path -LiteralPath $Work)) { Remove-Item -LiteralPath $Work -Recurse -Force -ErrorAction SilentlyContinue } }