Files
git_man/setup-1c-repo.ps1
T

412 lines
13 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ============================================================
# setup-1c-repo.ps1 - Настройка Git-репозитория под выгрузку 1С (конфигуратор)
#
# Версия: 1.2.0
# Автор: Michael BAG <mk@p7net.ru>
# Репозиторий: https://git.p7net.ru/tools/git_man
#
# Платформа: Windows (PowerShell 5.1+ / PowerShell 7+)
# Для Linux/macOS используйте setup-1c-repo.sh
#
# Использование:
# .\setup-1c-repo.ps1 [-DryRun] [-Force] [-Init] [-Renormalize] [-NoGitignore]
# [-Verbose] [-Quiet] [-Help] [-Version]
#
# Описание:
# Включает локальные настройки Git в текущей папке (cwd) для проектов
# с выгрузкой конфигурации/расширения из конфигуратора 1С:
# - UTF-8 с BOM (как у конфигуратора; BOM хранится как часть содержимого)
# - CRLF в рабочей копии для *.bsl / *.xml и др. текстовых файлов выгрузки
# - корректное отображение кириллических путей (core.quotepath=false)
# - длинные пути (core.longpaths=true)
# - создаёт/обновляет .gitattributes и .gitignore
# ============================================================
[CmdletBinding()]
param(
[switch]$DryRun,
[Alias('f')]
[switch]$Force,
[switch]$Init,
[switch]$Renormalize,
[switch]$NoGitignore,
[Alias('q')]
[switch]$Quiet,
[Alias('h')]
[switch]$Help,
[Alias('V')]
[switch]$Version
)
$ErrorActionPreference = 'Stop'
$ScriptVersion = '1.2.0'
function Show-Help {
@"
============================================================
📦 setup-1c-repo.ps1 v$ScriptVersion настройка репозитория под 1С
============================================================
ОПИСАНИЕ:
Настраивает локальный Git-репозиторий в ТЕКУЩЕЙ папке под
выгрузку из конфигуратора 1С (UTF-8 BOM + CRLF).
ИСПОЛЬЗОВАНИЕ:
.\setup-1c-repo.ps1 [ОПЦИИ]
.\setup-1c-repo.cmd [ОПЦИИ]
ОПЦИИ:
-Help, -h Показать эту справку
-Version, -V Показать версию скрипта
-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
============================================================
"@ | Write-Host
exit 0
}
function Show-Version {
Write-Host "setup-1c-repo.ps1 $ScriptVersion"
exit 0
}
if ($Help) { Show-Help }
if ($Version) { Show-Version }
function Write-Info([string]$Message) {
if (-not $Quiet) { Write-Host "$Message" -ForegroundColor Cyan }
}
function Write-Success([string]$Message) {
if (-not $Quiet) { Write-Host "$Message" -ForegroundColor Green }
}
function Write-WarnMsg([string]$Message) {
if (-not $Quiet) { Write-Host "⚠️ $Message" -ForegroundColor Yellow }
}
function Write-ErrMsg([string]$Message) {
Write-Host "$Message" -ForegroundColor Red
}
function Write-DebugMsg([string]$Message) {
if ($VerbosePreference -ne 'SilentlyContinue' -and -not $Quiet) {
Write-Host "🔍 $Message" -ForegroundColor Blue
}
}
function Write-Step([string]$Message) {
if (-not $Quiet) { Write-Host "$Message" -ForegroundColor Magenta }
}
$GitAttributesContent = @'
# .gitattributes — выгрузка конфигуратора 1С (UTF-8 BOM + CRLF)
# Создано setup-1c-repo.ps1 (git_man). Не удаляйте без необходимости.
#
# Правило: текстовые файлы выгрузки — text + eol=crlf (рабочая копия = CRLF,
# в объекте Git нормализуется к LF). Бинарники — binary (без конвертации EOL).
* text=auto
# --- Текстовые файлы выгрузки конфигуратора ---
*.bsl text eol=crlf
*.os text eol=crlf
*.xml text eol=crlf
*.txt text eol=crlf
*.html text eol=crlf
*.htm text eol=crlf
*.xsd text eol=crlf
*.xslt text eol=crlf
*.xsl text eol=crlf
*.Form text eol=crlf
*.Module text eol=crlf
*.max text eol=crlf
# --- Служебные / документация репозитория (LF) ---
*.md text eol=lf
*.json text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.sh text eol=lf
*.gitignore text eol=lf
*.gitattributes text eol=lf
.editorconfig text eol=lf
# --- Скрипты Windows ---
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# --- Бинарные артефакты 1С и медиа ---
*.bin binary
*.cf binary
*.cfe binary
*.cfu binary
*.epf binary
*.erf binary
*.axdt binary
*.addin binary
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.bmp binary
*.ico binary
*.webp binary
*.tif binary
*.tiff binary
*.svg -text
*.zip binary
*.rar binary
*.7z binary
*.gz binary
*.xls binary
*.xlsx binary
*.xlsm binary
*.doc binary
*.docx binary
*.pdf binary
*.rtf binary
*.ttf binary
*.otf binary
*.woff binary
*.woff2 binary
*.eot binary
'@
$GitIgnoreContent = @'
# .gitignore — типовые исключения для проектов 1С (конфигуратор)
# Создано setup-1c-repo.ps1 (git_man)
# Бинарные выгрузки конфигурации / расширений / обработок
*.cf
*.cfe
*.cfu
*.epf
*.erf
# Временные и резервные
*.tmp
*.bak
*.~*
*~
*.old
*.orig
# Логи и дампы
*.log
*.lgp
*.lgf
# ОС
Thumbs.db
ehthumbs.db
Desktop.ini
desktop.ini
.DS_Store
.AppleDouble
.LSOverride
# IDE / редакторы
.vs/
.vscode/
.idea/
*.suo
*.user
*.userosscache
*.sln.docstates
# Отладка / кэш
Debug/
debug/
cache/
*.pfl
'@
function Test-GitAvailable {
try {
$null = Get-Command git -ErrorAction Stop
return $true
} catch {
return $false
}
}
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
)
# 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)
}
function Write-FileSafe {
param(
[string]$Path,
[string]$Content,
[string]$Label
)
if ((Test-Path -LiteralPath $Path) -and -not $Force) {
Write-WarnMsg "$Label уже существует — пропуск (используйте -Force)"
return
}
if ($DryRun) {
if (Test-Path -LiteralPath $Path) {
Write-Host " [DRY-RUN] перезаписать $Path (бэкап $Path.bak)"
} else {
Write-Host " [DRY-RUN] создать $Path"
}
return
}
if (Test-Path -LiteralPath $Path) {
Copy-Item -LiteralPath $Path -Destination "$Path.bak" -Force
Write-Info "Бэкап: $Path.bak"
}
Write-Utf8File -Path $Path -Content $Content
Write-Success "Записан $Path"
}
# ============================================================
# Основной ход
# ============================================================
Write-Step "Проверка окружения (ОС: Windows)..."
if (-not (Test-GitAvailable)) {
Write-ErrMsg "Git не установлен или недоступен в PATH"
exit 1
}
if (-not (Test-GitRepository)) {
if ($Init) {
if ($DryRun) {
Write-Host " [DRY-RUN] git init"
} else {
& git init
if ($LASTEXITCODE -ne 0) { throw "git init завершился с ошибкой" }
Write-Success "Выполнен git init"
}
} else {
Write-ErrMsg "Текущая папка не является Git-репозиторием"
Write-Host " Запустите из корня репозитория или добавьте -Init" -ForegroundColor Red
exit 1
}
}
Write-Success "Окружение проверено"
Write-Step "Локальные настройки Git..."
# Кириллические пути без \320\...
Set-LocalGitConfig 'core.quotepath' 'false'
# Длинные пути Windows / глубокие деревья метаданных 1С
Set-LocalGitConfig 'core.longpaths' 'true'
# Кодировки UI и коммитов
Set-LocalGitConfig 'gui.encoding' 'utf-8'
Set-LocalGitConfig 'i18n.commitEncoding' 'utf-8'
# EOL полностью через .gitattributes
Set-LocalGitConfig 'core.autocrlf' 'false'
Set-LocalGitConfig 'core.safecrlf' 'warn'
# Рекомендации 1С:ГитКонвертер для крупных деревьев метаданных
Set-LocalGitConfig 'diff.renames' 'false'
Set-LocalGitConfig 'diff.renameLimit' '1'
if ($DryRun) {
Write-Info "Локальный git config (dry-run)"
} else {
Write-Success "Локальный git config применён"
}
Write-Step "Файл .gitattributes..."
Write-FileSafe -Path '.gitattributes' -Content $GitAttributesContent -Label '.gitattributes'
if (-not $NoGitignore) {
Write-Step "Файл .gitignore..."
Write-FileSafe -Path '.gitignore' -Content $GitIgnoreContent -Label '.gitignore'
} else {
Write-Info "Пропуск .gitignore (-NoGitignore)"
}
if ($Renormalize) {
Write-Step "Нормализация индекса (git add --renormalize .)..."
if ($DryRun) {
Write-Host " [DRY-RUN] git add --renormalize ."
} else {
& git add --renormalize .
if ($LASTEXITCODE -ne 0) { throw "git add --renormalize завершился с ошибкой" }
Write-Success "Индекс перенормализован"
Write-WarnMsg "Проверьте git status — возможны массовые изменения EOL"
}
}
if (-not $Quiet) {
Write-Host ""
Write-Host "============================================================"
Write-Host "📊 Итог настройки под выгрузку конфигуратора 1С" -ForegroundColor Cyan
Write-Host "============================================================"
Write-Host " ОС: Windows"
Write-Host " Каталог: $(Get-Location)"
Write-Host " Encoding: UTF-8 (BOM сохраняется в содержимом файлов)"
Write-Host " EOL (выгрузка): CRLF в рабочей копии (*.bsl, *.xml, …)"
Write-Host " core.autocrlf: false (управляет .gitattributes)"
Write-Host " core.quotepath: false"
Write-Host " core.longpaths: true"
if ($DryRun) {
Write-Host ""
Write-Host "⚠️ Режим -DryRun: изменения НЕ применены" -ForegroundColor Yellow
} else {
Write-Host ""
Write-Host "✅ Готово" -ForegroundColor Green
Write-Host ""
Write-Host "Следующие шаги:" -ForegroundColor Cyan
Write-Host " 1. git status"
Write-Host " 2. git 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 "============================================================"
Write-Host ""
}
exit 0