-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptKit.ps1
More file actions
234 lines (215 loc) · 11.3 KB
/
Copy pathScriptKit.ps1
File metadata and controls
234 lines (215 loc) · 11.3 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
# ============================================================================
# ScriptKit v1 -- shared console UI + helpers for build / run / setup scripts
# ============================================================================
# VENDORED helper. Copy this file into a repo and dot-source it near the top of
# a script:
# . (Join-Path $PSScriptRoot 'ScriptKit.ps1')
#
# Design rules (keep them when editing):
# * Pure presentation / small utilities -- NO Set-StrictMode (this dot-sources
# into foreign scripts and must not change their strictness).
# * English-only, no Cyrillic in code -- so Windows PowerShell 5.1 parses the
# file cleanly even without a BOM.
# * Box glyphs are built at runtime ([char]0x....) -- renders in PS 5.1.
# * Keep this file IDENTICAL across repos. Bump the version below on change so
# drift between copies is visible.
# ============================================================================
# --- UTF-8 console (box glyphs + check marks render instead of mojibake) ----
try { chcp 65001 | Out-Null } catch { }
try {
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
} catch { }
# --- Box-drawing glyphs (script scope -> visible to callers after dot-source) -
$script:SK_H = ([char]0x2500).ToString() # horizontal
$script:SK_TL = ([char]0x250C).ToString() # top-left
$script:SK_TR = ([char]0x2510).ToString() # top-right
$script:SK_BL = ([char]0x2514).ToString() # bottom-left
$script:SK_BR = ([char]0x2518).ToString() # bottom-right
$script:SK_V = ([char]0x2502).ToString() # vertical
$script:SK_TM = ([char]0x251C).ToString() # left tee (summary dividers)
$script:SK_BLOCK_F = ([char]0x2588).ToString() # full block (progress)
$script:SK_BLOCK_E = ([char]0x2591).ToString() # light shade (progress empty)
$script:SK_LogFile = $null
# ============================================================================
# Console UI
# ============================================================================
# Two-line framed banner. Line2 is an optional dimmed subtitle.
function Write-Banner {
param([string]$Line1, [string]$Line2 = '', [string]$Color = 'Cyan', [int]$Width = 58)
$bar = $script:SK_H * $Width
Write-Host ""
Write-Host (" " + $script:SK_TL + $bar + $script:SK_TR) -ForegroundColor $Color
Write-Host (" " + $script:SK_V + " " + $Line1) -ForegroundColor $Color
if ($Line2) { Write-Host (" " + $script:SK_V + " " + $Line2) -ForegroundColor DarkGray }
Write-Host (" " + $script:SK_BL + $bar + $script:SK_BR) -ForegroundColor $Color
}
# Phase separator + progress bar + [step/total] heading.
function Write-Step {
param([int]$Step, [int]$Total, [string]$Msg)
Write-Host ""
Write-Host (" " + $script:SK_H * 60) -ForegroundColor DarkGray
$pct = if ($Total -gt 0) { [math]::Floor(($Step - 1) / $Total * 100) } else { 0 }
$filled = [math]::Floor($pct / 2); $empty = 50 - $filled
if ($empty -lt 0) { $empty = 0 }
$bar = ($script:SK_BLOCK_F * $filled) + ($script:SK_BLOCK_E * $empty)
Write-Host " $bar ${pct}%" -ForegroundColor Cyan
Write-Host " [$Step/$Total] $Msg" -ForegroundColor Yellow
Write-Host ""
}
function Write-Ok { param([string]$Msg) Write-Host " $([char]0x2714) $Msg" -ForegroundColor Green }
function Write-Fail { param([string]$Msg) Write-Host " $([char]0x2718) $Msg" -ForegroundColor Red }
function Write-Warn { param([string]$Msg) Write-Host " $([char]0x26A0) $Msg" -ForegroundColor Yellow }
function Write-Info { param([string]$Msg) Write-Host " $([char]0x2022) $Msg" -ForegroundColor DarkGray }
# Tagged status line: [OK]/[FAIL]/[WARN]/[SKIP]/[INFO]/... + message.
function Write-Status {
param([string]$Text, [string]$Tag = 'OK')
$map = @{ OK='Green'; FAIL='Red'; WARN='Yellow'; SKIP='DarkGray'; INFO='Cyan';
DRY='Magenta'; MERGED='Green'; OPEN='Cyan'; CONFLICT='Red'; LOCAL='DarkGray' }
$c = $map[$Tag]; if (-not $c) { $c = 'Gray' }
Write-Host (" [{0}] " -f $Tag) -ForegroundColor $c -NoNewline
Write-Host $Text -ForegroundColor White
if ($script:SK_LogFile) { Write-Log -Msg ("[{0}] {1}" -f $Tag, $Text) -Level $Tag -NoConsole }
}
# ============================================================================
# Notifications
# ============================================================================
# Windows tray balloon. On SUCCESS prefer the app's own icon (never the red
# system error glyph); fall back to a state-appropriate system icon. All wrapped
# in try/catch so a headless/missing WinForms API silently no-ops.
function Show-Notification {
param([string]$Title, [string]$Body, [switch]$IsError, [string]$IconPath)
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop
Add-Type -AssemblyName System.Drawing -ErrorAction Stop
$icon = $null
if ($IconPath) {
try {
$full = (Resolve-Path -LiteralPath $IconPath -ErrorAction Stop).Path
$icon = [System.Drawing.Icon]::ExtractAssociatedIcon($full)
} catch { $icon = $null }
}
if (-not $icon) {
$icon = if ($IsError) { [System.Drawing.SystemIcons]::Error } else { [System.Drawing.SystemIcons]::Asterisk }
}
$tray = New-Object System.Windows.Forms.NotifyIcon
$tray.Icon = $icon
$tray.BalloonTipIcon = if ($IsError) { 'Error' } else { 'Info' }
$tray.BalloonTipTitle = $Title
$tray.BalloonTipText = $Body
$tray.Visible = $true
$tray.ShowBalloonTip(8000)
Start-Sleep -Milliseconds 1200 # let Windows capture the icon + render
$tray.Visible = $false
$tray.Dispose()
} catch { }
}
# ============================================================================
# Process / command helpers
# ============================================================================
# Run an external command in a background job with a hard timeout. Returns
# @{ Ok; Code; Out }. Code -2 == killed on timeout. No process ever hangs.
function Invoke-TimedCommand {
param([Parameter(Mandatory)][string]$FilePath, [string[]]$ArgList = @(), [int]$TimeoutSec = 120)
if ($TimeoutSec -lt 1) { $TimeoutSec = 60 }
$job = Start-Job -ScriptBlock {
param($exe, $a)
$out = & $exe @a 2>&1 | Out-String
[pscustomobject]@{ Code = $LASTEXITCODE; Out = $out }
} -ArgumentList $FilePath, (, $ArgList)
if (Wait-Job $job -Timeout $TimeoutSec) {
$res = Receive-Job $job; Remove-Job $job -Force -ErrorAction SilentlyContinue
$code = if ($res -and $null -ne $res.Code) { [int]$res.Code } else { 1 }
return @{ Ok = ($code -eq 0); Code = $code; Out = ([string]$res.Out).Trim() }
}
Stop-Job $job -ErrorAction SilentlyContinue; Remove-Job $job -Force -ErrorAction SilentlyContinue
return @{ Ok = $false; Code = -2; Out = "TIMEOUT after ${TimeoutSec}s (killed)" }
}
# Same as above but shows a live [|/-\] spinner with elapsed seconds.
function Invoke-TimedCommandWithSpinner {
param([Parameter(Mandatory)][string]$FilePath, [string[]]$ArgList = @(), [int]$TimeoutSec = 120, [string]$Activity = 'Working')
if ($TimeoutSec -lt 1) { $TimeoutSec = 60 }
$job = Start-Job -ScriptBlock {
param($exe, $a)
$out = & $exe @a 2>&1 | Out-String
[pscustomobject]@{ Code = $LASTEXITCODE; Out = $out }
} -ArgumentList $FilePath, (, $ArgList)
$spin = '|/-\'; $k = 0; $t0 = Get-Date
while ($null -eq (Wait-Job $job -Timeout 1)) {
$el = [int]((Get-Date) - $t0).TotalSeconds
Write-Host ("`r [{0}] {1} ({2}s) " -f $spin[$k % 4], $Activity, $el) -NoNewline -ForegroundColor Cyan
$k++
if ($el -ge $TimeoutSec) {
Stop-Job $job -ErrorAction SilentlyContinue; Remove-Job $job -Force -ErrorAction SilentlyContinue
Write-Host ("`r" + (' ' * 70) + "`r") -NoNewline
return @{ Ok = $false; Code = -2; Out = "TIMEOUT after ${TimeoutSec}s (killed)" }
}
}
Write-Host ("`r" + (' ' * 70) + "`r") -NoNewline
$res = Receive-Job $job; Remove-Job $job -Force -ErrorAction SilentlyContinue
$code = if ($res -and $null -ne $res.Code) { [int]$res.Code } else { 1 }
return @{ Ok = ($code -eq 0); Code = $code; Out = ([string]$res.Out).Trim() }
}
# Stop a running process by name (frees a locked exe before replacing it).
function Stop-NamedProcess {
param([Parameter(Mandatory)][string]$ProcessName)
$running = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
if (-not $running) { return $true }
try {
$running | Stop-Process -Force -ErrorAction Stop
Start-Sleep -Seconds 1
return $true
} catch {
Write-Warn ("Could not stop {0}: {1}" -f $ProcessName, $_.Exception.Message)
return $false
}
}
# ============================================================================
# Utilities
# ============================================================================
function Get-FileHashSHA256 {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return $null }
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
$bytes = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $Path).Path)
return ([BitConverter]::ToString($sha.ComputeHash($bytes)) -replace '-', '')
} finally { $sha.Dispose() }
}
# App version, best-effort: package.json -> Cargo.toml -> 'src-tauri\Cargo.toml' -> '?'.
function Get-AppVersion {
param([string]$Root = $PSScriptRoot)
$pkg = Join-Path $Root 'package.json'
if (Test-Path -LiteralPath $pkg) {
try { $j = Get-Content -LiteralPath $pkg -Raw -ErrorAction Stop | ConvertFrom-Json; if ($j.version) { return [string]$j.version } } catch { }
}
foreach ($rel in @('Cargo.toml', 'src-tauri\Cargo.toml')) {
$c = Join-Path $Root $rel
if (Test-Path -LiteralPath $c) {
$m = Select-String -LiteralPath $c -Pattern '(?m)^\s*version\s*=\s*"([^"]+)"' -ErrorAction SilentlyContinue | Select-Object -First 1
if ($m) { return $m.Matches[0].Groups[1].Value }
}
}
return '?'
}
# ============================================================================
# Logging (file + console)
# ============================================================================
# Start a timestamped log under <Root>\logs, keep newest $Keep files.
function Initialize-Logging {
param([string]$Root, [string]$Prefix = 'script', [int]$Keep = 15)
$logDir = Join-Path $Root 'logs'
if (-not (Test-Path -LiteralPath $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
$script:SK_LogFile = Join-Path $logDir ("{0}_{1}.log" -f $Prefix, (Get-Date -Format 'yyyyMMdd_HHmmss'))
Get-ChildItem -LiteralPath $logDir -Filter "$Prefix*.log" -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending | Select-Object -Skip $Keep |
ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue }
return $script:SK_LogFile
}
function Write-Log {
param([string]$Msg, [string]$Level = 'INFO', [switch]$NoConsole, [string]$Color = 'Gray')
if ($script:SK_LogFile) {
Add-Content -LiteralPath $script:SK_LogFile -Value ("[{0}] [{1}] {2}" -f (Get-Date -Format 'HH:mm:ss'), $Level, $Msg) -Encoding UTF8
}
if (-not $NoConsole) { Write-Host $Msg -ForegroundColor $Color }
}