29 Commits

Author SHA1 Message Date
d001ef3e82 New translations quality-commands.mdx (Russian)
[ci skip]
2026-07-06 03:25:46 +08:00
d3cdb8d479 New translations test-framework.mdx (Russian)
[ci skip]
2026-07-06 02:21:58 +08:00
b36d6a2109 New translations running-tests.mdx (Russian)
[ci skip]
2026-07-06 02:21:56 +08:00
facf44ddc3 New translations self-update.mdx (Russian)
[ci skip]
2026-07-06 02:21:53 +08:00
0840956347 New translations workspaces.mdx (Russian)
[ci skip]
2026-07-06 02:21:51 +08:00
4b779d1432 New translations platform-support.mdx (Russian)
[ci skip]
2026-07-06 02:21:48 +08:00
32d76ff80f New translations environment-variables.mdx (Russian)
[ci skip]
2026-07-06 02:21:46 +08:00
8a33a31445 New translations dependencies.mdx (Russian)
[ci skip]
2026-07-06 02:21:43 +08:00
0d4c2399c9 New translations dcr-toml.mdx (Russian)
[ci skip]
2026-07-06 02:21:41 +08:00
ec655d4783 New translations cross-compilation.mdx (Russian)
[ci skip]
2026-07-06 02:21:38 +08:00
b926bbdb31 New translations build-system.mdx (Russian)
[ci skip]
2026-07-06 02:21:36 +08:00
028c9ef16c New translations build-profiles.mdx (Russian)
[ci skip]
2026-07-06 02:21:33 +08:00
b840f658a2 New translations multi-package-workspace.mdx (Russian)
[ci skip]
2026-07-06 02:21:31 +08:00
7203996588 New translations library-project.mdx (Russian)
[ci skip]
2026-07-06 02:21:28 +08:00
57c35a1c99 New translations cross-to-windows.mdx (Russian)
[ci skip]
2026-07-06 02:21:26 +08:00
c7c743c0c9 New translations license.mdx (Russian)
[ci skip]
2026-07-06 02:21:23 +08:00
5876c71be7 New translations ide-integration.mdx (Russian)
[ci skip]
2026-07-06 02:21:21 +08:00
7cf2cd65b4 New translations installation.mdx (Russian)
[ci skip]
2026-07-06 02:21:18 +08:00
4a3c97d674 New translations first-steps.mdx (Russian)
[ci skip]
2026-07-06 02:21:16 +08:00
9ba9cade86 New translations faq.mdx (Russian)
[ci skip]
2026-07-06 02:21:13 +08:00
194963c6b9 New translations contributing.mdx (Russian)
[ci skip]
2026-07-06 02:21:11 +08:00
bd4648b278 New translations system-commands.mdx (Russian)
[ci skip]
2026-07-06 02:21:09 +08:00
f73eb0191e New translations quality-commands.mdx (Russian)
[ci skip]
2026-07-06 02:21:06 +08:00
0edda3658b New translations project-commands.mdx (Russian)
[ci skip]
2026-07-06 02:21:04 +08:00
63d0da68f3 New translations gen-commands.mdx (Russian)
[ci skip]
2026-07-06 02:21:01 +08:00
eee70da275 New translations dependency-commands.mdx (Russian)
[ci skip]
2026-07-06 02:20:59 +08:00
d44c62da6d New translations build-commands.mdx (Russian)
[ci skip]
2026-07-06 02:20:56 +08:00
8c032da3ee New translations changelog.mdx (Russian)
[ci skip]
2026-07-06 02:20:54 +08:00
19a1a6c21f New translations readme.mdx (Russian)
[ci skip]
2026-07-06 02:20:51 +08:00
28 changed files with 536 additions and 547 deletions

View File

@@ -1,63 +1,53 @@
---
sidebar_label: Introduction
sidebar_label: Введение
---
# DCR — C/C++ Build Tool & Package Manager
# DCR — Инструмент сборки C/C++ & Пакетный менеджер
<details>
<summary>Quick reference</summary>
<summary>Быстрая справка</summary>
```bash
# Installation
# Установка(Linux/MacOS скрипт)
curl -fsSL https://dcr.dexoron.su/install.sh | sh
# Create a project
# Создать проект
dcr new my-app
cd my-app
# Build and run
dcr build
# Собрать и запустить
dcr run
# Run tests
dcr test
# Add a dependency
dcr add fmt
# Generate IDE files
dcr gen vscode
```
</details>
## Contents
## Содержание
| Section | Description |
| ----------------------------------------------------- | --------------------------------------------- |
| [Getting Started](/docs/getting-started/installation) | Installation and first steps |
| [Commands](/docs/commands/project-commands) | All CLI commands |
| [Reference](/docs/reference/dcr-toml) | Configuration, build, dependencies, platforms |
| [Testing](/docs/testing/test-framework) | Built-in test framework |
| [Recipes](/docs/recipes/cross-to-windows) | Common scenarios |
| Раздел | Описание |
| ----------------------------------------------------- | -------------------------------------------- |
| [Getting Started](/docs/getting-started/installation) | Установка и первые шаги |
| [Commands](/docs/commands/project-commands) | Все CLI-команды DCR |
| [Reference](/docs/reference/dcr-toml) | Конфигурация, сборка, зависимости, платформы |
| [Testing](/docs/testing/test-framework) | Встроенный фреймворк тестирования |
| [Recipes](/docs/recipes/cross-to-windows) | Типовые сценарии |
| [IDE Integration](/docs/ide-integration) | VS Code, CLion, compile_commands.json |
| [Self Update](/docs/self-update) | Auto-update |
| [FAQ](/docs/faq) | Frequently asked questions |
| [Changelog](/docs/changelog) | Version history |
| [License](/docs/license) | DCR and vendored library licenses |
| [Contributing](/docs/contributing) | DCR development |
| [Self Update](/docs/self-update) | Автообновление |
| [FAQ](/docs/faq) | Частые вопросы |
| [Changelog](/docs/changelog) | История версий |
| [License](/docs/license) | Лицензии DCR и вендорных библиотек |
| [Contributing](/docs/contributing) | Разработка DCR |
## Features
## Особенности
* **Incremental builds** — mtime + `.d` headers + SHA256 fingerprint
* **Parallel compilation** — thread::scope, atomic task queue
* **4 backends** — gcc/clang, MSVC/clang-cl, GAS (ARM), NASM (x86)
* **7 project kinds** — bin, staticlib, sharedlib, efi, elf, none, custom
* **Cross-compilation** — short names and full triples
* **Profiles** — debug / release with field overrides
* **Workspaces** — multi-package projects with topological sort
* **Registry + Git + Path** — three dependency mechanisms
* **IDE generation** — VS Code, CLion, compile_commands.json, JSON metadata
* **pkg-config** — automatic system library discovery
* **Инкрементальная сборка** — mtime + `.d` headers + SHA256 fingerprint
* **Параллельная компиляция** — thread::scope, атомарная очередь задач
* **4 бэкенда** — gcc/clang, MSVC/clang-cl, GAS, NASM
* **7 типов проекта** — bin, staticlib, sharedlib, efi, elf, none, custom
* **Cross-compilation** — short names (linux, windows, macos) и полные triples
* **Профили** — debug / release с переопределением любого поля
* **Workspaces** — мультипакетные проекты с топологической сортировкой
* **Registry + Git + Path** — три механизма зависимостей
* **Генерация IDE** — VS Code, CLion, compile_commands.json, JSON metadata
* **pkg-config** — автоматический поиск системных библиотек
* **Per-command `--help`** — `dcr build --help`, `dcr new --help`, etc.
* **Man pages** — `man dcr`, `man dcr-build`, `man dcr-new`

View File

@@ -6,7 +6,7 @@ sidebar_label: Changelog
## 0.7.1 (2026-06-02)
### Added
### Добавлено:
* **`--help` for all commands** — `dcr build --help`, `dcr run --help`, `dcr new --help`,
`dcr init --help`, `dcr clean --help`, `dcr add --help`, `dcr fmt --help`,
@@ -29,7 +29,7 @@ sidebar_label: Changelog
* **Snap publishing** — automated Snapcraft publishing in CI.
* **Snap badge** — in README.
### Changed
### Изменено:
* **`validate_package_name` made public** — callable from CLI commands.
* **README platform table** — reorganized: libc variants as separate OS rows,
@@ -38,7 +38,7 @@ sidebar_label: Changelog
* **`tree.rs`, `fmt.rs`, and `setup.rs`** — now accept arguments for `--help`.
* **README install commands** — `| bash` → `| sh` for POSIX compatibility.
### Fixed
### Исправлено:
* **`dcr new \<invalid-name>` creates directory then fails** — validation now
happens before any file operations.
@@ -52,40 +52,40 @@ sidebar_label: Changelog
### Added
* **OpenBSD and NetBSD target support** — full platform routing with dynamic target triples using `std::env::consts::ARCH` and `std::env::consts::OS`. Affects `build`, `run`, `clean` commands and the platform module.
* **`src/platform/bsd.rs`** — new BSD platform module (shared by FreeBSD, OpenBSD, NetBSD) providing `bin_path`, `lib_path`, `elf_path`, `efi_path`, `shared_lib_path`.
* **`build.out_dir` config option** — custom output directory that overrides the default `target/\<triple>/\<profile>` path for final artifacts. Supported in `build`, `run`, and config validation.
* **`dcr fmt` command** — new CLI command that formats all C/C++ source files (`*.c`, `*.cpp`, `*.h`, `*.hpp`) in `src/` and `tests/` using `clang-format`.
* **Incremental linking** — `needs_link()` in `common.rs` checks if any object file is newer than the linked output, skipping unnecessary relinking. Implemented for all backends (`unix_cc`, `msvc`, `gas`, `nasm`).
* **`build.kind = "none"` and `"custom"`** — two new project kinds for special build scenarios that don't produce standard artifacts.
* **`install_bsd.sh`** — POSIX-compliant installation script for BSD systems (FreeBSD, OpenBSD, NetBSD) with binary download and source build modes.
* **Linux ARM64 support in `install.sh`** — added `Linux:aarch64|Linux:arm64` target detection for pre-built binary downloads.
* **BSD OS detection in `install.sh`** — detects FreeBSD, OpenBSD, NetBSD and determines target triple.
* **`rust-toolchain.toml`** — explicit toolchain pinning to `stable` channel.
* **Integration tests** — `build_with_target_config` (verifies `build.target = "linux"`) and `build_with_out_dir` (validates custom output directory).
* **`get_build_string_with_profile` made `pub`** — so `run.rs` can determine custom output directory configuration.
* **Поддержка целевых платформ OpenBSD и NetBSD** — полная маршрутизация по платформам с динамически генерируемыми тройками целевых параметров с использованием `std::env::consts::ARCH` и `std::env::consts::OS`. Затрагивает команды `build`, `run`, `clean` и модуль платформы.
* **`src/platform/bsd.rs`** — новый специальный модуль платформы BSD, общий для FreeBSD, OpenBSD и NetBSD, предоставляющий `bin_path`, `lib_path`, `elf_path`, `efi_path` и `shared_lib_path`.
* **`Параметр конфигурации build.out_dir`** — настраиваемый каталог вывода, который переопределяет путь по умолчанию `target/\<triple>/\<profile>` для конечных артефактов. Поддерживается в `build`, `run` и при проверке конфигурации.
* **Команда `dcr fmt`** — новая команда CLI, которая форматирует все исходные файлы C/C++ (`*.c`, `*.cpp`, `*.h`, `*.hpp`) в `src/` и `tests/` с помощью `clang-format`.
* **Инкрементальная компоновка** — функция `needs_link()` в `common.rs`, которая проверяет, не является ли какой-либо объектный файл более новым, чем скомпонованный результат, пропуская ненужную повторную компоновку. Реализовано для всех бэкэндов (`unix_cc`, `msvc`, `gas`, `nasm`).
* **`build.kind = «none»` и `«custom»`** — два новых типа проектов для специальных сценариев сборки, при которых не создается стандартный артефакт.
* **`install_bsd.sh`** — специальный скрипт установки, совместимый с POSIX, для систем BSD (FreeBSD, OpenBSD, NetBSD) с режимами загрузки бинарных файлов и сборки из исходного кода.
* **Поддержка Linux ARM64 в `install.sh`** — добавлено определение целевой тройки `Linux:aarch64|Linux:arm64` для загрузки готовых бинарных файлов.
* **Обнаружение ОС BSD в `install.sh`** — обнаружение FreeBSD, OpenBSD, NetBSD и определение целевой тройки.
* **`rust-toolchain.toml`** — явное привязывание инструментария к каналу `stable`.
* **Интеграционные тесты** — `build_with_target_config` (проверяет `build.target = «linux»`) и `build_with_out_dir` (проверяет настраиваемый каталог вывода).
* **`get_build_string_with_profile` стал `pub`** — чтобы `run.rs` мог определять конфигурацию настраиваемого каталога вывода.
### Changed
* **`build.target` semantics changed** — now strictly contains a target triple (e.g., `x86_64-unknown-linux-gnu`) or short name (`linux`, `macos`, `windows`). No longer used as custom output directory — this functionality moved to `build.out_dir`.
* **`build.standard` made optional** — changed from `String` to `Option\<String>`. Validation only enforces non-empty for non-ASM languages. Skipped in `dcr.toml` output if empty.
* **`dcr run` with `out_dir`** — now determines target directory respecting `build.out_dir` via `get_build_string_with_profile()` from `build.rs`.
* **`collect_sources()` returns empty vector** instead of error when no sources are found, allowing `kind = "none"` or `kind = "custom"` projects with no source files.
* **CI/CD release workflow refactored** — `git2` made target-specific (no vendored-openssl on Windows), Zig-based cross-compilation for non-x86_64 Linux targets, Arch Linux package version cleanup (dashes → dots), `gmake` symlink for NetBSD.
* **README compatibility table** — FreeBSD, OpenBSD, NetBSD build/run status upgraded from "community/best-effort" to "officially supported".
* **Documentation updated** — `build-section.md` describes new `build.target` and `build.out_dir` fields. `target-directory.md` rewritten to clarify the distinction.
* **Изменена семантика `build.target`** — теперь строго содержит тройку целей (например, `x86_64-unknown-linux-gnu`) или короткое имя (`linux`, `macos`, `windows`). Больше не используется в качестве пользовательского каталога вывода — эта функциональность перенесена в `build.out_dir`.
* **`build.standard` стал опциональным** — изменен с `String` на `Option\<String>`. Проверка обеспечивает только непустоту для языков, отличных от ASM. Пропускается в выводе `dcr.toml`, если пуст.
* **`dcr run` с `out_dir`** — теперь определяет целевой каталог с учетом `build.out_dir`, если он настроен, через `get_build_string_with_profile()` из `build.rs`.
* **`collect_sources()` возвращает пустой вектор** вместо ошибки, если не найдено ни одного исходного файла, что позволяет проектам с `kind = «none»` или `kind = «custom»` не иметь исходных файлов.
* **Рефакторинг рабочего процесса выпуска CI/CD** — `git2` стал целевым (без vendored-openssl на Windows), кросс-компиляция на основе Zig для целей Linux, отличных от x86_64, очистка версий пакетов Arch Linux (тире → точки), символьная ссылка `gmake` для NetBSD.
* **Таблица совместимости README** — статус сборки/работы на FreeBSD, OpenBSD, NetBSD повышен с «сообщество/по возможности» до «официально поддерживается».
* **Обновлена документация** — `build-section.md` описывает новые поля `build.target` и `build.out_dir`. `target-directory.md` переписан для уточнения различия.
### Fixed
* **stdout/stderr not inherited in `dcr run`** — child process output was captured and manually printed, breaking interactive programs. Fixed by switching to `Command::status()`.
* **Race condition in release CI** — matrix build jobs could upload assets to a release that didn't exist yet. Fixed by adding a dedicated `create-release` job.
* **Release GHA — stable toolchain override** — fixed Rust toolchain override issues in CI.
* **Arch Linux package version sanitization** — version strings with dashes (e.g., `0.7.0-dev`) are invalid for `pkgver`. Fixed by replacing dashes with dots.
* **GPG permissions after Docker** — Docker operations changed GPG directory ownership. Fixed by running `chown` after Docker commands.
* **RPM artifact paths** — RPM artifacts were placed in `rpm/x86_64/` instead of `fedora/x86_64/`. Fixed in Dexoron Packages Index workflow.
* **JSON parsing reliability in `install.sh`** — added `jq` as primary parser with `python3` fallback for dev channel release lookup.
* **stdout/stderr `dcr run` не наследуются** — вывод дочернего процесса захватывался и выводился вручную, что приводило к сбоям интерактивных программ. Исправлено путем перехода на `Command::status()`.
* **Условие гонки в CI релиза** — задания матрицы сборки могли загружать ресурсы в релиз, который еще не существовал. Исправлено добавлением специального задания `create-release`.
* **Релиз GHA — переопределение стабильного набора инструментов** — устранены проблемы с переопределением набора инструментов Rust в CI.
* **Очистка версий пакетов Arch Linux** — строки версий с дефисами (например, `0.7.0-dev`) являются недопустимыми для `pkgver` в Arch Linux. Исправлено путем замены дефисов точками.
* **Права доступа GPG после Docker** — операции Docker изменяли владельца каталога GPG. Исправлено путем запуска `chown` после команд Docker.
* **Пути к артефактам пакетов RPM** — артефакты RPM размещались в `rpm/x86_64/` вместо `fedora/x86_64/`. Исправлено в рабочем процессе Dexoron Packages Index.
* **Надежность разбора JSON в `install.sh`** — добавлен `jq` в качестве основного парсера с резервным вариантом `python3` для поиска релизов в канале dev.
### Removed
### Удалено:
* **`format_roots()` helper function** — removed from `common.rs`. Was only used by the old error handling path in `collect_sources()`.
* **Per-distribution artifact download steps** — three separate `actions/download-artifact` steps replaced with unified `gh release download --clobber`.
* **Вспомогательная функция `format_roots()`** — удалена из `common.rs`. Использовалась только старым путем обработки ошибок в `collect_sources()`.
* **Отдельные шаги загрузки артефактов для каждой дистрибуции** — три отдельных шага `actions/download-artifact` заменены на унифицированный `gh release download --clobber`.

View File

@@ -1,29 +1,30 @@
---
sidebar_label: Build commands (build, run, clean)
sidebar_label: Команды сборки (build, run, clean)
---
# Build Commands
# Команды сборки
## `dcr build`
Builds the project according to `dcr.toml`.
Собирает проект по `dcr.toml`.
```bash
dcr build # debug profile
dcr build --release # release build
dcr build --debug # explicit debug
dcr build # debug профиль
dcr build --release # release профиль
dcr build --debug # явно debug
dcr build --profile custom # произвольный профиль
dcr build --target aarch64-unknown-linux-gnu
dcr build --force # full rebuild
dcr build --force # пересобрать всё с нуля
dcr build --clean # clean + build
dcr build --verbose # show compilation commands
dcr build --workspace pkg-a # build specific workspace package
dcr build --verbose # показать команды компиляции
dcr build --workspace pkg-a # собрать конкретный пакет в workspace
```
Artifacts: `target/\<triple>/\<profile>/\<binary-name>` (Linux with explicit target).
Артефакты: `target/\<triple>/\<profile>/\<binary-name>` (Linux с явным целевым объектом).
## `dcr run`
Builds (if sources are newer than artifacts) and runs the binary.
Собирает (если исходники новее артефакта) и запускает бинарник.
```bash
dcr run
@@ -32,11 +33,11 @@ dcr run --release
## `dcr clean`
Removes `target/` directory (or `target/\<target>/\<profile>`).
Удаляет директорию `target/`(или `target/\<target>/\<profile>`).
```bash
dcr clean
dcr clean --release # target/release/ only
dcr clean --target windows # target/x86_64-pc-windows-msvc/
dcr clean --all # clean all workspace packages
dcr clean --release # очистить target/release/
dcr clean --target windows # очистить target/x86_64-pc-windows-msvc/
dcr clean --all # очистить все пакеты workspace
```

View File

@@ -1,47 +1,47 @@
---
sidebar_label: Dependency commands (add, tree)
sidebar_label: Команды зависимостей (add, tree)
---
# Dependency Commands
# Команды зависимостей
## `dcr add \<name> [source]`
Adds a dependency to `dcr.toml`.
Добавляет зависимость в `dcr.toml`.
```bash
dcr add fmt # registry lookup
dcr add mylib ../path/to/lib # path as source
dcr add mylib path:./lib # explicit path prefix
dcr add mylib git:https://github.com/user/repo # explicit git prefix
dcr add mylib github:user/repo # GitHub shorthand
dcr add mylib gitlab:user/repo # GitLab shorthand
dcr add fmt # поиск в реестре
dcr add mylib ../path/to/lib # путь как источник
dcr add mylib path:./lib # явный префикс пути
dcr add mylib git:https://github.com/user/repo # явный префикс git
dcr add mylib github:user/repo # сокращённая запись GitHub
dcr add mylib gitlab:user/repo # сокращённая запись GitLab
```
Source prefixes:
Префиксы источника:
* `path:` — local path
* `git:` — generic git URL
* `github:` — expands to `https://github.com/\<user>/\<repo>`
* `gitlab:` — expands to `https://gitlab.com/\<user>/\<repo>`
* `http://` / `https://` / `git@` — full URL
* `path:` — локальный путь
* `git:` — URL адрес git-репозитория
* `github:` — расширение `https://github.com/\<user>/\<repo>`
* `gitlab:` — расширение `https://gitlab.com/\<user>/\<repo>`
* `http://` / `https://` / `git@` — полный URL
Flags:
Флаги:
* `--branch \<name>` — git branch
* `--branch \<name>` — git ветка
* `--tag \<name>` — git tag
* `--rev \<hash>` — git commit
If source is omitted — DCR searches connected registries.
Если источник не указан — DCR выполняет поиск в подключенных реестрах.
## `dcr tree`
Displays the project dependency tree.
Показывает дерево зависимостей проекта.
```bash
dcr tree
```
Example output:
Пример вывода:
```
my-app v0.1.0
@@ -50,4 +50,4 @@ my-app v0.1.0
└── catch2 (registry)
```
For path dependencies, recursively shows their own dependencies (from their `dcr.toml`).
В случае path зависимостей, рекурсивно отображает их собственные зависимости (из файла `dcr.toml`).

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Gen commands (vscode, clion, ...)
sidebar_label: Gen команды (vscode, clion, ...)
---
# Gen Commands
# Gen команды
## `dcr gen \<target>`
Generates IDE integration files.
Генерирует файл интеграции с IDE.
### vscode
@@ -14,12 +14,12 @@ Generates IDE integration files.
dcr gen vscode
```
Creates:
Создаёт:
* `.vscode/tasks.json` — `build` task (dcr build)
* `.vscode/launch.json` — debug launch configuration
* `.vscode/settings.json` — C/C++ settings (clangd paths, includes)
* `.vscode/extensions.json` — recommended extensions (vscode-clangd, vscode-lldb)
* `.vscode/tasks.json` — `build` задача (dcr build)
* `.vscode/launch.json` — конфигурация запуска отладки
* `.vscode/settings.json` — настройки C/C++ (clangd пути, includes)
* `.vscode/extensions.json` — рекомендуемые расширения (vscode-clangd, vscode-lldb)
### clion
@@ -27,12 +27,12 @@ Creates:
dcr gen clion
```
Creates:
Создаёт:
* `.idea/externalTools.xml` — external tools (build, run, clean, test)
* `.idea/customTargets.xml` — custom build targets
* `.idea/misc.xml` — C/C++ project settings
* `.idea/runConfigurations/\<name>.xml` — per-binary run configurations
* `.idea/externalTools.xml` — внешние инструменты (build, run, clean, test)
* `.idea/customTargets.xml` — пользовательские цели сборки
* `.idea/misc.xml` — настройки C/C++ проекта
* `.idea/runConfigurations/\<name>.xml` — конфигурация запуска
### compile-commands
@@ -40,7 +40,7 @@ Creates:
dcr gen compile-commands
```
Generates `compile_commands.json` — standard format for clangd, cpptools, static analyzers.
Генерирует `compile_commands.json` — стандартный формат для clangd, cpptools, статических анализаторов.
### project-info
@@ -48,7 +48,7 @@ Generates `compile_commands.json` — standard format for clangd, cpptools, stat
dcr gen project-info
```
Outputs JSON array with project metadata:
Выводит JSON с метаданными проекта:
```json
[

View File

@@ -1,31 +1,31 @@
---
sidebar_label: Project commands (new, init)
sidebar_label: Команды проекта (new, init)
---
# Project Commands
# Команды проекта
## `dcr new \<name>`
Creates a new project with a standard structure and `dcr.toml`. The `name` argument is required.
Создает новый проект со стандартной структурой и `dcr.toml`. Аргумент `name` является обязательным.
Only ASCII letters, digits, underscores `_` and hyphens `-` are allowed in the project name.
В названии проекта допускаются только ASCII буквы, цифры и подчеркивания `_` и дефисы `-`.
```bash
dcr new my-app
```
Generates:
Генерирует:
* `dcr.toml` with basic fields
* `src/main.c` with a `main` template
* `dcr.toml` с базовыми полями
* `src/main.c` с основным шаблоном
## `dcr init`
Initializes a DCR project in the current (empty) directory.
Инициализирует проект DCR в текущем (пустом) каталоге.
```bash
mkdir app && cd app
dcr init
```
The project name is taken from the current directory name. The directory name must follow the same naming rules as `dcr new`.
Название проекта взято из имени текущего каталога. Имя каталога должно соответствовать тем же правилам именования, что и в `dcr new`.

View File

@@ -1,40 +1,40 @@
---
sidebar_label: Quality commands (test, fmt)
sidebar_label: Команды качества (test, fmt)
---
# Quality Commands
# Команды качества
## `dcr test`
Runs tests.
Запускает тесты.
```bash
dcr test # debug profile
dcr test --release # release profile
dcr test --debug # explicit debug
dcr test --help # detailed help
dcr test # debug профиль
dcr test --release # release профиль
dcr test --debug # явный debug
dcr test --help # подробная справка
```
Before first use, initialize tests:
Перед первым запуском нужно инициализировать тесты:
```bash
dcr test --init
```
This creates `tests/dcr_test.h` (framework) and `tests/test.c` (template).
Это создаёт `tests/dcr_test.h` (фреймворк) и `tests/test.c` (шаблон).
What `dcr test` does:
Что делает `dcr test`:
1. Builds the project
2. Collects `tests/*.c` files (`.c` only, not `.cpp`)
3. Compiles and links each test file
4. Runs each test binary
5. Prints summary: TOTAL, PASS, SKIP, FAIL
6. Returns non-zero exit code on any FAIL
6. Возвращает ненулевой код при наличии FAIL
## `dcr fmt`
Formats C/C++ source files using `clang-format`.
Форматирует исходный код C/C++ через `clang-format`.
```bash
dcr fmt
@@ -42,7 +42,7 @@ dcr fmt
Processes: `src/**/*.{c,cpp,cxx,cc,h,hpp,hxx,hh}` and `tests/**/*.{c,cpp,cxx,cc,h,hpp,hxx,hh}`.
Uses `.clang-format` at the project root (if present), otherwise default clang-format style.
Используется файл `.clang-format` в корне проекта (если есть), иначе дефолтный стиль DCR.
## `dcr lint`

View File

@@ -1,12 +1,12 @@
---
sidebar_label: System commands (setup, --help, ...)
sidebar_label: Системные команды (setup, --help, ...)
---
# System Commands
# Системные команды
## `dcr setup`
Shows configured registries from `~/.dcr/config.toml`.
`~/.dcr/config.toml` — конфигурация реестров
```bash
dcr setup
@@ -26,6 +26,7 @@ Shows help for all commands.
```bash
dcr --help
dcr build --help # справка по конкретной команде
```
## `dcr --version`
@@ -33,19 +34,19 @@ dcr --help
Shows version and target triple.
```bash
dcr --version # dcr 0.7.0 (x86_64-unknown-linux-gnu)
dcr --version # dcr 0.7.0
```
## `dcr --update`
Self-update. Downloads the latest release binary from GitHub Releases and replaces the current one.
Самообновление. Скачивает последний релиз с GitHub Releases и заменяет текущий бинарник.
```bash
dcr --update
```
Features:
Особенности:
* Auto-detects platform and architecture
* Определяет платформу и архитектуру автоматически
* Warns if installed via AUR (use package manager instead)
* Works on Linux, macOS, Windows
* Работает на Linux, macOS, Windows

View File

@@ -14,19 +14,19 @@ cargo build
## Code style
All code must be formatted with `cargo fmt`:
Весь код форматируется через `cargo fmt`:
```bash
cargo fmt
```
## Linting
## Линтер
```bash
cargo clippy --all-targets -- -D warnings
```
## Tests
## Тесты
```bash
cargo test --all-targets
@@ -34,18 +34,18 @@ cargo test --all-targets
## PR process
1. Fork the repository
2. Create a branch: `git checkout -b feature/description`
3. Make changes
4. Run `cargo fmt && cargo clippy && cargo test`
5. Open a Pull Request
1. Форкните репозиторий
2. Создайте ветку: `git checkout -b feature/description`
3. Внесите изменения
4. Запустите `cargo fmt && cargo clippy --all-targets -- -D warnings && cargo test --all-targets`
5. Откройте Pull Request
## CI
CI runs:
В CI запускаются:
* `cargo fmt --check`
* `cargo clippy --all-targets -- -D warnings`
* `cargo test --all-targets`
* Build on Linux, macOS, Windows
* Integration tests
* Сборка под Linux, macOS, Windows, FreeBSD, OpenBSD, NetBSD
* Интеграционные тесты

View File

@@ -1,8 +1,8 @@
---
sidebar_label: FAQ
sidebar_label: Часто задаваемые вопросы
---
# FAQ
# Часто задаваемые вопросы
## Registry not found
@@ -18,7 +18,7 @@ name = "default"
url = "https://index.dcr.pm"
```
And check `DCR_INDEX_PATH`:
Если реестр кастомный, проверьте `DCR_INDEX_PATH`:
```bash
echo $DCR_INDEX_PATH
@@ -30,24 +30,24 @@ echo $DCR_INDEX_PATH
error: compiler not found
```
**Solution:** Ensure a compiler is installed and available in PATH.
**Решение:** Убедитесь, что компилятор установлен и доступен в PATH.
```bash
which gcc
which clang
```
Or specify explicitly via `[toolchain]` in `dcr.toml`.
Или укажите явно через `[toolchain]` или `DCR_COMPILER`.
## openssl-sys build failed
When building DCR from source:
При сборке DCR из исходников:
```
error: failed to run custom build command for openssl-sys
```
**Solution:** Install OpenSSL development headers:
**Решение:** Установите OpenSSL development headers:
```bash
# Ubuntu/Debian
@@ -60,22 +60,22 @@ sudo dnf install openssl-devel
brew install openssl
```
## Ctrl+C during build
## Ctrl+C во время сборки
DCR handles SIGINT: interrupts the current compilation and exits with non-zero code.
DCR корректно обрабатывает SIGINT: прерывает текущую компиляцию и завершает процесс с ненулевым кодом.
## How to create a library?
## Как создать библиотеку?
See [Library Recipe](/docs/recipes/library-project).
[Library Recipe](/docs/recipes/library-project).
## How to cross-compile to Windows?
See [Cross-Compile Recipe](/docs/recipes/cross-to-windows).
См. [Cross-Compile Recipe](/docs/recipes/cross-to-windows).
## How to create a multi-package project?
## Как сделать мультипакетный проект?
See [Workspace Recipe](/docs/recipes/multi-package-workspace).
См. [Workspace Recipe](/docs/recipes/multi-package-workspace).
## Lock file
## Lock-файл устарел
`dcr.lock` is created during builds (`dcr build`) when registry dependencies are present. To force an update — delete `dcr.lock` and run `dcr build`.
При изменении зависимостей `dcr.lock` автоматически обновляется при следующем `dcr add`. Если нужно принудительно обновить — удалите `dcr.lock` и выполните `dcr build`.

View File

@@ -1,17 +1,17 @@
---
sidebar_label: First steps
sidebar_label: Первые шаги
---
# First Steps
# Первые шаги
## Create a project
## Создать проект
```bash
dcr new my-app
cd my-app
```
Structure:
Будет создана структура:
```
my-app/
@@ -27,12 +27,17 @@ my-app/
name = "my-app"
version = "0.1.0"
type = "none"
description=""
author=""
license = "GPL-3.0-or-later"
[build]
language = "c"
standard = "c11"
compiler = "clang"
kind = "bin"
[dependencies]
```
## Build
@@ -43,20 +48,20 @@ dcr build
Output — `target/\<triple>/debug/my-app` (Linux) or `target/debug/my-app.exe` (Windows).
Build profiles:
Профиль:
```bash
dcr build --release # release build
dcr build --debug # debug (default)
dcr build --release # релизная сборка
dcr build --debug # дебажная (по умолчанию)
```
## Run
## Запустить
```bash
dcr run
```
Builds (if needed) and runs the binary.
Собирает (если нужно) и запускает бинарник.
## First test
@@ -65,8 +70,8 @@ dcr test --init # create test template
dcr test # run tests
```
## Formatting
## Форматирование
```bash
dcr fmt # clang-format with .clang-format
dcr fmt # clang-format по .clang-format
```

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Installation
sidebar_label: Установка
---
# Installation
# Установка
## Linux (Dexoron Packages)
Configure your package manager at https://pkg.dexoron.su and install:
Настройте менеджер пакетов на https://pkg.dexoron.su и установите:
**Arch Linux**
@@ -37,6 +37,8 @@ yay -S dcr
```sh
brew tap dexoron/dexoron
brew install dcr
# or
brew install dexoron/dexoron/dcr
```
## Snap (Linux)
@@ -62,13 +64,13 @@ cargo install dcr
## Linux / macOS (script)
```sh
curl -fsSL https://dcr.dexoron.su/install.sh | sh
curl -fsSL https://dcr.dexoron.su/install_bsd.sh | bash
```
## BSD (script)
```sh
curl -fsSL https://dcr.dexoron.su/install_bsd.sh | sh
curl -fsSL https://dcr.dexoron.su/install.sh | bash
```
## Windows (PowerShell)
@@ -90,7 +92,7 @@ ln -sf "$PWD/target/release/dcr" ~/.local/bin/dcr
Verify the installation:
```bash
dcr --version
dcr setup
```
Man pages are available after installation:
@@ -100,7 +102,7 @@ man dcr
man dcr-build
```
To use the registry, create `~/.dcr/config.toml`:
Команда создаёт `~/.dcr/` с дефолтным `config.toml` и скачивает публичный реестр.
```toml
[[registry]]

View File

@@ -1,8 +1,8 @@
---
sidebar_label: IDE Integration
sidebar_label: Интеграция с IDE
---
# IDE Integration
# Интеграция с IDE
## VS Code
@@ -10,14 +10,14 @@ sidebar_label: IDE Integration
dcr gen vscode
```
Generates in `.vscode/`:
Генерирует в `.vscode/`:
| File | Purpose |
| ----------------- | -------------------------------------------- |
| `tasks.json` | `build` task (dcr build) |
| `launch.json` | Debug launch configuration |
| `settings.json` | clangd/IntelliSense: include paths, standard |
| `extensions.json` | Recommends vscode-clangd, vscode-lldb |
| Файл | Назначение |
| ----------------- | ------------------------------------------- |
| `tasks.json` | Задача `build` (dcr build) |
| `launch.json` | Debug-запуск бинарника |
| `settings.json` | clangd/IntelliSense: include пути, стандарт |
| `extensions.json` | Рекомендует clangd, C/C++ |
## CLion
@@ -25,14 +25,14 @@ Generates in `.vscode/`:
dcr gen clion
```
Generates in `.idea/`:
Генерирует в `.idea/`:
| File | Purpose |
| ------------------------------------------------ | ----------------------------------------- |
| `externalTools.xml` | Build, Run, Clean, Test as external tools |
| `customTargets.xml` | Custom build targets |
| `misc.xml` | C/C++ project settings |
| `runConfigurations/\<name>.xml` | Per-binary run configurations |
| Файл | Назначение |
| ----------------------------------------- | ----------------------------------------------- |
| `externalTools.xml` | Build, Run, Clean, Test как внешние инструменты |
| `customTargets.xml` | Кастомные цели сборки |
| `misc.xml` | Настройки C/C++ проекта |
| `runConfigurations/dcr_build_and_run.xml` | Per-binary run configurations |
## compile_commands.json
@@ -40,7 +40,7 @@ Generates in `.idea/`:
dcr gen compile-commands
```
Generates `compile_commands.json` at project root. Standard format for clangd, C/C++ IntelliSense, static analyzers.
Генерирует `compile_commands.json` в корне проекта. Стандартный формат для:
## project-info
@@ -48,4 +48,4 @@ Generates `compile_commands.json` at project root. Standard format for clangd, C
dcr gen project-info
```
Outputs JSON array with project metadata (see [gen-commands](/docs/commands/gen-commands)).
Выводит JSON с метаданными проекта (см. [gen-commands](/docs/commands/gen-commands)).

View File

@@ -1,20 +1,20 @@
---
sidebar_label: License
sidebar_label: Лицензия
---
# License
# Лицензия
## DCR
DCR itself is [GPL-3.0-or-later](https://spdx.org/licenses/GPL-3.0-or-later.html) licensed.
DCR распространяется под лицензией [GPL-3.0-or-later](https://spdx.org/licenses/GPL-3.0-or-later.html).
> **Note:** DCR is a build tool, not a library. The GPL applies only to DCR's own source code. Projects built with DCR are not subject to DCR's license — their licensing is determined solely by their own code and dependencies.
> **Важно:** DCR — инструмент сборки, а не библиотека. GPL распространяется только на исходный код самого DCR. Проекты, собранные с помощью DCR, не подпадают под лицензию DCR — их лицензирование определяется исключительно их собственным кодом и зависимостями.
## Vendored libraries
## Вендорные библиотеки
DCR statically links the following C libraries through its vendored Rust dependencies:
DCR статически связывает следующие C-библиотеки через вендорные Rust-зависимости:
| Library | License | Bundled by |
| Библиотека | Лицензия | Bundled by |
| ------------------------------------------ | ------------------ | ----------------------------- |
| [libgit2](https://libgit2.org) | MIT OR Apache-2.0 | `git2` / `libgit2-sys` |
| [libssh2](https://libssh2.org) | MIT OR Apache-2.0 | `libgit2-sys` |
@@ -22,11 +22,11 @@ DCR statically links the following C libraries through its vendored Rust depende
| [OpenSSL](https://openssl.org) | Apache-2.0 | `openssl-sys` / `openssl-src` |
| [ring](https://github.com/briansmith/ring) | Apache-2.0 AND ISC | `rustls` |
## Rust dependencies
## Rust-зависимости
DCR is written in Rust. The following notable Rust crates are statically linked:
DCR написан на Rust. Ниже перечислены основные статически связываемые крейты:
| Crate | License |
| Крейт | Лицензия |
| --------------------------------------------- | ------------------------ |
| [`reqwest`](https://crates.io/crates/reqwest) | MIT OR Apache-2.0 |
| [`rustls`](https://crates.io/crates/rustls) | Apache-2.0 OR ISC OR MIT |
@@ -39,8 +39,8 @@ DCR is written in Rust. The following notable Rust crates are statically linked:
| [`hyper`](https://crates.io/crates/hyper) | MIT |
| [`ctrlc`](https://crates.io/crates/ctrlc) | MIT OR Apache-2.0 |
Full dependency tree (143 packages) is available in [`Cargo.lock`](https://github.com/dexoron/dcr/blob/main/Cargo.lock). The overwhelming majority are dual-licensed under MIT OR Apache-2.0.
Полное дерево зависимостей (143 пакета) доступно в [`Cargo.lock`](https://github.com/dexoron/dcr/blob/main/Cargo.lock). Подавляющее большинство имеют двойную лицензию MIT OR Apache-2.0.
## Additional credits
* DCR's CLI design and project model are inspired by [Cargo](https://doc.rust-lang.org/cargo/).
* Дизайн CLI и модель проектов DCR вдохновлены [Cargo](https://doc.rust-lang.org/cargo/).

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Cross-compile to Windows
sidebar_label: Кросс-компиляция для Windows
---
# Cross-Compile to Windows from Linux
# Кросс-компиляция для Windows на Linux
Building a Windows binary on Linux using mingw-w64.
Сборка Windows-бинаря на Linux с использованием mingw-w64.
## Install toolchain
## Установка toolchain
```bash
# Ubuntu/Debian
@@ -16,31 +16,29 @@ sudo apt install mingw-w64
sudo dnf install mingw64-gcc mingw64-binutils
```
## Configuration
## Конфигурация
```toml
[package]
name = "my-app"
version = "0.1.0"
type = "none"
type = "app"
[build]
language = "c"
standard = "c11"
compiler = "clang"
kind = "bin"
target = "x86_64-pc-windows-gnu" # explicit mingw, not msvc
standard = "c17"
target = "windows"
```
## Build
## Сборка
```bash
dcr build --target x86_64-pc-windows-gnu --release
dcr build --target windows --release
```
Artifact: `target/x86_64-pc-windows-gnu/release/my-app.exe`.
Артефакт: `target/x86_64-pc-windows-gnu/release/my-app.exe`.
## Custom toolchain
## Кастомный toolchain (опционально)
```toml
[toolchain]

View File

@@ -1,16 +1,15 @@
---
sidebar_label: Library project
sidebar_label: Проект библиотеки
---
# Library Project
# Проект библиотеки
Creating a static library and using it in another project.
Создание статической библиотеки и её использование в другом проекте.
## Step 1: Create the library
## Шаг 1: Создать библиотеку
```bash
dcr new my-lib
cd my-lib
```
`dcr.toml`:
@@ -19,11 +18,11 @@ cd my-lib
[package]
name = "my-lib"
version = "0.1.0"
type = "none"
type = "lib"
[build]
language = "c"
standard = "c11"
standard = "c17"
kind = "staticlib"
```
@@ -43,28 +42,29 @@ int add(int a, int b);
int add(int a, int b) { return a + b; }
```
## Step 2: Build
## Шаг 2: Собрать
```bash
cd my-lib
dcr build --release
```
Artifacts:
Артефакты:
* `target/\<triple>/release/libmy-lib.a` (Linux)
* `target/release/libmy-lib.a` (Linux/macOS)
* `target/release/my-lib.lib` (Windows)
* `target/include/` — header files
* `target/include/` — заголовочные файлы
## Step 3: Use in another project
## Шаг 3: Использовать в проекте
```bash
dcr new my-app
cd my-app
dcr add my-lib ../my-lib
dcr add ../my-lib
```
Automatically:
Автоматически:
* Adds include path to `target/include/` of the library
* Adds lib path to `target/\<triple>/release/`
* Links `libmy-lib.a` / `my-lib.lib`
* Добавляется include path на `target/include/` библиотеки
* Добавляется lib path на `target/release/`
* Линкуется `libmy-lib.a` / `my-lib.lib`

View File

@@ -1,19 +1,19 @@
---
sidebar_label: Multi-package workspace
sidebar_label: Рабочая область с несколькими пакетами
---
# Multi-Package Workspace
# Рабочая область с несколькими пакетами
A project with three packages: two libraries and a binary.
Проект из трёх пакетов: библиотека, утилита и основной бинарник.
## Structure
## Структура
```
workspace/
├── dcr.toml # root workspace
├── dcr.toml # корневой workspace
├── lib-core/
│ ├── dcr.toml
│ └── src/core.c
│ └── src/lib.rs
├── lib-utils/
│ ├── dcr.toml
│ └── src/utils.c
@@ -22,7 +22,7 @@ workspace/
└── src/main.c
```
## Root dcr.toml
## Корневой dcr.toml
```toml
[package]
@@ -33,22 +33,17 @@ type = "none"
[build]
inherit = true
language = "c"
standard = "c11"
standard = "c17"
[workspace.lib-core]
path = "lib-core"
[workspace.lib-utils]
path = "lib-utils"
deps = ["lib-core"]
[workspace.app]
path = "app"
deps = ["lib-core", "lib-utils"]
main = true
[workspace]
members = [
{ path = "lib-core" },
{ path = "lib-utils", deps = ["lib-core"] },
{ path = "app", deps = ["lib-core", "lib-utils"], main = true },
]
```
## Packages
## Пакеты
`lib-core/dcr.toml`:
@@ -56,7 +51,7 @@ main = true
[package]
name = "lib-core"
version = "0.1.0"
type = "none"
type = "lib"
[build]
kind = "staticlib"
@@ -68,7 +63,7 @@ kind = "staticlib"
[package]
name = "lib-utils"
version = "0.1.0"
type = "none"
type = "lib"
[build]
kind = "staticlib"
@@ -80,23 +75,23 @@ kind = "staticlib"
[package]
name = "app"
version = "0.1.0"
type = "none"
type = "app"
[build]
kind = "bin"
```
## Build
## Сборка
```bash
cd workspace
dcr build # builds everything in correct order
dcr build --workspace app # only app (lib-core and lib-utils built as deps)
dcr run # builds and runs main package
dcr build # собирает всё в правильном порядке
dcr build --workspace app # только app (lib-core и lib-utils собираются как зависимости)
dcr run # собирает и запускает main-пакет
```
Build order (topological sort):
Порядок сборки (топологическая сортировка):
1. `lib-core`
2. `lib-utils` (depends on lib-core)
3. `app` (depends on lib-core, lib-utils)
2. `lib-utils` (зависит от lib-core)
3. `app` (зависит от lib-core, lib-utils)

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Build profiles
sidebar_label: dcr build --profile lto
---
# Build Profiles
# Встроенные профили
Profiles allow overriding `[build]` fields for specific build modes.
Профили позволяют переопределять любые поля секции `[build]` для конкретного режима сборки.
## Configuration
## Конфигурация
```toml
[build]
@@ -18,31 +18,31 @@ cflags = ["-Wall"]
cflags = ["-O0", "-g"]
[build.release]
cflags = ["-O3", "-DNDEBUG"]
cflags = ["-O3", "-flto"]
```
## Merge rules
## Правила
Fields from `[build.\<profile>]` are merged on top of `[build]`:
Поля из `[build.\<profile>]` **мержатся поверх** `[build]`
* **Scalar fields** (strings, numbers, bools) — replaced
* **Arrays** (`cflags`, `ldflags`, ...) — **appended** (extend the `[build]` array)
* Массивы (`cflags`, `ldflags`, ...) **заменяются полностью**, а не дополняются
Set `inherit = false` to disable array inheritance (only profile's own arrays are used).
## Built-in profiles
## Кастомные профили
The default flags for each profile are composed from three config fields:
| Field | debug default | release default |
| ----------- | ------------------ | --------------- |
| `opt_level` | `"0"` | `"3"` |
| Field | Default cflags | Профили сборки |
| ----------- | ------------------ | -------------- |
| `opt_level` | `-O0 -g` | `"3"` |
| `debug` | `true` | `false` |
| `warnings` | `["all", "extra"]` | `[]` |
Which produce the equivalent compiler flags:
| Profile | Effective flags |
| Профиль | Effective flags |
| --------- | ---------------------------------------------------------- |
| `debug` | `-O0 -g -Wall -Wextra -fno-omit-frame-pointer -DDCR_DEBUG` |
| `release` | `-O3 -DNDEBUG` |
@@ -63,7 +63,7 @@ debug = false
warnings = ["all", "error"]
```
## Target-specific profiles
## Target-specific профили
```toml
[build.linux]
@@ -77,6 +77,6 @@ Application order (highest priority first):
1. `[build.\<target>.\<profile>]`
2. `[build.\<profile>.\<target>]`
3. `[build.\<target>]`
4. `[build.\<profile>]`
3. ]`или`[build.\<target>]\`
4. `[build.\<profile>]`.
5. `[build]`

View File

@@ -1,19 +1,19 @@
---
sidebar_label: Build system
sidebar_label: Система сборки
---
# Build System
## Compiler Backends
DCR supports 7 compilation backends. Selection is automatic based on file extension and `build.compiler` value.
DCR поддерживает 4 бэкенда компиляции. Выбор происходит автоматически на основе расширения файла и target triple.
| Backend | Files | When used |
| --------- | --------------------------------- | ------------------------------------- |
| `unix_cc` | `.c`, `.cpp`, `.cxx`, `.cc`, `.S` | gcc/clang on Linux/macOS/BSD |
| Backend | Файлы | Когда используется |
| --------- | --------------------------------------- | ------------------------------- |
| `unix_cc` | `.c`, `.cpp`, `.cxx`, `.cc`, `.s`, `.S` | gcc/clang на Linux/macOS/BSD |
| `msvc` | `.c`, `.cpp`, `.cxx`, `.cc` | Windows (cl, clang-cl) |
| `gas` | `.s` | ARM/ARM64 assembler (no preprocessor) |
| `nasm` | `.asm`, `.s` | x86/x86_64 NASM assembler |
| `gas` | `.s`, `.S` | ARM/ARM64 ассемблер |
| `nasm` | `.asm`, `.s` | x86/x86_64 ассемблер |
| `masm` | `.asm` | MASM (ml/ml64) on Windows |
| `fasm` | `.asm`, `.fasm` | Flat Assembler |
| `llvm_ir` | `.ll` | LLVM IR via `llc -filetype=obj` |
@@ -40,9 +40,9 @@ moc = "moc {in} -o {out}"
### Unix CC
* Compiler resolved via `resolve_compiler()`: `DCR_COMPILER` > `DCR_CC` > `[toolchain]` > `build.compiler` > `PATH`
* Supports `.d` files for header dependency tracking
* Flags: `-std=`, `-MMD -MF`, `-c -o`, `-I`, `-L`, `-l`
* Компилятор определяется через `resolve_compiler()`: CC/CXX из [toolchain], DCR_COMPILER/env, PATH
* Поддерживает генерацию `.d` файлов для header dependency tracking
* Флаги: `-std=`, `-MMD -MF`, `-c -o`, `-I`, `-L`, `-l`
* Conditional flags based on config:
* `freestanding` or bare-metal target: `-ffreestanding` (compile), `-nostdlib -static` (link)
* `lto`: `-flto` (compile + link)
@@ -50,54 +50,54 @@ moc = "moc {in} -o {out}"
### MSVC
* Supports cl.exe and clang-cl.exe
* Flags: `/std:`, `/Fo:`, `/Fe:`, `/I`, `/link`
* Поддерживает cl.exe и clang-cl.exe
* Флаги: `/std:`, `/Fo:`, `/Fe:`, `/I`, `/link`
### GAS / NASM / MASM / FASM / LLVM-IR
### GAS / NASM
* GAS: `-I`, `-c -o`, `--defsym`
* NASM: `-I`, `-o`, `-D`, `-f` (format: win64/elf64/macho64/macho32/elf32)
* NASM: `-I`, `-c -o`, `-D`, `-f` (формат: win64/elf64/macho64/macho32/elf32)
* MASM: `/nologo /c /Fo\<obj> <source>`
* FASM: `<source> \<output>` (output path is the object file)
* LLVM IR: `-filetype=obj <source> -o \<output>`
## Incremental Builds
Three levels of incrementality:
Три уровня инкрементальности:
1. **mtime** — if output is newer than all inputs, skip
2. **`.d` files** — header change tracking (including transitive)
3. **SHA256 fingerprint** — recompile if compiler flags changed (stored in `.dcr_fingerprint`)
1. **mtime** — если выходной файл новее всех входных, файл не перекомпилируется
2. **`.d` files** — отслеживание изменений в заголовочных файлах (включая транзитивные)
3. **SHA256 fingerprint** — если флаги компиляции изменились, файл перекомпилируется (fingerprint хранится в `.dcr_fingerprint`)
## Parallel Compilation
* `thread::scope` for thread pool
* Atomic task queue (`AtomicU64`)
* Mutex on stdout (`OUTPUT_MUTEX`)
* Используется `thread::scope` для создания пула потоков
* Атомарная очередь задач (`AtomicU64`)
* Мьютекс на запись в stdout (`OUTPUT_MUTEX`)
* Thread count = `available_parallelism()`, capped by `build.codegen-units` if set
## Build Kinds
| Kind | Type | Path (Linux example) |
| ----------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `bin` | Executable | `target/\<triple>/\<profile>/\<name>` (.exe on Windows) |
| `staticlib` | Static library | `target/\<triple>/\<profile>/lib\<name>.a` (.lib) |
| `sharedlib` | Dynamic library | `target/\<triple>/\<profile>/lib\<name>.so` (.dll/.dylib) |
| `efi` | UEFI application | `target/\<triple>/\<profile>/\<name>.efi` |
| `elf` | ELF without stdlib | `target/\<triple>/\<profile>/\<name>` |
| Kind | Тип | Path (Linux example) |
| ----------- | ------------------------------------ | ----------------------------------------------------------------------------------------------- |
| `bin` | Executable | `target/\<profile>/\<name>` (.exe) |
| `staticlib` | Статическая библиотека | `target/\<profile>/lib\<name>.a` (.lib) |
| `sharedlib` | Динамическая библиотека | `target/\<profile>/lib\<name>.so` (.dll/.dylib) |
| `efi` | UEFI приложение | `target/\<profile>/\<name>.efi` |
| `elf` | ELF без стандартной библиотеки | `target/\<profile>/\<name>` |
| `none` | Compile only, no link | — |
| `custom` | Full filename+extension control | `target/\<triple>/\<profile>/\<filename>.\<extension>` |
| `custom` | Полный контроль filename + extension | `target/\<profile>/\<filename>.\<extension>` |
## Build Steps
DCR supports pre-build and post-build steps:
DCR поддерживает pre-build и post-build шаги через Qt codegen:
* `build.steps` — commands before compilation
* `build.post_steps` — commands after compilation
Substitutions: `{stem}`, `{in}`, `{out}`, `{profile}`, `{version}`, `{name}`.
Подстановки: `{stem}`, `{in}`, `{out}`.
Example Qt codegen via build steps:
`rcc` — Resource Compiler: `{stem}.qrc → qrc_{stem}.cpp`
```toml
[build.steps]
@@ -113,19 +113,19 @@ Automatic lookup (read from raw config):
pkg_config = ["sdl2", "gl"]
```
DCR runs `pkg-config --cflags sdl2 gl` and `pkg-config --libs sdl2 gl` and adds results to compiler/linker flags.
DCR вызывает `pkg-config --cflags sdl2 gl` и `pkg-config --libs sdl2 gl` и добавляет результат в флаги компиляции/линковки.
## Variable Substitution
Supported variables:
| Variable | Description |
| ----------------------- | ---------------------------- |
| `{version}` | Package version |
| Variable | Описание |
| ----------------------- | ------------------------------- |
| `{version}` | Версия пакета |
| `{version_major}` | Major version part |
| `{version_minor}` | Minor version part |
| `{version_patch}` | Patch version |
| `{version_patch}` | Переменная |
| `{version_suffix}` | Suffix (e.g., `-rc1`) |
| `{version_suffix_dash}` | Suffix with dash |
| `{profile}` | Profile name (debug/release) |
| `{name}` | Package name |
| `{profile}` | Имя профиля (debug/release/...) |
| `{name}` | Имя пакета |

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Cross-compilation
sidebar_label: Кросс-компиляция
---
# Cross-Compilation
# Кросс-компиляция
## Short Names
DCR supports short platform names:
DCR поддерживает короткие имена платформ, которые автоматически раскрываются в полные triples:
| Short Name | Full Triple |
| ---------- | -------------------------- |
@@ -22,26 +22,26 @@ dcr build --target windows
```bash
dcr build --target aarch64-unknown-linux-gnu
dcr build --target x86_64-pc-windows-gnu # mingw
dcr build --target x86_64-pc-windows-gnu
dcr build --target armv7-unknown-linux-gnueabihf
```
## clang --target
When using clang, DCR injects `--target=\<triple>` into CFLAGS.
При использовании clang DCR автоматически inject-ит `--target=\<triple>` в CFLAGS/CXXFLAGS.
```toml
[build]
compiler = "clang"
target = "aarch64-unknown-linux-gnu"
# Auto: cflags += ["--target=aarch64-unknown-linux-gnu"]
# Авто: cflags = ["--target=aarch64-unknown-linux-gnu"]
```
## Bare-Metal / Freestanding
## Bare-Metal
For targets containing `none`, `-elf`, `eabi`, or `baremetal`, DCR automatically:
1. **Disables default flags** — no system include paths, no `-l` libc
1. Для none/elf/eabi/bare-metal target-ов отключаются DCR default флаги (нет `-I` системных путей, нет `-l` libc).
2. **Injects `-ffreestanding`** at compile time and `-nostdlib -static` at link time
You can also enable freestanding mode explicitly:

View File

@@ -1,49 +1,50 @@
---
sidebar_label: dcr.toml overview
sidebar_label: Обзор dcr.toml
---
# dcr.toml
# Обзор dcr.toml
Main project configuration file. Located at the project root.
Основной конфигурационный файл проекта. Располагается в корне проекта.
## Structure
## Структура
```toml
[package]
# required fields
# обязательные поля
[build]
# build settings
# настройки сборки
[build.debug] # optional: debug override
[build.release] # optional: release override
[build.debug] # опционально: переопределение для debug
[build.release] # опционально: переопределение для release
[build.linux] # optional: Linux override
[build.windows] # optional: Windows override
[build.windows.debug] # target + profile combination
[build.linux] # опционально: переопределение для Linux
[build.windows] # опционально: переопределение для Windows
[build.windows.debug] # комбинация target + profile
[toolchain]
# compiler/linker paths
# пути к компиляторам/линкеру
[dependencies]
# project dependencies
# зависимости проекта
[workspace]
# multi-package configuration
# мультипакетная конфигурация
[run]
# run settings
[run.release] # опционально: переопределение для release
# настройки запуска
```
## [package]
| Field | Required | Description |
| --------- | -------- | ----------------------- |
| `name` | yes | Project name |
| `version` | yes | Semantic version |
| `type` | yes | `app`, `lib`, `none` |
| `license` | no | SPDX license identifier |
| `author` | no | Author |
| Поле | Обязательное | Описание |
| --------- | ------------ | --------------------------- |
| `name` | да | Имя проекта |
| `version` | да | Семантическая версия |
| `type` | да | `app`, `lib`, `none` |
| `license` | нет | SPDX-идентификатор лицензии |
| `author` | нет | Автор |
```toml
[package]
@@ -60,58 +61,55 @@ author = "John Doe"
* `build.qt` — (bool) Enable automatic Qt meta-object handling (MOC, UIC, RCC). Requires `qt6` modules installed via `pkg-config`.
| Field | Default | Description |
| Поле | По умолчанию | Описание |
| ---------------- | ------------------------------------------- | --------------------------------------------------------------------- |
| `language` | `"c"` | `"c"`, `"c++"`, `"cpp"`, `"cxx"`, `"asm"` |
| `standard` | `"c11"` | C standard (`c11`, `c17`, `c23`) |
| `cxx_standard` | `"c++20"` | C++ standard (`c++17`, `c++20`, `c++23`) |
| `compiler` | `"clang"` | Preferred compiler |
| `language` | `"c"` | `"c"`, `"cxx"`, `"cpp"` |
| `standard` | `"c11"` | Стандарт C (`c11`, `c17`, `c23`) |
| `cxx_standard` | `"c++20"` | Стандарт C++ (`c++17`, `c++20`, `c++23`) |
| `compiler` | `cxxflags` | Предпочитаемый компилятор |
| `kind` | `"bin"` | `bin`, `staticlib`, `sharedlib`, `efi`, `elf`, `none`, `custom` |
| `target` | host | Target triple for cross-compilation |
| `platform` | `"native"` | `native`, `efi` |
| `cflags` | `[]` | Additional C/C++/ASM flags |
| `ldflags` | `[]` | Additional linker flags |
| `filename` | `""` | Custom output file name |
| `target` | хост | Target triple для кросс-компиляции |
| `platform` | `"native"` | `native`, `efi`, `freestanding` |
| `cflags` | `[]` | Дополнительные флаги C++ |
| `ldflags` | `[]` | Дополнительные флаги линковки |
| `filename` | `""` | Кастомное имя выходного файла |
| `extension` | `""` | Custom file extension |
| `roots` | `["src"]` | Source root directories |
| `exclude` | `[]` | Exclude patterns |
| `include` | `[]` | Additional include directories |
| `roots` | `["src"]` | Корневые директории с исходниками |
| `exclude` | `[]` | Паттерны исключений |
| `include` | `[]` | Дополнительные include-директории |
| `src_disable` | `false` | Disable auto source discovery |
| `inherit` | `false` | Inherit build from workspace root |
| `inherit` | `false` | Наследовать build от корня workspace |
| `clean` | `[]` | Glob patterns for custom clean paths |
| `out_dir` | `""` | Custom output directory |
| `workspace_only` | `false` | Workspace-only, not built standalone |
| `workspace_only` | `false` | Только для workspace, не собирать отдельно |
| `freestanding` | `false` | Compile in freestanding mode (`-ffreestanding` + `-nostdlib -static`) |
| `opt_level` | `"0"` (debug) / `"3"` (release) | Optimization level: `0`-`3`, `"s"`, `"z"` |
| `debug` | `true` (debug) / `false` (release) | Emit debug symbols (`-g`) |
| `ldscript` | `true` (debug) / `false` (release) | Emit debug symbols (`-g`) |
| `lto` | `false` | Link-time optimization (`-flto` for both compiler and linker) |
| `strip` | `false` | Strip symbols from output (`-s` in ldflags) |
| `warnings` | `["all", "extra"]` (debug) / `[]` (release) | Warning flags (e.g. `"all"`, `"extra"`, `"pedantic"`) |
| `asflags` | `false` | Strip symbols from output (`-s` in ldflags) |
| `true` | `["all", "extra"]` (debug) / `[]` (release) | Warning flags (e.g. `"all"`, `"extra"`, `"pedantic"`) |
| `panic` | `""` | Panic strategy: `"abort"` disables exceptions and unwind tables |
| `codegen-units` | `""` | Max parallel compilation jobs (`"0"` = auto) |
| `qt` | `false` | Enable automatic Qt meta-object handling (MOC, UIC, RCC) |
Settings from raw config (not in typed struct):
* `pkg_config` — list of pkg-config packages
* `ldscript` — linker script path
* Пакеты для pkg-config
* Путь к linker script
* `build.steps` / `build.post_steps` — codegen steps
Example:
```toml
[build]
language = "c++"
language = ["cpp", "c"]
standard = "c17"
standard = "c23"
cxx_standard = "c++23"
compiler = "clang"
kind = "sharedlib"
cflags = ["-Wall", "-Wextra"]
opt_level = "z"
lto = true
strip = true
panic = "abort"
codegen-units = "2"
pkg_config = ["sdl2", "gl"]
```
## [toolchain]
@@ -123,13 +121,16 @@ cxx = "/usr/bin/clang++"
as = "/usr/bin/as"
ar = "/usr/bin/ar"
ld = "/usr/bin/ld.lld"
uic = "/usr/bin/uic" # Qt
moc = "/usr/bin/moc" # Qt
rcc = "/usr/bin/rcc" # Qt
```
Raw config also supports `uic`, `moc`, `rcc` for Qt codegen.
## [dependencies]
See [dependencies](/docs/reference/dependencies).
См. [dependencies](/docs/reference/dependencies).
## [run]
@@ -138,15 +139,15 @@ See [dependencies](/docs/reference/dependencies).
cmd = "./target/{profile}/{name}"
```
Substitutions:
Подстановки:
* `{version}` — package version
* `{version_major}`, `{version_minor}`, `{version_patch}`, `{version_suffix}`, `{version_suffix_dash}` — version parts
* `{version}` — версия из [package]
* `pkg_config`
* `{profile}` — debug / release
* `{name}` — package name
* `{name}` — имя из [package]
Default `cmd` = `./target/{profile}/{name}` (macOS/Windows) or `./target/\<triple>/\<profile>/\<name>` (Linux).
По умолчанию `cmd` вычисляется как `./target/{profile}/{name}`.
## [workspace]
See [workspaces](/docs/reference/workspaces).
См. [workspaces](/docs/reference/workspaces).

View File

@@ -1,34 +1,34 @@
---
sidebar_label: Dependencies
sidebar_label: Зависимости
---
# Dependencies
# Зависимости
## Formats
## Форматы
The `[dependencies]` section supports three formats:
В секции `[dependencies]` поддерживаются три формата:
### String (registry)
```toml
[dependencies]
fmt = "10.1.1"
spdlog = "1.12"
catch2 = "3.4.0"
spdlog = "^1.12"
catch2 = ">=3.0,<4.0"
```
The version string is used as-is for registry lookup.
### Table (git)
### Табличный (git)
```toml
[dependencies]
fmt = { git = "https://github.com/fmtlib/fmt", tag = "10.1.1" }
```
Fields: `git`, `branch`, `tag`, `rev`.
Поля: `git`, `branch`, `tag`, `rev`, `features`.
### Table (path)
### Табличный (path)
```toml
[dependencies]
@@ -37,7 +37,11 @@ mylib = { path = "../mylib" }
## Registry
DCR uses a package registry for dependency lookup by name.
## RegistryDCR использует реестр пакетов для поиска зависимостей по имени.```toml
# ~/.dcr/config.toml
[registry]
main = { url = "https://github.com/dcr-ports/dcr-index", priority = 1 }
```
```toml
# ~/.dcr/config.toml
@@ -46,22 +50,22 @@ name = "default"
url = "https://index.dcr.pm"
```
Registry priority: order in `config.toml`. The `DCR_INDEX_PATH` variable overrides the path to `index.json`.
Registry priority: order in `config.toml`. Переменная `DCR_INDEX_PATH` переопределяет путь к index.json.
## Git dependencies
## Git-зависимости
DCR clones git repositories via `git2`:
При добавлении git-зависимости DCR клонирует репозиторий через `git2`:
* `branch` — switch to a branch
* `tag` — switch to a tag
* `rev` — switch to a specific commit
* `branch` — переключиться на ветку
* `tag` — переключиться на тег
* `rev` — переключиться на конкретный коммит
* `features` — feature flags (parsed, but does not affect build)
Cache path: `~/.dcr/git/\<hash>/`.
## Path dependencies
## Path-зависимости
Local paths. DCR automatically discovers include and lib directories from the neighbor's `dcr.toml`.
Локальные пути. DCR автоматически находит include и lib директории.
```toml
[dependencies]
@@ -71,14 +75,14 @@ mylib = { path = "../relative/path" }
## dcr.lock
Dependency lock file. Contains package names and sources.
Файл блокировки зависимостей. Содержит точные версии, хеши и источники.
Created during `dcr build` when registry dependencies are present. Not updated during `dcr add` — only on the next `dcr build`.
Created during `dcr build` when registry dependencies are present. Автоматически обновляется при `dcr add`.
## Resolution process
## Процесс резолва
1. Load all dependencies (registry → git → path)
1. Загружаются все зависимости (registry → git → path)
2. For path deps: recursively read their `dcr.toml`
3. For registry deps: search `index.json`
4. For git deps: clone to cache
5. Collect `include_dirs`, `lib_dirs`, `libs` for the compiler
5. Собираются include_dirs, lib_dirs, libs для передачи компилятору

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Environment variables
sidebar_label: Переменные среды
---
# Environment Variables
# Переменные среды
## DCR_COMPILER
Overrides the compiler for all languages. **Highest priority.**
Переопределяет компилятор для всех языков. **Highest priority.**
```bash
export DCR_COMPILER=clang
@@ -23,7 +23,7 @@ Compiler resolution priority:
## DCR_CC / DCR_CXX / DCR_AS
Per-language override (lower priority than `DCR_COMPILER`, higher than `[toolchain]`).
Приоритет: `[toolchain]` > `DCR_COMPILER` > `DCR_CC` > `PATH`.
```bash
export DCR_CC=gcc-14
@@ -42,7 +42,7 @@ export DCR_AR=llvm-ar
## DCR_DEBUG
Enables debug mode — prints all compilation commands to stderr before execution.
Включает режим отладки — печатает все команды компиляции перед выполнением.
```bash
export DCR_DEBUG=1
@@ -51,10 +51,10 @@ dcr build
## DCR_INDEX_PATH
Overrides the path to the registry `index.json`.
Переопределяет путь к index.json реестра.
```bash
export DCR_INDEX_PATH=/custom/path/index.json
```
Default: `~/.dcr/index.json`.
По умолчанию: `~/.dcr/index.json`.

View File

@@ -1,12 +1,12 @@
---
sidebar_label: Platform support
sidebar_label: Поддержка платформ
---
# Platform Support
# Поддержка платформ
## Target Triples
DCR normalizes target triples. Short platform names are expanded to full triples.
DCR нормализует target triple через `platform_triple::normalize_triple()`. Если задано имя платформы (short name), оно раскрывается в triple.
### Linux
@@ -14,9 +14,9 @@ DCR normalizes target triples. Short platform names are expanded to full triples
target/<arch>-unknown-linux-gnu/<profile>/
```
Architectures: `x86_64`, `aarch64` (host-detected).
Поддержка архитектур: `x86_64`, `aarch64`.
Artifact type: ELF. Extensions: `.so` (sharedlib), `.a` (staticlib).
Artifact type: ELF. Расширения: `.so` для sharedlib, `.a` для staticlib
### macOS
@@ -24,9 +24,9 @@ Artifact type: ELF. Extensions: `.so` (sharedlib), `.a` (staticlib).
target/<profile>/
```
Architectures: `x86_64`, `aarch64` (host-detected).
Поддержка архитектур: `x86_64`, `aarch64`.
Extensions: `.dylib` (sharedlib), `.a` (staticlib).
`.dylib` для sharedlib, `.a` для staticlib
### Windows
@@ -34,7 +34,7 @@ Extensions: `.dylib` (sharedlib), `.a` (staticlib).
target/<profile>/
```
Architectures: `x86_64`, `aarch64`.
Поддержка архитектур: `x86_64`, `aarch64`.
Extensions: `.exe` (bin), `.lib` (staticlib), `.dll` (sharedlib), `.efi` (UEFI).
@@ -44,8 +44,8 @@ Extensions: `.exe` (bin), `.lib` (staticlib), `.dll` (sharedlib), `.efi` (UEFI).
target/<arch>-unknown-<os>/<profile>/
```
Supported systems: `freebsd`, `openbsd`, `netbsd`, `dragonfly`.
Поддерживаемые системы: `freebsd`, `openbsd`, `netbsd`.
## Host Detection
## Определение хоста
DCR uses `std::env::consts::ARCH` and `std::env::consts::OS` for host platform detection. Used as fallback when `target` is not specified.
`platform_triple::host_triple()` возвращает тройку текущей системы. Используется как fallback, если `target` не указан.

View File

@@ -1,67 +1,59 @@
---
sidebar_label: Workspaces
sidebar_label: Рабочие пространства
---
# Workspaces
# Рабочие пространства
Workspaces allow managing multiple packages in a single repository.
Workspaces позволяют управлять несколькими пакетами в одном репозитории.
## Configuration
## Конфигурация
```toml
[workspace.lib-core]
path = "lib-core"
[workspace.lib-utils]
path = "lib-utils"
deps = ["lib-core"]
[workspace.app]
path = "app"
deps = ["lib-core", "lib-utils"]
main = true
[workspace]
members = [
{ path = "pkg-a" },
{ path = "pkg-b", deps = ["pkg-a"] },
{ path = "pkg-c", deps = ["pkg-a", "pkg-b"], main = true },
]
```
### Member fields
### Поля member
| Field | Description |
| ------ | ------------------------------------------------ |
| `path` | Path to the package (relative to workspace root) |
| `deps` | Dependencies on other members |
| `main` | Mark as the main package |
| Поле | Описание |
| ------ | -------------------------------------------- |
| `path` | Путь к пакету (относительно корня workspace) |
| `deps` | Зависимости от других member-ов |
| `main` | Пометить как главный пакет |
## Topological sort
## Топологическая сортировка
DCR automatically sorts packages by dependencies: package A is built before B if B depends on A.
DCR автоматически сортирует пакеты по зависимостям: пакет A собирается раньше B, если B зависит от A.
Cyclic dependencies are detected and cause an error.
Циклические зависимости обнаруживаются и приводят к ошибке.
## Build
## Сборка
```bash
dcr build # build all packages in dependency order
dcr build --workspace app # build only app (dependencies built automatically)
dcr build # собрать все пакеты
dcr build --workspace pkg-a # собрать только pkg-a
```
When building a workspace, member outputs (libraries) are automatically added to include/lib paths of dependent packages.
При сборке workspace выходные файлы member-ов (библиотеки) автоматически добавляются в include/lib пути зависимых пакетов.
## Clean
## Очистка
```bash
dcr clean # clean only root target/
dcr clean --all # clean target/ of all packages
dcr clean # очистить только корневой target/
dcr clean --all # очистить target/ всех пакетов
```
## Inheritance
## Наследование
If a member has `inherit = true` in its `[build]` section, fields from the root `[build]` are merged into the member:
Если у member-а нет своей секции `[build]`, а в корневом `[build]` указано `inherit = true`:
```toml
# root dcr.toml
[build]
inherit = true
language = "c"
standard = "c17"
# member inherits language and standard
```

View File

@@ -1,46 +1,46 @@
---
sidebar_label: Self Update
sidebar_label: Автоматическое обновление
---
# Self Update
# Автоматическое обновление
## dcr --update
Automatic update to the latest version. Downloads a binary (not an archive) from GitHub Releases and replaces the current executable.
Автоматическое обновление до последней версии. Downloads a binary (not an archive) from GitHub Releases and replaces the current executable.
```bash
dcr --update
```
## How it works
## Как это работает
1. DCR detects the current platform and architecture
1. DCR определяет текущую платформу и архитектуру
2. Fetches the latest release from `api.github.com/repos/dexoron/dcr/releases/latest`
3. Compares versions
4. Downloads the matching asset (direct binary URL, not archive)
5. Replaces the current executable via `self_replace`
5. Заменяет текущий исполняемый файл
## Asset naming
Pattern: `dcr-\<triple>` or `dcr-\<triple>.exe`
Шаблон: `dcr-\<triple>.\<ext> `
| Platform | Asset name |
| -------------- | -------------------------------- |
| Linux x86_64 | `dcr-x86_64-unknown-linux-gnu` |
| macOS x86_64 | `dcr-x86_64-apple-darwin` |
| macOS ARM64 | `dcr-aarch64-apple-darwin` |
| Windows x86_64 | `dcr-x86_64-pc-windows-msvc.exe` |
| Платформа | Asset name |
| -------------- | ------------------------------------- |
| Linux x86_64 | `dcr-x86_64-unknown-linux-gnu.tar.gz` |
| macOS x86_64 | `dcr-x86_64-apple-darwin.tar.gz` |
| macOS ARM64 | `dcr-aarch64-apple-darwin.tar.gz` |
| Windows x86_64 | `dcr-x86_64-pc-windows-msvc.zip` |
## AUR
If DCR was installed via AUR, `--update` shows a warning:
Если DCR установлен через AUR, `--update` выводит предупреждение:
```
Update via package manager: yay/paru -Syu {package_name} or sudo pacman -Syu {package_name}
```
## Errors
## Ошибки
* Cannot detect platform — error
* Cannot fetch release — error with URL
* No write permission — error (use `sudo` or manual install)
* Не удалось определить платформу — ошибка
* Не удалось скачать релиз — ошибка с URL
* Нет прав на запись бинарника — ошибка (нужен `sudo` или ручная установка)

View File

@@ -1,8 +1,8 @@
---
sidebar_label: Running tests
sidebar_label: Запуск тестов
---
# Running Tests
# Запуск тестов
## Execution
@@ -15,12 +15,12 @@ Builds the project, then compiles and runs test files from `tests/`.
## Profiles
```bash
dcr test # debug (default)
dcr test # debug (по умолчанию)
dcr test --release # release
dcr test --debug # explicit debug
dcr test --debug # явно debug
```
## Output
## Вывод
```
=====================
@@ -33,13 +33,13 @@ FAIL: 1
=====================
```
## Exit code
## Код возврата
* 0 — all tests passed (FAIL = 0)
* 1 — test failures or build error
* 0 — все тесты пройдены (FAIL = 0)
* 1 — есть упавшие тесты
## What gets built
* All `.c` files from `tests/` (`.cpp` not supported)
* Include path: `tests/` (for `dcr_test.h`)
* Linked with project if `package.type = "lib"` or `kind = "staticlib"`/`"sharedlib"`
* Все C/C++ файлы из `tests/`
* Include path: `tests/` (для `dcr_test.h`)
* Линкуется с основным проектом (если `type = "lib"`)

View File

@@ -1,33 +1,33 @@
---
sidebar_label: Test framework (EXPECT, TEST, ...)
sidebar_label: Тестовая инфраструктура (EXPECT, TEST, ...)
---
# Test Framework
# Тестовая инфраструктура
DCR has a built-in minimal test framework for C.
DCR имеет встроенный минималистичный фреймворк для тестирования на C/C++.
## Macros
## Макросы
### `EXPECT(expr)`
### `EXPECT(expr, ...)`
Asserts that an expression is true.
Проверяет, что выражение истинно.
```c
EXPECT(1 + 1 == 2);
EXPECT(ptr != NULL);
EXPECT(ptr != NULL, "ptr should not be NULL");
```
### `SKIP(reason)`
### `SKIP(...)`
Skips a test with a message.
Пропускает тест с опциональным сообщением.
```c
SKIP("not implemented on Windows");
SKIP("not implemented on Windows yet");
```
### `TEST(name)`
Defines a test.
Определяет тест.
```c
TEST(addition) {
@@ -36,34 +36,34 @@ TEST(addition) {
}
```
### `TEST_CASE(name)`
### `TEST_CASE(name, ...)`
Registers a test case.
```c
TEST_CASE(math) {
EXPECT(1 + 1 == 2);
TEST_CASE(math, a, b) {
EXPECT(a + b == b + a);
}
```
## Initialization
## Инициализация
```bash
dcr test --init
```
Creates:
Создаются файлы:
* `tests/dcr_test.h` — framework header (do not edit)
* `tests/test.c` — template with example test
* `tests/dcr_test.h` — заголовочный файл фреймворка
* `tests/test.c` — шаблон с примером теста
## Structure
## Структура tests/
```
tests/
├── dcr_test.h # framework (do not edit)
├── test.c # main tests
└── ... # additional .c test files
├── dcr_test.h # фреймворк (не редактировать)
├── test.c # основные тесты
└── ... # дополнительные .c файлы с тестами
```
Only `.c` files are compiled (`.cpp` is not supported).