Изменена сборка инсталляционного пакета

- Добавлена расширенный формат версии программы
- Добавлена документация в виде сконвертированной README.md в html страницу
- Флаг AddGitHash для использования git хэша в качестве дополнения к версии программы
- Автоочищение после сборки
This commit is contained in:
Alexander Zhirov 2025-06-03 02:25:40 +03:00
parent 37a87fe2dc
commit 6c1f19d903
Signed by: alexander
GPG key ID: C8D8BE544A27C511
4 changed files with 207 additions and 39 deletions

233
build.ps1
View file

@ -1,31 +1,111 @@
# PowerShell script to automate building and creating the installer
param (
[switch]$AddGitHash
)
# Путь к файлу version_.d
$versionFile = "source/snag/version_.d"
[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"
# Извлечение snagVersion из version_.d
$content = Get-Content -Path $versionFile -Raw -Encoding UTF8
if ($content -match 'enum\s+snagVersion\s*=\s*"([^"]+)"') {
$snagVersion = $Matches[1]
Write-Host "Extracted version: $snagVersion"
} else {
Write-Host "Failed to find snagVersion in $versionFile."
# Проверка существования файла snag.iss
if (-not (Test-Path $issFile)) {
Write-Host "File $issFile does not exist." -ForegroundColor Red
exit 1
}
# Чтение snag.iss
$issContent = Get-Content -Path $issFile -Raw -Encoding UTF8
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."
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."
Write-Host "Updated AppVersion to $snagVersion in $issFile." -ForegroundColor Green
}
# Обновление OutputBaseFileName
@ -34,19 +114,30 @@ $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."
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."
Write-Host "Updated OutputBaseFileName to $newOutputBaseFileName in $issFile." -ForegroundColor Green
}
# Сохранение обновленного snag.iss
Set-Content -Path $issFile -Value $issContent -Encoding UTF8
Write-Host "File $issFile successfully updated."
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 = @'
@ -56,48 +147,118 @@ import std.process : environment;
'@
# Чтение содержимого файла и замена строки
$content = Get-Content -Path $appDFile -Raw -Encoding UTF8
if ($content -match [regex]::Escape($newString)) {
Write-Host "The string in $appDFile is already updated. Skipping replacement."
} elseif ($content -match [regex]::Escape($originalString)) {
$content = $content -replace [regex]::Escape($originalString), $newString
Set-Content -Path $appDFile -Value $content -Encoding UTF8
Write-Host "The string in $appDFile has been successfully replaced."
} else {
Write-Host "The original string in $appDFile was not found."
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..."
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."
Write-Host "Error during dub build. Check dub_build.log for details." -ForegroundColor Red
exit 1
}
# Переход в директорию windows
Write-Host "Changing to the windows/ directory..."
Write-Host "Changing to the windows/ directory..." -ForegroundColor Green
Set-Location -Path "windows"
if (-not $?) {
Write-Host "Failed to change to the windows/ directory."
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..."
& 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' .\snag.iss > inno_setup.log 2>&1
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."
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..."
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."
Write-Host "Failed to change back to the parent directory." -ForegroundColor Red
exit 1
}
Write-Host "Build and installer compilation completed successfully!"
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

View file

@ -1,7 +1,7 @@
# Сборка из под Windows
Для сборки на Windows необходим установленный [Inno Setup](https://jrsoftware.org/isdl.php).
Для сборки на Windows необходим установленный [Inno Setup](https://jrsoftware.org/isdl.php) и для документации [pandoc](https://pandoc.org/).
```
.\build.ps1
.\build.ps1 -AddGitHash
```

View file

@ -1,4 +1,4 @@
; Сценарий для Inno Setup
; Сценарий для Inno Setup
[Setup]
AppName=Snag
AppVersion=version
@ -18,9 +18,12 @@ Source: "../bin/snag.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "snag.bat"; DestDir: "{app}"; Flags: ignoreversion
Source: "snag.json.bak"; DestDir: "{app}"; Flags: ignoreversion
Source: "../LICENSE"; DestDir: "{app}"; Flags: ignoreversion
Source: "style.css"; DestDir: "{app}\doc\"; Flags: ignoreversion
Source: "readme.html"; DestDir: "{app}\doc\"; Flags: ignoreversion
[Icons]
Name: "{group}\Snag"; Filename: "{app}\snag.bat"
Name: "{group}\README"; Filename: "{app}\doc\readme.html"
Name: "{group}\{cm:UninstallProgram,Snag}"; Filename: "{uninstallexe}"
[Run]

4
windows/style.css Normal file
View file

@ -0,0 +1,4 @@
body { font-family: Arial, sans-serif; margin: 20px; }
h1, h2, h3 { color: #333; }
pre { background: #f4f4f4; padding: 10px; border-radius: 5px; }
code { font-family: Consolas, monospace; }