Українська
Команди розробника
Крок 1. Скрипт для щоденних команд
Навіщо. До кінця підручника щоденна робота потребує понад десяток команд із довгими параметрами: запустити базу даних і застосувати міграції, запустити API з потрібним профілем, запустити сервер Angular зі своєї папки, виконати всі перевірки CI перед пушем. Набирати їх з пам’яті повільно й схильно до помилок, а новачкові спершу доводиться шукати їх у документації.
Невеликий скрипт у корені репозиторію перетворює кожну з них на одну коротку команду, яку легко знайти: ./Run.ps1 api, ./Run.ps1 test, ./Run.ps1 check. Його написано на PowerShell 7, що працює у Windows, macOS і Linux, тож уся команда користується тим самим скриптом.
Що зробити. Створіть Run.ps1 у корені репозиторію. Це остаточна версія скрипта; деякі команди потребують частин проєкту, які ми збудуємо пізніше (див. таблицю після лістингу).
powershell
#!/usr/bin/env pwsh
#Requires -Version 7.0
# Chatex developer commands. Run without arguments (or with 'help') to list them.
# Extra arguments after 'test' and 'migration' are passed on, see the examples in the help.
param(
[ValidateSet('help', 'setup', 'db', 'db-stop', 'migration', 'api', 'web', 'build', 'test', 'format', 'check', 'clean')]
[string] $Command = 'help'
)
$ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot
$Web = Join-Path $Root 'Source/Chatex.Web'
$Solution = 'Chatex.slnx'
$DataProject = 'Source/Chatex.Data'
$ApiProject = 'Source/Chatex.Api'
$Commands = [ordered]@{
'help' = 'Show this list.'
'setup' = 'First run: restore tools and packages, start the database and apply the migrations.'
'db' = 'Start PostgreSQL in Docker (compose.yaml) and apply the migrations.'
'db-stop' = 'Stop the PostgreSQL container; the data stays in its volume.'
'migration' = 'Add an EF Core migration: migration <Name>.'
'api' = 'Run the API on http://localhost:5214 (API reference at /scalar).'
'web' = 'Run the Angular dev server on http://localhost:4200 (start the API first).'
'build' = 'Build the solution and the web app.'
'test' = 'Run the backend and frontend tests; with arguments, run dotnet test with them instead.'
'format' = 'Format C# (dotnet format) and the web app (Prettier).'
'check' = 'Run everything CI runs: format checks, Release build, migration check, tests, audit, lint, build.'
'clean' = 'Delete build output (bin, obj, dist and the Angular cache).'
}
function Show-Help {
Write-Host 'Chatex developer commands' -ForegroundColor Cyan
Write-Host ''
Write-Host ' ./Run.ps1 <command> [arguments]'
Write-Host ''
foreach ($entry in $Commands.GetEnumerator()) {
Write-Host (' {0,-10} ' -f $entry.Key) -ForegroundColor Green -NoNewline
Write-Host $entry.Value
}
Write-Host ''
Write-Host 'Examples:' -ForegroundColor Cyan
Write-Host ' ./Run.ps1 setup'
Write-Host ' ./Run.ps1 migration AddMessageReactions'
Write-Host ' ./Run.ps1 test --project Tests/Chatex.Core.Tests --filter-class "*ChatServiceTests"'
Write-Host ' ./Run.ps1 check'
Write-Host ''
Write-Host 'Needs the .NET 10 SDK, Node.js 24 and Docker. See Docs/GettingStarted.md.'
}
# Runs a program in a folder (the repository root by default) and stops the script if it fails.
function Invoke-Step {
param(
[Parameter(Mandatory)] [string] $FilePath,
[string[]] $ArgumentList = @(),
[string] $WorkingDirectory = $Root
)
Write-Host "> $FilePath $($ArgumentList -join ' ')" -ForegroundColor DarkGray
Push-Location $WorkingDirectory
try {
& $FilePath @ArgumentList
if ($LASTEXITCODE -ne 0) {
throw "'$FilePath $($ArgumentList -join ' ')' failed with exit code $LASTEXITCODE."
}
}
finally {
Pop-Location
}
}
function Start-Database {
Invoke-Step docker 'compose', 'up', '--detach', '--wait'
Invoke-Step dotnet 'ef', 'database', 'update', '--project', $DataProject
}
switch ($Command) {
'help' {
Show-Help
}
'setup' {
Invoke-Step dotnet 'tool', 'restore'
Invoke-Step dotnet 'restore', $Solution
Invoke-Step npm 'ci' -WorkingDirectory $Web
Start-Database
Write-Host 'Ready: ./Run.ps1 api, then ./Run.ps1 web in a second terminal.' -ForegroundColor Cyan
}
'db' {
Start-Database
}
'db-stop' {
Invoke-Step docker 'compose', 'stop'
}
'migration' {
if ($args.Count -ne 1) {
throw 'Usage: ./Run.ps1 migration <Name>'
}
Invoke-Step dotnet 'ef', 'migrations', 'add', $args[0], '--project', $DataProject, '--output-dir', 'Migrations'
}
'api' {
Invoke-Step dotnet 'run', '--project', $ApiProject, '--launch-profile', 'http'
}
'web' {
Invoke-Step npm 'start' -WorkingDirectory $Web
}
'build' {
Invoke-Step dotnet 'build', $Solution
Invoke-Step npm 'run', 'build' -WorkingDirectory $Web
}
'test' {
if ($args.Count -gt 0) {
Invoke-Step dotnet (@('test') + $args)
}
else {
Invoke-Step dotnet 'test', '--solution', $Solution
Invoke-Step npm 'test', '--', '--watch=false' -WorkingDirectory $Web
}
}
'format' {
Invoke-Step dotnet 'format', $Solution
Invoke-Step npm 'run', 'format' -WorkingDirectory $Web
}
'check' {
# The same steps as .github/workflows/ci.yml.
Invoke-Step dotnet 'restore', $Solution
Invoke-Step dotnet 'tool', 'restore'
Invoke-Step dotnet 'format', $Solution, '--verify-no-changes', '--no-restore'
Invoke-Step dotnet 'build', $Solution, '-c', 'Release', '--no-restore'
Invoke-Step dotnet 'ef', 'migrations', 'has-pending-model-changes', '--project', $DataProject, '--configuration', 'Release', '--no-build'
Invoke-Step dotnet 'test', '--solution', $Solution, '-c', 'Release', '--no-build'
Invoke-Step npm 'ci' -WorkingDirectory $Web
Invoke-Step npm 'audit', '--omit=dev', '--audit-level=high' -WorkingDirectory $Web
Invoke-Step npm 'run', 'format:check' -WorkingDirectory $Web
Invoke-Step npm 'run', 'lint' -WorkingDirectory $Web
Invoke-Step npm 'test', '--', '--watch=false' -WorkingDirectory $Web
Invoke-Step npm 'run', 'build' -WorkingDirectory $Web
Write-Host 'All checks passed.' -ForegroundColor Green
}
'clean' {
$folders = @(
Get-ChildItem -Path (Join-Path $Root 'Source'), (Join-Path $Root 'Tests') -Directory |
ForEach-Object { Join-Path $_.FullName 'bin'; Join-Path $_.FullName 'obj' }
Join-Path $Web 'dist'
Join-Path $Web '.angular/cache'
) | Where-Object { Test-Path $_ }
foreach ($folder in $folders) {
Write-Host "Deleting $folder" -ForegroundColor DarkGray
Remove-Item -Recurse -Force $folder
}
}
}Як це працює:
param(...)з[ValidateSet(...)]– перший аргумент має бути однією з перелічених команд. Описка на кшталт./Run.ps1 tsetодразу завершується списком допустимих значень, а термінал доповнює назви команд за Tab. Без аргумента команда –help.$ErrorActionPreference = 'Stop'– помилка команди PowerShell зупиняє скрипт замість того, щоб дозволити йому перейти до наступного кроку.$Commands– впорядкований словник команд та їхніх описів;Show-Helpвиводить його, тож довідка завжди відповідає скрипту.Invoke-Step– запускає зовнішню програму (dotnet,npm,docker) у заданій папці, виводить команду сірим кольором і зупиняє скрипт, якщо програма завершилась помилкою. Зовнішні програми не викликають помилок PowerShell; про невдачу вони повідомляють кодом завершення, який PowerShell зберігає в$LASTEXITCODE. Без цієї перевіркиcheckрадісно запускав би тести після невдалого збирання.switch ($Command)– одна гілка на команду. Додаткові аргументи, не оголошені вparam, потрапляють в автоматичну змінну$args;testіmigrationпередають їх далі вdotnet.checkвиконує рівно ті кроки, що й робочий процес CI (тема 22), тож ви можете знайти проблему до пуша.
Не всі команди працюють одразу. Таблиця 2.2 показує, коли кожна стає придатною до використання.
Таблиця 2.2. Команди Run.ps1
| Команда | Що робить | Працює з |
|---|---|---|
help | виводить список команд | зараз |
api | запускає API на http://localhost:5214 | зараз (він ще відповідає «Hello World!») |
db-stop | зупиняє контейнер PostgreSQL | зараз |
db | запускає PostgreSQL і застосовує міграції | тема 4 (перша міграція) |
migration <Name> | додає міграцію EF Core | тема 4 |
test [options] | запускає тести | тема 6 з параметрами, наприклад ./Run.ps1 test --solution Chatex.slnx; без параметрів з теми 15 |
clean | видаляє bin, obj і результат збирання Angular | тема 6 (вона заглядає в папку Tests/, якої поки немає) |
build, format | збирає або форматує серверну частину й вебзастосунок | тема 15 (до того користуйтеся dotnet build і dotnet format Chatex.slnx) |
web | запускає сервер розробки Angular на http://localhost:4200 | тема 15 |
setup | перший запуск: інструменти, пакети, база даних | тема 15 |
check | усе, що виконує CI | тема 22 |
Перевірка
powershell
./Run.ps1Скрипт виводить список команд. Тепер запустіть через нього API:
powershell
./Run.ps1 apiСірий рядок > dotnet run --project Source/Chatex.Api --launch-profile http показує команду, яку він виконує, а API слухає http://localhost:5214. Зупиніть його за допомогою Ctrl+C.
«Running scripts is disabled on this system»
Windows PowerShell за замовчуванням блокує скрипти, а PowerShell 7 у Windows може блокувати скрипти, завантажені з інтернету. Запускайте скрипт із PowerShell 7, і якщо його все одно заблоковано, один раз дозвольте локальні скрипти для свого користувача:
powershell
Set-ExecutionPolicy -Scope CurrentUser RemoteSignedКрок 2. Перший коміт
Навіщо. Каркас готовий: він збирається без попереджень за суворих правил, база даних працює, а команди задокументовано в скрипті. Це добрий стан, до якого можна повертатися, тож ми його зберігаємо.
Що зробити. Подивіться, що буде закомічено, і закоміть:
powershell
git status --shortpowershell
git add .powershell
git commit -m "Create the solution with shared build settings and a local database"Перевірка
powershell
git log --onelineІсторія має один коміт. git status повідомляє nothing to commit, working tree clean, і жодної папки bin/ чи obj/ не закомічено:
powershell
git ls-filesСписок містить .editorconfig, .gitattributes, .gitignore, Chatex.slnx, Directory.Build.props, Directory.Packages.props, Run.ps1, compose.yaml, dotnet-tools.json, global.json і файли трьох проєктів у Source/.
Якщо ви маєте обліковий запис GitHub, зараз також слушний час створити там порожній приватний репозиторій і надіслати в нього код; він знадобиться нам для CI у темі 22:
powershell
git remote add origin https://github.com/<your-account>/Chatex.gitpowershell
git push -u origin main