-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbootstrap.ps1
More file actions
executable file
·364 lines (297 loc) · 10.9 KB
/
Copy pathbootstrap.ps1
File metadata and controls
executable file
·364 lines (297 loc) · 10.9 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#
# WINDOWS 11 BOOTSTRAP
#
# This script links files under WSL's ~/.dotfiles/windows/ directory into the
# Windows user profile. It expects the repository to exist in WSL and does not
# clone or download repository files into Windows. Linux symlinks under windows/
# are resolved in WSL before Windows symlinks are created.
#
# From PowerShell:
# & ([scriptblock]::Create((
# wsl.exe --distribution Ubuntu --exec bash -lc 'cat ~/.dotfiles/bootstrap.ps1'
# ) -join [Environment]::NewLine))
[CmdletBinding()]
param ()
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSVersion -lt [Version]'5.1')
{
throw 'PowerShell 5.1 or later is required.'
}
# Windows PowerShell 5.1's New-Item -ItemType SymbolicLink does not honor
# Developer Mode, so call CreateSymbolicLinkW with the unprivileged flag directly.
if (-not ('DotfilesSymbolicLink' -as [type]))
{
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
public static class DotfilesSymbolicLink
{
private const int SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1;
private const int SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x2;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateSymbolicLinkW", SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
private static extern bool CreateSymbolicLink(string linkPath, string targetPath, int flags);
public static void Create(string linkPath, string targetPath, bool isDirectory)
{
int flags = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
if (isDirectory)
{
flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
}
if (!CreateSymbolicLink(linkPath, targetPath, flags))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
'@
}
function Get-ErrorMessage ([Exception] $exception)
{
$currentException = $exception
while (($null -ne $currentException) -and ($null -ne $currentException.InnerException))
{
$currentException = $currentException.InnerException
}
if ($null -eq $currentException)
{
return ''
}
return $currentException.Message
}
function Join-TargetPath ([string] $basePath, [string] $relativePath)
{
$targetPath = $basePath
foreach ($relativePathSegment in ($relativePath -split '/'))
{
if ([string]::IsNullOrWhiteSpace($relativePathSegment))
{
continue
}
$targetPath = Join-Path -Path $targetPath -ChildPath $relativePathSegment
}
return $targetPath
}
function Test-CopyRelativePath ([string] $relativePath, [string[]] $prefixes)
{
foreach ($prefix in $prefixes)
{
if ($relativePath.StartsWith($prefix, [StringComparison]::Ordinal))
{
return $true
}
}
return $false
}
Write-Host 'Starting Windows bootstrap...'
$homePath = [Environment]::GetFolderPath('UserProfile')
if ([string]::IsNullOrWhiteSpace($homePath))
{
throw 'Windows user profile path could not be resolved.'
}
$wslDistribution = 'Ubuntu'
Write-Host "Resolving dotfiles path from WSL distribution: $wslDistribution..."
if (-not (Get-Command 'wsl.exe' -ErrorAction SilentlyContinue))
{
throw "wsl.exe was not found. This bootstrap expects the $wslDistribution WSL distribution with ~/.dotfiles."
}
$wslListScript = @'
set -eu
dotfiles_path="$(cd "$HOME/.dotfiles" 2>/dev/null && pwd -P)"
windows_path="$dotfiles_path/windows"
[ -d "$windows_path" ]
printf 'ROOT\t%s\n' "$(wslpath -w "$dotfiles_path")"
cd "$windows_path"
find . \( -type f -o -type l \) -print | sort | while IFS= read -r source_path
do
relative_path="${source_path#./}"
resolved_path="$(readlink -f "$source_path")"
if [ -d "$resolved_path" ]; then source_type='Directory'; else source_type='File'; fi
source_windows_path="$(wslpath -w "$resolved_path")"
printf 'ENTRY\t%s\t%s\t%s\n' "$relative_path" "$source_type" "$source_windows_path"
done
'@
# Windows PowerShell writes CRLF to native command stdin; remove CR before Bash parses the script.
$wslOutput = $wslListScript | & wsl.exe --distribution $wslDistribution --exec bash -c "tr -d '\r' | bash -s"
if ($LASTEXITCODE -ne 0)
{
throw "Windows dotfiles could not be listed from the $wslDistribution distribution. Ensure ~/.dotfiles/windows exists in WSL."
}
$dotfilesPath = ''
$linkEntries = @()
foreach ($wslOutputLine in $wslOutput)
{
if ([string]::IsNullOrWhiteSpace($wslOutputLine))
{
continue
}
$wslOutputFields = $wslOutputLine.Replace("`r", "") -split "`t", 4
if ($wslOutputFields[0] -eq 'ROOT')
{
if ($wslOutputFields.Count -ne 2)
{
throw "Invalid WSL root output: $wslOutputLine"
}
$dotfilesPath = $wslOutputFields[1]
continue
}
if ($wslOutputFields[0] -eq 'ENTRY')
{
if ($wslOutputFields.Count -ne 4)
{
throw "Invalid WSL entry output: $wslOutputLine"
}
if (($wslOutputFields[2] -ne 'File') -and ($wslOutputFields[2] -ne 'Directory'))
{
throw "Invalid WSL entry type: $wslOutputLine"
}
$linkEntries += [PSCustomObject] @{
RelativePath = $wslOutputFields[1]
IsDirectory = ($wslOutputFields[2] -eq 'Directory')
SourcePath = $wslOutputFields[3]
}
continue
}
throw "Unexpected WSL output: $wslOutputLine"
}
if ([string]::IsNullOrWhiteSpace($dotfilesPath))
{
throw "WSL returned an empty dotfiles path. Ensure ~/.dotfiles exists in the $wslDistribution distribution."
}
$sourceRoot = "$dotfilesPath\windows"
Write-Host "Using WSL dotfiles path: $dotfilesPath"
Write-Host "Link source: $sourceRoot"
Write-Host "Link target: $homePath"
# Codex Desktop may read files through WSL's /mnt/c path. That path can fail
# on Windows symlinks whose targets are WSL UNC paths, so materialize .codex.
# @see https://github.com/openai/codex/issues/18506
$copyRelativePathPrefixes = @(
'.codex/'
)
$linkPreflightEntries = @($linkEntries | Where-Object { -not (Test-CopyRelativePath $_.RelativePath $copyRelativePathPrefixes) })
if ($linkPreflightEntries.Count -gt 0)
{
$preflightDirectory = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath "dotfiles-bootstrap-$([Guid]::NewGuid().ToString('N'))"
$preflightEntries = @()
$preflightEntries += @($linkPreflightEntries | Where-Object { -not $_.IsDirectory } | Select-Object -First 1)
$preflightEntries += @($linkPreflightEntries | Where-Object { $_.IsDirectory } | Select-Object -First 1)
New-Item -ItemType Directory -Path $preflightDirectory -Force | Out-Null
try
{
$preflightIndex = 0
foreach ($preflightEntry in $preflightEntries)
{
if ($null -eq $preflightEntry)
{
continue
}
$preflightLinkPath = Join-Path -Path $preflightDirectory -ChildPath "symlink-test-$preflightIndex"
$preflightSourcePath = $preflightEntry.SourcePath
$preflightIsDirectory = $preflightEntry.IsDirectory
[DotfilesSymbolicLink]::Create($preflightLinkPath, $preflightSourcePath, $preflightIsDirectory)
$preflightIndex += 1
}
}
catch
{
$preflightErrorMessage = Get-ErrorMessage $_.Exception
throw "Symbolic link preflight failed before modifying files. Enable Developer Mode or run PowerShell as Administrator. Source: $preflightSourcePath. Error: $preflightErrorMessage"
}
finally
{
Remove-Item -LiteralPath $preflightDirectory -Force -Recurse -ErrorAction SilentlyContinue
}
}
foreach ($linkEntry in $linkEntries)
{
$relativePath = $linkEntry.RelativePath
$sourcePath = $linkEntry.SourcePath
$isDirectory = $linkEntry.IsDirectory
$shouldCopy = Test-CopyRelativePath $relativePath $copyRelativePathPrefixes
$targetPath = Join-TargetPath $homePath $relativePath
$targetParentPath = Split-Path -Path $targetPath -Parent
if ((-not [string]::IsNullOrWhiteSpace($targetParentPath)) -and (-not (Test-Path -LiteralPath $targetParentPath -PathType Container)))
{
New-Item -ItemType Directory -Path $targetParentPath -Force | Out-Null
}
$targetItem = Get-Item -LiteralPath $targetPath -Force -ErrorAction SilentlyContinue
if ($shouldCopy)
{
if ($null -ne $targetItem)
{
$isTargetLink = (($targetItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)
if ($isTargetLink)
{
Remove-Item -LiteralPath $targetPath -Force -Recurse
Write-Host "Existing symlink removed: $targetPath"
}
elseif ($isDirectory)
{
if ($targetItem.PSIsContainer)
{
Remove-Item -LiteralPath $targetPath -Force -Recurse
Write-Host "Existing directory removed: $targetPath"
}
else
{
$backupPath = "$targetPath.orig"
if (Test-Path -LiteralPath $backupPath)
{
Remove-Item -LiteralPath $targetPath -Force
}
else
{
Move-Item -LiteralPath $targetPath -Destination $backupPath
Write-Host "Existing item moved: $targetPath -> $backupPath"
}
}
}
elseif ($targetItem.PSIsContainer)
{
throw "Directory exists where file should be copied: $targetPath"
}
}
if ($isDirectory)
{
Copy-Item -LiteralPath $sourcePath -Destination $targetPath -Force -Recurse
Write-Host "Directory copied: $targetPath <- $sourcePath"
}
else
{
Copy-Item -LiteralPath $sourcePath -Destination $targetPath -Force
Write-Host "File copied: $targetPath <- $sourcePath"
}
continue
}
if ($null -ne $targetItem)
{
$isTargetLink = (($targetItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)
if ((-not $targetItem.PSIsContainer) -and (-not $isTargetLink))
{
$backupPath = "$targetPath.orig"
if (Test-Path -LiteralPath $backupPath)
{
throw "Backup path already exists: $backupPath"
}
Move-Item -LiteralPath $targetPath -Destination $backupPath
Write-Host "Existing item moved: $targetPath -> $backupPath"
}
else
{
continue
}
}
try
{
[DotfilesSymbolicLink]::Create($targetPath, $sourcePath, $isDirectory)
Write-Host "Symlink created: $targetPath -> $sourcePath"
}
catch
{
$linkErrorMessage = Get-ErrorMessage $_.Exception
throw "Failed to create symbolic link: $targetPath -> $sourcePath. Error: $linkErrorMessage"
}
}
Write-Host 'Windows bootstrap completed.'