refactor(windows): причёсан стиль chezmoi-скриптов и pwsh-профиля

- Зачем:
  - код Codex работал, но был тяжёл для чтения и сопровождения: 4 naming-конвенции, скрытая мутация $script:changed, 298 строк WT-скрипта почти без комментариев.
- Что:
  - profile.ps1: комментарии на русском перед каждой функцией, секционные разделители, wt-here → wt_here (единый snake_case), Get-PublicIp упрощён до Invoke-RestMethod, Chocolatey boilerplate обрезан.
  - WT-скрипт: Set/Remove-Prop возвращают bool вместо мутации $script:changed, naming выровнен в PascalCase, хелперы переименованы (Get-Prop, Set-Prop, Test-IsPS7, Test-IsStockPS7), комментарии к каждому блоку логики, вывод на русском.
  - Git-миграция: блок комментариев с описанием 4 сценариев, пояснение 3 вариантов ManagedStubs, naming выровнен, вывод на русском.
- Проверка:
  - pwsh -NoProfile -Command "[System.Management.Automation.Language.Parser]::ParseFile(...)" — синтаксис всех трёх файлов OK.
  - chezmoi -S "$HOME\dotfiles\chezmoi" apply --dry-run --verbose.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Dmitry DementievandClaude Opus 4.6 committed 2026-03-22 17:59:59 +03:00
1 parent c06ad1ecbb
commit 1963b6a117
3 files changed
+273 -379

No files matched your search

@@ -1,297 +1,239 @@
# Идемпотентная настройка Windows Terminal:
# - PS 7 = default profile (через source, без hardcoded commandline)
# - PS 5.1 переименован в "Legacy"
# - Azure Cloud Shell скрыт
# - дубли PS7-профилей удаляются
# - порядок: PS7 первый, PS5.1 второй, остальные как есть
#
# Скрипт НЕ перезаписывает settings.json, если ничего не изменилось.
if (-not ($IsWindows -or $PSVersionTable.PSEdition -eq 'Desktop')) { if (-not ($IsWindows -or $PSVersionTable.PSEdition -eq 'Desktop')) {
return return
} }
$settingsPath = Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json' $SettingsPath = Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
if (-not (Test-Path -LiteralPath $settingsPath)) { if (-not (Test-Path -LiteralPath $SettingsPath)) {
Write-Warning "Windows Terminal settings not found: $settingsPath" Write-Warning "Windows Terminal settings not found: $SettingsPath"
return return
} }
$PowerShellGuid = '{574e775e-4f2a-5b96-ac1e-a2962a402336}' # Well-known GUID и source для PS7 dynamic profile в WT.
$PowerShellSource = 'Windows.Terminal.PowershellCore' $PS7Guid = '{574e775e-4f2a-5b96-ac1e-a2962a402336}'
$LegacyPowerShellGuid = '{61c54bbd-c2c6-5271-96e7-009a87ff44bf}' $PS7Source = 'Windows.Terminal.PowershellCore'
$changed = $false $PS51Guid = '{61c54bbd-c2c6-5271-96e7-009a87ff44bf}'
$Changed = $false
function Get-JsonPropertyValue { # ── JSON-хелперы ─────────────────────────────────────────────────────
param( # ConvertFrom-Json даёт PSCustomObject; прямого .ContainsKey нет,
[Parameter(Mandatory = $true)] # поэтому работаем через PSObject.Properties.
$Object,
[Parameter(Mandatory = $true)]
[string]$Name
)
$Property = $Object.PSObject.Properties[$Name] function Get-Prop ($Object, [string]$Name) {
if ($null -eq $Property) { $P = $Object.PSObject.Properties[$Name]
return $null if ($null -eq $P) { return $null }
} return $P.Value
return $Property.Value
} }
function Test-JsonValueEqual { function Set-Prop ($Object, [string]$Name, $Value) {
param( # Возвращает $true, если значение действительно изменилось.
$Left, $P = $Object.PSObject.Properties[$Name]
$Right if ($null -eq $P) {
) $Object | Add-Member -NotePropertyName $Name -NotePropertyValue $Value
if ($null -eq $Left -and $null -eq $Right) {
return $true return $true
} }
if (-not (Test-PropEqual $P.Value $Value)) {
if ($null -eq $Left -or $null -eq $Right) { $P.Value = $Value
return $false return $true
} }
return $false
}
if ( function Remove-Prop ($Object, [string]$Name) {
$Left -is [System.Collections.IEnumerable] -and # Возвращает $true, если свойство существовало и было удалено.
-not ($Left -is [string]) $P = $Object.PSObject.Properties[$Name]
) { if ($null -ne $P) {
[void]$Object.PSObject.Properties.Remove($Name)
return $true
}
return $false
}
function Test-PropEqual ($Left, $Right) {
if ($null -eq $Left -and $null -eq $Right) { return $true }
if ($null -eq $Left -or $null -eq $Right) { return $false }
# Массивы и объекты сравниваем через JSON-сериализацию.
if ($Left -is [System.Collections.IEnumerable] -and -not ($Left -is [string])) {
return (ConvertTo-Json $Left -Depth 100 -Compress) -eq (ConvertTo-Json $Right -Depth 100 -Compress) return (ConvertTo-Json $Left -Depth 100 -Compress) -eq (ConvertTo-Json $Right -Depth 100 -Compress)
} }
return $Left -eq $Right return $Left -eq $Right
} }
function Set-JsonPropertyValue { function Test-PS7Available {
param( try { return $null -ne (Get-Command pwsh -ErrorAction SilentlyContinue) }
[Parameter(Mandatory = $true)] catch { return $false }
$Object,
[Parameter(Mandatory = $true)]
[string]$Name,
$Value
)
$Property = $Object.PSObject.Properties[$Name]
if ($null -eq $Property) {
$Object | Add-Member -NotePropertyName $Name -NotePropertyValue $Value
$script:changed = $true
return
}
if (-not (Test-JsonValueEqual -Left $Property.Value -Right $Value)) {
$Property.Value = $Value
$script:changed = $true
}
} }
function Remove-JsonPropertyValue { # ── Матчинг профилей ─────────────────────────────────────────────────
param(
[Parameter(Mandatory = $true)]
$Object,
[Parameter(Mandatory = $true)]
[string]$Name
)
$Property = $Object.PSObject.Properties[$Name] function Test-IsPS7 ($Profile) {
if ($null -ne $Property) { # Широкий матч: source ИЛИ commandline ИЛИ имя.
[void]$Object.PSObject.Properties.Remove($Name) $Src = [string](Get-Prop $Profile source)
$script:changed = $true $Cmd = [string](Get-Prop $Profile commandline)
} $Nm = [string](Get-Prop $Profile name)
if ($Src -eq $PS7Source) { return $true }
if ($Cmd -match '(?i)(^|[\\/ ])pwsh(?:\.exe)?(?:\s|$)') { return $true }
return $Nm -match '^(PowerShell|PowerShell 7)$'
} }
function Test-PowerShell7Available { function Test-IsStockPS7 ($Profile) {
try { # Узкий матч: только «стандартные» PS7-профили, которые безопасно удалять как дубли.
return $null -ne (Get-Command pwsh -ErrorAction SilentlyContinue | Select-Object -First 1) # Кастомные профили с нестандартным именем НЕ удаляются.
} $Src = [string](Get-Prop $Profile source)
catch { $Cmd = [string](Get-Prop $Profile commandline)
return $false $Nm = [string](Get-Prop $Profile name)
}
}
function Test-IsPowerShell7Profile {
param(
[Parameter(Mandatory = $true)]
$Profile
)
$Source = [string](Get-JsonPropertyValue -Object $Profile -Name source)
$Name = [string](Get-JsonPropertyValue -Object $Profile -Name name)
$CommandLine = [string](Get-JsonPropertyValue -Object $Profile -Name commandline)
if ($Source -eq $PowerShellSource) {
return $true
}
if ($CommandLine -match '(?i)(^|[\\/ ])pwsh(?:\.exe)?(?:\s|$)') {
return $true
}
return $Name -match '^(PowerShell|PowerShell 7)$'
}
function Test-IsDisposablePowerShell7Profile {
param(
[Parameter(Mandatory = $true)]
$Profile
)
$Source = [string](Get-JsonPropertyValue -Object $Profile -Name source)
$Name = [string](Get-JsonPropertyValue -Object $Profile -Name name)
$CommandLine = [string](Get-JsonPropertyValue -Object $Profile -Name commandline)
return ( return (
$Name -match '^(PowerShell|PowerShell 7)$' -and $Nm -match '^(PowerShell|PowerShell 7)$' -and
( ($Src -eq $PS7Source -or $Cmd -match '(?i)(^|[\\/ ])pwsh(?:\.exe)?(?:\s|$)')
$Source -eq $PowerShellSource -or
$CommandLine -match '(?i)(^|[\\/ ])pwsh(?:\.exe)?(?:\s|$)'
)
) )
} }
# ── Чтение settings.json ─────────────────────────────────────────────
try { try {
$originalSettings = Get-Content -LiteralPath $settingsPath -Raw $Settings = Get-Content -LiteralPath $SettingsPath -Raw | ConvertFrom-Json
$settings = $originalSettings | ConvertFrom-Json
} }
catch { catch {
Write-Warning "Failed to read Windows Terminal settings: $settingsPath" Write-Warning "Failed to read Windows Terminal settings: $SettingsPath"
Write-Warning $_ Write-Warning $_
return return
} }
if ($null -eq (Get-JsonPropertyValue -Object $settings -Name profiles)) { # Гарантируем наличие profiles.list (может отсутствовать на чистой установке).
$settings | Add-Member -NotePropertyName profiles -NotePropertyValue ([pscustomobject]@{ if ($null -eq (Get-Prop $Settings profiles)) {
defaults = [pscustomobject]@{} $Settings | Add-Member -NotePropertyName profiles -NotePropertyValue ([pscustomobject]@{
list = @() defaults = [pscustomobject]@{}; list = @()
}) })
$changed = $true $Changed = $true
}
if ($null -eq (Get-Prop $Settings.profiles list)) {
$Settings.profiles | Add-Member -NotePropertyName list -NotePropertyValue @()
$Changed = $true
} }
if ($null -eq (Get-JsonPropertyValue -Object $settings.profiles -Name list)) { # ── Поиск профилей ───────────────────────────────────────────────────
$settings.profiles | Add-Member -NotePropertyName list -NotePropertyValue @()
$changed = $true
}
$profiles = @($settings.profiles.list) $Profiles = @($Settings.profiles.list)
$powerShell7CandidateIndices = New-Object System.Collections.Generic.List[int] $PS7Candidates = New-Object System.Collections.Generic.List[int]
$legacyPowerShellIndex = $null $PS51Index = $null
for ($i = 0; $i -lt $profiles.Count; $i++) { for ($I = 0; $I -lt $Profiles.Count; $I++) {
$profile = $profiles[$i] $P = $Profiles[$I]
$guid = [string](Get-JsonPropertyValue -Object $profile -Name guid)
$source = [string](Get-JsonPropertyValue -Object $profile -Name source)
$commandLine = [string](Get-JsonPropertyValue -Object $profile -Name commandline)
if (Test-IsPowerShell7Profile -Profile $profile) { if (Test-IsPS7 $P) { [void]$PS7Candidates.Add($I) }
[void]$powerShell7CandidateIndices.Add($i)
# PS 5.1: по well-known GUID или по commandline.
$Guid = [string](Get-Prop $P guid)
$Cmd = [string](Get-Prop $P commandline)
if ($Guid -eq $PS51Guid -or $Cmd -match '(?i)WindowsPowerShell\\v1\.0\\powershell\.exe') {
$PS51Index = $I
} }
if ( # Azure Cloud Shell — скрыть.
$guid -eq $LegacyPowerShellGuid -or if ([string](Get-Prop $P source) -eq 'Windows.Terminal.Azure') {
$commandLine -match '(?i)WindowsPowerShell\\v1\.0\\powershell\.exe' if (Set-Prop $P hidden $true) { $Changed = $true }
) {
$legacyPowerShellIndex = $i
}
if ($source -eq 'Windows.Terminal.Azure') {
Set-JsonPropertyValue -Object $profile -Name hidden -Value $true
} }
} }
$powerShell7Index = $null # Предпочитаем кандидата с source (dynamic profile), иначе первый найденный.
foreach ($candidateIndex in $powerShell7CandidateIndices) { $PS7Index = $null
$candidate = $profiles[$candidateIndex] foreach ($Idx in $PS7Candidates) {
if ([string](Get-JsonPropertyValue -Object $candidate -Name source) -eq $PowerShellSource) { if ([string](Get-Prop $Profiles[$Idx] source) -eq $PS7Source) {
$powerShell7Index = $candidateIndex $PS7Index = $Idx; break
break
} }
} }
if ($null -eq $PS7Index -and $PS7Candidates.Count -gt 0) {
if ($null -eq $powerShell7Index -and $powerShell7CandidateIndices.Count -gt 0) { $PS7Index = $PS7Candidates[0]
$powerShell7Index = $powerShell7CandidateIndices[0]
} }
if ($null -eq $powerShell7Index) { # ── Создание / обновление PS7-профиля ────────────────────────────────
if (Test-PowerShell7Available) {
# Create a dynamic-profile override instead of a manual pwsh.exe launcher. if ($null -eq $PS7Index) {
$profiles += [pscustomobject]@{ if (Test-PS7Available) {
guid = $PowerShellGuid # Создаём override для dynamic profile (source, НЕ commandline).
hidden = $false $Profiles += [pscustomobject]@{
name = 'PowerShell 7' guid = $PS7Guid; hidden = $false; name = 'PowerShell 7'
source = $PowerShellSource source = $PS7Source; startingDirectory = '%USERPROFILE%'
startingDirectory = '%USERPROFILE%'
} }
$powerShell7Index = $profiles.Count - 1 $PS7Index = $Profiles.Count - 1
$changed = $true $Changed = $true
} }
else { else {
Write-Warning 'PowerShell 7 was not detected; leaving Windows Terminal default profile unchanged.' Write-Warning 'PowerShell 7 not found; default profile not changed.'
} }
} }
if ($null -ne $powerShell7Index) { if ($null -ne $PS7Index) {
$powerShell7Profile = $profiles[$powerShell7Index] $PS7Profile = $Profiles[$PS7Index]
Set-JsonPropertyValue -Object $powerShell7Profile -Name guid -Value $PowerShellGuid # source вместо commandline — WT сам найдёт pwsh через dynamic profile.
Set-JsonPropertyValue -Object $powerShell7Profile -Name source -Value $PowerShellSource if (Set-Prop $PS7Profile guid $PS7Guid) { $Changed = $true }
Remove-JsonPropertyValue -Object $powerShell7Profile -Name commandline if (Set-Prop $PS7Profile source $PS7Source) { $Changed = $true }
Set-JsonPropertyValue -Object $powerShell7Profile -Name name -Value 'PowerShell 7' if (Remove-Prop $PS7Profile commandline) { $Changed = $true }
Set-JsonPropertyValue -Object $powerShell7Profile -Name hidden -Value $false if (Set-Prop $PS7Profile name 'PowerShell 7') { $Changed = $true }
Set-JsonPropertyValue -Object $powerShell7Profile -Name startingDirectory -Value '%USERPROFILE%' if (Set-Prop $PS7Profile hidden $false) { $Changed = $true }
Set-JsonPropertyValue -Object $settings -Name defaultProfile -Value ([string](Get-JsonPropertyValue -Object $powerShell7Profile -Name guid)) if (Set-Prop $PS7Profile startingDirectory '%USERPROFILE%'){ $Changed = $true }
if (Set-Prop $Settings defaultProfile (Get-Prop $PS7Profile guid)) { $Changed = $true }
} }
if ($null -ne $legacyPowerShellIndex) { # ── PS 5.1 — переименовать в Legacy ──────────────────────────────────
$legacyPowerShellProfile = $profiles[$legacyPowerShellIndex]
Set-JsonPropertyValue -Object $legacyPowerShellProfile -Name name -Value 'Windows PowerShell 5.1 (Legacy)' if ($null -ne $PS51Index) {
Set-JsonPropertyValue -Object $legacyPowerShellProfile -Name hidden -Value $false $PS51 = $Profiles[$PS51Index]
if (Set-Prop $PS51 name 'Windows PowerShell 5.1 (Legacy)') { $Changed = $true }
if (Set-Prop $PS51 hidden $false) { $Changed = $true }
} }
$removedIndices = New-Object System.Collections.Generic.HashSet[int] # ── Удаление дублей PS7 ──────────────────────────────────────────────
foreach ($candidateIndex in $powerShell7CandidateIndices) { # Оставляем выбранный PS7Index, остальные stock-профили удаляем.
if ($candidateIndex -eq $powerShell7Index) {
continue
}
if (Test-IsDisposablePowerShell7Profile -Profile $profiles[$candidateIndex]) { $RemovedIndices = New-Object System.Collections.Generic.HashSet[int]
if ($removedIndices.Add($candidateIndex)) { foreach ($Idx in $PS7Candidates) {
$changed = $true if ($Idx -eq $PS7Index) { continue }
} if (Test-IsStockPS7 $Profiles[$Idx]) {
if ($RemovedIndices.Add($Idx)) { $Changed = $true }
} }
} }
$orderedProfiles = New-Object System.Collections.Generic.List[object] # ── Сборка нового порядка профилей ────────────────────────────────────
$addedIndices = New-Object System.Collections.Generic.HashSet[int] # PS7 первый, PS 5.1 второй, остальные в исходном порядке.
function Add-ProfileByIndex { $Ordered = New-Object System.Collections.Generic.List[object]
param( $Added = New-Object System.Collections.Generic.HashSet[int]
[int]$Index
)
if ($Index -lt 0) { function Add-ByIndex ([int]$Idx) {
return if ($Idx -lt 0 -or $RemovedIndices.Contains($Idx)) { return }
} if ($Added.Add($Idx)) { $Ordered.Add($Profiles[$Idx]) }
if ($removedIndices.Contains($Index)) {
return
}
if ($addedIndices.Add($Index)) {
$orderedProfiles.Add($profiles[$Index])
}
} }
Add-ProfileByIndex -Index $powerShell7Index Add-ByIndex $PS7Index
if ($null -ne $legacyPowerShellIndex) { if ($null -ne $PS51Index) { Add-ByIndex $PS51Index }
Add-ProfileByIndex -Index $legacyPowerShellIndex for ($I = 0; $I -lt $Profiles.Count; $I++) { Add-ByIndex $I }
}
for ($i = 0; $i -lt $profiles.Count; $i++) { $OrderedArray = @($Ordered.ToArray())
Add-ProfileByIndex -Index $i if ((ConvertTo-Json $Profiles -Depth 100 -Compress) -ne (ConvertTo-Json $OrderedArray -Depth 100 -Compress)) {
$Changed = $true
} }
$Settings.profiles.list = $OrderedArray
$orderedProfilesArray = @($orderedProfiles.ToArray()) # ── Запись, только если что-то реально изменилось ─────────────────────
if ((ConvertTo-Json $profiles -Depth 100 -Compress) -ne (ConvertTo-Json $orderedProfilesArray -Depth 100 -Compress)) {
$changed = $true
}
$settings.profiles.list = $orderedProfilesArray
if (-not $changed) { if (-not $Changed) {
Write-Host 'Windows Terminal settings already match the managed baseline.' Write-Host 'Windows Terminal: настройки уже соответствуют baseline.'
return return
} }
$backupPath = '{0}.bak-{1}' -f $settingsPath, (Get-Date -Format 'yyyyMMdd-HHmmss') $BackupPath = '{0}.bak-{1}' -f $SettingsPath, (Get-Date -Format 'yyyyMMdd-HHmmss')
Copy-Item -LiteralPath $settingsPath -Destination $backupPath -Force Copy-Item -LiteralPath $SettingsPath -Destination $BackupPath -Force
$settings | ConvertTo-Json -Depth 100 | Set-Content -LiteralPath $settingsPath -Encoding utf8BOM $Settings | ConvertTo-Json -Depth 100 | Set-Content -LiteralPath $SettingsPath -Encoding utf8BOM
Write-Host "Updated Windows Terminal settings: $settingsPath" Write-Host "Windows Terminal: обновлено $SettingsPath"
Write-Host "Backup saved to: $backupPath" Write-Host "Бэкап: $BackupPath"
@@ -1,10 +1,25 @@
# Миграция существующего ~/.gitconfig перед тем, как chezmoi подставит managed stub.
#
# Логика:
# 1. Если ~/.gitconfig нет — создаём пустой ~/.gitconfig.local и выходим.
# 2. Если ~/.gitconfig уже содержит managed stub — ничего не делаем.
# 3. Если ~/.gitconfig.local нет — переносим текущий .gitconfig в .local,
# удаляем из .local ключи, которые управляются baseline, и сохраняем бэкап.
# 4. Если ~/.gitconfig.local уже есть — просто бэкапим текущий .gitconfig
# (chezmoi перезапишет его managed stub-ом).
#
# Три варианта ManagedStubs — чтобы распознать и текущий формат,
# и предыдущие итерации (когда baseline жил в ~/.config/git/config).
if (-not ($IsWindows -or $PSVersionTable.PSEdition -eq 'Desktop')) { if (-not ($IsWindows -or $PSVersionTable.PSEdition -eq 'Desktop')) {
return return
} }
$GlobalGitConfig = Join-Path $HOME '.gitconfig' $GlobalConfig = Join-Path $HOME '.gitconfig'
$LocalGitConfig = Join-Path $HOME '.gitconfig.local' $LocalConfig = Join-Path $HOME '.gitconfig.local'
$BackupPath = '{0}.pre-chezmoi.bak-{1}' -f $GlobalGitConfig, (Get-Date -Format 'yyyyMMdd-HHmmss') $BackupPath = '{0}.pre-chezmoi.bak-{1}' -f $GlobalConfig, (Get-Date -Format 'yyyyMMdd-HHmmss')
# Все исторические варианты managed stub (нормализуются без \r и trim).
$ManagedStubs = @( $ManagedStubs = @(
@' @'
[core] [core]
@@ -38,61 +53,52 @@ $ManagedStubs = @(
'@ '@
) )
# Ключи baseline, которые нужно удалить из .local при миграции.
$ManagedKeys = @( $ManagedKeys = @(
'core.autocrlf', 'core.autocrlf', 'core.eol', 'core.quotepath', 'core.longpaths',
'core.eol', 'fetch.prune', 'pull.ff', 'init.defaultBranch'
'core.quotepath',
'core.longpaths',
'fetch.prune',
'pull.ff',
'init.defaultBranch'
) )
function Test-ManagedGitStub { function Test-IsManagedStub ([string]$Content) {
param( $Norm = ($Content -replace "`r", '').Trim()
[Parameter(Mandatory = $true)] foreach ($Stub in $ManagedStubs) {
[string]$Content if ($Norm -eq ($Stub -replace "`r", '').Trim()) { return $true }
)
$NormalizedContent = ($Content -replace "`r", '').Trim()
foreach ($ManagedStub in $ManagedStubs) {
$NormalizedStub = ($ManagedStub -replace "`r", '').Trim()
if ($NormalizedContent -eq $NormalizedStub) {
return $true
}
} }
return $false return $false
} }
if (-not (Test-Path -LiteralPath $GlobalGitConfig)) { # ── Основная логика ──────────────────────────────────────────────────
if (-not (Test-Path -LiteralPath $LocalGitConfig)) {
New-Item -ItemType File -Path $LocalGitConfig -Force | Out-Null # Случай 1: .gitconfig отсутствует — chezmoi создаст его сам.
if (-not (Test-Path -LiteralPath $GlobalConfig)) {
if (-not (Test-Path -LiteralPath $LocalConfig)) {
New-Item -ItemType File -Path $LocalConfig -Force | Out-Null
} }
return return
} }
$CurrentContent = Get-Content -LiteralPath $GlobalGitConfig -Raw # Случай 2: .gitconfig уже managed — ничего не делаем.
if (Test-ManagedGitStub -Content $CurrentContent) { $Content = Get-Content -LiteralPath $GlobalConfig -Raw
if (-not (Test-Path -LiteralPath $LocalGitConfig)) { if (Test-IsManagedStub $Content) {
New-Item -ItemType File -Path $LocalGitConfig -Force | Out-Null if (-not (Test-Path -LiteralPath $LocalConfig)) {
New-Item -ItemType File -Path $LocalConfig -Force | Out-Null
} }
return return
} }
if (-not (Test-Path -LiteralPath $LocalGitConfig)) { # Случай 3: .gitconfig.local нет — мигрируем.
Copy-Item -LiteralPath $GlobalGitConfig -Destination $BackupPath -Force if (-not (Test-Path -LiteralPath $LocalConfig)) {
Copy-Item -LiteralPath $GlobalGitConfig -Destination $LocalGitConfig -Force Copy-Item -LiteralPath $GlobalConfig -Destination $BackupPath -Force
Copy-Item -LiteralPath $GlobalConfig -Destination $LocalConfig -Force
foreach ($Key in $ManagedKeys) { foreach ($Key in $ManagedKeys) {
git config --file $LocalGitConfig --unset-all $Key 2>$null git config --file $LocalConfig --unset-all $Key 2>$null
} }
Write-Host "Мигрировано: ~/.gitconfig -> ~/.gitconfig.local"
Write-Host "Migrated existing ~/.gitconfig to ~/.gitconfig.local" Write-Host "Бэкап: $BackupPath"
Write-Host "Backup saved to: $BackupPath"
return return
} }
Copy-Item -LiteralPath $GlobalGitConfig -Destination $BackupPath -Force # Случай 4: .gitconfig.local уже есть — просто бэкапим.
Write-Warning "~/.gitconfig.local already exists; current ~/.gitconfig was backed up before managed stub overwrite." Copy-Item -LiteralPath $GlobalConfig -Destination $BackupPath -Force
Write-Host "Backup saved to: $BackupPath" Write-Warning "~/.gitconfig.local уже существует; текущий ~/.gitconfig сохранён в бэкап."
Write-Host "Бэкап: $BackupPath"
+64 -118
View File
@@ -1,13 +1,17 @@
# Keep PowerShell 7 console text I/O on UTF-8 for predictable native tool behavior. # ── UTF-8 ────────────────────────────────────────────────────────────
# Принудительный UTF-8 для pwsh 7 в интерактивной консоли,
# независимо от унаследованной code page.
# НЕ трогает PS 5.1, VS Code terminal, remoting и т.д.
if ($IsWindows -and $PSVersionTable.PSEdition -eq 'Core' -and $Host.Name -eq 'ConsoleHost') { if ($IsWindows -and $PSVersionTable.PSEdition -eq 'Core' -and $Host.Name -eq 'ConsoleHost') {
chcp 65001 > $null chcp 65001 > $null
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false) $Utf8 = New-Object System.Text.UTF8Encoding($false)
[Console]::InputEncoding = $Utf8NoBom [Console]::InputEncoding = $Utf8
[Console]::OutputEncoding = $Utf8NoBom [Console]::OutputEncoding = $Utf8
$OutputEncoding = $Utf8NoBom $OutputEncoding = $Utf8
} }
# Keep interactive editing comfortable without depending on extra prompt frameworks. # ── PSReadLine ───────────────────────────────────────────────────────
# Предиктивный ввод по истории, только для интерактивной консоли.
if ( if (
$Host.Name -eq 'ConsoleHost' -and $Host.Name -eq 'ConsoleHost' -and
-not [Console]::IsOutputRedirected -and -not [Console]::IsOutputRedirected -and
@@ -15,170 +19,112 @@ if (
(Get-Module -ListAvailable -Name PSReadLine) (Get-Module -ListAvailable -Name PSReadLine)
) { ) {
Import-Module PSReadLine -ErrorAction SilentlyContinue Import-Module PSReadLine -ErrorAction SilentlyContinue
Set-PSReadLineOption -PredictionSource History -ErrorAction SilentlyContinue Set-PSReadLineOption -PredictionSource History -ErrorAction SilentlyContinue
Set-PSReadLineOption -PredictionViewStyle ListView -ErrorAction SilentlyContinue Set-PSReadLineOption -PredictionViewStyle ListView -ErrorAction SilentlyContinue
Set-PSReadLineOption -HistoryNoDuplicates:$true -ErrorAction SilentlyContinue Set-PSReadLineOption -HistoryNoDuplicates:$true -ErrorAction SilentlyContinue
} }
function Reload-Profile { # ── Unix-хелперы (lowercase — привычка из bash) ─────────────────────
. $PROFILE
}
function which { # Перечитать профиль без перезапуска сессии.
param( function Reload-Profile { . $PROFILE }
[Parameter(Mandatory = $true)]
[string]$Name
)
# Показать все команды с данным именем (аналог which в bash).
function which ($Name) {
Get-Command -Name $Name -All | Select-Object CommandType, Name, Source Get-Command -Name $Name -All | Select-Object CommandType, Name, Source
} }
# Создать файл или обновить mtime (аналог touch в bash).
function touch { function touch {
param( param([Parameter(Mandatory, ValueFromRemainingArguments)][string[]]$Path)
[Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
[string[]]$Path
)
foreach ($Item in $Path) { foreach ($Item in $Path) {
if (Test-Path -LiteralPath $Item) { if (Test-Path -LiteralPath $Item) {
(Get-Item -LiteralPath $Item).LastWriteTime = Get-Date (Get-Item -LiteralPath $Item).LastWriteTime = Get-Date
} } else {
else {
New-Item -ItemType File -Path $Item -Force | Out-Null New-Item -ItemType File -Path $Item -Force | Out-Null
} }
} }
} }
function mkcd { # mkdir + cd в одно действие.
param( function mkcd ($Path) {
[Parameter(Mandatory = $true)]
[string]$Path
)
New-Item -ItemType Directory -Path $Path -Force | Out-Null New-Item -ItemType Directory -Path $Path -Force | Out-Null
Set-Location -Path $Path Set-Location -Path $Path
} }
function open { # Открыть путь в Explorer (аналог xdg-open / macOS open).
param( function open ($Path = '.') { Invoke-Item -Path $Path }
[string]$Path = '.'
)
Invoke-Item -Path $Path
}
# Перейти в корень текущего git-репозитория.
function croot { function croot {
if (-not (Get-Command git -ErrorAction SilentlyContinue)) { if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
Write-Error 'git is not available in PATH.' Write-Error 'git is not available in PATH.'; return
return
} }
$Root = git rev-parse --show-toplevel 2>$null $Root = git rev-parse --show-toplevel 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($Root)) { if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($Root)) {
Write-Error 'Not inside a Git repository.' Write-Error 'Not inside a Git repository.'; return
return
} }
Set-Location -Path $Root.Trim() Set-Location -Path $Root.Trim()
} }
# ── Прокси (аналог bash proxy_on/proxy_off/myip) ────────────────────
# Получить текущий внешний IP (или $null при ошибке/таймауте).
function Get-PublicIp { function Get-PublicIp {
$CurlExe = Get-Command curl.exe -ErrorAction SilentlyContinue try { return ([string](Invoke-RestMethod -Uri 'https://ifconfig.me/ip' -TimeoutSec 3)).Trim() }
if ($null -ne $CurlExe) { catch { return $null }
try {
$CurrentIp = & $CurlExe.Source --silent --show-error --max-time 3 https://ifconfig.me/ip
return ([string]$CurrentIp).Trim()
}
catch {
return $null
}
}
try {
return ([string](Invoke-RestMethod -Uri 'https://ifconfig.me/ip' -TimeoutSec 3)).Trim()
}
catch {
return $null
}
} }
# Включить прокси для текущей сессии (hproxy.local).
function proxy_on { function proxy_on {
$ProxyHost = 'hproxy.local' $Host_ = 'hproxy.local'; $Port = 12334
$ProxyPort = 12334
$env:HTTP_PROXY = 'http://{0}:{1}' -f $ProxyHost, $ProxyPort $env:HTTP_PROXY = "http://${Host_}:${Port}"
$env:HTTPS_PROXY = 'http://{0}:{1}' -f $ProxyHost, $ProxyPort $env:HTTPS_PROXY = "http://${Host_}:${Port}"
$env:ALL_PROXY = 'socks5://{0}:{1}' -f $ProxyHost, $ProxyPort $env:ALL_PROXY = "socks5://${Host_}:${Port}"
$env:NO_PROXY = '{0},localhost,127.0.0.1,.concept-software.ru' -f $ProxyHost $env:NO_PROXY = "${Host_},localhost,127.0.0.1,.concept-software.ru"
'Proxy enabled. Checking route...' $Ip = Get-PublicIp
$CurrentIp = Get-PublicIp "Proxy ON. IP: $(if ($Ip) { $Ip } else { 'unavailable' })"
if ([string]::IsNullOrWhiteSpace($CurrentIp)) {
'Current IP: unavailable'
}
else {
'Current IP: {0}' -f $CurrentIp
}
} }
# Выключить прокси для текущей сессии.
function proxy_off { function proxy_off {
foreach ($VariableName in 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY') { foreach ($V in 'HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','NO_PROXY') {
Remove-Item -Path ('Env:{0}' -f $VariableName) -ErrorAction SilentlyContinue Remove-Item -Path "Env:$V" -ErrorAction SilentlyContinue
}
'Proxy disabled. Checking route...'
$CurrentIp = Get-PublicIp
if ([string]::IsNullOrWhiteSpace($CurrentIp)) {
'Current IP: unavailable'
}
else {
'Current IP: {0}' -f $CurrentIp
} }
$Ip = Get-PublicIp
"Proxy OFF. IP: $(if ($Ip) { $Ip } else { 'unavailable' })"
} }
# Показать текущий внешний IP.
function myip { function myip {
$CurrentIp = Get-PublicIp $Ip = Get-PublicIp
if ([string]::IsNullOrWhiteSpace($CurrentIp)) { "IP: $(if ($Ip) { $Ip } else { 'unavailable' })"
'IP: unavailable'
}
else {
'IP: {0}' -f $CurrentIp
}
} }
# ── Шорткаты Windows Terminal ────────────────────────────────────────
if (Get-Command wt -ErrorAction SilentlyContinue) { if (Get-Command wt -ErrorAction SilentlyContinue) {
function wt-here { # Новое окно / вкладка / split-pane Windows Terminal в текущей директории.
wt -d (Get-Location).ProviderPath function wt_here { wt -d (Get-Location).ProviderPath }
} function wt_tab_here { wt -w 0 new-tab -d (Get-Location).ProviderPath }
function wt_split_here { wt -w 0 split-pane -d (Get-Location).ProviderPath }
function wt-tab-here {
wt -w 0 new-tab -d (Get-Location).ProviderPath
}
function wt-split-here {
wt -w 0 split-pane -d (Get-Location).ProviderPath
}
} }
# Keep stable hooks for machine-local overrides and future managed fragments. # ── Локальные дополнения ─────────────────────────────────────────────
# Машинно-специфичные добавки: profile.extra.ps1 или profile.d/*.ps1
$ExtraProfile = Join-Path $HOME '.config\powershell\profile.extra.ps1' $ExtraProfile = Join-Path $HOME '.config\powershell\profile.extra.ps1'
if (Test-Path -LiteralPath $ExtraProfile) { if (Test-Path -LiteralPath $ExtraProfile) { . $ExtraProfile }
. $ExtraProfile
}
$ExtraProfileDir = Join-Path $HOME '.config\powershell\profile.d' $ExtraProfileDir = Join-Path $HOME '.config\powershell\profile.d'
if (Test-Path -LiteralPath $ExtraProfileDir) { if (Test-Path -LiteralPath $ExtraProfileDir) {
foreach ($ProfileFragment in (Get-ChildItem -Path $ExtraProfileDir -Filter '*.ps1' -File | Sort-Object Name)) { Get-ChildItem -Path $ExtraProfileDir -Filter '*.ps1' -File |
. $ProfileFragment.FullName Sort-Object Name |
} ForEach-Object { . $_.FullName }
} }
# Import the Chocolatey Profile that contains the necessary code to enable # ── Chocolatey tab-completion ────────────────────────────────────────
# tab-completions to function for `choco`.
# Be aware that if you are missing these lines from your profile, tab completion
# for `choco` will not function.
# See https://ch0.co/tab-completion for details.
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1" $ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path -LiteralPath $ChocolateyProfile) { if (Test-Path -LiteralPath $ChocolateyProfile) { Import-Module $ChocolateyProfile }
Import-Module $ChocolateyProfile
}