snag/build.ps1
Alexander Zhirov 6c1f19d903
Изменена сборка инсталляционного пакета
- Добавлена расширенный формат версии программы
- Добавлена документация в виде сконвертированной README.md в html страницу
- Флаг AddGitHash для использования git хэша в качестве дополнения к версии программы
- Автоочищение после сборки
2025-06-03 02:25:40 +03:00

264 lines
10 KiB
PowerShell

param (
[switch]$AddGitHash
)
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# Путь к файлам
$originalVersionFile = "source/snag/version_.d"
$backupVersionFile = "source/snag/version_.d.bak"
# Создание backup файла, если он не существует
try {
if (-not (Test-Path $backupVersionFile)) {
Copy-Item -Path $originalVersionFile -Destination $backupVersionFile -Force
Write-Host "Created backup: Copied $originalVersionFile to $backupVersionFile" -ForegroundColor Green
}
} catch {
Write-Host "Error creating backup file: $_" -ForegroundColor Red
exit 1
}
# Чтение версии из backup файла
try {
$content = Get-Content -Path $backupVersionFile -Raw -Encoding UTF8 -ErrorAction Stop
if ($content -match 'enum\s+snagVersion\s*=\s*"([^"]+)"') {
$baseVersion = $Matches[1]
Write-Host "Extracted base version: $baseVersion" -ForegroundColor Cyan
} else {
Write-Host "Failed to find snagVersion in $backupVersionFile" -ForegroundColor Red
exit 1
}
} catch {
Write-Host "Error reading ${backupVersionFile}: $_" -ForegroundColor Red
exit 1
}
# Получение текущей даты и времени в формате yyddd.HHmm
$dateTime = Get-Date -Format "yy$(Get-Date -UFormat %j).HHmm"
# Получение git хэша, если требуется
$gitHash = ""
if ($AddGitHash) {
try {
if (Get-Command git -ErrorAction SilentlyContinue) {
$gitHash = git rev-parse --short HEAD
if ($LASTEXITCODE -eq 0) {
Write-Host "Git short hash: $gitHash" -ForegroundColor Cyan
} else {
Write-Host "Git command failed, proceeding without hash" -ForegroundColor Yellow
}
} else {
Write-Host "Git not found, proceeding without hash" -ForegroundColor Cyan
}
} catch {
Write-Host "Error executing git command: $_" -ForegroundColor Red
Write-Host "Proceeding without git hash" -ForegroundColor Yellow
}
} else {
Write-Host "Git hash inclusion disabled by parameter" -ForegroundColor Cyan
}
# Разделение базовой версии на основную часть и суффикс
$versionParts = $baseVersion -split '-'
$mainVersion = $versionParts[0] # Основная версия, например, "0.1.0"
$suffix = if ($versionParts.Count -gt 1) { "-$($versionParts[1])" } else { "" } # Суффикс, например, "-alpha.2" или пусто
# Формирование итоговой версии
$snagVersion = "${mainVersion}.${dateTime}${suffix}"
if ($AddGitHash -and $gitHash) {
$snagVersion = "${snagVersion}-${gitHash}"
}
Write-Host "Final version: $snagVersion" -ForegroundColor Cyan
# Замена версии в файле version_.d
try {
$content = Get-Content -Path $originalVersionFile -Raw -Encoding UTF8 -ErrorAction Stop
$newContent = $content -replace 'enum\s+snagVersion\s*=\s*"[^"]+"', "enum snagVersion = ""$snagVersion"""
Set-Content -Path $originalVersionFile -Value $newContent -Encoding UTF8 -ErrorAction Stop
Write-Host "Updated $originalVersionFile with new version: $snagVersion" -ForegroundColor Green
} catch {
Write-Host "Error updating ${originalVersionFile}: $_" -ForegroundColor Red
exit 1
}
# Путь к файлу snag.iss
$issFile = "windows/snag.iss"
# Проверка существования файла snag.iss
if (-not (Test-Path $issFile)) {
Write-Host "File $issFile does not exist." -ForegroundColor Red
exit 1
}
# Чтение snag.iss
try {
$issContent = Get-Content -Path $issFile -Raw -Encoding UTF8 -ErrorAction Stop
} catch {
Write-Host "Error reading ${issFile}: $_" -ForegroundColor Red
exit 1
}
# Обновление AppVersion
$appVersionPattern = "AppVersion=$snagVersion"
if ($issContent -match [regex]::Escape($appVersionPattern)) {
Write-Host "AppVersion in $issFile is already set to $snagVersion. Skipping update." -ForegroundColor Blue
} else {
$issContent = $issContent -replace 'AppVersion=version', "AppVersion=$snagVersion"
Write-Host "Updated AppVersion to $snagVersion in $issFile." -ForegroundColor Green
}
# Обновление OutputBaseFileName
$appName = "snag_"
$postfix = "_windows-installer"
$newOutputBaseFileName = "$appName$snagVersion$postfix"
$outputBasePattern = "OutputBaseFileName=$newOutputBaseFileName"
if ($issContent -match [regex]::Escape($outputBasePattern)) {
Write-Host "OutputBaseFileName in $issFile is already set to $newOutputBaseFileName. Skipping update." -ForegroundColor Blue
} else {
$issContent = $issContent -replace 'OutputBaseFileName=SnagInstaller', "OutputBaseFileName=$newOutputBaseFileName"
Write-Host "Updated OutputBaseFileName to $newOutputBaseFileName in $issFile." -ForegroundColor Green
}
# Сохранение обновленного snag.iss
try {
Set-Content -Path $issFile -Value $issContent -Encoding UTF8 -ErrorAction Stop
Write-Host "File $issFile successfully updated." -ForegroundColor Green
} catch {
Write-Host "Error writing to ${issFile}: $_" -ForegroundColor Red
exit 1
}
# Путь к файлу app.d
$appDFile = "source/app.d"
# Проверка существования файла app.d
if (-not (Test-Path $appDFile)) {
Write-Host "File $appDFile does not exist." -ForegroundColor Red
exit 1
}
# Исходная и целевая строки для замены
$originalString = 'string configFile = argumets.option("config", "snag.json");'
$newString = @'
import std.process : environment;
import std.path : buildPath;
string configFile = argumets.option("config", environment.get("USERPROFILE").buildPath("snag\\snag.json"));
'@
# Чтение содержимого файла и замена строки
try {
$content = Get-Content -Path $appDFile -Raw -Encoding UTF8 -ErrorAction Stop
if ($content -match [regex]::Escape($newString)) {
Write-Host "The string in $appDFile is already updated. Skipping replacement." -ForegroundColor Blue
} elseif ($content -match [regex]::Escape($originalString)) {
$content = $content -replace [regex]::Escape($originalString), $newString
Set-Content -Path $appDFile -Value $content -Encoding UTF8 -ErrorAction Stop
Write-Host "The string in $appDFile has been successfully replaced." -ForegroundColor Green
} else {
Write-Host "The original string in $appDFile was not found." -ForegroundColor Red
exit 1
}
} catch {
Write-Host "Error processing ${appDFile}: $_" -ForegroundColor Red
exit 1
}
# Проверяем наличие dub в системе
try {
Get-Command dub -ErrorAction Stop | Select-Object -ExpandProperty Source > $null 2>&1
} catch {
Write-Host "Error: Pandoc is not installed or not in PATH" -ForegroundColor Red
exit 1
}
# Выполнение команды dub build
Write-Host "Starting build with dub..." -ForegroundColor Green
dub build --build=release > dub_build.log 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host "Error during dub build. Check dub_build.log for details." -ForegroundColor Red
exit 1
}
# Переход в директорию windows
Write-Host "Changing to the windows/ directory..." -ForegroundColor Green
Set-Location -Path "windows"
if (-not $?) {
Write-Host "Failed to change to the windows/ directory." -ForegroundColor Red
exit 1
}
# Проверка существования файлов для pandoc
$readmeFile = "../README.md"
$cssFile = "style.css"
$outputHtml = "readme.html"
if (-not (Test-Path $readmeFile)) {
Write-Host "File $readmeFile does not exist." -ForegroundColor Red
exit 1
}
if (-not (Test-Path $cssFile)) {
Write-Host "File $cssFile does not exist." -ForegroundColor Red
exit 1
}
# Проверяем наличие pandoc в системе
try {
Get-Command pandoc -ErrorAction Stop | Select-Object -ExpandProperty Source > $null 2>&1
} catch {
Write-Host "Error: Pandoc is not installed or not in PATH" -ForegroundColor Red
exit 1
}
# Выполнение команды pandoc
Write-Host "Converting README.md to readme.html using pandoc..." -ForegroundColor Green
pandoc -s -o $outputHtml $readmeFile --css=$cssFile > pandoc.log 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host "Error during pandoc conversion. Check pandoc.log for details." -ForegroundColor Red
exit 1
}
Write-Host "Successfully converted README.md to $outputHtml." -ForegroundColor Green
# Проверка существования Inno Setup
$innoSetupPath = 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe'
if (-not (Test-Path $innoSetupPath)) {
Write-Host "Inno Setup compiler not found at $innoSetupPath."
exit 1
}
# Запуск компиляции Inno Setup
Write-Host "Starting Inno Setup compilation..." -ForegroundColor Green
& $innoSetupPath .\snag.iss > inno_setup.log 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host "Error during Inno Setup compilation. Check inno_setup.log for details." -ForegroundColor Red
exit 1
}
# Выход из директории windows
Write-Host "Changing back to the parent directory..." -ForegroundColor Green
Set-Location -Path ..
if (-not $?) {
Write-Host "Failed to change back to the parent directory." -ForegroundColor Red
exit 1
}
try {
# Выполняем git restore (отмена изменений в отслеживаемых файлах)
Write-Host "Running 'git restore .'..." -ForegroundColor Cyan
git restore .
if ($LASTEXITCODE -ne 0) {
throw "git restore failed with exit code $LASTEXITCODE"
}
# Выполняем git clean (удаление неотслеживаемых файлов)
Write-Host "Running 'git clean -f -d'..." -ForegroundColor Cyan
git clean -f -d | ForEach-Object { Write-Host $_ -ForegroundColor Yellow }
if ($LASTEXITCODE -ne 0) {
throw "git clean failed with exit code $LASTEXITCODE"
}
Write-Host "Git cleanup completed successfully!" -ForegroundColor Green
}
catch {
Write-Host "ERROR: $_" -ForegroundColor Red
}
Write-Host "Build and installer compilation completed successfully!" -ForegroundColor Green