@adrifer/winix 0.2.4-preview.2 → 0.3.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Repository mode never installs Nix or changes the system before confirmation.
5
+ if [[ "${1:-}" == --help || "${1:-}" == -h ]]; then
6
+ printf '%s\n' \
7
+ 'Usage: bash bootstrap-linux.sh --repository HTTPS_URL --ref BRANCH --host HOST [--destination PATH] [--config-directory winix] [--prepare-only] [--dry-run] [--yes]' \
8
+ 'Uses existing Nix for temporary Git/Python tools, or requires installed git and python3.' \
9
+ 'No Node/npm, package installation, reboot, checkout reset, or activation without confirmation.'
10
+ exit 0
11
+ fi
12
+
13
+ arguments=("$@")
14
+ repository='' hostname='' dry_run=0
15
+ while (($#)); do
16
+ case "$1" in
17
+ --repository|--ref|--host|--destination|--config-directory)
18
+ [[ $# -ge 2 && -n "$2" && "$2" != -* ]] || { echo "Missing value for $1" >&2; exit 2; }
19
+ case "$1" in
20
+ --repository) repository="$2" ;;
21
+ --host) hostname="$2" ;;
22
+ esac
23
+ shift 2 ;;
24
+ --dry-run) dry_run=1; shift ;;
25
+ --yes|--prepare-only) shift ;;
26
+ *) echo "Unknown bootstrap option: $1" >&2; exit 2 ;;
27
+ esac
28
+ done
29
+ [[ -n "$repository" && -n "$hostname" ]] || { echo '--repository and --host are required; see --help' >&2; exit 2; }
30
+ [[ "$repository" == https://* && "$repository" != *'@'* && "$repository" != *'?'* && "$repository" != *'#'* ]] || {
31
+ echo 'Repository must be HTTPS without credentials, query, or fragment' >&2; exit 2;
32
+ }
33
+ set -- "${arguments[@]}"
34
+ if ((dry_run)); then
35
+ printf '%s\n' 'Dry run: would validate arguments, ensure temporary tools, clone/validate the checkout, read its exact Winix pin, verify release downloads, then preview/confirm activation. No changes or config evaluation performed.'
36
+ exit 0
37
+ fi
38
+
39
+ if [[ "${WINIX_BOOTSTRAP_TOOLS:-}" != 1 ]] && command -v nix >/dev/null 2>&1; then
40
+ printf '%s\n' 'Preparing a temporary Git/Python environment using existing Nix; no profile changes.'
41
+ export WINIX_BOOTSTRAP_TOOLS=1
42
+ export NIX_CONFIG="${NIX_CONFIG:+$NIX_CONFIG$'\n'}extra-experimental-features = nix-command flakes"
43
+ pin='github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f'
44
+ exec nix shell --no-write-lock-file "$pin#git" "$pin#python3" "$pin#bash" \
45
+ --command bash "$0" "$@"
46
+ fi
47
+ command -v git >/dev/null 2>&1 || { echo 'Git is required. Install it through your approved package manager, or provide an existing Nix installation.' >&2; exit 1; }
48
+ command -v python3 >/dev/null 2>&1 || { echo 'Python 3 is required for bootstrap JSON and HTTPS handling; Node/npm are not needed.' >&2; exit 1; }
49
+
50
+ python3 - "$@" <<'PY'
51
+ import argparse
52
+ import hashlib
53
+ import json
54
+ import os
55
+ from pathlib import Path
56
+ import platform
57
+ import re
58
+ import shlex
59
+ import shutil
60
+ import subprocess
61
+ import sys
62
+ import tempfile
63
+ import urllib.request
64
+ from urllib.parse import urlparse
65
+
66
+
67
+ def run(args, cwd=None, capture=False):
68
+ return subprocess.run(args, cwd=cwd, check=True, text=True,
69
+ stdout=subprocess.PIPE if capture else None).stdout
70
+
71
+
72
+ def confirm(message, yes):
73
+ if yes:
74
+ return
75
+ # stdin contains this script, not an interactive terminal.
76
+ try:
77
+ with open("/dev/tty", "r+") as tty:
78
+ tty.write(message + " [y/N] ")
79
+ tty.flush()
80
+ answer = tty.readline().strip().lower()
81
+ except OSError as error:
82
+ raise RuntimeError("Interactive confirmation unavailable; pass --yes only after reviewing the repository/script") from error
83
+ if answer not in ("y", "yes"):
84
+ raise RuntimeError("Bootstrap cancelled")
85
+
86
+
87
+ def safe_directory(path):
88
+ for current in (path, *path.parents):
89
+ if current.is_symlink() or (current.exists() and not current.is_dir()):
90
+ raise RuntimeError("Unsafe bootstrap directory: " + str(current))
91
+
92
+
93
+ class HTTPSRedirects(urllib.request.HTTPRedirectHandler):
94
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
95
+ if urlparse(newurl).scheme != "https":
96
+ raise RuntimeError("Refusing non-HTTPS download redirect")
97
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
98
+
99
+
100
+ opener = urllib.request.build_opener(HTTPSRedirects)
101
+
102
+
103
+ def fetch(url):
104
+ with opener.open(url, timeout=90) as response:
105
+ return response.read()
106
+
107
+
108
+ def download(release, name, destination):
109
+ sums = fetch(release + "/SHA256SUMS").decode("utf-8")
110
+ entries = re.findall(r"^([a-fA-F0-9]{64})\s+\*?" + re.escape(name) + r"$", sums, re.M)
111
+ if len(entries) != 1:
112
+ raise RuntimeError("Missing or duplicate release checksum for " + name)
113
+ if destination.is_symlink():
114
+ raise RuntimeError("Refusing linked executable destination")
115
+ expected = entries[0].lower()
116
+ if destination.is_file() and hashlib.sha256(destination.read_bytes()).hexdigest() == expected:
117
+ return
118
+ data = fetch(release + "/" + name)
119
+ if hashlib.sha256(data).hexdigest() != expected:
120
+ raise RuntimeError("Executable checksum mismatch; nothing was executed")
121
+ fd, temporary = tempfile.mkstemp(prefix=".download-", dir=destination.parent)
122
+ try:
123
+ with os.fdopen(fd, "wb") as stream:
124
+ stream.write(data)
125
+ os.chmod(temporary, 0o755)
126
+ os.replace(temporary, destination)
127
+ finally:
128
+ if os.path.exists(temporary):
129
+ os.unlink(temporary)
130
+
131
+
132
+ def main():
133
+ parser = argparse.ArgumentParser()
134
+ parser.add_argument("--repository", required=True)
135
+ parser.add_argument("--ref", default="main")
136
+ parser.add_argument("--host", required=True)
137
+ parser.add_argument("--destination", default=str(Path.home() / "dotfiles"))
138
+ parser.add_argument("--config-directory", default="winix")
139
+ parser.add_argument("--prepare-only", action="store_true")
140
+ parser.add_argument("--yes", action="store_true")
141
+ args = parser.parse_args()
142
+ uri = urlparse(args.repository)
143
+ if uri.scheme != "https" or not uri.hostname or uri.username or uri.password or uri.query or uri.fragment:
144
+ raise RuntimeError("Repository must be HTTPS without credentials, query, or fragment")
145
+ if not args.ref or args.ref.startswith("-") or any(c in args.ref + args.host for c in "\x00\r\n"):
146
+ raise RuntimeError("Invalid host/ref")
147
+ subdir = Path(args.config_directory)
148
+ if subdir.is_absolute() or ".." in subdir.parts:
149
+ raise RuntimeError("config-directory must be inside the checkout")
150
+ destination = Path(os.path.abspath(os.path.expanduser(args.destination)))
151
+ safe_directory(destination)
152
+ confirm("Trust " + args.repository + " and allow cloning/downloads? Config evaluation is confirmed separately.", args.yes)
153
+ if not destination.exists():
154
+ run(["git", "clone", "--origin", "origin", "--", args.repository, str(destination)])
155
+ run(["git", "checkout", args.ref], destination)
156
+ if not (destination / ".git").is_dir():
157
+ raise RuntimeError("Existing destination is not a regular Git checkout; refusing adoption")
158
+ safe_directory(destination / ".git")
159
+ if run(["git", "remote", "get-url", "origin"], destination, True).strip() != args.repository:
160
+ raise RuntimeError("Existing checkout has a different origin")
161
+ if run(["git", "status", "--porcelain", "--untracked-files=normal"], destination, True).strip():
162
+ raise RuntimeError("Checkout has local changes; bootstrap never resets, cleans, or stashes them")
163
+ head = run(["git", "rev-parse", "HEAD"], destination, True).strip()
164
+ wanted = run(["git", "rev-parse", "--verify", args.ref + "^{commit}"], destination, True).strip()
165
+ if head != wanted:
166
+ raise RuntimeError("Existing checkout differs from the requested local ref; switch it explicitly. No automatic pull/reset.")
167
+ config = destination / subdir
168
+ safe_directory(config)
169
+ package = json.loads((config / "package.json").read_text())
170
+ spec = package.get("dependencies", {}).get("@adrifer/winix") or package.get("devDependencies", {}).get("@adrifer/winix")
171
+ if not isinstance(spec, str):
172
+ raise RuntimeError("Missing exact @adrifer/winix dependency")
173
+ version = spec if re.fullmatch(r"\d+\.\d+\.\d+(?:-preview\.\d+)?", spec) else None
174
+ if not version:
175
+ match = re.fullmatch(r"https://github\.com/adrifer/winix/releases/download/v(\d+\.\d+\.\d+(?:-preview\.\d+)?)/adrifer-winix-\1\.tgz", spec)
176
+ if not match:
177
+ raise RuntimeError("Winix pin must be an exact version or matching official release SDK URL")
178
+ version = match[1]
179
+ architecture = {"x86_64": "x64", "aarch64": "arm64"}.get(platform.machine())
180
+ if not architecture or sys.platform != "linux":
181
+ raise RuntimeError("Supported standalone targets: Linux x64 and ARM64")
182
+ runtime = config / ".winix" / "runtime" / version
183
+ safe_directory(runtime)
184
+ runtime.mkdir(parents=True, exist_ok=True)
185
+ release = "https://github.com/adrifer/winix/releases/download/v" + version
186
+ binary = runtime / "winix.bin"
187
+ download(release, "winix-linux-" + architecture, binary)
188
+ nixos = Path("/etc/NIXOS").exists()
189
+ launcher = runtime / "winix"
190
+ if launcher.is_symlink() or (launcher.exists() and not launcher.is_file()):
191
+ raise RuntimeError("Unsafe runtime launcher")
192
+ if nixos:
193
+ if not shutil.which("nix"):
194
+ raise RuntimeError("Existing NixOS installation must provide nix")
195
+ pin = "github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f"
196
+ for name, output in (("libc", "glibc.out"), ("compiler", "stdenv.cc.cc.lib")):
197
+ run(["nix", "build", "--no-write-lock-file", "--out-link", str(runtime / name), pin + "#" + output])
198
+ linker = "ld-linux-x86-64.so.2" if architecture == "x64" else "ld-linux-aarch64.so.1"
199
+ command = [str(runtime / "libc" / "lib" / linker), "--argv0", str(binary),
200
+ "--library-path", str(runtime / "libc" / "lib") + ":" + str(runtime / "compiler" / "lib"), str(binary)]
201
+ else:
202
+ command = [str(binary)]
203
+ if launcher.exists() and not launcher.read_text().startswith("#!/usr/bin/env bash\n# Generated by Winix bootstrap\n"):
204
+ raise RuntimeError("Refusing to overwrite an unrecognized runtime launcher")
205
+ launcher.write_text("#!/usr/bin/env bash\n# Generated by Winix bootstrap\nset -euo pipefail\nexport WINIX_STANDALONE_EXECUTABLE=" +
206
+ shlex.quote(str(launcher)) + "\nexec " + shlex.join(command) + ' "$@"\n')
207
+ launcher.chmod(0o755)
208
+ if run([str(launcher), "--version"], config, True).strip() != version:
209
+ raise RuntimeError("Executable version does not match the checkout")
210
+ command = [str(launcher), "bootstrap", "--host", args.host]
211
+ if args.prepare_only:
212
+ command.append("--prepare-only")
213
+ if args.yes:
214
+ command.append("--yes")
215
+ # Config confirmations in Winix require a terminal, not the Python source pipe.
216
+ with open("/dev/tty", "r") if not args.yes else open(os.devnull) as input_stream:
217
+ subprocess.run(command, cwd=config, stdin=input_stream, check=True)
218
+
219
+
220
+ if __name__ == "__main__":
221
+ try:
222
+ main()
223
+ except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error:
224
+ print("Winix bootstrap failed: " + str(error), file=sys.stderr)
225
+ sys.exit(1)
226
+ PY
@@ -1,7 +1,7 @@
1
1
  #Requires -Version 5.1
2
2
  <#
3
3
  .SYNOPSIS
4
- Checks or installs the Windows prerequisites for Winix, without activating a host.
4
+ Checks/installs Winix prerequisites, or prepares a trusted repository and confirms host activation.
5
5
  .PARAMETER Check
6
6
  Only inspect prerequisites. No installation or configuration enablement is performed.
7
7
  .PARAMETER Yes
@@ -10,13 +10,28 @@ Accept prerequisite installation and WinGet configuration enablement without pro
10
10
  Install/select Node LTS through NVM for Windows instead of standalone Node.js.
11
11
  .PARAMETER Standalone
12
12
  Check/install only native prerequisites for the Winix executable; Node.js/npm are not needed.
13
+ .PARAMETER Repository
14
+ Opt into HTTPS repository bootstrap. The checkout's exact SDK pin selects the executable.
15
+ .PARAMETER HostName
16
+ Declared Winix target for repository mode; does not rename Windows.
17
+ .PARAMETER PrepareOnly
18
+ Prepare prerequisites/runtime and validate/preview the repository without activating a host.
19
+ .PARAMETER DryRun
20
+ Describe repository bootstrap without downloads, installation, cloning or config evaluation.
13
21
  #>
14
22
  [CmdletBinding()]
15
23
  param(
16
24
  [switch]$Check,
17
25
  [switch]$Yes,
18
26
  [switch]$UseNvm,
19
- [switch]$Standalone
27
+ [switch]$Standalone,
28
+ [string]$Repository,
29
+ [string]$Ref = 'main',
30
+ [string]$Destination = (Join-Path $HOME 'dotfiles'),
31
+ [string]$ConfigDirectory = 'winix',
32
+ [string]$HostName,
33
+ [switch]$PrepareOnly,
34
+ [switch]$DryRun
20
35
  )
21
36
 
22
37
  function Get-WinixBootstrapApplication {
@@ -110,7 +125,7 @@ function Test-WinixBootstrapCapabilities {
110
125
  $script = @'
111
126
  $ErrorActionPreference = 'Stop'
112
127
  Get-Command Find-PSResource, Install-PSResource -ErrorAction Stop | Out-Null
113
- Get-PSResourceRepository -Name PSGallery -ErrorAction Stop | Out-Null
128
+ Get-Command Get-PSResourceRepository, Register-PSResourceRepository -ErrorAction Stop | Out-Null
114
129
  '@
115
130
  $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script))
116
131
  Invoke-WinixBootstrapNative $pwsh @('-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', $encoded) | Out-Null
@@ -128,7 +143,7 @@ Get-PSResourceRepository -Name PSGallery -ErrorAction Stop | Out-Null
128
143
  }
129
144
  }
130
145
  if (-not $Standalone) { Write-Host 'OK: npm and Node TypeScript support.' }
131
- Write-Host 'OK: PSResourceGet/PSGallery and required DSC resources.'
146
+ Write-Host 'OK: PSResourceGet and required DSC resources (repository selection belongs to the host config).'
132
147
  }
133
148
 
134
149
  function Invoke-WinixWindowsBootstrap {
@@ -215,9 +230,174 @@ Then rerun this bootstrap. No prerequisites have been installed.
215
230
  Write-Host 'Open a new PowerShell 7 terminal before preparing the Winix/config checkout and running winix check or switch --dry.'
216
231
  }
217
232
 
233
+ function Assert-WinixBootstrapDirectory {
234
+ param([string]$Path)
235
+ $current = [IO.Path]::GetFullPath($Path)
236
+ while ($current) {
237
+ if (Test-Path -LiteralPath $current) {
238
+ $item = Get-Item -LiteralPath $current -Force
239
+ if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
240
+ throw "Unsafe bootstrap directory (not a directory or is a link): $current"
241
+ }
242
+ }
243
+ $parent = Split-Path $current -Parent
244
+ if ($parent -eq $current) { break }
245
+ $current = $parent
246
+ }
247
+ }
248
+
249
+ function Get-WinixCheckoutVersion {
250
+ param([string]$Directory)
251
+ $package = Get-Content -LiteralPath (Join-Path $Directory 'package.json') -Raw | ConvertFrom-Json
252
+ $spec = $package.dependencies.'@adrifer/winix'
253
+ if (-not $spec) { $spec = $package.devDependencies.'@adrifer/winix' }
254
+ if ($spec -isnot [string]) { throw 'Checkout must declare a string-valued exact @adrifer/winix dependency.' }
255
+ if ($spec -match '^\d+\.\d+\.\d+(?:-preview\.\d+)?$') { return $spec }
256
+ if ($spec -match '^https://github\.com/adrifer/winix/releases/download/v(\d+\.\d+\.\d+(?:-preview\.\d+)?)/adrifer-winix-\1\.tgz$') {
257
+ return $Matches[1]
258
+ }
259
+ throw 'Checkout must pin an exact @adrifer/winix version or matching official GitHub release SDK URL.'
260
+ }
261
+
262
+ function Invoke-WinixBootstrapHost {
263
+ param([string]$Binary, [string[]]$Arguments)
264
+ & $Binary @Arguments
265
+ if ($LASTEXITCODE -ne 0) { throw "Winix bootstrap failed (exit $LASTEXITCODE). Resolve the error and rerun; no checkout reset/reboot is performed." }
266
+ }
267
+
268
+ function Get-WinixBootstrapSha256 {
269
+ param([string]$Path)
270
+ $stream = [IO.File]::OpenRead($Path)
271
+ $algorithm = [Security.Cryptography.SHA256]::Create()
272
+ try { return [BitConverter]::ToString($algorithm.ComputeHash($stream)).Replace('-', '') }
273
+ finally { $algorithm.Dispose(); $stream.Dispose() }
274
+ }
275
+
276
+ function Save-WinixVerifiedDownload {
277
+ param([string]$Url, [string]$ChecksumUrl, [string]$Asset, [string]$Destination)
278
+ if (Test-Path -LiteralPath $Destination) {
279
+ if ((Get-Item -LiteralPath $Destination -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
280
+ throw "Refusing linked download destination: $Destination"
281
+ }
282
+ }
283
+ $temporary = "$Destination.$([guid]::NewGuid().ToString('N')).download"
284
+ try {
285
+ $sums = (Invoke-WebRequest -UseBasicParsing -Uri $ChecksumUrl -TimeoutSec 90).Content
286
+ if ($sums -is [byte[]]) { $sums = [Text.Encoding]::UTF8.GetString($sums) }
287
+ $entries = @($sums -split '\r?\n' | Where-Object { $_ -match ('^[a-fA-F0-9]{64}\s+\*?' + [regex]::Escape($Asset) + '$') })
288
+ if ($entries.Count -ne 1) { throw "Release checksum missing or duplicated for $Asset" }
289
+ $expected = ($entries[0] -split '\s+')[0]
290
+ if ((Test-Path -LiteralPath $Destination) -and (Get-WinixBootstrapSha256 $Destination) -eq $expected) {
291
+ return
292
+ }
293
+ Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $temporary -TimeoutSec 90
294
+ if ((Get-WinixBootstrapSha256 $temporary) -ne $expected) {
295
+ throw "Release checksum mismatch for $Asset; nothing was executed"
296
+ }
297
+ Move-Item -LiteralPath $temporary -Destination $Destination -Force
298
+ } finally {
299
+ if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
300
+ }
301
+ }
302
+
303
+ function Invoke-WinixRepositoryBootstrap {
304
+ param(
305
+ [string]$Repository, [string]$Ref = 'main', [string]$Destination = (Join-Path $HOME 'dotfiles'), [string]$ConfigDirectory = 'winix',
306
+ [string]$HostName, [switch]$Yes, [switch]$PrepareOnly, [switch]$DryRun
307
+ )
308
+ $ErrorActionPreference = 'Stop'
309
+ $uri = $null
310
+ if (-not [uri]::TryCreate($Repository, [UriKind]::Absolute, [ref]$uri) -or
311
+ $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) {
312
+ throw 'Repository must be HTTPS without credentials, query, or fragment.'
313
+ }
314
+ if (-not $HostName -or $HostName.StartsWith('-') -or $HostName -match '[\x00\r\n]') { throw '-HostName requires a declared host name, not a Windows rename.' }
315
+ if (-not $Ref -or $Ref.StartsWith('-') -or $Ref -match '[\x00\r\n]') { throw 'Invalid repository ref.' }
316
+ if ([IO.Path]::IsPathRooted($ConfigDirectory) -or $ConfigDirectory -match '(^|[\\/])\.\.([\\/]|$)' -or $ConfigDirectory -match '[:\x00\r\n]') {
317
+ throw 'ConfigDirectory must be inside the checkout.'
318
+ }
319
+ $Destination = [IO.Path]::GetFullPath($Destination)
320
+ Assert-WinixBootstrapDirectory $Destination
321
+ $config = [IO.Path]::GetFullPath((Join-Path $Destination $ConfigDirectory))
322
+ if ($DryRun) {
323
+ Write-Host "Would ensure Git, clone/validate $Repository ($Ref) at $Destination, read its Winix pin, verify downloads, prepare prerequisites and preview host $HostName. No changes or config evaluation performed."
324
+ return
325
+ }
326
+ Write-Host "Repository: $Repository ($Ref), checkout: $Destination, config: $config, host: $HostName"
327
+ if (-not $Yes) {
328
+ if ([Console]::IsInputRedirected) { throw 'Noninteractive repository bootstrap requires -Yes.' }
329
+ if ((Read-Host 'Trust this repository and allow bootstrap downloads/prerequisite installation? [y/N]').Trim() -notmatch '^(?i:y|yes)$') {
330
+ throw 'Bootstrap cancelled.'
331
+ }
332
+ }
333
+ Update-WinixBootstrapPath
334
+ $git = Get-WinixBootstrapApplication 'git.exe'
335
+ if (-not $git) {
336
+ $winget = Get-WinixBootstrapApplication 'winget.exe'
337
+ if (-not $winget) { throw 'WinGet is unavailable. Install App Installer, open a new terminal, and rerun.' }
338
+ Invoke-WinixBootstrapNative $winget @('install', '--id', 'Git.Git', '--exact', '--source', 'winget',
339
+ '--silent', '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity') | ForEach-Object { Write-Host $_ }
340
+ Update-WinixBootstrapPath
341
+ $git = Get-WinixBootstrapApplication 'git.exe'
342
+ if (-not $git) { throw 'Git is not ready. Open a new terminal or restart if requested, then rerun the same bootstrap.' }
343
+ }
344
+ if (-not (Test-Path -LiteralPath $Destination)) {
345
+ Invoke-WinixBootstrapNative $git @('clone', '--origin', 'origin', '--', $Repository, $Destination) | ForEach-Object { Write-Host $_ }
346
+ # A normal clone retains history; branch selection never advances on a later bootstrap.
347
+ if ($Ref -ne 'main' -or (Invoke-WinixBootstrapNative $git @('-C', $Destination, 'branch', '--show-current')) -ne 'main') {
348
+ Invoke-WinixBootstrapNative $git @('-C', $Destination, 'checkout', $Ref) | ForEach-Object { Write-Host $_ }
349
+ }
350
+ }
351
+ if (-not (Test-Path -LiteralPath (Join-Path $Destination '.git') -PathType Container)) { throw 'Existing destination is not a regular Git checkout; refusing adoption.' }
352
+ Assert-WinixBootstrapDirectory (Join-Path $Destination '.git')
353
+ if (((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'remote', 'get-url', 'origin')) -join '').Trim() -ne $Repository) {
354
+ throw 'Existing checkout has a different origin; refusing to change it.'
355
+ }
356
+ if ((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'status', '--porcelain', '--untracked-files=normal'))) {
357
+ throw 'Checkout has local changes. Commit/stash them explicitly; bootstrap never resets or cleans files.'
358
+ }
359
+ $head = ((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'rev-parse', 'HEAD')) -join '').Trim()
360
+ $wanted = ((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'rev-parse', '--verify', "$Ref^{commit}")) -join '').Trim()
361
+ if ($head -ne $wanted) { throw 'Existing checkout is not at the requested local ref; switch it explicitly. Bootstrap never pulls or resets.' }
362
+ Assert-WinixBootstrapDirectory $config
363
+ $version = Get-WinixCheckoutVersion $config
364
+ $architecture = [Environment]::GetEnvironmentVariable('PROCESSOR_ARCHITEW6432')
365
+ if (-not $architecture) { $architecture = $env:PROCESSOR_ARCHITECTURE }
366
+ switch ($architecture.ToUpperInvariant()) {
367
+ 'AMD64' { $asset = 'winix-windows-x64.exe' }
368
+ 'ARM64' { $asset = 'winix-windows-arm64.exe' }
369
+ default { throw "Unsupported Windows architecture: $architecture" }
370
+ }
371
+ $runtime = Join-Path $config ".winix\runtime\$version"
372
+ Assert-WinixBootstrapDirectory $runtime
373
+ New-Item -ItemType Directory -Path $runtime -Force | Out-Null
374
+ $release = "https://github.com/adrifer/winix/releases/download/v$version"
375
+ $binary = Join-Path $runtime 'winix.exe'
376
+ Save-WinixVerifiedDownload "$release/$asset" "$release/SHA256SUMS" $asset $binary
377
+ $prerequisites = Join-Path $runtime 'bootstrap-windows.ps1'
378
+ Save-WinixVerifiedDownload "$release/bootstrap-windows.ps1" "$release/bootstrap-windows.ps1.sha256" 'bootstrap-windows.ps1' $prerequisites
379
+ if (((Invoke-WinixBootstrapNative $binary @('--version')) -join '').Trim() -ne $version) { throw 'Downloaded executable version does not match the checkout.' }
380
+ & $prerequisites -Standalone -Yes
381
+ if (-not $?) { throw 'Prerequisites failed; resolve the error/reboot manually, then rerun the same bootstrap.' }
382
+ $arguments = @('bootstrap', '--host', $HostName)
383
+ if ($PrepareOnly) { $arguments += '--prepare-only' }
384
+ if ($Yes) { $arguments += '--yes' }
385
+ Push-Location -LiteralPath $config
386
+ try { Invoke-WinixBootstrapHost $binary $arguments }
387
+ finally { Pop-Location }
388
+ }
389
+
218
390
  if ($MyInvocation.InvocationName -ne '.') {
219
391
  try {
220
- Invoke-WinixWindowsBootstrap -Check:$Check -Yes:$Yes -UseNvm:$UseNvm -Standalone:$Standalone
392
+ if ($Repository) {
393
+ if ($Check -or $UseNvm) { throw 'Repository mode cannot be combined with -Check or -UseNvm; it always uses standalone prerequisites.' }
394
+ Invoke-WinixRepositoryBootstrap -Repository $Repository -Ref $Ref -Destination $Destination `
395
+ -ConfigDirectory $ConfigDirectory -HostName $HostName -Yes:$Yes -PrepareOnly:$PrepareOnly -DryRun:$DryRun
396
+ } elseif ($DryRun -or $PrepareOnly -or $HostName) {
397
+ throw '-DryRun, -PrepareOnly and -HostName require -Repository. Use -Check for prerequisite-only inspection.'
398
+ } else {
399
+ Invoke-WinixWindowsBootstrap -Check:$Check -Yes:$Yes -UseNvm:$UseNvm -Standalone:$Standalone
400
+ }
221
401
  } catch {
222
402
  Write-Error $_ -ErrorAction Continue
223
403
  exit 1