Repository navigation
Expand file tree
/
Copy pathengine.ps1
More file actions
837 lines (754 loc) · 31.4 KB
/
Copy pathengine.ps1
File metadata and controls
837 lines (754 loc) · 31.4 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
<#
.SYNOPSIS
github-setup engine: detect, plan, apply, verify and undo the machine-wide
settings that make GitHub git operations use SSH over port 443.
.DESCRIPTION
Dot-source this file. It holds no UI: `cli.ps1` and `gui.ps1` are thin
front-ends over these functions, so there is exactly one implementation of
every decision.
Why this exists at all: on this network TCP to github.com answers in ~100 ms
while the HTTPS request on top of it takes 18-23 s. The connection is fine;
the TLS layer is throttled. SSH bypasses it and completes in ~3 s. Fixing that
means three pieces of machine state, and one of them (url.insteadOf) only
matches URLs by prefix, so mirrored remotes need their own rewrite.
Everything this module changes is user-scope and is recorded in a backup
before it is touched, so `Invoke-GitHubSetupUndo` can put it all back.
#>
# Not set to 'Stop': `ssh -T` reports a failed authentication on stderr and
# exits non-zero by design, and Windows PowerShell 5.1 turns a native command's
# stderr into a terminating error under 'Stop'. Every check that matters tests
# $LASTEXITCODE or its own condition explicitly.
$ErrorActionPreference = 'Continue'
$script:BackupDir = Join-Path $env:LOCALAPPDATA 'github-setup'
$script:SshDir = Join-Path $env:USERPROFILE '.ssh'
$script:SshConfig = Join-Path $script:SshDir 'config'
$script:DefaultPort = 443
# A public repository that exists purely to be a probe. Small, stable, owned by
# GitHub itself, and readable over SSH once a key is registered.
$script:ProbeRepo = 'https://github.com/octocat/Hello-World.git'
$script:ProbeSsh = 'git@github.com:octocat/Hello-World.git'
# Latin-1 maps every byte to one character, so text read this way can be
# searched without decoding, and written back byte-for-byte. The existing ssh
# config on this machine contains mojibake comments (GBK bytes that were once
# Chinese); decoding it as UTF-8 to rewrite it would corrupt them further.
$script:Latin1 = [Text.Encoding]::GetEncoding(28591)
# AI assistants that ship as VS Code extensions. They run inside VS Code and use
# its git integration, so "VS Code uses the system git" already settles them.
$script:KnownAiExtensions = @(
@{ Id = 'alibaba-cloud.tongyi-lingma'; Name = '通义灵码' }
@{ Id = 'saoudrizwan.claude-dev'; Name = 'Cline' }
@{ Id = 'rooveterinaryinc.roo-cline'; Name = 'Roo Code' }
@{ Id = 'anthropic.claude-code'; Name = 'Claude Code' }
@{ Id = 'continue.continue'; Name = 'Continue' }
@{ Id = 'tabnine.tabnine-vscode'; Name = 'Tabnine' }
)
# --------------------------------------------------------------------------
# small helpers
# --------------------------------------------------------------------------
<#
.SYNOPSIS
Run a native command with a hard timeout and measure how long it took.
.DESCRIPTION
`git ls-remote` against a throttled endpoint can hang for minutes, and a UI
that hangs is worse than one that reports a timeout. Windows PowerShell 5.1
has no timeout for native commands, hence the explicit process handling.
.PARAMETER Exe
Executable to run.
.PARAMETER Arguments
Its arguments.
.PARAMETER TimeoutMs
Give up after this long.
.OUTPUTS
Hashtable with TimedOut, ExitCode, Output and Ms.
#>
function Invoke-NativeTimed {
param(
[Parameter(Mandatory = $true)][string]$Exe,
[string[]]$Arguments = @(),
[int]$TimeoutMs = 30000
)
$quoted = @()
foreach ($a in $Arguments) {
if ($a -match '\s') { $quoted += ('"' + $a + '"') } else { $quoted += $a }
}
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($quoted -join ' ')
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
# A prompt would block forever in a windowless process.
$psi.EnvironmentVariables['GIT_TERMINAL_PROMPT'] = '0'
$psi.EnvironmentVariables['GIT_ASKPASS'] = 'echo'
$psi.EnvironmentVariables['SSH_ASKPASS'] = 'echo'
$proc = $null
$sw = [Diagnostics.Stopwatch]::StartNew()
try { $proc = [System.Diagnostics.Process]::Start($psi) } catch {
$sw.Stop()
return @{ TimedOut = $false; ExitCode = -1; Output = $_.Exception.Message; Ms = $sw.ElapsedMilliseconds }
}
$finished = $proc.WaitForExit($TimeoutMs)
$sw.Stop()
$text = ''
try { $text = $proc.StandardOutput.ReadToEnd() + $proc.StandardError.ReadToEnd() } catch { }
if (-not $finished) { try { $proc.Kill() } catch { } }
$code = -1
if ($finished) { $code = $proc.ExitCode }
try { $proc.Dispose() } catch { }
return @{ TimedOut = -not $finished; ExitCode = $code; Output = $text.Trim(); Ms = $sw.ElapsedMilliseconds }
}
<#
.SYNOPSIS
Run git in a directory and return its exit code and output.
#>
function Invoke-Git {
param(
[string[]]$Arguments = @(),
[string]$WorkDir = ''
)
$prefix = @()
if ($WorkDir -ne '') { $prefix = @('-C', $WorkDir) }
$all = $prefix + $Arguments
$out = (@(& git @all 2>&1) -join "`n").Trim()
return @{ ExitCode = $LASTEXITCODE; Output = $out }
}
# --------------------------------------------------------------------------
# detection
# --------------------------------------------------------------------------
<#
.SYNOPSIS
The SSH key to use, preferring one that already exists.
.DESCRIPTION
Minting a key per tool is how key sprawl starts. If a usable private key with
a matching .pub is already here, use it; otherwise name the default that
-Apply will create.
#>
function Get-SshKeyPath {
$candidates = @(
(Join-Path $script:SshDir 'id_ed25519_github'),
(Join-Path $script:SshDir 'id_rsa_3072'),
(Join-Path $script:SshDir 'id_ed25519'),
(Join-Path $script:SshDir 'id_rsa')
)
foreach ($c in $candidates) {
if ((Test-Path $c) -and (Test-Path ($c + '.pub'))) { return $c }
}
return (Join-Path $script:SshDir 'id_ed25519_github')
}
<#
.SYNOPSIS
Whether GitHub accepts this key, and on which port.
.DESCRIPTION
`ssh -T git@github.com` prints "Hi <user>! You've successfully authenticated"
and still exits non-zero, so the text is the answer, not the exit code.
.PARAMETER KeyPath
Private key to offer.
.PARAMETER Port
Port to try. 443 is the default because corporate networks often drop 22.
#>
function Test-SshRegistration {
param(
[Parameter(Mandatory = $true)][string]$KeyPath,
[int]$Port = $script:DefaultPort
)
if (-not (Test-Path $KeyPath)) {
return @{ Registered = $false; Login = ''; Detail = '私钥不存在' }
}
$hostName = 'ssh.github.com'
$args = @('-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=12',
'-o', 'StrictHostKeyChecking=accept-new', '-o', 'IdentitiesOnly=yes',
'-i', $KeyPath, '-p', "$Port", "git@$hostName")
$r = Invoke-NativeTimed -Exe 'ssh' -Arguments $args -TimeoutMs 20000
if ($r.TimedOut) { return @{ Registered = $false; Login = ''; Detail = '连接超时' } }
$m = [regex]::Match($r.Output, 'Hi\s+([^!]+)!')
if ($r.Output -match 'successfully authenticated') {
return @{ Registered = $true; Login = $(if ($m.Success) { $m.Groups[1].Value } else { '' }); Detail = '已注册' }
}
return @{ Registered = $false; Login = ''; Detail = ($r.Output -replace '\s+', ' ') }
}
<#
.SYNOPSIS
Read the ssh config as byte-preserving text (Latin-1).
#>
function Get-SshConfigText {
if (-not (Test-Path $script:SshConfig)) { return '' }
return $script:Latin1.GetString([IO.File]::ReadAllBytes($script:SshConfig))
}
<#
.SYNOPSIS
Find the `Host github.com` block, if any.
#>
function Get-GithubSshBlock {
$text = Get-SshConfigText
$match = [regex]::Match($text, '(?ms)^[ \t]*Host[ \t]+github\.com[ \t]*\r?\n((?:[ \t]+\S.*\r?\n?)*)')
if (-not $match.Success) {
return @{ Present = $false; Port = 0; HostName = '' }
}
$body = $match.Groups[1].Value
$portMatch = [regex]::Match($body, '(?im)^[ \t]*Port[ \t]+(\d+)')
$hostMatch = [regex]::Match($body, '(?im)^[ \t]*HostName[ \t]+(\S+)')
return @{
Present = $true
Port = $(if ($portMatch.Success) { [int]$portMatch.Groups[1].Value } else { 22 })
HostName = $(if ($hostMatch.Success) { $hostMatch.Groups[1].Value } else { '' })
}
}
<#
.SYNOPSIS
The git URL rewrites currently configured, as `key = value` strings.
#>
function Get-GitUrlRewrites {
$r = Invoke-Git -Arguments @('config', '--global', '--get-regexp', '^url\..*\.insteadof$')
if ($r.ExitCode -ne 0 -or $r.Output -eq '') { return @() }
return @($r.Output -split "`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' })
}
<#
.SYNOPSIS
Repositories below a directory whose github remotes are not plain SSH.
.DESCRIPTION
`url.insteadOf` rewrites by prefix, so a remote cloned through a mirror such
as https://ghfast.top/https://github.com/o/r.git is never matched -- and that
is precisely the URL that is slowest to push, because a read-only mirror
cannot accept a push at all.
.PARAMETER Root
Directory to scan, bounded to three levels.
#>
function Get-GitHubRemotes {
param([Parameter(Mandatory = $true)][string]$Root)
if (-not (Test-Path $Root)) { return @() }
$rootPath = (Resolve-Path -Path $Root).Path
$repoRoots = New-Object System.Collections.ArrayList
$queue = New-Object System.Collections.Queue
$queue.Enqueue(@($rootPath, 0))
while ($queue.Count -gt 0) {
$item = $queue.Dequeue()
$dir = $item[0]
$depth = $item[1]
if (Test-Path (Join-Path $dir '.git')) { [void]$repoRoots.Add($dir); continue }
if ($depth -ge 3) { continue }
foreach ($child in (Get-ChildItem -Path $dir -Directory -Force -ErrorAction SilentlyContinue)) {
$skip = @('.git', 'node_modules', 'dist', 'bin', 'obj', 'target', '.venv', 'venv', 'build', 'out', '.next')
if ($skip -contains $child.Name) { continue }
$queue.Enqueue(@($child.FullName, $depth + 1))
}
}
$found = New-Object System.Collections.ArrayList
foreach ($repo in $repoRoots) {
foreach ($remote in (Get-RepoRemoteUrls -Repo $repo)) {
$url = $remote.Url
$isSsh = $url -match '^(git@github\.com:|ssh://git@github\.com/)'
$m = [regex]::Match($url, 'github\.com[/:]([^/]+)/([^/]+?)(?:\.git)?/?$')
$target = ''
if ($m.Success) {
$target = 'git@github.com:' + $m.Groups[1].Value + '/' + $m.Groups[2].Value + '.git'
}
[void]$found.Add([pscustomobject]@{
Repo = $repo
Name = $remote.Name
Url = $url
AlreadySsh = $isSsh
Target = $target
NeedsFix = ((-not $isSsh) -and ($target -ne '') -and ($target -ne $url))
})
}
}
return @($found)
}
<#
.SYNOPSIS
Read a repository's remotes straight out of `.git/config`.
.DESCRIPTION
Deliberately does not run git. Measured on this machine, `git remote` plus
`git remote get-url` per repository cost about a second each -- the enterprise
antivirus inspects every process creation -- and scanning five repositories
took 9.8 s, all of it spent waiting on processes that only read a text file.
`.git/config` is an INI file, so reading it is a millisecond of file I/O. The
only shape worth handling is a worktree or submodule, where `.git` is a file
containing `gitdir: <path>` rather than a directory.
.PARAMETER Repo
Repository root.
.OUTPUTS
Array of objects with Name and Url.
#>
function Get-RepoRemoteUrls {
param([Parameter(Mandatory = $true)][string]$Repo)
$dotGit = Join-Path $Repo '.git'
$configPath = Join-Path $dotGit 'config'
if (Test-Path $dotGit -PathType Leaf) {
$first = ''
try { $first = (Get-Content -Path $dotGit -TotalCount 1 -ErrorAction Stop) } catch { return @() }
$m = [regex]::Match([string]$first, '^gitdir:\s*(.+)$')
if (-not $m.Success) { return @() }
$target = $m.Groups[1].Value.Trim()
if (-not [IO.Path]::IsPathRooted($target)) { $target = Join-Path $Repo $target }
$configPath = Join-Path $target 'config'
}
if (-not (Test-Path $configPath)) { return @() }
$text = ''
try { $text = [IO.File]::ReadAllText($configPath) } catch { return @() }
$result = New-Object System.Collections.ArrayList
# One section per remote; stops at the next section header or end of file.
$sections = [regex]::Matches($text, '(?ms)^\[remote\s+"([^"]+)"\][^\r\n]*\r?\n(.*?)(?=^\[|\z)')
foreach ($s in $sections) {
$name = $s.Groups[1].Value
$body = $s.Groups[2].Value
$urlMatch = [regex]::Match($body, '(?im)^\s*url\s*=\s*(.+?)\s*$')
if (-not $urlMatch.Success) { continue }
[void]$result.Add([pscustomobject]@{ Name = $name; Url = $urlMatch.Groups[1].Value })
}
return @($result)
}
# --------------------------------------------------------------------------
# transport measurement
# --------------------------------------------------------------------------
<#
.SYNOPSIS
Time a GitHub git operation over HTTPS and over SSH.
.DESCRIPTION
The numbers are the whole argument for this tool, so they are measured rather
than assumed -- and measured every time, because a proxy or a VPN changes them.
.OUTPUTS
Hashtable with HttpsMs, HttpsOk, SshMs, SshOk and the raw detail lines.
#>
function Measure-GitHubTransport {
param([string]$KeyPath = '', [int]$Port = $script:DefaultPort, [int]$TimeoutMs = 30000)
$https = Invoke-NativeTimed -Exe 'git' -Arguments @('ls-remote', '--heads', $script:ProbeRepo) -TimeoutMs $TimeoutMs
$result = @{
HttpsMs = $https.Ms
HttpsOk = ($https.ExitCode -eq 0)
HttpsRaw = $(if ($https.TimedOut) { '超时' } else { $https.Output })
SshMs = 0
SshOk = $false
SshRaw = '未测试'
}
if ($KeyPath -ne '' -and (Test-Path $KeyPath)) {
# -p is honoured by ssh, and thenInsteadOf means git can also use it; using
# ssh directly keeps this measurement independent of git's config.
$env:GIT_SSH_COMMAND = "ssh -i `"$KeyPath`" -p $Port -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
$ssh = Invoke-NativeTimed -Exe 'git' -Arguments @('ls-remote', '--heads', $script:ProbeSsh) -TimeoutMs $TimeoutMs
Remove-Item Env:\GIT_SSH_COMMAND -ErrorAction SilentlyContinue
$result.SshMs = $ssh.Ms
$result.SshOk = ($ssh.ExitCode -eq 0)
$result.SshRaw = $(if ($ssh.TimedOut) { '超时' } else { $ssh.Output })
}
return $result
}
# --------------------------------------------------------------------------
# tool matrix
# --------------------------------------------------------------------------
<#
.SYNOPSIS
Which installed tools reach GitHub through the system git, and which do not.
.DESCRIPTION
The point of this table is to avoid configuring things that need no
configuring. Anything that shells out to `git` inherits the global config, and
anything running *inside* such a tool inherits it too. Only a tool with its
own git implementation, or its own environment, needs separate handling --
and saying so is more useful than pretending everything needs a setting.
.OUTPUTS
Array of objects with Name, Kind, Verdict and Detail.
#>
function Get-GitHubToolMatrix {
$rows = New-Object System.Collections.ArrayList
$git = Get-Command git -ErrorAction SilentlyContinue
if ($git) {
$ver = (Invoke-Git -Arguments @('--version')).Output
[void]$rows.Add([pscustomobject]@{
Name = 'git 命令行'; Kind = '工具'; Verdict = '核心'
Detail = "$ver @ $($git.Source)"
})
}
<#
Read a settings.json for an explicit git.path override.
A tool that sets one is *not* fixed by the global config, because it runs
some other git binary.
#>
$readGitPath = {
param([string]$Path)
if (-not (Test-Path $Path)) { return $null }
try {
$txt = (Get-Content $Path -Raw -ErrorAction Stop)
# settings.json is JSON with comments in practice, so a regex beats a parser.
$m = [regex]::Match($txt, '"git\.path"\s*:\s*"([^"]*)"')
if ($m.Success) { return $m.Groups[1].Value }
return ''
} catch { return $null }
}
$editors = @(
@{ Name = 'VS Code'; Exe = 'code'; Settings = (Join-Path $env:APPDATA 'Code\User\settings.json'); Dir = (Join-Path $env:LOCALAPPDATA 'Programs\Microsoft VS Code') }
@{ Name = 'Cursor'; Exe = 'cursor'; Settings = (Join-Path $env:APPDATA 'Cursor\User\settings.json'); Dir = (Join-Path $env:LOCALAPPDATA 'Programs\Cursor') }
)
foreach ($ed in $editors) {
$installed = (Get-Command $ed.Exe -ErrorAction SilentlyContinue) -or (Test-Path $ed.Dir)
if (-not $installed) { continue }
$gitPath = & $readGitPath $ed.Settings
if ($gitPath -eq $null) {
[void]$rows.Add([pscustomobject]@{
Name = $ed.Name; Kind = 'IDE'; Verdict = '继承'
Detail = '未找到设置文件,默认使用 PATH 里的 git'
})
} elseif ($gitPath -eq '') {
[void]$rows.Add([pscustomobject]@{
Name = $ed.Name; Kind = 'IDE'; Verdict = '继承'
Detail = 'git.path 未设置,使用 PATH 里的系统 git'
})
} else {
[void]$rows.Add([pscustomobject]@{
Name = $ed.Name; Kind = 'IDE'; Verdict = '独立'
Detail = "git.path = $gitPath —— 它用的是这个 git,全局配置只在它是同一份 git 时才生效"
})
}
}
# Other installed AI desktops. We can see they exist; we cannot see how they
# reach git, so the honest verdict is "unknown, verify here".
$others = @(
@{ Name = 'opencode 桌面版'; Dir = (Join-Path $env:LOCALAPPDATA 'Programs\@opencode-aidesktop') }
@{ Name = 'JetBrains IDE'; Dir = 'C:\Program Files\JetBrains' }
)
foreach ($o in $others) {
if (-not (Test-Path $o.Dir)) { continue }
[void]$rows.Add([pscustomobject]@{
Name = $o.Name; Kind = 'IDE'; Verdict = '未知'
Detail = '无法从外部判断它调用哪个 git;在它的终端里跑一次验证命令即可确认'
})
}
# AI assistants that are VS Code extensions. They run inside VS Code, so the
# VS Code row already decided for them.
$extDir = Join-Path $env:USERPROFILE '.vscode\extensions'
if (Test-Path $extDir) {
$installedNames = @(Get-ChildItem $extDir -Directory -ErrorAction SilentlyContinue | ForEach-Object { $_.Name })
foreach ($ai in $script:KnownAiExtensions) {
$hit = $installedNames | Where-Object { $_ -like ($ai.Id + '-*') } | Select-Object -First 1
if (-not $hit) { continue }
[void]$rows.Add([pscustomobject]@{
Name = $ai.Name; Kind = 'VS Code 扩展'; Verdict = '继承'
Detail = '运行在 VS Code 内,使用 VS Code 的 git 集成'
})
}
}
foreach ($pm in @('npm', 'pnpm')) {
if (-not (Get-Command $pm -ErrorAction SilentlyContinue)) { continue }
[void]$rows.Add([pscustomobject]@{
Name = $pm; Kind = '包管理器'; Verdict = '继承'
Detail = 'github: 与 git+https:// 依赖会调用 git,因此走同一份全局配置'
})
}
if (Get-Command go -ErrorAction SilentlyContinue) {
$proxy = ((& go env GOPROXY) -join '').Trim()
$private = $env:GOPRIVATE
$verdict = '部分'
$detail = "GOPROXY = $proxy;公开模块走代理,不走 git"
if ([string]::IsNullOrWhiteSpace($private)) {
$detail += '。GOPRIVATE 未设置 —— 私有仓库会尝试走代理而失败,需要设为 github.com/<你的账号>/*'
} else {
$detail += "。GOPRIVATE = $private,这些模块走 git"
$verdict = '继承'
}
[void]$rows.Add([pscustomobject]@{ Name = 'Go modules'; Kind = '包管理器'; Verdict = $verdict; Detail = $detail })
}
if (Get-Command wsl -ErrorAction SilentlyContinue) {
[void]$rows.Add([pscustomobject]@{
Name = 'WSL 里的 git'; Kind = '独立环境'; Verdict = '独立'
Detail = 'WSL 有自己的 ~/.ssh 和 git config,Windows 侧的配置对它无效,需要在 WSL 内再配一次'
})
}
$dshVars = @(Get-ChildItem Env: -ErrorAction SilentlyContinue | Where-Object { $_.Name -like 'DSH_*' })
if ($dshVars.Count -gt 0) {
[void]$rows.Add([pscustomobject]@{
Name = 'DSH 里的 agent'; Kind = '当前环境'; Verdict = '继承'
Detail = '与用户同一身份、同一个 git;但沙箱必须是完全权限,否则读不到 ~/.ssh'
})
}
return @($rows)
}
# --------------------------------------------------------------------------
# plan / apply / undo
# --------------------------------------------------------------------------
<#
.SYNOPSIS
Everything the UI needs to draw itself, gathered in one pass.
.PARAMETER ScanRoot
Optional directory scanned for repositories with mirrored remotes.
#>
function Get-GitHubSetupState {
param([string]$ScanRoot = '')
$keyPath = Get-SshKeyPath
$keyExists = Test-Path $keyPath
$registration = Test-SshRegistration -KeyPath $keyPath -Port $script:DefaultPort
$block = Get-GithubSshBlock
$rewrites = Get-GitUrlRewrites
$hasRewrite = $false
foreach ($r in $rewrites) {
if ($r -match 'git@github\.com:') { $hasRewrite = $true }
}
$remotes = @()
if ($ScanRoot -ne '') { $remotes = Get-GitHubRemotes -Root $ScanRoot }
return @{
KeyPath = $keyPath
KeyExists = $keyExists
KeyPublic = $(if ($keyExists -and (Test-Path ($keyPath + '.pub'))) { ((Get-Content ($keyPath + '.pub') -Raw).Trim()) } else { '' })
Registered = $registration.Registered
Login = $registration.Login
RegisterDetail = $registration.Detail
Port = $script:DefaultPort
SshBlock = $block
Rewrites = $rewrites
HasRewrite = $hasRewrite
Remotes = $remotes
NeedsFixCount = @($remotes | Where-Object { $_.NeedsFix }).Count
ScanRoot = $ScanRoot
BackupDir = $script:BackupDir
}
}
<#
.SYNOPSIS
The list of changes `Invoke-GitHubSetupApply` would make.
.PARAMETER State
Output of Get-GitHubSetupState.
#>
function Get-GitHubSetupPlan {
param([Parameter(Mandatory = $true)]$State)
$plan = New-Object System.Collections.ArrayList
if (-not $State.KeyExists) {
[void]$plan.Add(@{ Step = 'key'; Text = "创建 SSH key:$($State.KeyPath)" })
}
if (-not $State.Registered) {
[void]$plan.Add(@{ Step = 'register'; Text = '把公钥加到 GitHub(需要你自己确认,工具不会代劳)' })
}
if (-not $State.SshBlock.Present -or $State.SshBlock.Port -ne $State.Port -or $State.SshBlock.HostName -ne 'ssh.github.com') {
[void]$plan.Add(@{ Step = 'sshconfig'; Text = "在 ~/.ssh/config 写入 Host github.com -> ssh.github.com:$($State.Port)" })
}
if (-not $State.HasRewrite) {
[void]$plan.Add(@{ Step = 'insteadof'; Text = '设置 git 全局重写:https://github.com/ -> git@github.com:' })
}
$toFix = @($State.Remotes | Where-Object { $_.NeedsFix })
if ($toFix.Count -gt 0) {
[void]$plan.Add(@{ Step = 'remotes'; Text = "改写 $($toFix.Count) 个镜像前缀的 remote 为 SSH" })
}
return @($plan)
}
<#
.SYNOPSIS
Write the backup that `Invoke-GitHubSetupUndo` reads.
.PARAMETER State
Current state, before any change.
.PARAMETER Remotes
The remotes about to be rewritten.
#>
function Save-GitHubSetupBackup {
param([Parameter(Mandatory = $true)]$State, [object[]]$Remotes = @())
if (-not (Test-Path $script:BackupDir)) { New-Item -ItemType Directory -Path $script:BackupDir -Force | Out-Null }
$sshBytes = @()
$sshExisted = Test-Path $script:SshConfig
if ($sshExisted) { $sshBytes = [IO.File]::ReadAllBytes($script:SshConfig) }
$record = [pscustomobject]@{
createdAt = (Get-Date).ToString('o')
sshConfig = [pscustomobject]@{
path = $script:SshConfig
existedBefore = $sshExisted
# Base64 of the raw bytes: the file may hold mojibake that must survive a
# round trip, and re-encoding text would not preserve it.
originalBase64 = [Convert]::ToBase64String([byte[]]$sshBytes)
}
urlRewrites = @($State.Rewrites)
remotes = @($Remotes | ForEach-Object {
[pscustomobject]@{ repo = $_.Repo; name = $_.Name; oldUrl = $_.Url }
})
}
$file = Join-Path $script:BackupDir ('backup-' + (Get-Date).ToString('yyyyMMdd-HHmmss') + '.json')
$record | ConvertTo-Json -Depth 6 | Set-Content -Path $file -Encoding UTF8
return $file
}
<#
.SYNOPSIS
Apply the settings, returning the log lines the UI should show.
.DESCRIPTION
Ordered so that nothing is rewritten before the key is known to work: setting
url.insteadOf while SSH is unauthenticated would turn every HTTPS clone on the
machine into a failing SSH one.
.PARAMETER State
Output of Get-GitHubSetupState.
.PARAMETER ScanRoot
Directory to scan for mirrored remotes.
.PARAMETER WhatIf
Report what would happen without writing anything.
#>
function Invoke-GitHubSetupApply {
param([Parameter(Mandatory = $true)]$State, [string]$ScanRoot = '', [switch]$WhatIf)
$log = New-Object System.Collections.ArrayList
$add = { param($t) [void]$log.Add($t) }
# 1. the key
if (-not $State.KeyExists) {
if ($WhatIf) {
& $add "将创建 SSH key:$($State.KeyPath)"
& $add '(预览:未创建)'
return @($log)
}
# `-N '""'` is not a typo: Windows PowerShell 5.1 drops a genuinely empty
# argument, so `-N ''` reaches ssh-keygen as `-N -C ...` and fails.
& ssh-keygen -t ed25519 -N '""' -C 'github-ssh-443' -q -f $State.KeyPath | Out-Null
if ($LASTEXITCODE -ne 0) {
& $add '创建 SSH key 失败'
return @($log)
}
& $add "已创建 SSH key:$($State.KeyPath)"
} else {
& $add "复用已有 SSH key:$($State.KeyPath)"
}
# 2. is it registered? Nothing downstream is safe until it is.
$registration = Test-SshRegistration -KeyPath $State.KeyPath -Port $State.Port
if (-not $registration.Registered) {
& $add 'GitHub 还不认识这把公钥,已停止。'
& $add '请把下面这行加到 https://github.com/settings/keys ,或在「公钥」里复制后重试:'
if ((Test-Path ($State.KeyPath + '.pub'))) {
& $add ((Get-Content ($State.KeyPath + '.pub') -Raw).Trim())
}
& $add '(此时改写 git 配置会让本机所有 HTTPS 克隆失效,所以不做。)'
return @($log)
}
& $add "公钥已注册:$(if ($registration.Login -ne '') { $registration.Login } else { '(GitHub 未返回用户名)' })"
$remotesToFix = @($State.Remotes | Where-Object { $_.NeedsFix })
# 3. ssh config
$block = Get-GithubSshBlock
$wantBlock = (-not $block.Present) -or ($block.Port -ne $State.Port) -or ($block.HostName -ne 'ssh.github.com')
if ($wantBlock) {
if ($WhatIf) {
& $add "将写入 ~/.ssh/config 的 Host github.com 块(端口 $($State.Port))"
} else {
$backupFile = Save-GitHubSetupBackup -State $State -Remotes $remotesToFix
& $add "已备份原配置:$backupFile"
$lines = @(
''
'# Added by github-setup'
'# ssh.github.com:443 exists because port 22 is dropped on many corporate'
'# networks, and because HTTPS to github.com is TLS-throttled on this one.'
'Host github.com'
' HostName ssh.github.com'
" Port $($State.Port)"
' User git'
(' IdentityFile ' + ($State.KeyPath -replace '\\', '/'))
' IdentitiesOnly yes'
' ServerAliveInterval 30'
' ServerAliveCountMax 4'
)
$text = ($lines -join "`r`n") + "`r`n"
$existing = @()
if (Test-Path $script:SshConfig) { $existing = [IO.File]::ReadAllBytes($script:SshConfig) }
# Appended as ASCII bytes: no decode, so nothing already in the file can
# be altered by the round trip.
[IO.File]::WriteAllBytes($script:SshConfig, [byte[]]$existing + [Text.Encoding]::ASCII.GetBytes($text))
& $add '已写入 ~/.ssh/config'
}
} else {
& $add '~/.ssh/config 已有正确的 github 块,跳过'
}
# 4. the global rewrite
$stateAfter = Get-GitUrlRewrites
$already = $false
foreach ($r in $stateAfter) { if ($r -match 'git@github\.com:') { $already = $true } }
if (-not $already) {
if ($WhatIf) {
& $add '将设置 git 全局 url.insteadOf'
} else {
& git config --global url."git@github.com:".insteadOf 'https://github.com/' | Out-Null
& git config --global --add url."git@github.com:".insteadOf 'ssh://git@github.com/' | Out-Null
& $add '已设置 git 全局 url.insteadOf'
}
} else {
& $add 'git 全局重写已存在,跳过'
}
# 5. mirrored remotes
if ($remotesToFix.Count -gt 0) {
foreach ($r in $remotesToFix) {
if ($WhatIf) {
& $add "将改写 $(Split-Path $r.Repo -Leaf) [$($r.Name)]:$($r.Url) -> $($r.Target)"
} else {
$res = Invoke-Git -Arguments @('remote', 'set-url', $r.Name, $r.Target) -WorkDir $r.Repo
if ($res.ExitCode -eq 0) {
& $add "已改写 $(Split-Path $r.Repo -Leaf) [$($r.Name)] -> $($r.Target)"
} else {
& $add "改写失败 $(Split-Path $r.Repo -Leaf):$($res.Output)"
}
}
}
} elseif ($ScanRoot -ne '') {
& $add '没有需要改写的镜像 remote'
}
return @($log)
}
<#
.SYNOPSIS
Restore the most recent backup.
.DESCRIPTION
Reverses all three kinds of change, in reverse order: remotes, git rewrites,
then the ssh config bytes. Anything the backup does not mention is left alone.
.PARAMETER BackupFile
A specific backup; defaults to the newest one.
#>
function Invoke-GitHubSetupUndo {
param([string]$BackupFile = '')
$log = New-Object System.Collections.ArrayList
$add = { param($t) [void]$log.Add($t) }
if ($BackupFile -eq '') {
if (-not (Test-Path $script:BackupDir)) { & $add '没有找到备份目录'; return @($log) }
$latest = Get-ChildItem $script:BackupDir -Filter 'backup-*.json' -File -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (-not $latest) { & $add '没有备份可以恢复'; return @($log) }
$BackupFile = $latest.FullName
}
if (-not (Test-Path $BackupFile)) { & $add "备份不存在:$BackupFile"; return @($log) }
$record = Get-Content $BackupFile -Raw -Encoding UTF8 | ConvertFrom-Json
& $add "使用备份:$BackupFile($($record.createdAt))"
foreach ($r in @($record.remotes)) {
if ($null -eq $r) { continue }
$res = Invoke-Git -Arguments @('remote', 'set-url', $r.name, $r.oldUrl) -WorkDir $r.repo
if ($res.ExitCode -eq 0) {
& $add "已恢复 remote:$(Split-Path $r.repo -Leaf) [$($r.name)] -> $($r.oldUrl)"
} else {
& $add "恢复 remote 失败:$(Split-Path $r.repo -Leaf) $($res.Output)"
}
}
& git config --global --unset-all 'url.git@github.com:.insteadOf' 2>$null | Out-Null
foreach ($rw in @($record.urlRewrites)) {
if ([string]::IsNullOrWhiteSpace($rw)) { continue }
# Each entry is "key=value" as `git config --get-regexp` prints it.
$idx = $rw.IndexOf(' ')
if ($idx -gt 0) {
$k = $rw.Substring(0, $idx)
$v = $rw.Substring($idx + 1)
& git config --global --add $k $v | Out-Null
}
}
& $add '已恢复 git 全局 url.insteadOf'
$ssh = $record.sshConfig
if ($null -ne $ssh) {
if ([string]::IsNullOrWhiteSpace($ssh.originalBase64)) {
if (Test-Path $ssh.path) { Remove-Item $ssh.path -Force }
& $add '已删除 ~/.ssh/config(备份时它不存在)'
} else {
[IO.File]::WriteAllBytes($ssh.path, [Convert]::FromBase64String($ssh.originalBase64))
& $add '已恢复 ~/.ssh/config 原始内容'
}
}
return @($log)
}
<#
.SYNOPSIS
The newest backup file, or $null.
#>
function Get-LatestBackup {
if (-not (Test-Path $script:BackupDir)) { return $null }
$latest = Get-ChildItem $script:BackupDir -Filter 'backup-*.json' -File -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if ($latest) { return $latest.FullName }
return $null
}
<#
.SYNOPSIS
The command a user can paste into any tool to prove it works there.
#>
function Get-VerificationCommand {
param([Parameter(Mandatory = $true)][string]$KeyPath, [int]$Port = $script:DefaultPort)
return "git -c core.sshCommand='ssh -i `"$KeyPath`" -p $Port -o IdentitiesOnly=yes' ls-remote --heads https://github.com/octocat/Hello-World.git"
}