Compare commits

...
Sign in to create a new pull request.

5 commits

Author SHA1 Message Date
6c1f19d903
Изменена сборка инсталляционного пакета
- Добавлена расширенный формат версии программы
- Добавлена документация в виде сконвертированной README.md в html страницу
- Флаг AddGitHash для использования git хэша в качестве дополнения к версии программы
- Автоочищение после сборки
2025-06-03 02:25:40 +03:00
37a87fe2dc
Merge branch 'develop' into windows 2025-06-02 19:53:41 +03:00
60f94613ba
Merge branch 'develop' into windows 2025-06-02 18:11:36 +03:00
860bea587d
Merge branch 'develop' into windows 2025-06-02 18:07:55 +03:00
cff4d3baf6
Добавлена сборка в инсталляционный файл для Windows 2025-05-30 14:13:37 +03:00
6 changed files with 345 additions and 0 deletions

264
build.ps1 Normal file
View file

@ -0,0 +1,264 @@
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

7
windows.md Normal file
View file

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

21
windows/snag.bat Normal file
View file

@ -0,0 +1,21 @@
@echo off
chcp 65001 > nul
set "SCRIPT_DIR=%~dp0"
set "SNAG_PATH=%SCRIPT_DIR%"
set "PATH=%PATH%;%SNAG_PATH%"
echo -----------------------------------------------
echo Snag Application Launcher
echo -----------------------------------------------
echo.
echo NOTE: Ensure the config file exists at:
echo "%USERPROFILE%\snag\snag.json"
echo.
echo To get started, type: snag --help
echo -----------------------------------------------
echo.
cd /d "%USERPROFILE%"
cmd /k

33
windows/snag.iss Normal file
View file

@ -0,0 +1,33 @@
; Сценарий для Inno Setup
[Setup]
AppName=Snag
AppVersion=version
DefaultDirName={commonpf}\snag
DefaultGroupName=Snag
OutputDir=Output
OutputBaseFileName=SnagInstaller
Compression=lzma
SolidCompression=yes
LicenseFile=../LICENSE
[Languages]
Name: "russian"; MessagesFile: "compiler:Languages\Russian.isl"
[Files]
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]
Filename: "{app}\snag.bat"; Description: "{cm:LaunchProgram,Snag}"; Flags: nowait postinstall skipifsilent
[CustomMessages]
russian.LaunchProgram=Запустить Snag

16
windows/snag.json.bak Normal file
View file

@ -0,0 +1,16 @@
{
"git": "",
"project": "",
"email": "",
"author": "",
"presnag": [
],
"postsnag": [
],
"rules": {
"tracking": [
],
"ignore": [
]
}
}

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; }