Repository navigation
Expand file tree
/
Copy pathgui.ps1
More file actions
438 lines (388 loc) · 16.9 KB
/
Copy pathgui.ps1
File metadata and controls
438 lines (388 loc) · 16.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
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
<#
.SYNOPSIS
WinForms front-end for github-setup.
.DESCRIPTION
This file only draws and dispatches. Every decision lives in engine.ps1, which
the CLI front-end uses too -- so "what the button does" cannot drift from
"what the command does".
Long operations (the latency measurement runs `git ls-remote` against a
throttled endpoint and can take half a minute) run synchronously with a wait
cursor and a status line. For a tool used a few times per machine that is a
better trade than background-worker plumbing, but it does mean the window does
not repaint while a measurement is in flight -- hence the explicit DoEvents
before each long call.
.NOTES
Saved as UTF-8 with BOM on purpose: Windows PowerShell 5.1 reads a BOM-less
UTF-8 script as ANSI, which would turn every Chinese label into mojibake. If
you edit this file, keep the BOM.
#>
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# The launcher starts this with -WindowStyle Hidden, so an unhandled error would
# otherwise close silently and look like "the tool did nothing".
trap {
# A hidden console means an unhandled error would vanish. Keep the text.
try {
$logDir = Join-Path $env:LOCALAPPDATA 'github-setup'
if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
[IO.File]::WriteAllText((Join-Path $logDir 'last-error.log'),
($_.Exception.Message + "`r`n`r`n" + $_.InvocationInfo.PositionMessage),
(New-Object Text.UTF8Encoding($false)))
} catch { }
[void][System.Windows.Forms.MessageBox]::Show(
($_.Exception.Message + "`r`n`r`n" + $_.InvocationInfo.PositionMessage),
'github-setup 出错')
exit 1
}
$here = Split-Path -Parent $PSCommandPath
. (Join-Path $here 'engine.ps1')
$script:SettingsFile = Join-Path $script:BackupDir 'settings.json'
<#
.SYNOPSIS
Load the remembered scan root.
#>
function Get-SavedScanRoot {
try {
if (Test-Path $script:SettingsFile) {
$o = Get-Content $script:SettingsFile -Raw -Encoding UTF8 | ConvertFrom-Json
if ($o.scanRoot) { return [string]$o.scanRoot }
}
} catch { }
return ''
}
<#
.SYNOPSIS
Remember the scan root, so the next launch does not ask again.
#>
function Save-ScanRoot {
param([string]$Root)
try {
if (-not (Test-Path $script:BackupDir)) { New-Item -ItemType Directory -Path $script:BackupDir -Force | Out-Null }
@{ scanRoot = $Root } | ConvertTo-Json | Set-Content -Path $script:SettingsFile -Encoding UTF8
} catch { }
}
# --------------------------------------------------------------------------
# form
# --------------------------------------------------------------------------
$form = New-Object System.Windows.Forms.Form
$form.Text = 'GitHub 访问一键设置'
$form.Size = New-Object System.Drawing.Size(880, 730)
$form.StartPosition = 'CenterScreen'
$form.MinimumSize = New-Object System.Drawing.Size(880, 730)
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 9)
$statusView = New-Object System.Windows.Forms.ListView
$statusView.Location = New-Object System.Drawing.Point(12, 12)
$statusView.Size = New-Object System.Drawing.Size(840, 158)
$statusView.View = 'Details'
$statusView.FullRowSelect = $true
$statusView.GridLines = $true
$statusView.HeaderStyle = 'Nonclickable'
[void]$statusView.Columns.Add('项目', 190)
[void]$statusView.Columns.Add('状态', 640)
$form.Controls.Add($statusView)
$latencyLabel = New-Object System.Windows.Forms.Label
$latencyLabel.Location = New-Object System.Drawing.Point(12, 176)
$latencyLabel.Size = New-Object System.Drawing.Size(840, 20)
$latencyLabel.Text = '延迟:尚未实测'
$form.Controls.Add($latencyLabel)
$scanLabel = New-Object System.Windows.Forms.Label
$scanLabel.Location = New-Object System.Drawing.Point(12, 204)
$scanLabel.Size = New-Object System.Drawing.Size(120, 22)
$scanLabel.Text = '扫描仓库目录'
$form.Controls.Add($scanLabel)
$scanBox = New-Object System.Windows.Forms.TextBox
$scanBox.Location = New-Object System.Drawing.Point(136, 202)
$scanBox.Size = New-Object System.Drawing.Size(566, 24)
$scanBox.Text = Get-SavedScanRoot
$form.Controls.Add($scanBox)
$browseButton = New-Object System.Windows.Forms.Button
$browseButton.Location = New-Object System.Drawing.Point(708, 200)
$browseButton.Size = New-Object System.Drawing.Size(70, 26)
$browseButton.Text = '浏览…'
$form.Controls.Add($browseButton)
$refreshButton = New-Object System.Windows.Forms.Button
$refreshButton.Location = New-Object System.Drawing.Point(784, 200)
$refreshButton.Size = New-Object System.Drawing.Size(68, 26)
$refreshButton.Text = '重新检测'
$form.Controls.Add($refreshButton)
$fixButton = New-Object System.Windows.Forms.Button
$fixButton.Location = New-Object System.Drawing.Point(12, 236)
$fixButton.Size = New-Object System.Drawing.Size(130, 32)
$fixButton.Text = '一键修复'
$fixButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 9, [System.Drawing.FontStyle]::Bold)
$form.Controls.Add($fixButton)
$previewButton = New-Object System.Windows.Forms.Button
$previewButton.Location = New-Object System.Drawing.Point(150, 236)
$previewButton.Size = New-Object System.Drawing.Size(130, 32)
$previewButton.Text = '仅预览'
$form.Controls.Add($previewButton)
$measureButton = New-Object System.Windows.Forms.Button
$measureButton.Location = New-Object System.Drawing.Point(288, 236)
$measureButton.Size = New-Object System.Drawing.Size(150, 32)
$measureButton.Text = '实测延迟'
$form.Controls.Add($measureButton)
$undoButton = New-Object System.Windows.Forms.Button
$undoButton.Location = New-Object System.Drawing.Point(446, 236)
$undoButton.Size = New-Object System.Drawing.Size(130, 32)
$undoButton.Text = '撤销全部'
$form.Controls.Add($undoButton)
$copyKeyButton = New-Object System.Windows.Forms.Button
$copyKeyButton.Location = New-Object System.Drawing.Point(584, 236)
$copyKeyButton.Size = New-Object System.Drawing.Size(130, 32)
$copyKeyButton.Text = '复制公钥'
$form.Controls.Add($copyKeyButton)
$openGithubButton = New-Object System.Windows.Forms.Button
$openGithubButton.Location = New-Object System.Drawing.Point(722, 236)
$openGithubButton.Size = New-Object System.Drawing.Size(130, 32)
$openGithubButton.Text = '打开 GitHub'
$form.Controls.Add($openGithubButton)
$toolsLabel = New-Object System.Windows.Forms.Label
$toolsLabel.Location = New-Object System.Drawing.Point(12, 278)
$toolsLabel.Size = New-Object System.Drawing.Size(840, 20)
$toolsLabel.Text = '各工具是否走这份配置(双击任一行:复制可在该工具里运行的验证命令)'
$form.Controls.Add($toolsLabel)
$toolsView = New-Object System.Windows.Forms.ListView
$toolsView.Location = New-Object System.Drawing.Point(12, 300)
$toolsView.Size = New-Object System.Drawing.Size(840, 180)
$toolsView.View = 'Details'
$toolsView.FullRowSelect = $true
$toolsView.GridLines = $true
$toolsView.HeaderStyle = 'Nonclickable'
[void]$toolsView.Columns.Add('工具', 150)
[void]$toolsView.Columns.Add('类别', 96)
[void]$toolsView.Columns.Add('结论', 70)
[void]$toolsView.Columns.Add('说明', 500)
$form.Controls.Add($toolsView)
# GUI tools cannot be driven from here -- there is no "run git inside VS Code"
# entry point -- so the honest test is a command the user pastes into that
# tool's own terminal. Double-clicking a row copies it.
$toolsView.Add_DoubleClick({
if ($null -eq $script:State) { return }
$command = Get-VerificationCommand -KeyPath $script:State.KeyPath -Port $script:State.Port
try {
[System.Windows.Forms.Clipboard]::SetText($command)
Write-Log "已复制验证命令(粘到该工具自己的终端里运行):`r`n$command"
} catch {
Write-Log ("复制失败,请手动运行:`r`n$command")
}
})
$logBox = New-Object System.Windows.Forms.TextBox
$logBox.Location = New-Object System.Drawing.Point(12, 490)
$logBox.Size = New-Object System.Drawing.Size(840, 186)
$logBox.Multiline = $true
$logBox.ScrollBars = 'Vertical'
$logBox.ReadOnly = $true
$logBox.BackColor = [System.Drawing.Color]::White
$logBox.Font = New-Object System.Drawing.Font('Consolas', 9)
$form.Controls.Add($logBox)
<#
.SYNOPSIS
Append one line to the log pane.
#>
function Write-Log {
param([string]$Text)
$stamp = (Get-Date).ToString('HH:mm:ss')
$logBox.AppendText("[$stamp] $Text`r`n")
$logBox.SelectionStart = $logBox.TextLength
$logBox.ScrollToCaret()
[System.Windows.Forms.Application]::DoEvents()
}
<#
.SYNOPSIS
A green/red marker plus a word, so the column scans at a glance.
#>
function Get-Marker {
param([bool]$Ok)
if ($Ok) { return '✓ 已就绪' }
return '✗ 未就绪'
}
# Cached state, so a button click does not re-probe the network.
$script:State = $null
<#
.SYNOPSIS
Re-detect and repaint everything.
.PARAMETER Measure
Also time the transports. Slow, and only on request.
#>
function Update-View {
param([switch]$Measure)
$scanRoot = $scanBox.Text.Trim()
if ($scanRoot -ne '') {
if (Test-Path $scanRoot) { Save-ScanRoot -Root $scanRoot }
else { Write-Log "扫描目录不存在,已忽略:$scanRoot"; $scanRoot = '' }
}
Write-Log '正在检测…'
$form.Cursor = [System.Windows.Forms.Cursors]::WaitCursor
[System.Windows.Forms.Application]::DoEvents()
try {
$script:State = Get-GitHubSetupState -ScanRoot $scanRoot
$s = $script:State
$statusView.Items.Clear()
# Built as data, then rendered. An earlier version passed each row as
# `& $addRow 'text' $( if ... ) (bool)` and the boolean did not reliably
# bind, which turned a passing check red -- a UI that cries wolf is worse
# than no UI. Three verdicts rather than two: "not scanned yet" is neither
# done nor broken.
$statusRows = @(
@{
Name = 'SSH key'
Value = $(if ($s.KeyExists) { $s.KeyPath } else { '尚未创建(点「一键修复」会创建)' })
Kind = $(if ($s.KeyExists) { 'ok' } else { 'todo' })
}
@{
Name = 'GitHub 是否认识这把公钥'
Value = $(if ($s.Registered) {
'已注册' + $(if ($s.Login -ne '') { ",账号 $($s.Login)" } else { '' })
} else { $s.RegisterDetail })
Kind = $(if ($s.Registered) { 'ok' } else { 'todo' })
}
@{
Name = 'ssh 配置(Host github.com)'
Value = $(if ($s.SshBlock.Present) { "$($s.SshBlock.HostName):$($s.SshBlock.Port)" } else { '未配置' })
Kind = $(if ($s.SshBlock.Present -and $s.SshBlock.Port -eq $s.Port -and $s.SshBlock.HostName -eq 'ssh.github.com') { 'ok' } else { 'todo' })
}
@{
Name = 'git 全局 URL 重写'
Value = $(if ($s.HasRewrite) { 'https://github.com/ -> git@github.com:' } else { '未设置' })
Kind = $(if ($s.HasRewrite) { 'ok' } else { 'todo' })
}
@{
Name = '镜像前缀的 remote'
Value = $(if ($scanRoot -eq '') { '未扫描(可在上方选择目录)' }
elseif ($s.Remotes.Count -eq 0) { '未发现仓库' }
elseif ($s.NeedsFixCount -eq 0) { "共 $($s.Remotes.Count) 个,全部已是 SSH" }
else { "共 $($s.Remotes.Count) 个,其中 $($s.NeedsFixCount) 个需改写" })
Kind = $(if ($scanRoot -eq '') { 'info' } elseif ($s.NeedsFixCount -eq 0) { 'ok' } else { 'todo' })
}
)
foreach ($entry in $statusRows) {
$row = New-Object System.Windows.Forms.ListViewItem($entry.Name)
[void]$row.SubItems.Add($entry.Value)
switch ($entry.Kind) {
'ok' { $row.ForeColor = [System.Drawing.Color]::FromArgb(0, 110, 40) }
'todo' { $row.ForeColor = [System.Drawing.Color]::FromArgb(170, 40, 40) }
default { $row.ForeColor = [System.Drawing.Color]::FromArgb(110, 110, 110) }
}
[void]$statusView.Items.Add($row)
}
$toolsView.Items.Clear()
foreach ($t in (Get-GitHubToolMatrix)) {
$row = New-Object System.Windows.Forms.ListViewItem($t.Name)
[void]$row.SubItems.Add($t.Kind)
[void]$row.SubItems.Add($t.Verdict)
[void]$row.SubItems.Add($t.Detail)
switch ($t.Verdict) {
'核心' { $row.ForeColor = [System.Drawing.Color]::FromArgb(0, 110, 40) }
'继承' { $row.ForeColor = [System.Drawing.Color]::FromArgb(0, 110, 40) }
'部分' { $row.ForeColor = [System.Drawing.Color]::FromArgb(170, 110, 0) }
'独立' { $row.ForeColor = [System.Drawing.Color]::FromArgb(170, 110, 0) }
default { $row.ForeColor = [System.Drawing.Color]::FromArgb(120, 120, 120) }
}
[void]$toolsView.Items.Add($row)
}
if ($Measure) {
$latencyLabel.Text = '延迟:实测中(最长约 60 秒)…'
[System.Windows.Forms.Application]::DoEvents()
$m = Measure-GitHubTransport -KeyPath $s.KeyPath -Port $s.Port
$latencyLabel.Text = ('延迟:HTTPS {0} ms{1} SSH {2} ms{3}' -f `
$m.HttpsMs,
$(if ($m.HttpsOk) { '' } else { '(失败)' }),
$m.SshMs,
$(if ($s.Registered) { $(if ($m.SshOk) { '' } else { '(失败)' }) } else { '(公钥未注册,未测)' }))
Write-Log ("HTTPS ls-remote: {0} ms {1}" -f $m.HttpsMs, $(if ($m.HttpsOk) { 'OK' } else { '失败' }))
if ($s.Registered) {
Write-Log ("SSH ls-remote: {0} ms {1}" -f $m.SshMs, $(if ($m.SshOk) { 'OK' } else { '失败' }))
if ($m.SshOk -and $m.HttpsMs -gt 0 -and $m.SshMs -gt 0) {
$ratio = [math]::Round($m.HttpsMs / [math]::Max($m.SshMs, 1), 1)
Write-Log ("SSH 比 HTTPS 快 {0} 倍" -f $ratio)
}
}
}
$plan = @(Get-GitHubSetupPlan -State $s)
if ($plan.Count -eq 0) { Write-Log '检测完成:全部已就绪,无需改动。' }
else { Write-Log ("检测完成:有 {0} 项待处理。" -f $plan.Count) }
} finally {
$form.Cursor = [System.Windows.Forms.Cursors]::Default
}
}
# --------------------------------------------------------------------------
# events
# --------------------------------------------------------------------------
$browseButton.Add_Click({
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
$dialog.Description = '选择存放 git 仓库的根目录(会扫描三层)'
if ($scanBox.Text.Trim() -ne '' -and (Test-Path $scanBox.Text.Trim())) { $dialog.SelectedPath = $scanBox.Text.Trim() }
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
$scanBox.Text = $dialog.SelectedPath
Update-View
}
})
$refreshButton.Add_Click({ Update-View })
$measureButton.Add_Click({ Update-View -Measure })
$previewButton.Add_Click({
if ($null -eq $script:State) { Update-View }
Write-Log '—— 预览(不会修改任何东西)——'
$plan = @(Get-GitHubSetupPlan -State $script:State)
if ($plan.Count -eq 0) { Write-Log '没有需要做的事。'; return }
foreach ($p in $plan) { Write-Log (" 将执行:{0}" -f $p.Text) }
foreach ($line in (Invoke-GitHubSetupApply -State $script:State -ScanRoot $scanBox.Text.Trim() -WhatIf)) {
Write-Log (" " + $line)
}
})
$fixButton.Add_Click({
if ($null -eq $script:State) { Update-View }
Write-Log '—— 开始修复 ——'
$form.Cursor = [System.Windows.Forms.Cursors]::WaitCursor
[System.Windows.Forms.Application]::DoEvents()
try {
foreach ($line in (Invoke-GitHubSetupApply -State $script:State -ScanRoot $scanBox.Text.Trim())) {
Write-Log $line
}
} finally {
$form.Cursor = [System.Windows.Forms.Cursors]::Default
}
Write-Log '—— 修复结束,重新检测 ——'
Update-View -Measure
})
$undoButton.Add_Click({
$latest = Get-LatestBackup
if ($null -eq $latest) { Write-Log '没有找到备份,无法撤销。'; return }
$confirm = [System.Windows.Forms.MessageBox]::Show(
"将按备份回滚:`r`n$latest`r`n`r`n继续吗?",
'撤销全部改动',
[System.Windows.Forms.MessageBoxButtons]::YesNo,
[System.Windows.Forms.MessageBoxIcon]::Question)
if ($confirm -ne [System.Windows.Forms.DialogResult]::Yes) { return }
Write-Log '—— 开始撤销 ——'
foreach ($line in (Invoke-GitHubSetupUndo -BackupFile $latest)) { Write-Log $line }
Update-View
})
$copyKeyButton.Add_Click({
if ($null -eq $script:State) { Update-View }
if ($script:State.KeyPublic -eq '') {
Write-Log '还没有公钥可复制 —— 先点「一键修复」创建 key。'
return
}
try {
[System.Windows.Forms.Clipboard]::SetText($script:State.KeyPublic)
Write-Log '公钥已复制到剪贴板。粘到 https://github.com/settings/keys 即可。'
} catch {
Write-Log ('复制失败:' + $_.Exception.Message)
}
})
$openGithubButton.Add_Click({
try {
Start-Process 'https://github.com/settings/keys'
Write-Log '已在浏览器打开 GitHub 的 SSH keys 设置页(这个页面本身可能比较慢)。'
} catch {
Write-Log ('打开浏览器失败:' + $_.Exception.Message)
}
})
$form.Add_Shown({
Write-Log 'git 访问 GitHub 的一键设置。先点「实测延迟」看现状,再点「一键修复」。'
Update-View
if ($script:State -and -not $script:State.Registered) {
Write-Log '下一步:点「一键修复」创建 key,再点「复制公钥」并粘到 GitHub。'
}
})
[void]$form.ShowDialog()