Готово (v1.2.2): без --path / -Path скрипт сразу завершается с ошибкой.

This commit is contained in:
5 changed files with 277 additions and 106 deletions
+122 -67
View File
@@ -1,7 +1,7 @@
# ============================================================
# setup-1c-repo.ps1 - Настройка Git-репозитория под выгрузку 1С (конфигуратор)
#
# Версия: 1.2.0
# Версия: 1.2.2
# Автор: Michael BAG <mk@p7net.ru>
# Репозиторий: https://git.p7net.ru/tools/git_man
#
@@ -9,12 +9,12 @@
# Для Linux/macOS используйте setup-1c-repo.sh
#
# Использование:
# .\setup-1c-repo.ps1 [-DryRun] [-Force] [-Init] [-Renormalize] [-NoGitignore]
# [-Verbose] [-Quiet] [-Help] [-Version]
# .\setup-1c-repo.ps1 -Path DIR [-DryRun] [-Force] [-Init] [-Renormalize]
# [-NoGitignore] [-Verbose] [-Quiet] [-Help] [-Version]
#
# Описание:
# Включает локальные настройки Git в текущей папке (cwd) для проектов
# с выгрузкой конфигурации/расширения из конфигуратора 1С:
# Включает локальные настройки Git в указанной папке (-Path / -Repo;
# обязательный параметр) для проектов с выгрузкой из конфигуратора 1С:
# - UTF-8 с BOM (как у конфигуратора; BOM хранится как часть содержимого)
# - CRLF в рабочей копии для *.bsl / *.xml и др. текстовых файлов выгрузки
# - корректное отображение кириллических путей (core.quotepath=false)
@@ -24,6 +24,10 @@
[CmdletBinding()]
param(
[Parameter()]
[Alias('Repo', 'RepoPath')]
[string]$Path,
[switch]$DryRun,
[Alias('f')]
[switch]$Force,
@@ -39,7 +43,7 @@ param(
)
$ErrorActionPreference = 'Stop'
$ScriptVersion = '1.2.0'
$ScriptVersion = '1.2.2'
function Show-Help {
@"
@@ -48,28 +52,32 @@ function Show-Help {
============================================================
ОПИСАНИЕ:
Настраивает локальный Git-репозиторий в ТЕКУЩЕЙ папке под
выгрузку из конфигуратора 1С (UTF-8 BOM + CRLF).
Настраивает локальный Git-репозиторий под выгрузку из
конфигуратора 1С (UTF-8 BOM + CRLF).
Путь к репозиторию обязателен: -Path / -Repo.
ИСПОЛЬЗОВАНИЕ:
.\setup-1c-repo.ps1 [ОПЦИИ]
.\setup-1c-repo.cmd [ОПЦИИ]
.\setup-1c-repo.ps1 -Path DIR [ОПЦИИ]
.\setup-1c-repo.cmd -Path DIR [ОПЦИИ]
ОПЦИИ:
-Help, -h Показать эту справку
-Version, -V Показать версию скрипта
-Path, -Repo DIR Папка репозитория для настройки (обязательно)
-DryRun Только показать, что будет сделано
-Force, -f Перезаписать существующие .gitattributes / .gitignore
-Init Выполнить git init, если папка ещё не репозиторий
(создаёт каталог, если его нет)
-Renormalize После настройки: git add --renormalize .
-NoGitignore Не создавать/не менять .gitignore
-Verbose, -v Подробный вывод
-Quiet, -q Минимальный вывод (только ошибки)
ПРИМЕРЫ:
.\setup-1c-repo.ps1
.\setup-1c-repo.ps1 -Force -Renormalize
.\setup-1c-repo.ps1 -Init -DryRun
.\setup-1c-repo.ps1 -Path D:\projects\uas_ep -Force
.\setup-1c-repo.ps1 -Repo ..\my-1c-dump -Init
.\setup-1c-repo.ps1 -Path . -Force -Renormalize
.\setup-1c-repo.ps1 -Path C:\tmp\new-1c -Init -DryRun
============================================================
"@ | Write-Host
@@ -242,91 +250,138 @@ function Test-GitAvailable {
}
}
function Test-GitRepository {
if (Test-Path -LiteralPath '.git') { return $true }
return $false
}
function Set-LocalGitConfig {
param([string]$Key, [string]$Value)
if ($DryRun) {
Write-Host " [DRY-RUN] git config --local $Key $Value"
return
}
& git config --local $Key $Value
if ($LASTEXITCODE -ne 0) {
throw "Не удалось установить git config $Key=$Value"
}
Write-DebugMsg "config $Key=$Value"
}
function Write-Utf8File {
param(
[string]$Path,
[string]$Content
[string]$FilePath,
[string]$Content,
[string]$BaseDir
)
# UTF-8 без BOM: для .gitattributes/.gitignore достаточно; BOM у *.bsl
# — содержимое выгрузки конфигуратора, не этих служебных файлов.
$normalized = $Content -replace "`r`n", "`n" -replace "`r", "`n"
$normalized = $normalized.TrimEnd("`n") + "`n"
$encoding = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText((Join-Path (Get-Location) $Path), $normalized, $encoding)
$fullPath = Join-Path $BaseDir $FilePath
[System.IO.File]::WriteAllText($fullPath, $normalized, $encoding)
}
function Write-FileSafe {
param(
[string]$Path,
[string]$FilePath,
[string]$Content,
[string]$Label
[string]$Label,
[string]$BaseDir
)
if ((Test-Path -LiteralPath $Path) -and -not $Force) {
$fullPath = Join-Path $BaseDir $FilePath
if ((Test-Path -LiteralPath $fullPath) -and -not $Force) {
Write-WarnMsg "$Label уже существует — пропуск (используйте -Force)"
return
}
if ($DryRun) {
if (Test-Path -LiteralPath $Path) {
Write-Host " [DRY-RUN] перезаписать $Path (бэкап $Path.bak)"
if (Test-Path -LiteralPath $fullPath) {
Write-Host " [DRY-RUN] перезаписать $fullPath (бэкап $FilePath.bak)"
} else {
Write-Host " [DRY-RUN] создать $Path"
Write-Host " [DRY-RUN] создать $fullPath"
}
return
}
if (Test-Path -LiteralPath $Path) {
Copy-Item -LiteralPath $Path -Destination "$Path.bak" -Force
Write-Info "Бэкап: $Path.bak"
if (Test-Path -LiteralPath $fullPath) {
Copy-Item -LiteralPath $fullPath -Destination "$fullPath.bak" -Force
Write-Info "Бэкап: $FilePath.bak"
}
Write-Utf8File -Path $Path -Content $Content
Write-Success "Записан $Path"
Write-Utf8File -FilePath $FilePath -Content $Content -BaseDir $BaseDir
Write-Success "Записан $FilePath"
}
function Set-LocalGitConfig {
param(
[string]$Key,
[string]$Value,
[string]$WorkTree
)
if ($DryRun) {
Write-Host " [DRY-RUN] git -C `"$WorkTree`" config --local $Key $Value"
return
}
& git -C $WorkTree config --local $Key $Value
if ($LASTEXITCODE -ne 0) {
throw "Не удалось установить git config $Key=$Value"
}
Write-DebugMsg "config $Key=$Value"
}
# ============================================================
# Целевой каталог
# ============================================================
if ([string]::IsNullOrWhiteSpace($Path)) {
Write-ErrMsg "Не указан путь к репозиторию"
Write-Host " Обязательно: -Path DIR или -Repo DIR" -ForegroundColor Red
Write-Host " Справка: .\setup-1c-repo.ps1 -Help" -ForegroundColor Red
exit 1
}
$TargetDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
# ============================================================
# Основной ход
# ============================================================
Write-Step "Проверка окружения (ОС: Windows)..."
Write-Info "Целевой каталог: $TargetDir"
if (-not (Test-GitAvailable)) {
Write-ErrMsg "Git не установлен или недоступен в PATH"
exit 1
}
if (-not (Test-GitRepository)) {
$repoReady = $false
if (-not (Test-Path -LiteralPath $TargetDir -PathType Container)) {
if ($Init) {
if ($DryRun) {
Write-Host " [DRY-RUN] git init"
Write-Host " [DRY-RUN] New-Item -ItemType Directory `"$TargetDir`""
Write-Host " [DRY-RUN] git -C `"$TargetDir`" init"
} else {
& git init
New-Item -ItemType Directory -Path $TargetDir -Force | Out-Null
Write-Success "Создан каталог: $TargetDir"
& git -C $TargetDir init
if ($LASTEXITCODE -ne 0) { throw "git init завершился с ошибкой" }
Write-Success "Выполнен git init"
$repoReady = $true
}
} else {
Write-ErrMsg "Текущая папка не является Git-репозиторием"
Write-Host " Запустите из корня репозитория или добавьте -Init" -ForegroundColor Red
Write-ErrMsg "Папка не существует: $TargetDir"
Write-Host " Укажите существующий путь или добавьте -Init" -ForegroundColor Red
exit 1
}
} else {
$gitMarker = Join-Path $TargetDir '.git'
if (Test-Path -LiteralPath $gitMarker) {
$repoReady = $true
} elseif ($Init) {
if ($DryRun) {
Write-Host " [DRY-RUN] git -C `"$TargetDir`" init"
} else {
& git -C $TargetDir init
if ($LASTEXITCODE -ne 0) { throw "git init завершился с ошибкой" }
Write-Success "Выполнен git init"
$repoReady = $true
}
} else {
Write-ErrMsg "Папка не является Git-репозиторием: $TargetDir"
Write-Host " Укажите корень репозитория (-Path) или добавьте -Init" -ForegroundColor Red
exit 1
}
}
# В dry-run без реального каталога дальше только показываем действия
if (-not $DryRun -and -not $repoReady -and -not (Test-Path -LiteralPath (Join-Path $TargetDir '.git'))) {
Write-ErrMsg "Репозиторий не готов: $TargetDir"
exit 1
}
Write-Success "Окружение проверено"
@@ -334,18 +389,18 @@ Write-Success "Окружение проверено"
Write-Step "Локальные настройки Git..."
# Кириллические пути без \320\...
Set-LocalGitConfig 'core.quotepath' 'false'
Set-LocalGitConfig -Key 'core.quotepath' -Value 'false' -WorkTree $TargetDir
# Длинные пути Windows / глубокие деревья метаданных 1С
Set-LocalGitConfig 'core.longpaths' 'true'
Set-LocalGitConfig -Key 'core.longpaths' -Value 'true' -WorkTree $TargetDir
# Кодировки UI и коммитов
Set-LocalGitConfig 'gui.encoding' 'utf-8'
Set-LocalGitConfig 'i18n.commitEncoding' 'utf-8'
Set-LocalGitConfig -Key 'gui.encoding' -Value 'utf-8' -WorkTree $TargetDir
Set-LocalGitConfig -Key 'i18n.commitEncoding' -Value 'utf-8' -WorkTree $TargetDir
# EOL полностью через .gitattributes
Set-LocalGitConfig 'core.autocrlf' 'false'
Set-LocalGitConfig 'core.safecrlf' 'warn'
Set-LocalGitConfig -Key 'core.autocrlf' -Value 'false' -WorkTree $TargetDir
Set-LocalGitConfig -Key 'core.safecrlf' -Value 'warn' -WorkTree $TargetDir
# Рекомендации 1С:ГитКонвертер для крупных деревьев метаданных
Set-LocalGitConfig 'diff.renames' 'false'
Set-LocalGitConfig 'diff.renameLimit' '1'
Set-LocalGitConfig -Key 'diff.renames' -Value 'false' -WorkTree $TargetDir
Set-LocalGitConfig -Key 'diff.renameLimit' -Value '1' -WorkTree $TargetDir
if ($DryRun) {
Write-Info "Локальный git config (dry-run)"
@@ -354,11 +409,11 @@ if ($DryRun) {
}
Write-Step "Файл .gitattributes..."
Write-FileSafe -Path '.gitattributes' -Content $GitAttributesContent -Label '.gitattributes'
Write-FileSafe -FilePath '.gitattributes' -Content $GitAttributesContent -Label '.gitattributes' -BaseDir $TargetDir
if (-not $NoGitignore) {
Write-Step "Файл .gitignore..."
Write-FileSafe -Path '.gitignore' -Content $GitIgnoreContent -Label '.gitignore'
Write-FileSafe -FilePath '.gitignore' -Content $GitIgnoreContent -Label '.gitignore' -BaseDir $TargetDir
} else {
Write-Info "Пропуск .gitignore (-NoGitignore)"
}
@@ -366,9 +421,9 @@ if (-not $NoGitignore) {
if ($Renormalize) {
Write-Step "Нормализация индекса (git add --renormalize .)..."
if ($DryRun) {
Write-Host " [DRY-RUN] git add --renormalize ."
Write-Host " [DRY-RUN] git -C `"$TargetDir`" add --renormalize ."
} else {
& git add --renormalize .
& git -C $TargetDir add --renormalize .
if ($LASTEXITCODE -ne 0) { throw "git add --renormalize завершился с ошибкой" }
Write-Success "Индекс перенормализован"
Write-WarnMsg "Проверьте git status — возможны массовые изменения EOL"
@@ -381,7 +436,7 @@ if (-not $Quiet) {
Write-Host "📊 Итог настройки под выгрузку конфигуратора 1С" -ForegroundColor Cyan
Write-Host "============================================================"
Write-Host " ОС: Windows"
Write-Host " Каталог: $(Get-Location)"
Write-Host " Каталог: $TargetDir"
Write-Host " Encoding: UTF-8 (BOM сохраняется в содержимом файлов)"
Write-Host " EOL (выгрузка): CRLF в рабочей копии (*.bsl, *.xml, …)"
Write-Host " core.autocrlf: false (управляет .gitattributes)"
@@ -395,13 +450,13 @@ if (-not $Quiet) {
Write-Host "✅ Готово" -ForegroundColor Green
Write-Host ""
Write-Host "Следующие шаги:" -ForegroundColor Cyan
Write-Host " 1. git status"
Write-Host " 2. git add .gitattributes .gitignore"
Write-Host " 1. git -C `"$TargetDir`" status"
Write-Host " 2. git -C `"$TargetDir`" add .gitattributes .gitignore"
Write-Host ' 3. git commit -m "Настройки Git для выгрузки конфигуратора 1С"'
if (-not $Renormalize) {
Write-Host " 4. При необходимости нормализовать EOL:"
Write-Host " .\setup-1c-repo.ps1 -Renormalize"
Write-Host " или: git add --renormalize ."
Write-Host " .\setup-1c-repo.ps1 -Path `"$TargetDir`" -Renormalize"
Write-Host " или: git -C `"$TargetDir`" add --renormalize ."
}
}
Write-Host "============================================================"