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> <details>
<summary>Quick reference</summary> <summary>Быстрая справка</summary>
```bash ```bash
# Installation # Установка(Linux/MacOS скрипт)
curl -fsSL https://dcr.dexoron.su/install.sh | sh curl -fsSL https://dcr.dexoron.su/install.sh | sh
# Create a project # Создать проект
dcr new my-app dcr new my-app
cd my-app cd my-app
# Build and run # Собрать и запустить
dcr build
dcr run dcr run
# Run tests
dcr test
# Add a dependency
dcr add fmt
# Generate IDE files
dcr gen vscode
``` ```
</details> </details>
## Contents ## Содержание
| Section | Description | | Раздел | Описание |
| ----------------------------------------------------- | --------------------------------------------- | | ----------------------------------------------------- | -------------------------------------------- |
| [Getting Started](/docs/getting-started/installation) | Installation and first steps | | [Getting Started](/docs/getting-started/installation) | Установка и первые шаги |
| [Commands](/docs/commands/project-commands) | All CLI commands | | [Commands](/docs/commands/project-commands) | Все CLI-команды DCR |
| [Reference](/docs/reference/dcr-toml) | Configuration, build, dependencies, platforms | | [Reference](/docs/reference/dcr-toml) | Конфигурация, сборка, зависимости, платформы |
| [Testing](/docs/testing/test-framework) | Built-in test framework | | [Testing](/docs/testing/test-framework) | Встроенный фреймворк тестирования |
| [Recipes](/docs/recipes/cross-to-windows) | Common scenarios | | [Recipes](/docs/recipes/cross-to-windows) | Типовые сценарии |
| [IDE Integration](/docs/ide-integration) | VS Code, CLion, compile_commands.json | | [IDE Integration](/docs/ide-integration) | VS Code, CLion, compile_commands.json |
| [Self Update](/docs/self-update) | Auto-update | | [Self Update](/docs/self-update) | Автообновление |
| [FAQ](/docs/faq) | Frequently asked questions | | [FAQ](/docs/faq) | Частые вопросы |
| [Changelog](/docs/changelog) | Version history | | [Changelog](/docs/changelog) | История версий |
| [License](/docs/license) | DCR and vendored library licenses | | [License](/docs/license) | Лицензии DCR и вендорных библиотек |
| [Contributing](/docs/contributing) | DCR development | | [Contributing](/docs/contributing) | Разработка DCR |
## Features ## Особенности
* **Incremental builds** — mtime + `.d` headers + SHA256 fingerprint * **Инкрементальная сборка** — mtime + `.d` headers + SHA256 fingerprint
* **Parallel compilation** — thread::scope, atomic task queue * **Параллельная компиляция** — thread::scope, атомарная очередь задач
* **4 backends** — gcc/clang, MSVC/clang-cl, GAS (ARM), NASM (x86) * **4 бэкенда** — gcc/clang, MSVC/clang-cl, GAS, NASM
* **7 project kinds** — bin, staticlib, sharedlib, efi, elf, none, custom * **7 типов проекта** — bin, staticlib, sharedlib, efi, elf, none, custom
* **Cross-compilation** — short names and full triples * **Cross-compilation** — short names (linux, windows, macos) и полные triples
* **Profiles** — debug / release with field overrides * **Профили** — debug / release с переопределением любого поля
* **Workspaces** — multi-package projects with topological sort * **Workspaces** — мультипакетные проекты с топологической сортировкой
* **Registry + Git + Path** — three dependency mechanisms * **Registry + Git + Path** — три механизма зависимостей
* **IDE generation** — VS Code, CLion, compile_commands.json, JSON metadata * **Генерация IDE** — VS Code, CLion, compile_commands.json, JSON metadata
* **pkg-config** — automatic system library discovery * **pkg-config** — автоматический поиск системных библиотек
* **Per-command `--help`** — `dcr build --help`, `dcr new --help`, etc. * **Per-command `--help`** — `dcr build --help`, `dcr new --help`, etc.
* **Man pages** — `man dcr`, `man dcr-build`, `man dcr-new` * **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) ## 0.7.1 (2026-06-02)
### Added ### Добавлено:
* **`--help` for all commands** — `dcr build --help`, `dcr run --help`, `dcr new --help`, * **`--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`, `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 publishing** — automated Snapcraft publishing in CI.
* **Snap badge** — in README. * **Snap badge** — in README.
### Changed ### Изменено:
* **`validate_package_name` made public** — callable from CLI commands. * **`validate_package_name` made public** — callable from CLI commands.
* **README platform table** — reorganized: libc variants as separate OS rows, * **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`. * **`tree.rs`, `fmt.rs`, and `setup.rs`** — now accept arguments for `--help`.
* **README install commands** — `| bash` → `| sh` for POSIX compatibility. * **README install commands** — `| bash` → `| sh` for POSIX compatibility.
### Fixed ### Исправлено:
* **`dcr new \<invalid-name>` creates directory then fails** — validation now * **`dcr new \<invalid-name>` creates directory then fails** — validation now
happens before any file operations. happens before any file operations.
@@ -52,40 +52,40 @@ sidebar_label: Changelog
### Added ### 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. * **Поддержка целевых платформ OpenBSD и NetBSD** — полная маршрутизация по платформам с динамически генерируемыми тройками целевых параметров с использованием `std::env::consts::ARCH` и `std::env::consts::OS`. Затрагивает команды `build`, `run`, `clean` и модуль платформы.
* **`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`. * **`src/platform/bsd.rs`** — новый специальный модуль платформы BSD, общий для FreeBSD, OpenBSD и NetBSD, предоставляющий `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. * **`Параметр конфигурации build.out_dir`** — настраиваемый каталог вывода, который переопределяет путь по умолчанию `target/\<triple>/\<profile>` для конечных артефактов. Поддерживается в `build`, `run` и при проверке конфигурации.
* **`dcr fmt` command** — new CLI command that formats all C/C++ source files (`*.c`, `*.cpp`, `*.h`, `*.hpp`) in `src/` and `tests/` using `clang-format`. * **Команда `dcr fmt`** — новая команда CLI, которая форматирует все исходные файлы C/C++ (`*.c`, `*.cpp`, `*.h`, `*.hpp`) в `src/` и `tests/` с помощью `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`). * **Инкрементальная компоновка** — функция `needs_link()` в `common.rs`, которая проверяет, не является ли какой-либо объектный файл более новым, чем скомпонованный результат, пропуская ненужную повторную компоновку. Реализовано для всех бэкэндов (`unix_cc`, `msvc`, `gas`, `nasm`).
* **`build.kind = "none"` and `"custom"`** — two new project kinds for special build scenarios that don't produce standard artifacts. * **`build.kind = «none»` и `«custom»`** — два новых типа проектов для специальных сценариев сборки, при которых не создается стандартный артефакт.
* **`install_bsd.sh`** — POSIX-compliant installation script for BSD systems (FreeBSD, OpenBSD, NetBSD) with binary download and source build modes. * **`install_bsd.sh`** — специальный скрипт установки, совместимый с POSIX, для систем BSD (FreeBSD, OpenBSD, NetBSD) с режимами загрузки бинарных файлов и сборки из исходного кода.
* **Linux ARM64 support in `install.sh`** — added `Linux:aarch64|Linux:arm64` target detection for pre-built binary downloads. * **Поддержка Linux ARM64 в `install.sh`** — добавлено определение целевой тройки `Linux:aarch64|Linux:arm64` для загрузки готовых бинарных файлов.
* **BSD OS detection in `install.sh`** — detects FreeBSD, OpenBSD, NetBSD and determines target triple. * **Обнаружение ОС BSD в `install.sh`** — обнаружение FreeBSD, OpenBSD, NetBSD и определение целевой тройки.
* **`rust-toolchain.toml`** — explicit toolchain pinning to `stable` channel. * **`rust-toolchain.toml`** — явное привязывание инструментария к каналу `stable`.
* **Integration tests** — `build_with_target_config` (verifies `build.target = "linux"`) and `build_with_out_dir` (validates custom output directory). * **Интеграционные тесты** — `build_with_target_config` (проверяет `build.target = «linux»`) и `build_with_out_dir` (проверяет настраиваемый каталог вывода).
* **`get_build_string_with_profile` made `pub`** — so `run.rs` can determine custom output directory configuration. * **`get_build_string_with_profile` стал `pub`** — чтобы `run.rs` мог определять конфигурацию настраиваемого каталога вывода.
### Changed ### 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.target`** — теперь строго содержит тройку целей (например, `x86_64-unknown-linux-gnu`) или короткое имя (`linux`, `macos`, `windows`). Больше не используется в качестве пользовательского каталога вывода — эта функциональность перенесена в `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. * **`build.standard` стал опциональным** — изменен с `String` на `Option\<String>`. Проверка обеспечивает только непустоту для языков, отличных от ASM. Пропускается в выводе `dcr.toml`, если пуст.
* **`dcr run` with `out_dir`** — now determines target directory respecting `build.out_dir` via `get_build_string_with_profile()` from `build.rs`. * **`dcr run` с `out_dir`** — теперь определяет целевой каталог с учетом `build.out_dir`, если он настроен, через `get_build_string_with_profile()` из `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. * **`collect_sources()` возвращает пустой вектор** вместо ошибки, если не найдено ни одного исходного файла, что позволяет проектам с `kind = «none»` или `kind = «custom»` не иметь исходных файлов.
* **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. * **Рефакторинг рабочего процесса выпуска CI/CD** — `git2` стал целевым (без vendored-openssl на Windows), кросс-компиляция на основе Zig для целей Linux, отличных от x86_64, очистка версий пакетов Arch Linux (тире → точки), символьная ссылка `gmake` для NetBSD.
* **README compatibility table** — FreeBSD, OpenBSD, NetBSD build/run status upgraded from "community/best-effort" to "officially supported". * **Таблица совместимости README** — статус сборки/работы на FreeBSD, OpenBSD, NetBSD повышен с «сообщество/по возможности» до «официально поддерживается».
* **Documentation updated** — `build-section.md` describes new `build.target` and `build.out_dir` fields. `target-directory.md` rewritten to clarify the distinction. * **Обновлена документация** — `build-section.md` описывает новые поля `build.target` и `build.out_dir`. `target-directory.md` переписан для уточнения различия.
### Fixed ### 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()`. * **stdout/stderr `dcr run` не наследуются** — вывод дочернего процесса захватывался и выводился вручную, что приводило к сбоям интерактивных программ. Исправлено путем перехода на `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. * **Условие гонки в CI релиза** — задания матрицы сборки могли загружать ресурсы в релиз, который еще не существовал. Исправлено добавлением специального задания `create-release`.
* **Release GHA — stable toolchain override** — fixed Rust toolchain override issues in CI. * **Релиз GHA — переопределение стабильного набора инструментов** — устранены проблемы с переопределением набора инструментов Rust в 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. * **Очистка версий пакетов Arch Linux** — строки версий с дефисами (например, `0.7.0-dev`) являются недопустимыми для `pkgver` в Arch Linux. Исправлено путем замены дефисов точками.
* **GPG permissions after Docker** — Docker operations changed GPG directory ownership. Fixed by running `chown` after Docker commands. * **Права доступа GPG после Docker** — операции Docker изменяли владельца каталога GPG. Исправлено путем запуска `chown` после команд Docker.
* **RPM artifact paths** — RPM artifacts were placed in `rpm/x86_64/` instead of `fedora/x86_64/`. Fixed in Dexoron Packages Index workflow. * **Пути к артефактам пакетов RPM** — артефакты RPM размещались в `rpm/x86_64/` вместо `fedora/x86_64/`. Исправлено в рабочем процессе Dexoron Packages Index.
* **JSON parsing reliability in `install.sh`** — added `jq` as primary parser with `python3` fallback for dev channel release lookup. * **Надежность разбора 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()`. * **Вспомогательная функция `format_roots()`** — удалена из `common.rs`. Использовалась только старым путем обработки ошибок в `collect_sources()`.
* **Per-distribution artifact download steps** — three separate `actions/download-artifact` steps replaced with unified `gh release download --clobber`. * **Отдельные шаги загрузки артефактов для каждой дистрибуции** — три отдельных шага `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` ## `dcr build`
Builds the project according to `dcr.toml`. Собирает проект по `dcr.toml`.
```bash ```bash
dcr build # debug profile dcr build # debug профиль
dcr build --release # release build dcr build --release # release профиль
dcr build --debug # explicit debug dcr build --debug # явно debug
dcr build --profile custom # произвольный профиль
dcr build --target aarch64-unknown-linux-gnu dcr build --target aarch64-unknown-linux-gnu
dcr build --force # full rebuild dcr build --force # пересобрать всё с нуля
dcr build --clean # clean + build dcr build --clean # clean + build
dcr build --verbose # show compilation commands dcr build --verbose # показать команды компиляции
dcr build --workspace pkg-a # build specific workspace package dcr build --workspace pkg-a # собрать конкретный пакет в workspace
``` ```
Artifacts: `target/\<triple>/\<profile>/\<binary-name>` (Linux with explicit target). Артефакты: `target/\<triple>/\<profile>/\<binary-name>` (Linux с явным целевым объектом).
## `dcr run` ## `dcr run`
Builds (if sources are newer than artifacts) and runs the binary. Собирает (если исходники новее артефакта) и запускает бинарник.
```bash ```bash
dcr run dcr run
@@ -32,11 +33,11 @@ dcr run --release
## `dcr clean` ## `dcr clean`
Removes `target/` directory (or `target/\<target>/\<profile>`). Удаляет директорию `target/`(или `target/\<target>/\<profile>`).
```bash ```bash
dcr clean dcr clean
dcr clean --release # target/release/ only dcr clean --release # очистить target/release/
dcr clean --target windows # target/x86_64-pc-windows-msvc/ dcr clean --target windows # очистить target/x86_64-pc-windows-msvc/
dcr clean --all # clean all workspace packages 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]` ## `dcr add \<name> [source]`
Adds a dependency to `dcr.toml`. Добавляет зависимость в `dcr.toml`.
```bash ```bash
dcr add fmt # registry lookup dcr add fmt # поиск в реестре
dcr add mylib ../path/to/lib # path as source dcr add mylib ../path/to/lib # путь как источник
dcr add mylib path:./lib # explicit path prefix dcr add mylib path:./lib # явный префикс пути
dcr add mylib git:https://github.com/user/repo # explicit git prefix dcr add mylib git:https://github.com/user/repo # явный префикс git
dcr add mylib github:user/repo # GitHub shorthand dcr add mylib github:user/repo # сокращённая запись GitHub
dcr add mylib gitlab:user/repo # GitLab shorthand dcr add mylib gitlab:user/repo # сокращённая запись GitLab
``` ```
Source prefixes: Префиксы источника:
* `path:` — local path * `path:` — локальный путь
* `git:` — generic git URL * `git:` — URL адрес git-репозитория
* `github:` — expands to `https://github.com/\<user>/\<repo>` * `github:` — расширение `https://github.com/\<user>/\<repo>`
* `gitlab:` — expands to `https://gitlab.com/\<user>/\<repo>` * `gitlab:` — расширение `https://gitlab.com/\<user>/\<repo>`
* `http://` / `https://` / `git@` — full URL * `http://` / `https://` / `git@` — полный URL
Flags: Флаги:
* `--branch \<name>` — git branch * `--branch \<name>` — git ветка
* `--tag \<name>` — git tag * `--tag \<name>` — git tag
* `--rev \<hash>` — git commit * `--rev \<hash>` — git commit
If source is omitted — DCR searches connected registries. Если источник не указан — DCR выполняет поиск в подключенных реестрах.
## `dcr tree` ## `dcr tree`
Displays the project dependency tree. Показывает дерево зависимостей проекта.
```bash ```bash
dcr tree dcr tree
``` ```
Example output: Пример вывода:
``` ```
my-app v0.1.0 my-app v0.1.0
@@ -50,4 +50,4 @@ my-app v0.1.0
└── catch2 (registry) └── 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>` ## `dcr gen \<target>`
Generates IDE integration files. Генерирует файл интеграции с IDE.
### vscode ### vscode
@@ -14,12 +14,12 @@ Generates IDE integration files.
dcr gen vscode dcr gen vscode
``` ```
Creates: Создаёт:
* `.vscode/tasks.json` — `build` task (dcr build) * `.vscode/tasks.json` — `build` задача (dcr build)
* `.vscode/launch.json` — debug launch configuration * `.vscode/launch.json` — конфигурация запуска отладки
* `.vscode/settings.json` — C/C++ settings (clangd paths, includes) * `.vscode/settings.json` — настройки C/C++ (clangd пути, includes)
* `.vscode/extensions.json` — recommended extensions (vscode-clangd, vscode-lldb) * `.vscode/extensions.json` — рекомендуемые расширения (vscode-clangd, vscode-lldb)
### clion ### clion
@@ -27,12 +27,12 @@ Creates:
dcr gen clion dcr gen clion
``` ```
Creates: Создаёт:
* `.idea/externalTools.xml` — external tools (build, run, clean, test) * `.idea/externalTools.xml` — внешние инструменты (build, run, clean, test)
* `.idea/customTargets.xml` — custom build targets * `.idea/customTargets.xml` — пользовательские цели сборки
* `.idea/misc.xml` — C/C++ project settings * `.idea/misc.xml` — настройки C/C++ проекта
* `.idea/runConfigurations/\<name>.xml` — per-binary run configurations * `.idea/runConfigurations/\<name>.xml` — конфигурация запуска
### compile-commands ### compile-commands
@@ -40,7 +40,7 @@ Creates:
dcr gen compile-commands dcr gen compile-commands
``` ```
Generates `compile_commands.json` — standard format for clangd, cpptools, static analyzers. Генерирует `compile_commands.json` — стандартный формат для clangd, cpptools, статических анализаторов.
### project-info ### project-info
@@ -48,7 +48,7 @@ Generates `compile_commands.json` — standard format for clangd, cpptools, stat
dcr gen project-info dcr gen project-info
``` ```
Outputs JSON array with project metadata: Выводит JSON с метаданными проекта:
```json ```json
[ [

View File

@@ -1,31 +1,31 @@
--- ---
sidebar_label: Project commands (new, init) sidebar_label: Команды проекта (new, init)
--- ---
# Project Commands # Команды проекта
## `dcr new \<name>` ## `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 ```bash
dcr new my-app dcr new my-app
``` ```
Generates: Генерирует:
* `dcr.toml` with basic fields * `dcr.toml` с базовыми полями
* `src/main.c` with a `main` template * `src/main.c` с основным шаблоном
## `dcr init` ## `dcr init`
Initializes a DCR project in the current (empty) directory. Инициализирует проект DCR в текущем (пустом) каталоге.
```bash ```bash
mkdir app && cd app mkdir app && cd app
dcr init 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` ## `dcr test`
Runs tests. Запускает тесты.
```bash ```bash
dcr test # debug profile dcr test # debug профиль
dcr test --release # release profile dcr test --release # release профиль
dcr test --debug # explicit debug dcr test --debug # явный debug
dcr test --help # detailed help dcr test --help # подробная справка
``` ```
Before first use, initialize tests: Перед первым запуском нужно инициализировать тесты:
```bash ```bash
dcr test --init 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 1. Builds the project
2. Collects `tests/*.c` files (`.c` only, not `.cpp`) 2. Collects `tests/*.c` files (`.c` only, not `.cpp`)
3. Compiles and links each test file 3. Compiles and links each test file
4. Runs each test binary 4. Runs each test binary
5. Prints summary: TOTAL, PASS, SKIP, FAIL 5. Prints summary: TOTAL, PASS, SKIP, FAIL
6. Returns non-zero exit code on any FAIL 6. Возвращает ненулевой код при наличии FAIL
## `dcr fmt` ## `dcr fmt`
Formats C/C++ source files using `clang-format`. Форматирует исходный код C/C++ через `clang-format`.
```bash ```bash
dcr fmt 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}`. 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` ## `dcr lint`

View File

@@ -1,12 +1,12 @@
--- ---
sidebar_label: System commands (setup, --help, ...) sidebar_label: Системные команды (setup, --help, ...)
--- ---
# System Commands # Системные команды
## `dcr setup` ## `dcr setup`
Shows configured registries from `~/.dcr/config.toml`. `~/.dcr/config.toml` — конфигурация реестров
```bash ```bash
dcr setup dcr setup
@@ -26,6 +26,7 @@ Shows help for all commands.
```bash ```bash
dcr --help dcr --help
dcr build --help # справка по конкретной команде
``` ```
## `dcr --version` ## `dcr --version`
@@ -33,19 +34,19 @@ dcr --help
Shows version and target triple. Shows version and target triple.
```bash ```bash
dcr --version # dcr 0.7.0 (x86_64-unknown-linux-gnu) dcr --version # dcr 0.7.0
``` ```
## `dcr --update` ## `dcr --update`
Self-update. Downloads the latest release binary from GitHub Releases and replaces the current one. Самообновление. Скачивает последний релиз с GitHub Releases и заменяет текущий бинарник.
```bash ```bash
dcr --update dcr --update
``` ```
Features: Особенности:
* Auto-detects platform and architecture * Определяет платформу и архитектуру автоматически
* Warns if installed via AUR (use package manager instead) * 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 ## Code style
All code must be formatted with `cargo fmt`: Весь код форматируется через `cargo fmt`:
```bash ```bash
cargo fmt cargo fmt
``` ```
## Linting ## Линтер
```bash ```bash
cargo clippy --all-targets -- -D warnings cargo clippy --all-targets -- -D warnings
``` ```
## Tests ## Тесты
```bash ```bash
cargo test --all-targets cargo test --all-targets
@@ -34,18 +34,18 @@ cargo test --all-targets
## PR process ## PR process
1. Fork the repository 1. Форкните репозиторий
2. Create a branch: `git checkout -b feature/description` 2. Создайте ветку: `git checkout -b feature/description`
3. Make changes 3. Внесите изменения
4. Run `cargo fmt && cargo clippy && cargo test` 4. Запустите `cargo fmt && cargo clippy --all-targets -- -D warnings && cargo test --all-targets`
5. Open a Pull Request 5. Откройте Pull Request
## CI ## CI
CI runs: В CI запускаются:
* `cargo fmt --check` * `cargo fmt --check`
* `cargo clippy --all-targets -- -D warnings` * `cargo clippy --all-targets -- -D warnings`
* `cargo test --all-targets` * `cargo test --all-targets`
* Build on Linux, macOS, Windows * Сборка под Linux, macOS, Windows, FreeBSD, OpenBSD, NetBSD
* Integration tests * Интеграционные тесты

View File

@@ -1,8 +1,8 @@
--- ---
sidebar_label: FAQ sidebar_label: Часто задаваемые вопросы
--- ---
# FAQ # Часто задаваемые вопросы
## Registry not found ## Registry not found
@@ -18,7 +18,7 @@ name = "default"
url = "https://index.dcr.pm" url = "https://index.dcr.pm"
``` ```
And check `DCR_INDEX_PATH`: Если реестр кастомный, проверьте `DCR_INDEX_PATH`:
```bash ```bash
echo $DCR_INDEX_PATH echo $DCR_INDEX_PATH
@@ -30,24 +30,24 @@ echo $DCR_INDEX_PATH
error: compiler not found error: compiler not found
``` ```
**Solution:** Ensure a compiler is installed and available in PATH. **Решение:** Убедитесь, что компилятор установлен и доступен в PATH.
```bash ```bash
which gcc which gcc
which clang which clang
``` ```
Or specify explicitly via `[toolchain]` in `dcr.toml`. Или укажите явно через `[toolchain]` или `DCR_COMPILER`.
## openssl-sys build failed ## openssl-sys build failed
When building DCR from source: При сборке DCR из исходников:
``` ```
error: failed to run custom build command for openssl-sys error: failed to run custom build command for openssl-sys
``` ```
**Solution:** Install OpenSSL development headers: **Решение:** Установите OpenSSL development headers:
```bash ```bash
# Ubuntu/Debian # Ubuntu/Debian
@@ -60,22 +60,22 @@ sudo dnf install openssl-devel
brew install openssl 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? ## 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 ```bash
dcr new my-app dcr new my-app
cd my-app cd my-app
``` ```
Structure: Будет создана структура:
``` ```
my-app/ my-app/
@@ -27,12 +27,17 @@ my-app/
name = "my-app" name = "my-app"
version = "0.1.0" version = "0.1.0"
type = "none" type = "none"
description=""
author=""
license = "GPL-3.0-or-later"
[build] [build]
language = "c" language = "c"
standard = "c11" standard = "c11"
compiler = "clang" compiler = "clang"
kind = "bin" kind = "bin"
[dependencies]
``` ```
## Build ## Build
@@ -43,20 +48,20 @@ dcr build
Output — `target/\<triple>/debug/my-app` (Linux) or `target/debug/my-app.exe` (Windows). Output — `target/\<triple>/debug/my-app` (Linux) or `target/debug/my-app.exe` (Windows).
Build profiles: Профиль:
```bash ```bash
dcr build --release # release build dcr build --release # релизная сборка
dcr build --debug # debug (default) dcr build --debug # дебажная (по умолчанию)
``` ```
## Run ## Запустить
```bash ```bash
dcr run dcr run
``` ```
Builds (if needed) and runs the binary. Собирает (если нужно) и запускает бинарник.
## First test ## First test
@@ -65,8 +70,8 @@ dcr test --init # create test template
dcr test # run tests dcr test # run tests
``` ```
## Formatting ## Форматирование
```bash ```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) ## Linux (Dexoron Packages)
Configure your package manager at https://pkg.dexoron.su and install: Настройте менеджер пакетов на https://pkg.dexoron.su и установите:
**Arch Linux** **Arch Linux**
@@ -37,6 +37,8 @@ yay -S dcr
```sh ```sh
brew tap dexoron/dexoron brew tap dexoron/dexoron
brew install dcr brew install dcr
# or
brew install dexoron/dexoron/dcr
``` ```
## Snap (Linux) ## Snap (Linux)
@@ -62,13 +64,13 @@ cargo install dcr
## Linux / macOS (script) ## Linux / macOS (script)
```sh ```sh
curl -fsSL https://dcr.dexoron.su/install.sh | sh curl -fsSL https://dcr.dexoron.su/install_bsd.sh | bash
``` ```
## BSD (script) ## BSD (script)
```sh ```sh
curl -fsSL https://dcr.dexoron.su/install_bsd.sh | sh curl -fsSL https://dcr.dexoron.su/install.sh | bash
``` ```
## Windows (PowerShell) ## Windows (PowerShell)
@@ -90,7 +92,7 @@ ln -sf "$PWD/target/release/dcr" ~/.local/bin/dcr
Verify the installation: Verify the installation:
```bash ```bash
dcr --version dcr setup
``` ```
Man pages are available after installation: Man pages are available after installation:
@@ -100,7 +102,7 @@ man dcr
man dcr-build man dcr-build
``` ```
To use the registry, create `~/.dcr/config.toml`: Команда создаёт `~/.dcr/` с дефолтным `config.toml` и скачивает публичный реестр.
```toml ```toml
[[registry]] [[registry]]

View File

@@ -1,8 +1,8 @@
--- ---
sidebar_label: IDE Integration sidebar_label: Интеграция с IDE
--- ---
# IDE Integration # Интеграция с IDE
## VS Code ## VS Code
@@ -10,14 +10,14 @@ sidebar_label: IDE Integration
dcr gen vscode dcr gen vscode
``` ```
Generates in `.vscode/`: Генерирует в `.vscode/`:
| File | Purpose | | Файл | Назначение |
| ----------------- | -------------------------------------------- | | ----------------- | ------------------------------------------- |
| `tasks.json` | `build` task (dcr build) | | `tasks.json` | Задача `build` (dcr build) |
| `launch.json` | Debug launch configuration | | `launch.json` | Debug-запуск бинарника |
| `settings.json` | clangd/IntelliSense: include paths, standard | | `settings.json` | clangd/IntelliSense: include пути, стандарт |
| `extensions.json` | Recommends vscode-clangd, vscode-lldb | | `extensions.json` | Рекомендует clangd, C/C++ |
## CLion ## CLion
@@ -25,14 +25,14 @@ Generates in `.vscode/`:
dcr gen clion dcr gen clion
``` ```
Generates in `.idea/`: Генерирует в `.idea/`:
| File | Purpose | | Файл | Назначение |
| ------------------------------------------------ | ----------------------------------------- | | ----------------------------------------- | ----------------------------------------------- |
| `externalTools.xml` | Build, Run, Clean, Test as external tools | | `externalTools.xml` | Build, Run, Clean, Test как внешние инструменты |
| `customTargets.xml` | Custom build targets | | `customTargets.xml` | Кастомные цели сборки |
| `misc.xml` | C/C++ project settings | | `misc.xml` | Настройки C/C++ проекта |
| `runConfigurations/\<name>.xml` | Per-binary run configurations | | `runConfigurations/dcr_build_and_run.xml` | Per-binary run configurations |
## compile_commands.json ## compile_commands.json
@@ -40,7 +40,7 @@ Generates in `.idea/`:
dcr gen compile-commands 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 ## project-info
@@ -48,4 +48,4 @@ Generates `compile_commands.json` at project root. Standard format for clangd, C
dcr gen project-info 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
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` | | [libgit2](https://libgit2.org) | MIT OR Apache-2.0 | `git2` / `libgit2-sys` |
| [libssh2](https://libssh2.org) | MIT OR Apache-2.0 | `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` | | [OpenSSL](https://openssl.org) | Apache-2.0 | `openssl-sys` / `openssl-src` |
| [ring](https://github.com/briansmith/ring) | Apache-2.0 AND ISC | `rustls` | | [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 | | [`reqwest`](https://crates.io/crates/reqwest) | MIT OR Apache-2.0 |
| [`rustls`](https://crates.io/crates/rustls) | Apache-2.0 OR ISC OR MIT | | [`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 | | [`hyper`](https://crates.io/crates/hyper) | MIT |
| [`ctrlc`](https://crates.io/crates/ctrlc) | MIT OR Apache-2.0 | | [`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 ## 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 ```bash
# Ubuntu/Debian # Ubuntu/Debian
@@ -16,31 +16,29 @@ sudo apt install mingw-w64
sudo dnf install mingw64-gcc mingw64-binutils sudo dnf install mingw64-gcc mingw64-binutils
``` ```
## Configuration ## Конфигурация
```toml ```toml
[package] [package]
name = "my-app" name = "my-app"
version = "0.1.0" version = "0.1.0"
type = "none" type = "app"
[build] [build]
language = "c" language = "c"
standard = "c11" standard = "c17"
compiler = "clang" target = "windows"
kind = "bin"
target = "x86_64-pc-windows-gnu" # explicit mingw, not msvc
``` ```
## Build ## Сборка
```bash ```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 ```toml
[toolchain] [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 ```bash
dcr new my-lib dcr new my-lib
cd my-lib
``` ```
`dcr.toml`: `dcr.toml`:
@@ -19,11 +18,11 @@ cd my-lib
[package] [package]
name = "my-lib" name = "my-lib"
version = "0.1.0" version = "0.1.0"
type = "none" type = "lib"
[build] [build]
language = "c" language = "c"
standard = "c11" standard = "c17"
kind = "staticlib" kind = "staticlib"
``` ```
@@ -43,28 +42,29 @@ int add(int a, int b);
int add(int a, int b) { return a + b; } int add(int a, int b) { return a + b; }
``` ```
## Step 2: Build ## Шаг 2: Собрать
```bash ```bash
cd my-lib
dcr build --release 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/release/my-lib.lib` (Windows)
* `target/include/` — header files * `target/include/` — заголовочные файлы
## Step 3: Use in another project ## Шаг 3: Использовать в проекте
```bash ```bash
dcr new my-app dcr new my-app
cd 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 * Добавляется include path на `target/include/` библиотеки
* Adds lib path to `target/\<triple>/release/` * Добавляется lib path на `target/release/`
* Links `libmy-lib.a` / `my-lib.lib` * Линкуется `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/ workspace/
├── dcr.toml # root workspace ├── dcr.toml # корневой workspace
├── lib-core/ ├── lib-core/
│ ├── dcr.toml │ ├── dcr.toml
│ └── src/core.c │ └── src/lib.rs
├── lib-utils/ ├── lib-utils/
│ ├── dcr.toml │ ├── dcr.toml
│ └── src/utils.c │ └── src/utils.c
@@ -22,7 +22,7 @@ workspace/
└── src/main.c └── src/main.c
``` ```
## Root dcr.toml ## Корневой dcr.toml
```toml ```toml
[package] [package]
@@ -33,22 +33,17 @@ type = "none"
[build] [build]
inherit = true inherit = true
language = "c" language = "c"
standard = "c11" standard = "c17"
[workspace.lib-core] [workspace]
path = "lib-core" members = [
{ path = "lib-core" },
[workspace.lib-utils] { path = "lib-utils", deps = ["lib-core"] },
path = "lib-utils" { path = "app", deps = ["lib-core", "lib-utils"], main = true },
deps = ["lib-core"] ]
[workspace.app]
path = "app"
deps = ["lib-core", "lib-utils"]
main = true
``` ```
## Packages ## Пакеты
`lib-core/dcr.toml`: `lib-core/dcr.toml`:
@@ -56,7 +51,7 @@ main = true
[package] [package]
name = "lib-core" name = "lib-core"
version = "0.1.0" version = "0.1.0"
type = "none" type = "lib"
[build] [build]
kind = "staticlib" kind = "staticlib"
@@ -68,7 +63,7 @@ kind = "staticlib"
[package] [package]
name = "lib-utils" name = "lib-utils"
version = "0.1.0" version = "0.1.0"
type = "none" type = "lib"
[build] [build]
kind = "staticlib" kind = "staticlib"
@@ -80,23 +75,23 @@ kind = "staticlib"
[package] [package]
name = "app" name = "app"
version = "0.1.0" version = "0.1.0"
type = "none" type = "app"
[build] [build]
kind = "bin" kind = "bin"
``` ```
## Build ## Сборка
```bash ```bash
cd workspace cd workspace
dcr build # builds everything in correct order dcr build # собирает всё в правильном порядке
dcr build --workspace app # only app (lib-core and lib-utils built as deps) dcr build --workspace app # только app (lib-core и lib-utils собираются как зависимости)
dcr run # builds and runs main package dcr run # собирает и запускает main-пакет
``` ```
Build order (topological sort): Порядок сборки (топологическая сортировка):
1. `lib-core` 1. `lib-core`
2. `lib-utils` (depends on lib-core) 2. `lib-utils` (зависит от lib-core)
3. `app` (depends on lib-core, lib-utils) 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 ```toml
[build] [build]
@@ -18,31 +18,31 @@ cflags = ["-Wall"]
cflags = ["-O0", "-g"] cflags = ["-O0", "-g"]
[build.release] [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 * **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). 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: The default flags for each profile are composed from three config fields:
| Field | debug default | release default | | Field | Default cflags | Профили сборки |
| ----------- | ------------------ | --------------- | | ----------- | ------------------ | -------------- |
| `opt_level` | `"0"` | `"3"` | | `opt_level` | `-O0 -g` | `"3"` |
| `debug` | `true` | `false` | | `debug` | `true` | `false` |
| `warnings` | `["all", "extra"]` | `[]` | | `warnings` | `["all", "extra"]` | `[]` |
Which produce the equivalent compiler flags: Which produce the equivalent compiler flags:
| Profile | Effective flags | | Профиль | Effective flags |
| --------- | ---------------------------------------------------------- | | --------- | ---------------------------------------------------------- |
| `debug` | `-O0 -g -Wall -Wextra -fno-omit-frame-pointer -DDCR_DEBUG` | | `debug` | `-O0 -g -Wall -Wextra -fno-omit-frame-pointer -DDCR_DEBUG` |
| `release` | `-O3 -DNDEBUG` | | `release` | `-O3 -DNDEBUG` |
@@ -63,7 +63,7 @@ debug = false
warnings = ["all", "error"] warnings = ["all", "error"]
``` ```
## Target-specific profiles ## Target-specific профили
```toml ```toml
[build.linux] [build.linux]
@@ -77,6 +77,6 @@ Application order (highest priority first):
1. `[build.\<target>.\<profile>]` 1. `[build.\<target>.\<profile>]`
2. `[build.\<profile>.\<target>]` 2. `[build.\<profile>.\<target>]`
3. `[build.\<target>]` 3. ]`или`[build.\<target>]\`
4. `[build.\<profile>]` 4. `[build.\<profile>]`.
5. `[build]` 5. `[build]`

View File

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

View File

@@ -1,12 +1,12 @@
--- ---
sidebar_label: Cross-compilation sidebar_label: Кросс-компиляция
--- ---
# Cross-Compilation # Кросс-компиляция
## Short Names ## Short Names
DCR supports short platform names: DCR поддерживает короткие имена платформ, которые автоматически раскрываются в полные triples:
| Short Name | Full Triple | | Short Name | Full Triple |
| ---------- | -------------------------- | | ---------- | -------------------------- |
@@ -22,26 +22,26 @@ dcr build --target windows
```bash ```bash
dcr build --target aarch64-unknown-linux-gnu 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 dcr build --target armv7-unknown-linux-gnueabihf
``` ```
## clang --target ## clang --target
When using clang, DCR injects `--target=\<triple>` into CFLAGS. При использовании clang DCR автоматически inject-ит `--target=\<triple>` в CFLAGS/CXXFLAGS.
```toml ```toml
[build] [build]
compiler = "clang" compiler = "clang"
target = "aarch64-unknown-linux-gnu" 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: 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 2. **Injects `-ffreestanding`** at compile time and `-nostdlib -static` at link time
You can also enable freestanding mode explicitly: 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 ```toml
[package] [package]
# required fields # обязательные поля
[build] [build]
# build settings # настройки сборки
[build.debug] # optional: debug override [build.debug] # опционально: переопределение для debug
[build.release] # optional: release override [build.release] # опционально: переопределение для release
[build.linux] # optional: Linux override [build.linux] # опционально: переопределение для Linux
[build.windows] # optional: Windows override [build.windows] # опционально: переопределение для Windows
[build.windows.debug] # target + profile combination [build.windows.debug] # комбинация target + profile
[toolchain] [toolchain]
# compiler/linker paths # пути к компиляторам/линкеру
[dependencies] [dependencies]
# project dependencies # зависимости проекта
[workspace] [workspace]
# multi-package configuration # мультипакетная конфигурация
[run] [run]
# run settings [run.release] # опционально: переопределение для release
# настройки запуска
``` ```
## [package] ## [package]
| Field | Required | Description | | Поле | Обязательное | Описание |
| --------- | -------- | ----------------------- | | --------- | ------------ | --------------------------- |
| `name` | yes | Project name | | `name` | да | Имя проекта |
| `version` | yes | Semantic version | | `version` | да | Семантическая версия |
| `type` | yes | `app`, `lib`, `none` | | `type` | да | `app`, `lib`, `none` |
| `license` | no | SPDX license identifier | | `license` | нет | SPDX-идентификатор лицензии |
| `author` | no | Author | | `author` | нет | Автор |
```toml ```toml
[package] [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`. * `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"` | | `language` | `"c"` | `"c"`, `"cxx"`, `"cpp"` |
| `standard` | `"c11"` | C standard (`c11`, `c17`, `c23`) | | `standard` | `"c11"` | Стандарт C (`c11`, `c17`, `c23`) |
| `cxx_standard` | `"c++20"` | C++ standard (`c++17`, `c++20`, `c++23`) | | `cxx_standard` | `"c++20"` | Стандарт C++ (`c++17`, `c++20`, `c++23`) |
| `compiler` | `"clang"` | Preferred compiler | | `compiler` | `cxxflags` | Предпочитаемый компилятор |
| `kind` | `"bin"` | `bin`, `staticlib`, `sharedlib`, `efi`, `elf`, `none`, `custom` | | `kind` | `"bin"` | `bin`, `staticlib`, `sharedlib`, `efi`, `elf`, `none`, `custom` |
| `target` | host | Target triple for cross-compilation | | `target` | хост | Target triple для кросс-компиляции |
| `platform` | `"native"` | `native`, `efi` | | `platform` | `"native"` | `native`, `efi`, `freestanding` |
| `cflags` | `[]` | Additional C/C++/ASM flags | | `cflags` | `[]` | Дополнительные флаги C++ |
| `ldflags` | `[]` | Additional linker flags | | `ldflags` | `[]` | Дополнительные флаги линковки |
| `filename` | `""` | Custom output file name | | `filename` | `""` | Кастомное имя выходного файла |
| `extension` | `""` | Custom file extension | | `extension` | `""` | Custom file extension |
| `roots` | `["src"]` | Source root directories | | `roots` | `["src"]` | Корневые директории с исходниками |
| `exclude` | `[]` | Exclude patterns | | `exclude` | `[]` | Паттерны исключений |
| `include` | `[]` | Additional include directories | | `include` | `[]` | Дополнительные include-директории |
| `src_disable` | `false` | Disable auto source discovery | | `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 | | `clean` | `[]` | Glob patterns for custom clean paths |
| `out_dir` | `""` | Custom output directory | | `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`) | | `freestanding` | `false` | Compile in freestanding mode (`-ffreestanding` + `-nostdlib -static`) |
| `opt_level` | `"0"` (debug) / `"3"` (release) | Optimization level: `0`-`3`, `"s"`, `"z"` | | `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) | | `lto` | `false` | Link-time optimization (`-flto` for both compiler and linker) |
| `strip` | `false` | Strip symbols from output (`-s` in ldflags) | | `asflags` | `false` | Strip symbols from output (`-s` in ldflags) |
| `warnings` | `["all", "extra"]` (debug) / `[]` (release) | Warning flags (e.g. `"all"`, `"extra"`, `"pedantic"`) | | `true` | `["all", "extra"]` (debug) / `[]` (release) | Warning flags (e.g. `"all"`, `"extra"`, `"pedantic"`) |
| `panic` | `""` | Panic strategy: `"abort"` disables exceptions and unwind tables | | `panic` | `""` | Panic strategy: `"abort"` disables exceptions and unwind tables |
| `codegen-units` | `""` | Max parallel compilation jobs (`"0"` = auto) | | `codegen-units` | `""` | Max parallel compilation jobs (`"0"` = auto) |
| `qt` | `false` | Enable automatic Qt meta-object handling (MOC, UIC, RCC) | | `qt` | `false` | Enable automatic Qt meta-object handling (MOC, UIC, RCC) |
Settings from raw config (not in typed struct): Settings from raw config (not in typed struct):
* `pkg_config` — list of pkg-config packages * Пакеты для pkg-config
* `ldscript` — linker script path * Путь к linker script
* `build.steps` / `build.post_steps` — codegen steps * `build.steps` / `build.post_steps` — codegen steps
Example: Example:
```toml ```toml
[build] [build]
language = "c++" language = ["cpp", "c"]
standard = "c17"
standard = "c23" standard = "c23"
cxx_standard = "c++23" cxx_standard = "c++23"
compiler = "clang" compiler = "clang"
kind = "sharedlib" kind = "sharedlib"
cflags = ["-Wall", "-Wextra"] cflags = ["-Wall", "-Wextra"]
opt_level = "z" pkg_config = ["sdl2", "gl"]
lto = true
strip = true
panic = "abort"
codegen-units = "2"
``` ```
## [toolchain] ## [toolchain]
@@ -123,13 +121,16 @@ cxx = "/usr/bin/clang++"
as = "/usr/bin/as" as = "/usr/bin/as"
ar = "/usr/bin/ar" ar = "/usr/bin/ar"
ld = "/usr/bin/ld.lld" 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. Raw config also supports `uic`, `moc`, `rcc` for Qt codegen.
## [dependencies] ## [dependencies]
See [dependencies](/docs/reference/dependencies). См. [dependencies](/docs/reference/dependencies).
## [run] ## [run]
@@ -138,15 +139,15 @@ See [dependencies](/docs/reference/dependencies).
cmd = "./target/{profile}/{name}" cmd = "./target/{profile}/{name}"
``` ```
Substitutions: Подстановки:
* `{version}` — package version * `{version}` — версия из [package]
* `{version_major}`, `{version_minor}`, `{version_patch}`, `{version_suffix}`, `{version_suffix_dash}` — version parts * `pkg_config`
* `{profile}` — debug / release * `{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] ## [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) ### String (registry)
```toml ```toml
[dependencies] [dependencies]
fmt = "10.1.1" fmt = "10.1.1"
spdlog = "1.12" spdlog = "^1.12"
catch2 = "3.4.0" catch2 = ">=3.0,<4.0"
``` ```
The version string is used as-is for registry lookup. The version string is used as-is for registry lookup.
### Table (git) ### Табличный (git)
```toml ```toml
[dependencies] [dependencies]
fmt = { git = "https://github.com/fmtlib/fmt", tag = "10.1.1" } 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 ```toml
[dependencies] [dependencies]
@@ -37,7 +37,11 @@ mylib = { path = "../mylib" }
## Registry ## 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 ```toml
# ~/.dcr/config.toml # ~/.dcr/config.toml
@@ -46,22 +50,22 @@ name = "default"
url = "https://index.dcr.pm" 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 * `branch` — переключиться на ветку
* `tag` — switch to a tag * `tag` — переключиться на тег
* `rev` — switch to a specific commit * `rev` — переключиться на конкретный коммит
* `features` — feature flags (parsed, but does not affect build) * `features` — feature flags (parsed, but does not affect build)
Cache path: `~/.dcr/git/\<hash>/`. 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 ```toml
[dependencies] [dependencies]
@@ -71,14 +75,14 @@ mylib = { path = "../relative/path" }
## dcr.lock ## 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` 2. For path deps: recursively read their `dcr.toml`
3. For registry deps: search `index.json` 3. For registry deps: search `index.json`
4. For git deps: clone to cache 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 ## DCR_COMPILER
Overrides the compiler for all languages. **Highest priority.** Переопределяет компилятор для всех языков. **Highest priority.**
```bash ```bash
export DCR_COMPILER=clang export DCR_COMPILER=clang
@@ -23,7 +23,7 @@ Compiler resolution priority:
## DCR_CC / DCR_CXX / DCR_AS ## DCR_CC / DCR_CXX / DCR_AS
Per-language override (lower priority than `DCR_COMPILER`, higher than `[toolchain]`). Приоритет: `[toolchain]` > `DCR_COMPILER` > `DCR_CC` > `PATH`.
```bash ```bash
export DCR_CC=gcc-14 export DCR_CC=gcc-14
@@ -42,7 +42,7 @@ export DCR_AR=llvm-ar
## DCR_DEBUG ## DCR_DEBUG
Enables debug mode — prints all compilation commands to stderr before execution. Включает режим отладки — печатает все команды компиляции перед выполнением.
```bash ```bash
export DCR_DEBUG=1 export DCR_DEBUG=1
@@ -51,10 +51,10 @@ dcr build
## DCR_INDEX_PATH ## DCR_INDEX_PATH
Overrides the path to the registry `index.json`. Переопределяет путь к index.json реестра.
```bash ```bash
export DCR_INDEX_PATH=/custom/path/index.json 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 ## 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 ### Linux
@@ -14,9 +14,9 @@ DCR normalizes target triples. Short platform names are expanded to full triples
target/<arch>-unknown-linux-gnu/<profile>/ 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 ### macOS
@@ -24,9 +24,9 @@ Artifact type: ELF. Extensions: `.so` (sharedlib), `.a` (staticlib).
target/<profile>/ target/<profile>/
``` ```
Architectures: `x86_64`, `aarch64` (host-detected). Поддержка архитектур: `x86_64`, `aarch64`.
Extensions: `.dylib` (sharedlib), `.a` (staticlib). `.dylib` для sharedlib, `.a` для staticlib
### Windows ### Windows
@@ -34,7 +34,7 @@ Extensions: `.dylib` (sharedlib), `.a` (staticlib).
target/<profile>/ target/<profile>/
``` ```
Architectures: `x86_64`, `aarch64`. Поддержка архитектур: `x86_64`, `aarch64`.
Extensions: `.exe` (bin), `.lib` (staticlib), `.dll` (sharedlib), `.efi` (UEFI). 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>/ 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 ```toml
[workspace.lib-core] [workspace]
path = "lib-core" members = [
{ path = "pkg-a" },
[workspace.lib-utils] { path = "pkg-b", deps = ["pkg-a"] },
path = "lib-utils" { path = "pkg-c", deps = ["pkg-a", "pkg-b"], main = true },
deps = ["lib-core"] ]
[workspace.app]
path = "app"
deps = ["lib-core", "lib-utils"]
main = true
``` ```
### Member fields ### Поля member
| Field | Description | | Поле | Описание |
| ------ | ------------------------------------------------ | | ------ | -------------------------------------------- |
| `path` | Path to the package (relative to workspace root) | | `path` | Путь к пакету (относительно корня workspace) |
| `deps` | Dependencies on other members | | `deps` | Зависимости от других member-ов |
| `main` | Mark as the main package | | `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 ```bash
dcr build # build all packages in dependency order dcr build # собрать все пакеты
dcr build --workspace app # build only app (dependencies built automatically) 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 ```bash
dcr clean # clean only root target/ dcr clean # очистить только корневой target/
dcr clean --all # clean target/ of all packages 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 ```toml
# root dcr.toml
[build] [build]
inherit = true inherit = true
language = "c" language = "c"
standard = "c17" standard = "c17"
# member inherits language and standard
``` ```

View File

@@ -1,46 +1,46 @@
--- ---
sidebar_label: Self Update sidebar_label: Автоматическое обновление
--- ---
# Self Update # Автоматическое обновление
## dcr --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 ```bash
dcr --update 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` 2. Fetches the latest release from `api.github.com/repos/dexoron/dcr/releases/latest`
3. Compares versions 3. Compares versions
4. Downloads the matching asset (direct binary URL, not archive) 4. Downloads the matching asset (direct binary URL, not archive)
5. Replaces the current executable via `self_replace` 5. Заменяет текущий исполняемый файл
## Asset naming ## Asset naming
Pattern: `dcr-\<triple>` or `dcr-\<triple>.exe` Шаблон: `dcr-\<triple>.\<ext> `
| Platform | Asset name | | Платформа | Asset name |
| -------------- | -------------------------------- | | -------------- | ------------------------------------- |
| Linux x86_64 | `dcr-x86_64-unknown-linux-gnu` | | Linux x86_64 | `dcr-x86_64-unknown-linux-gnu.tar.gz` |
| macOS x86_64 | `dcr-x86_64-apple-darwin` | | macOS x86_64 | `dcr-x86_64-apple-darwin.tar.gz` |
| macOS ARM64 | `dcr-aarch64-apple-darwin` | | macOS ARM64 | `dcr-aarch64-apple-darwin.tar.gz` |
| Windows x86_64 | `dcr-x86_64-pc-windows-msvc.exe` | | Windows x86_64 | `dcr-x86_64-pc-windows-msvc.zip` |
## AUR ## 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} 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 * Не удалось скачать релиз — ошибка с URL
* No write permission — error (use `sudo` or manual install) * Нет прав на запись бинарника — ошибка (нужен `sudo` или ручная установка)

View File

@@ -1,8 +1,8 @@
--- ---
sidebar_label: Running tests sidebar_label: Запуск тестов
--- ---
# Running Tests # Запуск тестов
## Execution ## Execution
@@ -15,12 +15,12 @@ Builds the project, then compiles and runs test files from `tests/`.
## Profiles ## Profiles
```bash ```bash
dcr test # debug (default) dcr test # debug (по умолчанию)
dcr test --release # release 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) * 0 — все тесты пройдены (FAIL = 0)
* 1 — test failures or build error * 1 — есть упавшие тесты
## What gets built ## What gets built
* All `.c` files from `tests/` (`.cpp` not supported) * Все C/C++ файлы из `tests/`
* Include path: `tests/` (for `dcr_test.h`) * Include path: `tests/` (для `dcr_test.h`)
* Linked with project if `package.type = "lib"` or `kind = "staticlib"`/`"sharedlib"` * Линкуется с основным проектом (если `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 ```c
EXPECT(1 + 1 == 2); 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 ```c
SKIP("not implemented on Windows"); SKIP("not implemented on Windows yet");
``` ```
### `TEST(name)` ### `TEST(name)`
Defines a test. Определяет тест.
```c ```c
TEST(addition) { TEST(addition) {
@@ -36,34 +36,34 @@ TEST(addition) {
} }
``` ```
### `TEST_CASE(name)` ### `TEST_CASE(name, ...)`
Registers a test case. Registers a test case.
```c ```c
TEST_CASE(math) { TEST_CASE(math, a, b) {
EXPECT(1 + 1 == 2); EXPECT(a + b == b + a);
} }
``` ```
## Initialization ## Инициализация
```bash ```bash
dcr test --init dcr test --init
``` ```
Creates: Создаются файлы:
* `tests/dcr_test.h` — framework header (do not edit) * `tests/dcr_test.h` — заголовочный файл фреймворка
* `tests/test.c` — template with example test * `tests/test.c` — шаблон с примером теста
## Structure ## Структура tests/
``` ```
tests/ tests/
├── dcr_test.h # framework (do not edit) ├── dcr_test.h # фреймворк (не редактировать)
├── test.c # main tests ├── test.c # основные тесты
└── ... # additional .c test files └── ... # дополнительные .c файлы с тестами
``` ```
Only `.c` files are compiled (`.cpp` is not supported). Only `.c` files are compiled (`.cpp` is not supported).