27 Commits

Author SHA1 Message Date
4e3601b1df Changed: openssl dependency is now conditional (cfg(not(windows))) — no longer pulled in on Windows, fixing Windows CI builds that lack Perl Locale::Maketext::Simple. On Linux (including musl cross-compilation) the vendored OpenSSL build is unchanged. 2026-05-26 17:57:37 +08:00
7969209eae Added:
- `build.kind = "efi"` — UEFI PE32+ executable support. Links with `-shared -nostdlib -Wl,-dll -Wl,--subsystem,10`, output via `efi_path()` with `.efi` extension, rejected by `dcr run`.
- `build.kind = "elf"` — bare-metal ELF executable support. Uses `elf_path()` output path, rejected by `dcr run`, no extra linker flags.

Fixed:

- `dcr run` with `--target` or `build.target` now correctly finds the binary in the arch-specific target directory.
- `dcr run` checks profile-specific `build.{profile}.kind` before rejecting library builds (previously only checked `build.kind`).
- `dcr clean` now reads `build.target` from `dcr.toml` when no `--target` flag is given.
- Linux: target directory is now consistent — `target/<arch>-unknown-linux-gnu/<profile>/` (no stale `target/<profile>/`).
- `dcr.lock` is now populated with all resolved dependencies (registry, path, git) instead of being always empty.
- Git dependencies are now properly recognized and recorded in `dcr.lock`.
- `is_registry_dep` correctly identifies version-based registry dependency tables (`{ version = "..." }`) and rejects tables with unknown keys.
- `dcr test` accepts `--debug`/`--release` flags (defaults to `debug` profile instead of always `release`).
- Build fingerprint cache (`build_cache_path`) now includes `target_dir` — different targets no longer share a single cache entry.
- `object_path` no longer hardcodes the `src/` prefix — works correctly with custom `build.roots` (e.g. `roots = ["lib"]`).
- `dcr update` now generates `.exe` candidates for all Windows targets, not just `x86_64-pc-windows-msvc`.
- Compiler existence is verified before starting the build (clear error if compiler is not found in PATH).
- Consolidated duplicate `OUTPUT_MUTEX` definitions — MSVC backend now uses the shared mutex from `common.rs`.
- Registry cache root directory is created if missing (prevents cryptic errors when `~/.dcr/` does not exist).
2026-05-26 16:38:23 +08:00
adfa24f8f4 feat: add AGENTS.md for quick start and CI guidelines; update documentation for dcr add and dcr build commands 2026-05-22 15:14:56 +08:00
ef2fb1e8e4 feat: update version to 0.6.7, enhance build configuration, and add dcr tree command 2026-05-22 14:37:45 +08:00
9ad968374e fix: target system
add: new field in dcr.toml - filename, extension
2026-05-21 00:02:24 +08:00
c4a49cb345 feat: add openssl dependency and update git2 configuration 2026-05-18 16:58:44 +08:00
527a789410 fix: update git2 dependency to use vendored-openssl 2026-05-18 16:46:11 +08:00
6b9e731c7b fix: update git2 dependency to disable default features and enable https 2026-05-18 16:41:01 +08:00
b2854db91b refactor: simplify Linux cross-compilation setup and install cargo-zigbuild 2026-05-18 16:31:29 +08:00
fce9c44181 Merge pull request #7 from dexoron/dev
v0.6.6
2026-05-18 16:15:34 +08:00
3b54500d4d Merge branch 'master' into dev 2026-05-18 16:15:22 +08:00
933fae749d Fixed:
- Path dependencies now work correctly: `dcr add` stores them as `{ path =
"./..." }` tables, `is_registry_dep` properly distinguishes registry strings
from path/git strings, and `deps/mod.rs` resolves both table-form and
legacy string-form path dependencies
- Registry dependency paths no longer hardcoded to `project_root/dcr-index`;
now use `package_root_from_registry_info()` which resolves relative to the
registry cache root (`~/.dcr/`)
- Registry dependencies are now actually built: `build_project_at()` is
called when `include_dir` or `lib_dir` is missing

Added:

- `SIGINT`/`Ctrl+C` handler via `ctrlc` crate — `dcr build` now checks
`BUILD_INTERRUPTED` flag at key points and aborts cleanly
- `utils/build.rs` — extracted shared utilities: `parse_version_info`,
`normalize_target_os`, `resolve_compiler`, `primary_language`,
`resolve_pkg_config_flags` and config helpers. Eliminates code duplication
between `cli/build.rs`, `cli/run.rs`, `cli/clean.rs`, `cli/gen.rs`
- `utils/fs.rs::with_dir` — extracted common directory-scoped execution
- `run_command_sync_output` in `builder/common.rs` with global `OUTPUT_MUTEX`
— synchronized compiler output across all backends (unix_cc, gas, nasm, msvc)
- New helper functions in `deps/register.rs`: `get_registry_cache_root`,
`package_root_from_registry_info`, `registry_include_dir`, `registry_lib_dir`,
`path_from_string_dep`
- Unit tests for `register.rs` (`is_registry_dep`, `package_root_from_registry_info`),
`deps/mod.rs` (`path_dep_path`, `push_default_lib_dirs`),
`utils/build.rs` (`normalize_target_os`, `parse_version_info`)

Removed:

- Removed unused dependencies `indicatif` and `console` from `Cargo.toml`
2026-05-18 16:13:33 +08:00
kie
9ab7ce15db Merge pull request #6 from dexoron/feat-tree
feat: add dcr tree command
2026-05-15 12:44:56 +03:00
peoplemiau1
954f2870ba style: final formatting and clippy fixes for tree.rs 2026-05-15 12:39:28 +03:00
peoplemiau1
9a24a80d59 fix: address clippy warnings in tree.rs 2026-05-15 12:22:05 +03:00
peoplemiau1
a123f647c8 style: fix formatting in tree.rs 2026-05-15 12:10:09 +03:00
peoplemiau1
8f04a37eb0 feat: add dcr tree command to visualize dependencies 2026-05-15 12:06:41 +03:00
441c9f4df3 update: add dev release support and update cross build 2026-05-15 11:40:17 +08:00
60b9c4f983 Merge pull request #5 from peoplemiau1/master
refactor: optimize parallel build and fix architectural issues
2026-05-14 21:35:36 +08:00
peoplemiau1
f5fd273e29 refactor: optimize parallel build and fix architectural issues 2026-05-13 19:35:43 +03:00
d6840fc7a2 Merge pull request #4 from peoplemiau1/master
feat: parallel compilation for all builders
2026-05-14 00:02:02 +08:00
peoplemiau1
f507148849 style: format code according to project standards 2026-05-13 18:59:59 +03:00
peoplemiau1
cfc6be1e95 feat: parallel compilation for all builders 2026-05-13 18:50:42 +03:00
2de836a421 feat: Add installation of Linux cross compilation tools for builds 2026-05-13 20:39:03 +08:00
ed85f801e9 refactor: Improve registry sorting logic for package resolution 2026-05-13 19:43:25 +08:00
9d8dcda366 style: Update macOS target descriptions for clarity 2026-05-13 19:41:26 +08:00
0193834bfd feat: Enhance dependency management and project setup
- Added support for registry-based dependencies in the dependencies section.
- Updated the package section to include a project type field.
- Introduced a new CLI command `dcr setup` to load and display registry configurations.
- Implemented a new module for handling registry operations, including loading and resolving packages from registries.
- Enhanced the build process to handle library packaging, including copying headers and libraries to the appropriate target directories.
- Updated the CLI to support building library packages and added tests for library package builds.
- Improved error handling and output messages during dependency resolution and package fetching.
2026-05-13 19:24:53 +08:00
62 changed files with 3221 additions and 1726 deletions

View File

@@ -15,6 +15,8 @@ permissions:
jobs: jobs:
publish-aur: publish-aur:
# Не публикуем dev/pre-release теги в AUR
if: "!contains(github.ref_name, '-')"
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment: aur environment: aur
steps: steps:
@@ -133,4 +135,4 @@ jobs:
git add PKGBUILD .SRCINFO git add PKGBUILD .SRCINFO
git commit -m "dcr ${{ steps.meta.outputs.pkgver }}" git commit -m "dcr ${{ steps.meta.outputs.pkgver }}"
git push git push

View File

@@ -4,6 +4,11 @@ on:
push: push:
tags: tags:
- "v*" - "v*"
workflow_dispatch:
inputs:
tag:
description: "Tag to build and upload assets for (e.g. v0.6.5)"
required: true
permissions: permissions:
contents: write contents: write
@@ -13,12 +18,21 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
# При ручном запуске чекаутим нужный тег
ref: ${{ github.event.inputs.tag || github.ref }}
- name: Prepare Release Notes - name: Prepare Release Notes
shell: bash shell: bash
run: | run: |
set -euo pipefail set -euo pipefail
tag="${GITHUB_REF_NAME#v}" # При ручном запуске берём версию из инпута, иначе из тега
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
tag="${{ github.event.inputs.tag }}"
tag="${tag#v}"
else
tag="${GITHUB_REF_NAME#v}"
fi
notes_file=".github/release-notes.md" notes_file=".github/release-notes.md"
if grep -q "^## \\[${tag}\\]" CHANGELOG.md; then if grep -q "^## \\[${tag}\\]" CHANGELOG.md; then
awk -v ver="$tag" ' awk -v ver="$tag" '
@@ -42,51 +56,126 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
# ── Linux GNU ──────────────────────────────────────────────────────
- os: ubuntu-latest - os: ubuntu-latest
target: x86_64-unknown-linux-gnu target: x86_64-unknown-linux-gnu
asset_name: dcr-x86_64-unknown-linux-gnu
- os: ubuntu-latest
target: aarch64-unknown-linux-gnu
apt: gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
env_cc: CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc
env_linker: CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
# ── Linux Musl ─────────────────────────────────────────────────────
- os: ubuntu-latest
target: x86_64-unknown-linux-musl
apt: musl-tools
env_cc: CC_x86_64_unknown_linux_musl=musl-gcc
env_linker: CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER=musl-gcc
- os: ubuntu-latest
target: aarch64-unknown-linux-musl
musl_cross: aarch64-linux-musl-cross
env_cc: CC_aarch64_unknown_linux_musl=aarch64-linux-musl-gcc
env_linker: CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-musl-gcc
# ── macOS ──────────────────────────────────────────────────────────
- os: macos-15-intel - os: macos-15-intel
target: x86_64-apple-darwin target: x86_64-apple-darwin
asset_name: dcr-x86_64-apple-darwin
- os: macos-15 - os: macos-latest
target: aarch64-apple-darwin target: aarch64-apple-darwin
asset_name: dcr-aarch64-apple-darwin
# ── Windows MSVC ───────────────────────────────────────────────────
- os: windows-latest - os: windows-latest
target: x86_64-pc-windows-msvc target: x86_64-pc-windows-msvc
asset_name: dcr-x86_64-pc-windows-msvc.exe
- os: windows-latest
target: aarch64-pc-windows-msvc
# ── Windows GNU ────────────────────────────────────────────────────
- os: windows-latest
target: x86_64-pc-windows-gnu
# gnullvm исключён: LLVM MinGW не предустановлен на GitHub Actions
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
needs: notes needs: notes
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.tag || github.ref }}
- name: Download Release Notes - name: Download Release Notes
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
name: release-notes name: release-notes
path: .github path: .github
- name: Install cargo-zigbuild (Linux cross-compilation)
if: runner.os == 'Linux'
run: |
pip install cargo-zigbuild
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Setup LLVM + MinGW (gnullvm)
if: contains(matrix.target, 'gnullvm')
shell: pwsh
run: |
choco install llvm mingw -y --no-progress
echo "C:\Program Files\LLVM\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Setup Rust - name: Setup Rust
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
with: with:
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Build - name: Build
run: cargo build --release --target ${{ matrix.target }} shell: bash
run: |
if [ "${{ runner.os }}" = "Linux" ] && [ "${{ matrix.target }}" != "x86_64-unknown-linux-gnu" ]; then
cargo zigbuild --release --target ${{ matrix.target }}
else
cargo build --release --target ${{ matrix.target }}
fi
- name: Derive version string
shell: bash
run: |
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
RAW_TAG="${{ github.event.inputs.tag }}"
else
RAW_TAG="${GITHUB_REF_NAME}"
fi
echo "RELEASE_TAG=${RAW_TAG}" >> "$GITHUB_ENV"
echo "RELEASE_VERSION=${RAW_TAG#v}" >> "$GITHUB_ENV"
- name: Derive asset name (Unix)
if: runner.os != 'Windows'
shell: bash
run: |
echo "ASSET_NAME=dcr-${{ matrix.target }}-${RELEASE_VERSION}" >> "$GITHUB_ENV"
- name: Derive asset name (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
"ASSET_NAME=dcr-${{ matrix.target }}-$($env:RELEASE_VERSION).exe" >> $env:GITHUB_ENV
- name: Prepare Artifact (Unix) - name: Prepare Artifact (Unix)
if: runner.os != 'Windows' if: runner.os != 'Windows'
shell: bash shell: bash
run: | run: cp target/${{ matrix.target }}/release/dcr "$ASSET_NAME"
cp target/${{ matrix.target }}/release/dcr ${{ matrix.asset_name }}
- name: Prepare Artifact (Windows) - name: Prepare Artifact (Windows)
if: runner.os == 'Windows' if: runner.os == 'Windows'
shell: pwsh shell: pwsh
run: | run: Copy-Item "target/${{ matrix.target }}/release/dcr.exe" "$env:ASSET_NAME"
Copy-Item "target/${{ matrix.target }}/release/dcr.exe" "${{ matrix.asset_name }}"
- name: Upload Release Asset - name: Upload Release Asset
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
files: ${{ matrix.asset_name }} tag_name: ${{ env.RELEASE_TAG }}
files: ${{ env.ASSET_NAME }}
body_path: .github/release-notes.md body_path: .github/release-notes.md
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}

4
.gitignore vendored
View File

@@ -2,4 +2,6 @@ target/
sandbox/** sandbox/**
.idea/ .idea/
.vscode/ .vscode/
.env .env
personal/

126
AGENT.md
View File

@@ -1,126 +0,0 @@
# AGENT.md
## Project Overview
**DCR (Dexoron Cargo Realization)** — CLI-утилита для управления C/C++/ASM проектами в стиле Cargo.
- **Язык реализации**: Rust (edition 2024)
- **Лицензия**: MIT
- **Репозиторий**: [github.com/dexoron/dcr](https://github.com/dexoron/dcr)
## Architecture
### Source Tree (`src/`)
```
src/
├── main.rs # Точка входа, маршрутизация CLI-команд
├── config.rs # Глобальные константы: профили сборки, шаблон main.c
├── cli/ # Реализация CLI-команд
│ ├── new.rs # dcr new <name>
│ ├── init.rs # dcr init
│ ├── build.rs # dcr build [--debug|--release]
│ ├── run.rs # dcr run [--debug|--release]
│ ├── clean.rs # dcr clean [--all]
│ ├── help.rs # dcr --help
│ └── flag_update.rs # dcr --update (self-update через GitHub Releases)
├── core/ # Бизнес-логика
│ ├── config.rs # Парсинг/валидация/форматирование dcr.toml (struct Config)
│ ├── deps.rs # Разрешение path-зависимостей, генерация dcr.lock
│ ├── runner.rs # Запуск скомпилированного бинарника
│ ├── workspace.rs # Поддержка [workspace] и упорядочивание сборки
│ └── builder/ # Бэкенды компиляторов/ассемблеров
│ ├── mod.rs # Общий интерфейс сборки
│ ├── gcc.rs # GCC backend
│ ├── clang.rs # Clang backend
│ ├── msvc.rs # MSVC backend
│ ├── nasm.rs # NASM backend (ASM)
│ └── gas.rs # GAS backend (ASM)
├── platform/ # Платформенно-зависимая логика
│ ├── mod.rs # Общий интерфейс платформ
│ ├── linux.rs
│ ├── macos.rs
│ └── windows.rs
└── utils/ # Вспомогательные утилиты
├── fs.rs # Работа с файловой системой
├── log.rs # Логирование (error, warn)
└── text.rs # Форматирование текста / цвета
```
### Key Concepts
- **`dcr.toml`** — конфигурационный файл проекта (аналог `Cargo.toml`). Секции: `[package]`, `[build]`, `[toolchain]`, `[dependencies]`, `[workspace]`.
- **Профили сборки**: `debug` (по умолчанию) и `release`. Встроенные флаги зависят от компилятора. Пользовательские флаги через `build.cflags` / `build.ldflags`.
- **Инкрементальная сборка**: объектные файлы кешируются по mtime. Отслеживание заголовков пока не реализовано (см. `TODO.md`).
- **Workspace**: корневой `dcr.toml` с секцией `[workspace]` описывает member-проекты и их зависимости; сборка происходит в топологическом порядке.
- **Path dependencies**: зависимости по путям автоматически добавляют include/lib-пути; генерируется `dcr.lock`.
- **Build kinds**: `bin` (бинарник), `staticlib` (`.a`), `sharedlib` (`.so`/`.dylib`/`.dll`).
## Supported Platforms
| Platform | Target triple |
|---|---|
| Linux | `x86_64-unknown-linux-gnu` |
| macOS Intel | `x86_64-apple-darwin` |
| macOS ARM | `aarch64-apple-darwin` |
| Windows | `x86_64-pc-windows-msvc` |
## Dependencies (Cargo)
| Crate | Purpose |
|---|---|
| `reqwest` | HTTP-запросы для `--update` (blocking, rustls-tls) |
| `serde` | Сериализация/десериализация |
| `toml` | Парсинг `dcr.toml` |
| `sha2` | Хеширование при обновлении |
| `self-replace` | Замена бинарника при `--update` |
## Development
### Build & Run
```bash
cargo build # debug build
cargo build --release # release build
cargo run -- new hello # создать проект "hello"
```
### Code Quality
```bash
cargo fmt --all
cargo clippy --all-targets --all-features -- -D warnings
cargo check
cargo test
```
### CI/CD
- **CI**: `.github/workflows/ci.yml` — проверки при PR/push
- **Release**: `.github/workflows/release.yml` — сборка бинарников при пуше тега `v*`
### Tests
- Интеграционные CLI-тесты: `tests/cli_basic.rs`
## Code Conventions
- Rust stable edition 2024
- Форматирование: `cargo fmt`
- Линтинг: `cargo clippy` без warnings
- Функции — маленькие и сфокусированные
- Имена — понятные и описательные
- Пользовательские сообщения CLI — на английском языке
- Вывод ошибок/предупреждений через `utils::log::{error, warn}`
## TODO
- В файле `TODO.md`
## Useful Links
- Документация проекта: `docs/`
- Changelog: `CHANGELOG.md`
- Contributing: `CONTRIBUTING.md`
- FAQ: `FAQ.md`
- Установка: `install.sh` (Linux/macOS), `install.ps1` (Windows)

56
AGENTS.md Normal file
View File

@@ -0,0 +1,56 @@
# AGENTS.md
## Quick start
```bash
cargo build --release && ./target/release/dcr setup
```
## Pre-PR (CI) gate
```bash
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo check --all-targets --all-features
cargo test
```
CI (`.github/workflows/ci.yml`) runs fmt, clippy, check — **not** tests.
## Tests
- Integration tests in `tests/` build the dcr binary and run it in temp dirs under `sandbox/cli-tests/` (gitignored).
- Some tests **skip** if no C compiler (`gcc`/`clang`/`cc`) is found at runtime.
- Compiler can be overridden via `DCR_COMPILER` or `DCR_CC` env vars.
- Tests use `$CARGO_BIN_EXE_dcr` when available, else `target/debug/dcr`.
## Architecture
- **Single Rust package** (edition 2024), not a workspace. Only one binary: `dcr`.
- **Entrypoint**: `src/main.rs` — matches `args[1]` against command names.
- **Compiler backends** in `src/core/builder/`: `unix_cc` (gcc/clang), `msvc` (cl/clang-cl), `gas`, `nasm`. Dispatched by matching compiler name string.
- **Config**: `dcr.toml` (per-project), `~/.dcr/config.toml` (registry), `~/.dcr/index.json` (index). Defaults: `language=c`, `standard=c11`, `compiler=clang`, `kind=bin`.
- **`build.rs`** embeds `TARGET` as `DCR_TARGET` env var (shown in `--version`).
- **CLI output** must be in English. Use `utils::log` for messaging.
## Key commands
| Command | Notes |
|---|---|
| `dcr new <name>` | Creates project dir |
| `dcr init` | Init from CWD (must be empty) |
| `dcr build [--debug\|--release] [--target <triple>]` | Default profile: `--debug` |
| `dcr run [--debug\|--release]` | Only for `kind = "bin"` |
| `dcr clean [--debug\|--release] [--all]` | `--all` for workspace roots |
| `dcr tree` | Dependency tree viewer |
| `dcr test [--init]` | Runs/test project tests |
| `dcr gen <vscode\|clion\|compile-commands>` | IDE integration |
| `dcr --update` | Self-update from GitHub Releases |
## Cross-compilation
`--target` accepts short names (`linux`, `macos`, `windows`) or full triples. In CI, Linux cross-builds use `cargo-zigbuild`. When `build.target` is set in `dcr.toml`, DCR auto-injects `--target=<value>` into cflags (clang). Bare-metal targets (containing `none`/`-elf`/`eabi`/`baremetal`) skip DCR's default compiler flags.
## Dependencies (Cargo)
reqwest (blocking+json+rustls-tls), serde, toml, git2, openssl (vendored), self-replace, sha2, ctrlc.

View File

@@ -1,5 +1,101 @@
# Changelog # Changelog
## [0.6.7] - 2026-05-26
Added:
- `build.kind = "efi"` — UEFI PE32+ executable support. Links with `-shared -nostdlib -Wl,-dll -Wl,--subsystem,10`, output via `efi_path()` with `.efi` extension, rejected by `dcr run`.
- `build.kind = "elf"` — bare-metal ELF executable support. Uses `elf_path()` output path, rejected by `dcr run`, no extra linker flags.
- `build.filename` and `build.extension` in `dcr.toml` — complete control over the final artifact name without relying on `package.name`.
Example:
```toml
[build]
filename = "KERNEL"
extension = "EFI"
```
Produces `KERNEL.EFI` (works for `bin`, `staticlib`, and `sharedlib`).
- Automatic injection of `--target=<build.target>` into compiler flags when `build.target` is set in `dcr.toml`. This greatly simplifies clang-based cross-compilation (especially for bare-metal targets like `aarch64-none-elf`).
- Bare-metal targets (containing `none`, `-elf`, `eabi`, `baremetal`) no longer receive DCR's internal default flags (`-g`, `-Wall`, `-Wextra`, `-fno-omit-frame-pointer`, `-DDCR_DEBUG`, etc.). Prevents unwanted sections (`.comment`, debug info, etc.) that break custom linker scripts when `inherit = true`.
- `build.ldscript` in `dcr.toml` — linker script path passed as `-T <path>` to the linker. Essential for bare-metal/embedded/freestanding targets.
- `dcr build --verbose` — prints compiler/linker command lines (also works with `DCR_DEBUG` env var).
- `dcr add <name>` without a source argument — if a registry is configured, DCR looks up the package by name and adds it as a version dependency.
Fixed:
- `build.target` declared in `dcr.toml` is now correctly used as the default target even when `--target` is not passed on the command line (previously the host target was always forced for config resolution).
- `dcr run` with `--target` or `build.target` now correctly finds the binary in the arch-specific target directory.
- `dcr run` checks profile-specific `build.{profile}.kind` before rejecting library builds (previously only checked `build.kind`).
- `dcr clean` now reads `build.target` from `dcr.toml` when no `--target` flag is given.
- Linux: target directory is now consistent — `target/<arch>-unknown-linux-gnu/<profile>/` (no stale `target/<profile>/`).
- `dcr.lock` is now populated with all resolved dependencies (registry, path, git) instead of being always empty.
- Git dependencies are now properly recognized and recorded in `dcr.lock`.
- `is_registry_dep` correctly identifies version-based registry dependency tables (`{ version = "..." }`) and rejects tables with unknown keys.
- `dcr test` accepts `--debug`/`--release` flags (defaults to `debug` profile instead of always `release`).
- Build fingerprint cache (`build_cache_path`) now includes `target_dir` — different targets no longer share a single cache entry.
- `object_path` no longer hardcodes the `src/` prefix — works correctly with custom `build.roots` (e.g. `roots = ["lib"]`).
- `dcr update` now generates `.exe` candidates for all Windows targets, not just `x86_64-pc-windows-msvc`.
- Compiler existence is verified before starting the build (clear error if compiler is not found in PATH).
- Consolidated duplicate `OUTPUT_MUTEX` definitions — MSVC backend now uses the shared mutex from `common.rs`.
- Registry cache root directory is created if missing (prevents cryptic errors when `~/.dcr/` does not exist).
Changed:
- `openssl` dependency is now conditional (`cfg(not(windows))`) — no longer pulled in on Windows, fixing Windows CI builds that lack Perl `Locale::Maketext::Simple`. On Linux (including musl cross-compilation) the vendored OpenSSL build is unchanged.
## [0.6.6] - 2026-05-18
Fixed:
- Path dependencies now work correctly: `dcr add` stores them as `{ path =
"./..." }` tables, `is_registry_dep` properly distinguishes registry strings
from path/git strings, and `deps/mod.rs` resolves both table-form and
legacy string-form path dependencies
- Registry dependency paths no longer hardcoded to `project_root/dcr-index`;
now use `package_root_from_registry_info()` which resolves relative to the
registry cache root (`~/.dcr/`)
- Registry dependencies are now actually built: `build_project_at()` is
called when `include_dir` or `lib_dir` is missing
Added:
- `SIGINT`/`Ctrl+C` handler via `ctrlc` crate — `dcr build` now checks
`BUILD_INTERRUPTED` flag at key points and aborts cleanly
- `utils/build.rs` — extracted shared utilities: `parse_version_info`,
`normalize_target_os`, `resolve_compiler`, `primary_language`,
`resolve_pkg_config_flags` and config helpers. Eliminates code duplication
between `cli/build.rs`, `cli/run.rs`, `cli/clean.rs`, `cli/gen.rs`
- `utils/fs.rs::with_dir` — extracted common directory-scoped execution
- `run_command_sync_output` in `builder/common.rs` with global `OUTPUT_MUTEX`
— synchronized compiler output across all backends (unix_cc, gas, nasm, msvc)
- New helper functions in `deps/register.rs`: `get_registry_cache_root`,
`package_root_from_registry_info`, `registry_include_dir`, `registry_lib_dir`,
`path_from_string_dep`
- Unit tests for `register.rs` (`is_registry_dep`, `package_root_from_registry_info`),
`deps/mod.rs` (`path_dep_path`, `push_default_lib_dirs`),
`utils/build.rs` (`normalize_target_os`, `parse_version_info`)
- `dcr tree` command — visual dependency tree viewer (similar to `cargo tree`)
Removed:
- Removed unused dependencies `indicatif` and `console` from `Cargo.toml`
## [0.6.5] - 2026-05-13
Added:
- New dependency registry system
- Package type support (`lib`, `app`, `none`) in `dcr.toml`
- Library packaging functionality: automatically generates `include` and `lib` directories in `target/` for `lib` type projects
- Expanded CI build targets:
- Linux: `aarch64-unknown-linux-gnu`, `x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`
- Windows: `aarch64-pc-windows-msvc`, `x86_64-pc-windows-gnu`, `aarch64-pc-windows-gnullvm`
Changed:
- `src/core/deps/` modular architecture overhaul
- Native platform pathing defaults for Linux (now dynamic architecture detection)
- Improved `run` command output handling
## [0.6.0] - 2026-05-12 ## [0.6.0] - 2026-05-12
Added: Added:

167
Cargo.lock generated
View File

@@ -35,6 +35,15 @@ dependencies = [
"generic-array", "generic-array",
] ]
[[package]]
name = "block2"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [
"objc2",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.19.1" version = "3.19.1"
@@ -71,18 +80,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "console"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
dependencies = [
"encode_unicode",
"libc",
"unicode-width",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.17" version = "0.2.17"
@@ -103,16 +100,28 @@ dependencies = [
] ]
[[package]] [[package]]
name = "dcr" name = "ctrlc"
version = "0.6.0" version = "3.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162"
dependencies = [ dependencies = [
"console", "dispatch2",
"nix",
"windows-sys 0.61.2",
]
[[package]]
name = "dcr"
version = "0.6.7"
dependencies = [
"ctrlc",
"git2", "git2",
"glob", "glob",
"indicatif", "openssl",
"reqwest", "reqwest",
"self-replace", "self-replace",
"serde", "serde",
"serde_json",
"sha2", "sha2",
"toml", "toml",
] ]
@@ -127,6 +136,18 @@ dependencies = [
"crypto-common", "crypto-common",
] ]
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags",
"block2",
"libc",
"objc2",
]
[[package]] [[package]]
name = "displaydoc" name = "displaydoc"
version = "0.2.5" version = "0.2.5"
@@ -138,12 +159,6 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "encode_unicode"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@@ -178,6 +193,21 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.2" version = "1.2.2"
@@ -548,19 +578,6 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "indicatif"
version = "0.18.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25470f23803092da7d239834776d653104d551bc4d7eacaf31e6837854b8e9eb"
dependencies = [
"console",
"portable-atomic",
"unicode-width",
"unit-prefix",
"web-time",
]
[[package]] [[package]]
name = "ipnet" name = "ipnet"
version = "2.11.0" version = "2.11.0"
@@ -696,18 +713,79 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "nix"
version = "0.31.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d6d0705320c1e6ba1d912b5e37cf18071b6c2e9b7fa8215a1e8a7651966f5d3"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "objc2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.3" version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "openssl"
version = "0.10.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf0b434746ee2832f4f0baf10137e1cabb18cbe6912c69e2e33263c45250f542"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "openssl-probe" name = "openssl-probe"
version = "0.1.6" version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
[[package]]
name = "openssl-src"
version = "300.6.0+3.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8e8cbfd3a4a8c8f089147fd7aaa33cf8c7450c4d09f8f80698a0cf093abeff4"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "openssl-sys" name = "openssl-sys"
version = "0.9.115" version = "0.9.115"
@@ -716,6 +794,7 @@ checksum = "158fe5b292746440aa6e7a7e690e55aeb72d41505e2804c23c6973ad0e9c9781"
dependencies = [ dependencies = [
"cc", "cc",
"libc", "libc",
"openssl-src",
"pkg-config", "pkg-config",
"vcpkg", "vcpkg",
] ]
@@ -744,12 +823,6 @@ version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "portable-atomic"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.4" version = "0.1.4"
@@ -1372,24 +1445,12 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.6" version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "unit-prefix"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
[[package]] [[package]]
name = "untrusted" name = "untrusted"
version = "0.9.0" version = "0.9.0"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "dcr" name = "dcr"
version = "0.6.0" version = "0.6.7"
edition = "2024" edition = "2024"
build = "build.rs" build = "build.rs"
@@ -11,6 +11,9 @@ serde = { version = "1", features = ["derive"] }
self-replace = "1" self-replace = "1"
sha2 = "0.10" sha2 = "0.10"
toml = "1.0.3" toml = "1.0.3"
indicatif = "0.18.4"
console = "0.16.3"
git2 = "0.20.4" git2 = "0.20.4"
serde_json = "1"
ctrlc = "3"
[target.'cfg(not(windows))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }

View File

@@ -16,19 +16,21 @@ The current implementation is written in Rust.
- Clean build artifacts - Clean build artifacts
- Generate IDE integration files (VS Code, CLion) and compilation databases - Generate IDE integration files (VS Code, CLion) and compilation databases
- Generate a minimal C project template - Generate a minimal C project template
- Build static and shared libraries - Build static, shared libraries, UEFI PE32+ executables, and bare-metal ELF executables
- Git and Path dependency support with `dcr.lock` and automatic resolution - Dependency management:
- Git and Path dependencies with `dcr.lock`
- Registry-based dependency resolution
- Library packaging functionality (auto-generate `include/` and `lib/` for `type = "lib"` packages)
- ASM projects with NASM/GAS or via GCC/Clang - ASM projects with NASM/GAS or via GCC/Clang
- Mixed language projects (`language = ["c", "asm"]` and similar) - Mixed language projects
- Cross-compilation with `--target` (short names: `linux`, `macos`, `windows`) - Cross-compilation with `--target` (full triple support and short names)
- Target-specific configurations and inheritance - Target-specific configurations and inheritance
- Update the binary via `dcr --update` (GitHub Releases, not for pacman/AUR installs) - Update the binary via `dcr --update` (GitHub Releases)
## Supported Platforms ## Supported Platforms
- Linux: `x86_64-unknown-linux-gnu` - Linux: x86_64/aarch64 (GNU and Musl)
- macOS Intel: `x86_64-apple-darwin` - macOS: x86_64/aarch64
- macOS Apple Silicon: `aarch64-apple-darwin` - Windows: x86_64/aarch64 (MSVC, GNU, LLVM)
- Windows: `x86_64-pc-windows-msvc`
## Installation ## Installation
@@ -107,9 +109,13 @@ Creates a project with the specified name in the current directory.
### `dcr init` ### `dcr init`
Creates a project in the current directory. The project name is taken from the directory name. The directory must be empty. Creates a project in the current directory. The project name is taken from the directory name. The directory must be empty.
### `dcr setup`
Initializes the registry system by reading `~/.dcr/config.toml` and verifying the availability of configured indices.
### `dcr add <name> <source>` ### `dcr add <name> <source>`
Adds a dependency to `dcr.toml`. Adds a dependency to `dcr.toml`.
Sources can be `path:`, `github:`, `gitlab:`, `git:`, or a full URL. If a registry is configured, `dcr` automatically finds the package.
Git/Path syntax: `path:`, `github:`, `gitlab:`, `git:`, or a full URL.
Use `--branch`, `--tag`, or `--rev` for Git dependencies. Use `--branch`, `--tag`, or `--rev` for Git dependencies.
### `dcr build [profile]` ### `dcr build [profile]`
@@ -148,7 +154,9 @@ You can also set `build.target` to override the output directory (profile-indepe
You can set `build.platform` to pass `-march=<platform>` (GCC/Clang) or `/arch:*` (MSVC) where supported. You can set `build.platform` to pass `-march=<platform>` (GCC/Clang) or `/arch:*` (MSVC) where supported.
Use `build.kind = "staticlib"` to build a static library instead of a binary. Use `build.kind = "staticlib"` to build a static library instead of a binary.
Use `build.kind = "sharedlib"` to build a shared library (`.so`/`.dylib`/`.dll`). Use `build.kind = "sharedlib"` to build a shared library (`.so`/`.dylib`/`.dll`).
`dcr run` is only for `build.kind = "bin"` and will fail for libraries. Use `build.kind = "efi"` to build a UEFI PE32+ executable (`.efi`).
Use `build.kind = "elf"` to build a bare-metal ELF executable.
`dcr run` is only for `build.kind = "bin"` and will fail for libraries, EFI, and ELF.
Use `build.exclude`/`build.include` to control source/header collection. Use `build.exclude`/`build.include` to control source/header collection.
Use `build.roots` and `build.src_disable` to replace the default `src/` root. Use `build.roots` and `build.src_disable` to replace the default `src/` root.
Use `build.steps` and `build.post_steps` to run custom commands. Use `build.steps` and `build.post_steps` to run custom commands.
@@ -183,6 +191,7 @@ See [Cross-compilation guide](docs/dependencies-and-build/cross-compilation.md)
## Configuration ## Configuration
The main project file is `dcr.toml`. The main project file is `dcr.toml`.
For multi-registry management, use `~/.dcr/config.toml`.
Example `dcr.toml`: Example `dcr.toml`:
@@ -190,11 +199,13 @@ Example `dcr.toml`:
[package] [package]
name = "hello" name = "hello"
version = "0.1.0" version = "0.1.0"
type = "app" # or "lib", "none"
[build] [build]
language = "c" language = "c"
standard = "c11" standard = "c11"
compiler = "clang" compiler = "clang"
kind = "bin" # "bin", "staticlib", "sharedlib", "efi", "elf"
# Optional platform hint # Optional platform hint
# platform = "x86_64" # platform = "x86_64"
# Optional custom flags # Optional custom flags

View File

@@ -27,6 +27,7 @@
* [dcr clean](commands/dcr-clean.md) * [dcr clean](commands/dcr-clean.md)
* [dcr gen](commands/dcr-gen.md) * [dcr gen](commands/dcr-gen.md)
* [dcr test](commands/dcr-test.md) * [dcr test](commands/dcr-test.md)
* [dcr tree](commands/dcr-tree.md)
## Dependencies & Build ## Dependencies & Build

View File

@@ -5,11 +5,15 @@ Add a dependency to `dcr.toml`.
## Usage ## Usage
```bash ```bash
dcr add <name> <source> [options] dcr add <name> [source] [options]
``` ```
If `<source>` is omitted and a registry is configured, DCR will look up the
package by name in the registry and add it as a version dependency.
## Sources ## Sources
- *omitted*: Look up in the configured registry.
- `path:./path/to/lib`: Local directory. - `path:./path/to/lib`: Local directory.
- `github:user/repo`: GitHub repository. - `github:user/repo`: GitHub repository.
- `gitlab:user/repo`: GitLab repository. - `gitlab:user/repo`: GitLab repository.
@@ -29,4 +33,5 @@ dcr add my_lib path:./libs/my_lib
dcr add cool_lib github:user/cool_lib dcr add cool_lib github:user/cool_lib
dcr add shared_lib gitlab:org/shared --branch develop dcr add shared_lib gitlab:org/shared --branch develop
dcr add custom_lib git:git.internal.com/r/lib --tag v1.0.0 dcr add custom_lib git:git.internal.com/r/lib --tag v1.0.0
dcr add mylib # Looks up in registry
``` ```

View File

@@ -25,6 +25,8 @@ dcr build --debug --clean
## Config values used ## Config values used
- `package.name` - `package.name`
- `build.filename`
- `build.extension`
- `build.compiler` - `build.compiler`
- `build.language` - `build.language`
- `build.standard` - `build.standard`
@@ -33,6 +35,7 @@ dcr build --debug --clean
- `build.platform` - `build.platform`
- `build.cflags` - `build.cflags`
- `build.ldflags` - `build.ldflags`
- `build.ldscript`
- `build.debug` / `build.release` - `build.debug` / `build.release`
- `build.exclude` - `build.exclude`
- `build.include` - `build.include`
@@ -56,11 +59,16 @@ dcr build --debug --clean
- Profile flag (`--debug` / `--release`) can appear in any argument position (duplicates are rejected). - Profile flag (`--debug` / `--release`) can appear in any argument position (duplicates are rejected).
- Unknown profile flags return an error. - Unknown profile flags return an error.
- `--target <triple>` builds for specified target (short names: `linux`, `macos`, `windows`). - `--target <triple>` builds for specified target (short names: `linux`, `macos`, `windows`).
- `--verbose` prints the compiler/linker command lines to stderr (also works via `DCR_DEBUG` env var).
- If no `--target`, builds for `build.targets` or native. - If no `--target`, builds for `build.targets` or native.
- Incremental rebuild checks source/object mtime and tracked header dependencies. - Incremental rebuild checks source/object mtime and tracked header dependencies.
- `--force` skips build cache checks and recompiles. - `--force` skips build cache checks and recompiles.
- `--clean` removes `target/<profile>` and `build.clean` paths before building. - `--clean` removes `target/<profile>` and `build.clean` paths before building.
- `build.filename` + `build.extension` allow full control over the final artifact name (e.g. `KERNEL.BIN` instead of using `package.name`). When `build.kind = "efi"`, the output is a PE32+ executable with `.efi` extension.
- `build.kind = "efi"` links with `-shared -nostdlib -Wl,-dll -Wl,--subsystem,10` for UEFI PE32+ format. Use `build.filename` and `build.extension` for full control over the artifact name.
- `build.kind = "elf"` produces a bare-metal ELF executable. Linking flags are user-controlled via `build.ldflags` (no PIE/CRT defaults are added).
- Default GCC/Clang profile flags: `debug` -> `-O0 -g -Wall -Wextra -fno-omit-frame-pointer -DDCR_DEBUG`, `release` -> `-O3 -DNDEBUG`. - Default GCC/Clang profile flags: `debug` -> `-O0 -g -Wall -Wextra -fno-omit-frame-pointer -DDCR_DEBUG`, `release` -> `-O3 -DNDEBUG`.
These defaults are **not applied** for bare-metal targets (e.g. `aarch64-none-elf`, targets containing `none` / `-elf` / `eabi`).
- For `language = "asm"` with `compiler = "as"`/`"gas"`, use `.s` files (no preprocessing). For `.S`, use `gcc` or `clang`. - For `language = "asm"` with `compiler = "as"`/`"gas"`, use `.s` files (no preprocessing). For `.S`, use `gcc` or `clang`.
- In workspace root, `dcr build` builds all members in dependency order. - In workspace root, `dcr build` builds all members in dependency order.
- `build.exclude` removes paths from source/header collection; `build.include` re-allows matching paths and has priority over `exclude`. - `build.exclude` removes paths from source/header collection; `build.include` re-allows matching paths and has priority over `exclude`.

View File

@@ -15,7 +15,7 @@ dcr clean --release --all
## Behavior ## Behavior
- Without arguments: removes entire `target/`. - Without arguments: removes entire `target/`.
- With profile: removes only `target/<profile>/`. - With profile: removes only the profile-specific directory. Respects `build.target` from config: if `build.target = "aarch64-unknown-linux-gnu"`, cleans `target/aarch64-unknown-linux-gnu/<profile>/`.
- With `--all`: also cleans all workspace members. - With `--all`: also cleans all workspace members.
- Additionally removes paths from `build.clean` if configured. - Additionally removes paths from `build.clean` if configured.
- `build.clean` supports `{profile}` and version placeholders. - `build.clean` supports `{profile}` and version placeholders.

View File

@@ -23,7 +23,7 @@ dcr run --debug --clean
## Restrictions ## Restrictions
- If `build.kind = "staticlib"` or `build.kind = "sharedlib"`, `run` exits with error. - If `build.kind` (or `build.{profile}.kind`) is `"staticlib"` or `"sharedlib"`, `run` exits with error.
- The profile is selected from the first argument. - The profile is selected from the first argument.
- `--target <triple>` runs the binary for specified target (short names: `linux`, `macos`, `windows`). - `--target <triple>` runs the binary for specified target (short names: `linux`, `macos`, `windows`).
- `--force` skips build cache checks and recompiles. - `--force` skips build cache checks and recompiles.

View File

@@ -6,6 +6,7 @@ Runs the project's test suite.
```sh ```sh
dcr test dcr test
dcr test --debug
dcr test --release dcr test --release
dcr test --target linux dcr test --target linux
dcr test --init dcr test --init
@@ -39,6 +40,6 @@ DCR uses a simple test framework:
- Test binary is linked with the main project (for lib projects) or standalone. - Test binary is linked with the main project (for lib projects) or standalone.
- `--init` creates `tests/dcr_test.h` and `tests/test.c` if missing. - `--init` creates `tests/dcr_test.h` and `tests/test.c` if missing.
- Tests run in release mode by default for performance. - Tests run in debug mode by default. Use `--release` for release mode.
- Custom test logic can be added by editing `tests/test.c`. - Custom test logic can be added by editing `tests/test.c`.
- Fails if no `tests/test.c` exists (run `dcr test --init` first). - Fails if no `tests/test.c` exists (run `dcr test --init` first).

22
docs/commands/dcr-tree.md Normal file
View File

@@ -0,0 +1,22 @@
# dcr tree
Displays a visual dependency tree for the current project (similar to `cargo tree`).
## Usage
```sh
dcr tree
dcr tree --invert
dcr tree -p some-package
```
## What it shows
- All direct and transitive dependencies
- Version of each dependency
- Whether a dependency is a registry, git, or path dependency
## Notes
- Useful for debugging dependency issues and understanding the build graph.
- Output format is inspired by `cargo tree`.

View File

@@ -8,6 +8,8 @@ language = "c"
standard = "c11" standard = "c11"
compiler = "clang" compiler = "clang"
kind = "bin" kind = "bin"
# filename = "KERNEL"
# extension = "BIN"
# optional: # optional:
# inherit = true # Inherit from base (default true) # inherit = true # Inherit from base (default true)
# targets = ["linux", "macos"] # Multiple targets to build # targets = ["linux", "macos"] # Multiple targets to build
@@ -31,13 +33,17 @@ kind = "bin"
Mixed languages can be specified as an array, for example `["c", "c++", "asm"]`. Mixed languages can be specified as an array, for example `["c", "c++", "asm"]`.
- `standard` (string, required): language standard passed to compiler. - `standard` (string, required): language standard passed to compiler.
- `compiler` (string, required): compiler command (for example `clang`, `gcc`, `cl`). - `compiler` (string, required): compiler command (for example `clang`, `gcc`, `cl`).
- `kind` (string, required): `bin`, `staticlib`, or `sharedlib`. - `kind` (string, required): `bin`, `staticlib`, `sharedlib`, `efi`, or `elf`.
- `filename` (string, optional): custom output filename (without extension). Overrides `package.name` for the final artifact.
- `extension` (string, optional): custom file extension without the leading dot (e.g. `BIN`, `efi`, `EFI`). Combined with `filename`.
- `inherit` (bool, optional): inherit settings from base `[build]` (default `true`). If `false`, only use target/profile specific settings. - `inherit` (bool, optional): inherit settings from base `[build]` (default `true`). If `false`, only use target/profile specific settings.
- `targets` (string array, optional): list of targets to build simultaneously. Supports short names (`linux`, `macos`, `windows`). - `targets` (string array, optional): list of targets to build simultaneously. Supports short names (`linux`, `macos`, `windows`).
- `target` (string, optional): custom output directory for final artifact. - `target` (string, optional): custom output directory for final artifact.
When set, DCR automatically injects `--target=<value>` into `cflags` (useful for clang cross-compilation).
- `platform` (string, optional): architecture hint for compiler (used for `-march` or `/arch`). - `platform` (string, optional): architecture hint for compiler (used for `-march` or `/arch`).
- `cflags` (string array, optional): extra compile flags. - `cflags` (string array, optional): extra compile flags.
- `ldflags` (string array, optional): extra link flags. - `ldflags` (string array, optional): extra link flags.
- `ldscript` (string, optional): linker script path. Passed as `-T <path>` to the linker. Useful for bare-metal/embedded/freestanding targets.
- `exclude` (string array, optional): paths or glob patterns to skip during source/header collection. - `exclude` (string array, optional): paths or glob patterns to skip during source/header collection.
- `include` (string array, optional): allowlist paths or globs that override `exclude`. - `include` (string array, optional): allowlist paths or globs that override `exclude`.
- `include` directory entries (non-glob) are also passed to the compiler as `-I` include paths. - `include` directory entries (non-glob) are also passed to the compiler as `-I` include paths.
@@ -145,4 +151,4 @@ rcc = "rcc"
- Compiler backend is selected by compiler string (`gcc`, `clang`, `cl`, `clang-cl`). - Compiler backend is selected by compiler string (`gcc`, `clang`, `cl`, `clang-cl`).
- Empty or unknown compiler value falls back to clang-like build path. - Empty or unknown compiler value falls back to clang-like build path.
- `run` is not allowed for library kinds (`staticlib`, `sharedlib`). - `run` is not allowed for library kinds (`staticlib`, `sharedlib`), `efi`, or `elf`.

View File

@@ -1,23 +1,36 @@
# Dependencies section # Dependencies section
DCR currently supports path dependencies. DCR supports registry-based dependencies and path dependencies.
## Example ## Example
```toml ```toml
[dependencies] [dependencies]
# Registry dependency
mylib = "0.1.0"
# Git dependency
json = { git = "https://github.com/nlohmann/json", tag = "v3.11.2" }
# Path dependency
frecli = { path = "./lib/frecli", include = ["."], lib = ["."], libs = ["frecli"] } frecli = { path = "./lib/frecli", include = ["."], lib = ["."], libs = ["frecli"] }
``` ```
## Supported fields per dependency ## Supported dependency types
### Registry dependencies
Defined by name and version string. DCR automatically resolves the package from the configured registry index.
### Git dependencies
Defined by repository URL and optionally branch, tag, or revision.
- `git` (string, required): repository URL.
- `branch`, `tag`, `rev` (string, optional): Git reference.
### Path dependencies
- `path` (string, required): absolute path or path relative to project root. - `path` (string, required): absolute path or path relative to project root.
- `include` (string array, optional): include directories inside dependency. - `include` (string array, optional): include directories inside dependency.
- `lib` (string array, optional): library directories inside dependency. - `lib` (string array, optional): library directories inside dependency.
- `libs` (string array, optional): library names for linker. - `libs` (string array, optional): library names for linker.
- `system` (bool, optional): currently `system = true` is rejected.
## Defaults ## Defaults for path dependencies
- If `include` is omitted, DCR tries `<dep>/include`. - If `include` is omitted, DCR tries `<dep>/include`.
- If `lib` is omitted, DCR tries `<dep>/lib`, then `<dep>/lib64`. - If `lib` is omitted, DCR tries `<dep>/lib`, then `<dep>/lib64`.
@@ -25,6 +38,7 @@ frecli = { path = "./lib/frecli", include = ["."], lib = ["."], libs = ["frecli"
## Validation ## Validation
- Dependency value must be a TOML table. - Dependency value must be a string (registry) or a TOML table (path).
- `path` is mandatory. - Registry dependencies use the version string to match versions in the registry.
- `path` is mandatory for path dependencies.
- `include`/`lib`/`libs` must be arrays of strings if provided. - `include`/`lib`/`libs` must be arrays of strings if provided.

View File

@@ -6,15 +6,18 @@
[package] [package]
name = "my-app" name = "my-app"
version = "0.1.0" version = "0.1.0"
type = "app"
``` ```
## Fields ## Fields
- `name` (string, required): used as output artifact base name. - `name` (string, required): used as output artifact base name.
- `version` (string, required): used in `dcr.lock` project entry. - `version` (string, required): used in `dcr.lock` project entry.
- `type` (string, optional): project type (`app`, `lib`, `none`).
## Notes ## Notes
- Empty `name` or `version` makes config invalid. - Empty `name` or `version` makes config invalid.
- `dcr new` sets `name` from the passed project name. - `dcr new` sets `name` from the passed project name.
- `dcr init` sets `name` from current directory name. - `dcr init` sets `name` from current directory name.
- If `type = "lib"`, DCR generates `include/` and `lib/` directories in the target path, copying public headers and built libraries.

View File

@@ -178,6 +178,8 @@ compiler = "aarch64-linux-gnu-gcc"' >> dcr.toml
dcr build --target aarch64-linux-gnu --release dcr build --target aarch64-linux-gnu --release
``` ```
**Note:** If you set `target = "aarch64-linux-gnu"` (or any value) directly under `[build]`, DCR will automatically add `--target=...` to cflags when using clang. You usually don't need to repeat it manually.
### Windows Build on Linux ### Windows Build on Linux
```bash ```bash

View File

@@ -49,7 +49,7 @@ dcr clean --release --all
## Notes ## Notes
- `run` is unavailable for `build.kind = "staticlib"` and `build.kind = "sharedlib"`. - `run` is unavailable for `build.kind = "staticlib"`, `build.kind = "sharedlib"`, `build.kind = "efi"`, and `build.kind = "elf"`.
- Build profile flag (`--debug` / `--release`) can be passed in any argument position. - Build profile flag (`--debug` / `--release`) can be passed in any argument position.
- Unknown profile flags produce an error. - Unknown profile flags produce an error.
- In workspace root, `clean --all` cleans all member projects. - In workspace root, `clean --all` cleans all member projects.

View File

@@ -5,9 +5,13 @@
```text ```text
dcr new <name> dcr new <name>
dcr init dcr init
dcr build [--debug|--release] dcr setup
dcr add <name> <source>(optional)
dcr build [--debug|--release] [--target <triple>]
dcr run [--debug|--release] dcr run [--debug|--release]
dcr clean [--debug|--release] [--all] dcr clean [--debug|--release] [--all]
dcr tree
dcr test
dcr gen <subcommand> dcr gen <subcommand>
dcr --help dcr --help
dcr --version dcr --version
@@ -16,11 +20,13 @@ dcr --update
## Notes on argument parsing ## Notes on argument parsing
- `build`/`run` parse flags in any order (`--debug|--release`, `--force`, `--clean`) and reject duplicates. - `build`/`run` parse flags in any order (`--debug|--release`, `--force`, `--clean`, `--verbose`) and reject duplicates.
- `new` requires exactly one argument. - `new` requires exactly one argument.
- `init` and `--update` do not accept extra arguments. - `init` and `--update` do not accept extra arguments.
- `clean` accepts `--debug|--release` and optional `--all`. - `clean` accepts `--debug|--release` and optional `--all`.
- `gen` supports `project-info`, `compile-commands`, `vscode`, `clion`. - `gen` supports `project-info`, `compile-commands`, `vscode`, `clion`.
- `tree` shows a dependency tree (similar to `cargo tree`).
- `test` / `tests` runs the project's tests.
## Exit behavior overview ## Exit behavior overview

View File

@@ -12,10 +12,13 @@ language = "c|c++|cpp|cxx|asm" # required (string or array)
standard = "string" # required standard = "string" # required
compiler = "string" # required compiler = "string" # required
kind = "bin|staticlib|sharedlib" # required kind = "bin|staticlib|sharedlib" # required
filename = "string" # optional (custom output name without extension)
extension = "string" # optional (custom extension without dot, e.g. "BIN")
target = "string" # optional target = "string" # optional
platform = "string" # optional platform = "string" # optional
cflags = ["string", "..."] # optional cflags = ["string", "..."] # optional
ldflags = ["string", "..."] # optional ldflags = ["string", "..."] # optional
ldscript = "string" # optional (linker script, passed as -T<path>)
exclude = ["string", "..."] # optional exclude = ["string", "..."] # optional
include = ["string", "..."] # optional include = ["string", "..."] # optional
roots = ["string", "..."] # optional roots = ["string", "..."] # optional

View File

@@ -1,15 +1,16 @@
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$RepoUrl = 'https://github.com/dexoron/dcr' $RepoUrl = 'https://github.com/dexoron/dcr'
$ApiUrl = 'https://api.github.com/repos/dexoron/dcr/releases/latest' $ApiLatest = 'https://api.github.com/repos/dexoron/dcr/releases/latest'
$ApiAll = 'https://api.github.com/repos/dexoron/dcr/releases'
$InstallPath = Join-Path $env:LOCALAPPDATA 'dcr' $InstallPath = Join-Path $env:LOCALAPPDATA 'dcr'
$BinPath = Join-Path $env:USERPROFILE '.local\bin' $BinPath = Join-Path $env:USERPROFILE '.local\bin'
$BinaryPath = Join-Path $InstallPath 'dcr.exe' $BinaryPath = Join-Path $InstallPath 'dcr.exe'
function Info($msg) { Write-Host "[INFO] $msg" -ForegroundColor Cyan } function Info($msg) { Write-Host "[INFO] $msg" -ForegroundColor Cyan }
function Ok($msg) { Write-Host "[OK] $msg" -ForegroundColor Green } function Ok($msg) { Write-Host "[OK] $msg" -ForegroundColor Green }
function Warn($msg) { Write-Host "[WARN] $msg" -ForegroundColor Yellow } function Warn($msg) { Write-Host "[WARN] $msg" -ForegroundColor Yellow }
function Fail($msg) { Write-Host "[ERROR] $msg" -ForegroundColor Red; exit 1 } function Fail($msg) { Write-Host "[ERROR] $msg" -ForegroundColor Red; exit 1 }
function Require-Cmd($name) { function Require-Cmd($name) {
if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { if (-not (Get-Command $name -ErrorAction SilentlyContinue)) {
@@ -17,6 +18,20 @@ function Require-Cmd($name) {
} }
} }
function Select-Channel {
Write-Host "Choose channel:"
Write-Host " 1) Latest stable release (default)"
Write-Host " 2) Latest dev (pre-release)"
$choice = Read-Host "Enter 1 or 2 [1]"
if ([string]::IsNullOrWhiteSpace($choice)) { $choice = '1' }
switch ($choice) {
'1' { return 'stable' }
'2' { return 'dev' }
default { Fail 'Unknown option' }
}
}
function Select-Mode { function Select-Mode {
Write-Host "Choose installation mode:" Write-Host "Choose installation mode:"
Write-Host " 1) Download prebuilt binary from GitHub Release (recommended)" Write-Host " 1) Download prebuilt binary from GitHub Release (recommended)"
@@ -26,7 +41,7 @@ function Select-Mode {
switch ($choice) { switch ($choice) {
'1' { return 'release' } '1' { return 'release' }
'2' { return 'build' } '2' { return 'build' }
default { Fail 'Unknown option' } default { Fail 'Unknown option' }
} }
} }
@@ -38,18 +53,35 @@ function Get-Target {
return 'x86_64-pc-windows-msvc' return 'x86_64-pc-windows-msvc'
} }
function Fetch-ReleaseJson($channel) {
if ($channel -eq 'dev') {
Info "Looking for latest dev (pre-release)..."
$releases = Invoke-RestMethod -Method Get -Uri $ApiAll
$pre = $releases | Where-Object { $_.prerelease -eq $true } | Select-Object -First 1
if (-not $pre) { Fail "No dev (pre-release) found on GitHub" }
return $pre
} else {
return Invoke-RestMethod -Method Get -Uri $ApiLatest
}
}
function Install-FromRelease { function Install-FromRelease {
param([string]$target) param([string]$target, [string]$channel)
New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null
$assetName = "dcr-$target.exe" $release = Fetch-ReleaseJson $channel
Info "Fetching latest release..." $tag = $release.tag_name
$release = Invoke-RestMethod -Method Get -Uri $ApiUrl $version = $tag.TrimStart('v')
# Имя бинарника: dcr-<triple>-<version>.exe
$assetName = "dcr-$target-$version.exe"
Info "Fetching release $tag (channel: $channel)..."
$asset = $release.assets | Where-Object { $_.name -eq $assetName } | Select-Object -First 1 $asset = $release.assets | Where-Object { $_.name -eq $assetName } | Select-Object -First 1
if (-not $asset) { if (-not $asset) {
Fail "Asset $assetName not found in release $($release.tag_name)" Fail "Asset $assetName not found in release $tag"
} }
Info "Downloading $assetName..." Info "Downloading $assetName..."
@@ -58,7 +90,7 @@ function Install-FromRelease {
} }
function Install-FromSource { function Install-FromSource {
param([string]$target) param([string]$target, [string]$channel)
Require-Cmd 'git' Require-Cmd 'git'
Require-Cmd 'cargo' Require-Cmd 'cargo'
@@ -67,7 +99,15 @@ function Install-FromSource {
if (Test-Path $tmp) { Remove-Item -Recurse -Force $tmp } if (Test-Path $tmp) { Remove-Item -Recurse -Force $tmp }
Info 'Cloning repository...' Info 'Cloning repository...'
git clone --depth 1 $RepoUrl $tmp | Out-Null if ($channel -eq 'dev') {
# Пробуем ветку dev
$result = git clone --depth 1 --branch dev $RepoUrl $tmp 2>&1
if ($LASTEXITCODE -ne 0) {
git clone --depth 1 $RepoUrl $tmp | Out-Null
}
} else {
git clone --depth 1 $RepoUrl $tmp | Out-Null
}
Info 'Building release binary...' Info 'Building release binary...'
Push-Location $tmp Push-Location $tmp
@@ -100,14 +140,15 @@ function Setup-Path {
} }
Info 'Starting DCR installation' Info 'Starting DCR installation'
$mode = Select-Mode $channel = Select-Channel
$target = Get-Target $mode = Select-Mode
$target = Get-Target
if ($mode -eq 'build') { if ($mode -eq 'build') {
Install-FromSource -target $target Install-FromSource -target $target -channel $channel
} else { } else {
Install-FromRelease -target $target Install-FromRelease -target $target -channel $channel
} }
Setup-Path Setup-Path
Ok 'Installation completed successfully' Ok 'Installation completed successfully'

View File

@@ -6,7 +6,8 @@ INSTALL_PATH="$HOME/.local/share/dcr"
BINPATH="$HOME/.local/bin" BINPATH="$HOME/.local/bin"
LOGFILE="$HOME/.cache/dcr-install.log" LOGFILE="$HOME/.cache/dcr-install.log"
REPO_URL="https://github.com/dexoron/dcr" REPO_URL="https://github.com/dexoron/dcr"
GITHUB_API="https://api.github.com/repos/dexoron/dcr/releases/latest" GITHUB_API_LATEST="https://api.github.com/repos/dexoron/dcr/releases/latest"
GITHUB_API_ALL="https://api.github.com/repos/dexoron/dcr/releases"
RED='\033[0;31m' RED='\033[0;31m'
GREEN='\033[0;32m' GREEN='\033[0;32m'
@@ -17,13 +18,16 @@ NC='\033[0m'
mkdir -p "$(dirname "$LOGFILE")" mkdir -p "$(dirname "$LOGFILE")"
exec > >(tee -a "$LOGFILE") 2>&1 exec > >(tee -a "$LOGFILE") 2>&1
log() { echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"; } log() { echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"; }
success() { echo -e "${GREEN}✔ $1${NC}"; } success() { echo -e "${GREEN}✔ $1${NC}"; }
warn() { echo -e "${YELLOW}⚠ $1${NC}"; } warn() { echo -e "${YELLOW}⚠ $1${NC}"; }
error() { echo -e "${RED}✖ $1${NC}"; } error() { echo -e "${RED}✖ $1${NC}"; }
trap 'error "Error on line $LINENO"; exit 1' ERR trap 'error "Error on line $LINENO"; exit 1' ERR
INSTALL_MODE=""
CHANNEL=""
check_os() { check_os() {
case "$(uname -s)" in case "$(uname -s)" in
Linux|Darwin) ;; Linux|Darwin) ;;
@@ -37,13 +41,11 @@ detect_target() {
arch="$(uname -m)" arch="$(uname -m)"
case "$os:$arch" in case "$os:$arch" in
Linux:x86_64) TARGET_TRIPLE="x86_64-unknown-linux-gnu" ;; Linux:x86_64) TARGET_TRIPLE="x86_64-unknown-linux-gnu" ;;
Darwin:x86_64) TARGET_TRIPLE="x86_64-apple-darwin" ;; Darwin:x86_64) TARGET_TRIPLE="x86_64-apple-darwin" ;;
Darwin:arm64|Darwin:aarch64) TARGET_TRIPLE="aarch64-apple-darwin" ;; Darwin:arm64|Darwin:aarch64) TARGET_TRIPLE="aarch64-apple-darwin" ;;
*) error "Unsupported platform: $os/$arch"; exit 1 ;; *) error "Unsupported platform: $os/$arch"; exit 1 ;;
esac esac
ASSET_NAME="dcr-${TARGET_TRIPLE}"
} }
check_common_dependencies() { check_common_dependencies() {
@@ -51,14 +53,106 @@ check_common_dependencies() {
} }
check_build_dependencies() { check_build_dependencies() {
command -v git >/dev/null 2>&1 || { error "git is not installed"; exit 1; } command -v git >/dev/null 2>&1 || { error "git is not installed"; exit 1; }
command -v cargo >/dev/null 2>&1 || { error "cargo is not installed"; exit 1; } command -v cargo >/dev/null 2>&1 || { error "cargo is not installed"; exit 1; }
} }
select_channel() {
echo "Choose channel:"
echo " 1) Latest stable release (default)"
echo " 2) Latest dev (pre-release)"
read -r -p "Enter 1 or 2 [1]: " choice
case "${choice:-1}" in
1) CHANNEL="stable" ;;
2) CHANNEL="dev" ;;
*) error "Unknown option"; exit 1 ;;
esac
}
select_install_mode() {
echo "Choose installation mode:"
echo " 1) Download prebuilt binary from GitHub Release (recommended)"
echo " 2) Build from git"
read -r -p "Enter 1 or 2 [1]: " choice
case "${choice:-1}" in
1) INSTALL_MODE="release" ;;
2) INSTALL_MODE="build" ;;
*) error "Unknown option"; exit 1 ;;
esac
}
# Возвращает JSON нужного релиза в stdout
fetch_release_json() {
if [[ "$CHANNEL" == "dev" ]]; then
log "Looking for latest dev (pre-release)..."
local json
json="$(curl -fsSL "$GITHUB_API_ALL")"
# Первый pre-release в списке
local result
result="$(printf '%s' "$json" | python3 - <<'EOF'
import sys, json
releases = json.load(sys.stdin)
pre = [r for r in releases if r.get("prerelease", False)]
if not pre:
print("{}", end="")
else:
print(json.dumps(pre[0]), end="")
EOF
)"
if [[ -z "$result" || "$result" == "{}" ]]; then
error "No dev (pre-release) found on GitHub"
exit 1
fi
printf '%s' "$result"
else
curl -fsSL "$GITHUB_API_LATEST"
fi
}
download_binary() {
local release_json tag version asset_name download_url
release_json="$(fetch_release_json)"
tag="$(printf '%s\n' "$release_json" | \
sed -n 's/.*"tag_name": "\([^"]*\)".*/\1/p' | head -n1)"
if [[ -z "$tag" ]]; then
error "Failed to determine release version"
exit 1
fi
# Версия без ведущего 'v'
version="${tag#v}"
# Имя бинарника: dcr-<triple>-<version>
asset_name="dcr-${TARGET_TRIPLE}-${version}"
log "Fetching release ${tag} (channel: ${CHANNEL})..."
download_url="$(printf '%s\n' "$release_json" | \
sed -n "s#.*\"browser_download_url\": \"\([^\"]*/${asset_name}\)\".*#\1#p" | head -n1)"
if [[ -z "$download_url" ]]; then
error "Asset ${asset_name} not found in release ${tag}"
exit 1
fi
mkdir -p "$INSTALL_PATH"
curl -fL "$download_url" -o "$INSTALL_PATH/dcr"
chmod +x "$INSTALL_PATH/dcr"
success "Binary ${asset_name} downloaded (${tag})"
}
prepare_sources() { prepare_sources() {
log "Fetching sources..." log "Fetching sources..."
rm -rf "$TMPDIR" rm -rf "$TMPDIR"
git clone --depth 1 "$REPO_URL" "$TMPDIR" git clone --depth 1 "$REPO_URL" "$TMPDIR"
if [[ "$CHANNEL" == "dev" ]]; then
# Клонируем dev ветку, если она есть
git clone --depth 1 --branch dev "$REPO_URL" "$TMPDIR" 2>/dev/null || \
git clone --depth 1 "$REPO_URL" "$TMPDIR"
fi
success "Sources fetched" success "Sources fetched"
} }
@@ -68,34 +162,6 @@ build_binary() {
success "Build completed" success "Build completed"
} }
fetch_latest_release_json() {
curl -fsSL "$GITHUB_API"
}
download_binary() {
log "Fetching latest release..."
local release_json download_url tag
release_json="$(fetch_latest_release_json)"
tag="$(printf '%s\n' "$release_json" | sed -n 's/.*"tag_name": "\([^"]*\)".*/\1/p' | head -n1)"
if [[ -z "$tag" ]]; then
error "Failed to determine release version"
exit 1
fi
download_url="$(printf '%s\n' "$release_json" | sed -n "s#.*\"browser_download_url\": \"\([^\"]*${ASSET_NAME}\)\".*#\1#p" | head -n1)"
if [[ -z "$download_url" ]]; then
error "Asset ${ASSET_NAME} not found in release ${tag}"
exit 1
fi
mkdir -p "$INSTALL_PATH"
curl -fL "$download_url" -o "$INSTALL_PATH/dcr"
chmod +x "$INSTALL_PATH/dcr"
success "Binary ${ASSET_NAME} downloaded (${tag})"
}
install_built_binary() { install_built_binary() {
mkdir -p "$INSTALL_PATH" mkdir -p "$INSTALL_PATH"
cp "$TMPDIR/target/release/dcr" "$INSTALL_PATH/dcr" cp "$TMPDIR/target/release/dcr" "$INSTALL_PATH/dcr"
@@ -122,25 +188,13 @@ cleanup() {
rm -rf "$TMPDIR" 2>/dev/null || true rm -rf "$TMPDIR" 2>/dev/null || true
} }
select_install_mode() {
echo "Choose installation mode:"
echo " 1) Download prebuilt binary from GitHub Release (recommended)"
echo " 2) Build from git"
read -r -p "Enter 1 or 2 [1]: " choice
case "${choice:-1}" in
1) INSTALL_MODE="release" ;;
2) INSTALL_MODE="build" ;;
*) error "Unknown option"; exit 1 ;;
esac
}
main() { main() {
log "Starting DCR installation" log "Starting DCR installation"
check_os check_os
detect_target detect_target
check_common_dependencies check_common_dependencies
select_channel
select_install_mode select_install_mode
cleanup cleanup
@@ -161,4 +215,4 @@ main() {
log "Log saved to $LOGFILE" log "Log saved to $LOGFILE"
} }
main "$@" main "$@"

View File

@@ -1,4 +1,5 @@
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::deps::register;
use crate::utils::fs::find_project_root; use crate::utils::fs::find_project_root;
use crate::utils::log::error; use crate::utils::log::error;
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
@@ -12,6 +13,7 @@ pub struct AddArgs {
pub branch: Option<String>, pub branch: Option<String>,
pub tag: Option<String>, pub tag: Option<String>,
pub rev: Option<String>, pub rev: Option<String>,
pub version_from_registry: Option<String>,
} }
pub fn add(args: &[String]) -> i32 { pub fn add(args: &[String]) -> i32 {
@@ -68,7 +70,11 @@ pub fn add(args: &[String]) -> i32 {
Value::Table(table) Value::Table(table)
} }
} else if let Some(path) = add_args.path { } else if let Some(path) = add_args.path {
Value::String(path) let mut table = Map::new();
table.insert("path".to_string(), Value::String(path));
Value::Table(table)
} else if let Some(version) = add_args.version_from_registry {
Value::String(version)
} else { } else {
error("Dependency source (path or git) must be provided"); error("Dependency source (path or git) must be provided");
return 1; return 1;
@@ -122,8 +128,38 @@ fn parse_add_args(args: &[String]) -> Result<AddArgs, i32> {
} }
source_spec = s.clone(); source_spec = s.clone();
} else { } else {
error("Dependency source is required"); // No source provided — try registry auto-lookup
return Err(1); match register::resolve_package_from_registry(&name) {
Ok(info) => {
let version = info
.get("latest_version")
.or_else(|| info.get("version"))
.and_then(|v| v.as_str())
.ok_or_else(|| {
(
"Registry entry for `".to_string() + &name + "` has no version field",
1,
)
})
.map_err(|(msg, code)| {
error(&msg);
code
})?;
return Ok(AddArgs {
name,
path: None,
git: None,
branch: None,
tag: None,
rev: None,
version_from_registry: Some(version.to_string()),
});
}
Err(e) => {
error(&format!("Cannot add `{}` without source: {}", name, e));
return Err(1);
}
}
} }
while let Some(arg) = iter.next() { while let Some(arg) = iter.next() {
@@ -195,5 +231,6 @@ fn parse_add_args(args: &[String]) -> Result<AddArgs, i32> {
branch, branch,
tag, tag,
rev, rev,
version_from_registry: None,
}) })
} }

View File

@@ -3,18 +3,30 @@ use crate::cli::flags::parse_build_run_flags;
use crate::core::builder::common; use crate::core::builder::common;
use crate::core::builder::{BuildContext, build as build_project, collect_sources}; use crate::core::builder::{BuildContext, build as build_project, collect_sources};
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::deps::resolve_deps; use crate::core::deps::{register, resolve_deps};
use crate::core::workspace::parse_workspace; use crate::core::workspace::parse_workspace;
use crate::utils::fs::{check_dir, find_project_root}; use crate::utils::build::{
use crate::utils::log::{error, warn}; get_bool_with_profile, get_config_opt, get_config_str, get_language_with_profile,
normalize_target_os, parse_version_info, profile_table, resolve_compiler,
resolve_pkg_config_flags, resolve_tool,
};
use crate::utils::fs::{check_dir, find_project_root, with_dir};
use crate::utils::log::error;
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
use glob::glob; use glob::glob;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Once;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant; use std::time::Instant;
static BUILD_INTERRUPTED: AtomicBool = AtomicBool::new(false);
static SIGNAL_HANDLER: Once = Once::new();
pub fn build(args: &[String]) -> i32 { pub fn build(args: &[String]) -> i32 {
install_signal_handler();
BUILD_INTERRUPTED.store(false, Ordering::SeqCst);
let start_dir = match std::env::current_dir() { let start_dir = match std::env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
Err(_) => { Err(_) => {
@@ -38,7 +50,15 @@ pub fn build(args: &[String]) -> i32 {
Err(code) => return code, Err(code) => return code,
}; };
// If no target specified, use default host target for target-specific config if flags.target.is_none() {
let config_path = root.join("dcr.toml");
if let Ok(config) = Config::open(config_path.to_str().unwrap()) {
let bt = get_build_string_with_profile(&config, "target", "debug");
if !bt.is_empty() {
flags.target = Some(bt);
}
}
}
if flags.target.is_none() { if flags.target.is_none() {
let default_target = if cfg!(target_os = "linux") { let default_target = if cfg!(target_os = "linux") {
"x86_64-unknown-linux-gnu" "x86_64-unknown-linux-gnu"
@@ -57,7 +77,13 @@ pub fn build(args: &[String]) -> i32 {
let _ = clean(&clean_args); let _ = clean(&clean_args);
} }
match with_dir(&root, || { match with_dir(&root, || {
build_from_root(&root, &flags.profile, flags.target.as_deref(), flags.force) build_from_root(
&root,
&flags.profile,
flags.target.as_deref(),
flags.force,
flags.verbose,
)
}) { }) {
Ok(()) => 0, Ok(()) => 0,
Err(msg) => { Err(msg) => {
@@ -67,77 +93,20 @@ pub fn build(args: &[String]) -> i32 {
} }
} }
fn get_config_str(config: &Config, key: &str) -> String { fn install_signal_handler() {
config SIGNAL_HANDLER.call_once(|| {
.get(key) let _ = ctrlc::set_handler(|| {
.and_then(|v| v.as_str()) BUILD_INTERRUPTED.store(true, Ordering::SeqCst);
.unwrap_or("") });
.to_string() });
} }
fn get_config_language(config: &Config, key: &str) -> Result<String, String> { fn check_interrupted() -> Result<(), String> {
let value = config.get(key).ok_or_else(|| format!("{key} is missing"))?; if BUILD_INTERRUPTED.load(Ordering::SeqCst) {
if let Some(s) = value.as_str() { Err("Build interrupted".to_string())
let trimmed = s.trim(); } else {
if trimmed.is_empty() { Ok(())
return Err(format!("{key} is empty"));
}
return Ok(trimmed.to_string());
} }
let arr = value
.as_array()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let mut parts = Vec::new();
for item in arr {
let s = item
.as_str()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} contains empty value"));
}
parts.push(trimmed.to_string());
}
if parts.is_empty() {
return Err(format!("{key} is empty"));
}
Ok(parts.join("+"))
}
fn parse_language_value(value: &toml::Value, key: &str) -> Result<String, String> {
if let Some(s) = value.as_str() {
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} is empty"));
}
return Ok(trimmed.to_string());
}
let arr = value
.as_array()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let mut parts = Vec::new();
for item in arr {
let s = item
.as_str()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} contains empty value"));
}
parts.push(trimmed.to_string());
}
if parts.is_empty() {
return Err(format!("{key} is empty"));
}
Ok(parts.join("+"))
}
fn profile_table<'a>(config: &'a Config, profile: &str) -> Option<&'a toml::value::Table> {
config
.get("build")
.and_then(|v| v.as_table())
.and_then(|b| b.get(profile))
.and_then(|v| v.as_table())
} }
fn get_config_value_raw( fn get_config_value_raw(
@@ -211,7 +180,7 @@ fn get_string_with_profile_and_target(
} }
} }
fn get_string_with_profile(config: &Config, field: &str, profile: &str) -> String { fn get_build_string_with_profile(config: &Config, field: &str, profile: &str) -> String {
get_string_with_profile_and_target(config, field, profile, None) get_string_with_profile_and_target(config, field, profile, None)
} }
@@ -275,22 +244,18 @@ fn get_list_with_profile_and_target(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::utils::build::normalize_target_os;
#[test] #[test]
fn test_normalize_target_os() { fn test_normalize_target_os() {
assert_eq!(normalize_target_os("linux"), "x86_64-unknown-linux-gnu");
assert_eq!(normalize_target_os("macos"), "x86_64-apple-darwin");
assert_eq!(normalize_target_os("windows"), "x86_64-pc-windows-msvc");
assert_eq!( assert_eq!(
super::normalize_target_os("linux"), normalize_target_os("x86_64-unknown-linux-gnu"),
"x86_64-unknown-linux-gnu" "x86_64-unknown-linux-gnu"
); );
assert_eq!(super::normalize_target_os("macos"), "x86_64-apple-darwin"); assert_eq!(normalize_target_os("unknown"), "unknown");
assert_eq!(
super::normalize_target_os("windows"),
"x86_64-pc-windows-msvc"
);
assert_eq!(
super::normalize_target_os("x86_64-unknown-linux-gnu"),
"x86_64-unknown-linux-gnu"
);
assert_eq!(super::normalize_target_os("unknown"), "unknown");
} }
} }
@@ -306,34 +271,6 @@ fn get_targets(config: &Config, profile: &str) -> Result<Vec<String>, String> {
get_list_with_profile(config, "targets", profile) get_list_with_profile(config, "targets", profile)
} }
fn get_bool_with_profile(config: &Config, field: &str, profile: &str, default: bool) -> bool {
let base = config
.get(&format!("build.{field}"))
.and_then(|v| v.as_bool());
let profile_val = profile_table(config, profile)
.and_then(|table| table.get(field).and_then(|value| value.as_bool()));
profile_val.or(base).unwrap_or(default)
}
fn get_language_with_profile(config: &Config, profile: &str) -> Result<String, String> {
if let Some(table) = profile_table(config, profile)
&& let Some(value) = table.get("language")
{
return parse_language_value(value, &format!("build.{profile}.language"));
}
get_config_language(config, "build.language")
}
fn get_config_opt(config: &Config, key: &str) -> Option<String> {
let value = config.get(key)?.as_str()?;
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
fn get_config_list(config: &Config, key: &str) -> Result<Vec<String>, String> { fn get_config_list(config: &Config, key: &str) -> Result<Vec<String>, String> {
let value = match config.get(key) { let value = match config.get(key) {
Some(v) => v, Some(v) => v,
@@ -418,9 +355,15 @@ fn ensure_target_dirs(items: &[String], profile: &str, target_dir: Option<String
if let Some(dir) = &target_dir { if let Some(dir) = &target_dir {
let _ = fs::create_dir_all(dir); let _ = fs::create_dir_all(dir);
} else { } else {
let default_dir = if cfg!(target_os = "linux") {
let arch = std::env::consts::ARCH;
format!("{arch}-unknown-linux-gnu/{profile}")
} else {
profile.to_string()
};
let target_items = check_dir(Some("target")).unwrap_or_default(); let target_items = check_dir(Some("target")).unwrap_or_default();
if !target_items.contains(&profile.to_string()) { if !target_items.contains(&default_dir) {
let _ = fs::create_dir(format!("./target/{profile}")); let _ = fs::create_dir_all(format!("./target/{default_dir}"));
} }
} }
} }
@@ -446,6 +389,7 @@ fn build_from_root(
profile: &str, profile: &str,
target: Option<&str>, target: Option<&str>,
force: bool, force: bool,
verbose: bool,
) -> Result<(), String> { ) -> Result<(), String> {
let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?; let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?;
let project_name = get_config_str(&config, "package.name"); let project_name = get_config_str(&config, "package.name");
@@ -467,6 +411,7 @@ fn build_from_root(
let start_time = Instant::now(); let start_time = Instant::now();
for (i, build_target) in targets_to_build.iter().enumerate() { for (i, build_target) in targets_to_build.iter().enumerate() {
check_interrupted()?;
if targets_to_build.len() > 1 { if targets_to_build.len() > 1 {
println!( println!(
" Building target {} of {}: {}", " Building target {} of {}: {}",
@@ -476,7 +421,7 @@ fn build_from_root(
); );
} else { } else {
println!( println!(
" Building project `{}`\n Profile: {}\n Target: {}", " Building project `{}`\n Profile: {}\n Target: {}",
colored(&project_name, BOLD_GREEN), colored(&project_name, BOLD_GREEN),
colored(profile, BOLD_GREEN), colored(profile, BOLD_GREEN),
colored( colored(
@@ -486,12 +431,19 @@ fn build_from_root(
); );
} }
if let Some(workspace) = parse_workspace(&config, profile, build_target.as_deref(), root)? { if let Some(workspace) = parse_workspace(&config, profile, build_target.as_deref(), root)? {
build_workspace(&workspace, profile, build_target.as_deref(), force)?; build_workspace(&workspace, profile, build_target.as_deref(), force, verbose)?;
let excludes: Vec<std::path::PathBuf> = let excludes: Vec<std::path::PathBuf> =
workspace.members.iter().map(|m| m.path.clone()).collect(); workspace.members.iter().map(|m| m.path.clone()).collect();
build_project_at(root, profile, build_target.as_deref(), &excludes, force)?; build_project_at(
root,
profile,
build_target.as_deref(),
&excludes,
force,
verbose,
)?;
} else { } else {
build_project_at(root, profile, build_target.as_deref(), &[], force)?; build_project_at(root, profile, build_target.as_deref(), &[], force, verbose)?;
} }
} }
let elapsed = ((start_time.elapsed().as_secs_f64() * 100.0).trunc()) / 100.0; let elapsed = ((start_time.elapsed().as_secs_f64() * 100.0).trunc()) / 100.0;
@@ -508,9 +460,10 @@ fn build_workspace(
profile: &str, profile: &str,
target: Option<&str>, target: Option<&str>,
force: bool, force: bool,
verbose: bool,
) -> Result<(), String> { ) -> Result<(), String> {
for member in &workspace.members { for member in &workspace.members {
build_project_at(&member.path, profile, target, &[], force)?; build_project_at(&member.path, profile, target, &[], force, verbose)?;
} }
Ok(()) Ok(())
} }
@@ -521,8 +474,10 @@ fn build_project_at(
target: Option<&str>, target: Option<&str>,
exclude_dirs: &[std::path::PathBuf], exclude_dirs: &[std::path::PathBuf],
force: bool, force: bool,
verbose: bool,
) -> Result<(), String> { ) -> Result<(), String> {
with_dir(project_root, || { with_dir(project_root, || {
check_interrupted()?;
let items = check_dir(None).map_err(|_| "Failed to read project directory".to_string())?; let items = check_dir(None).map_err(|_| "Failed to read project directory".to_string())?;
if !items.contains(&"dcr.toml".to_string()) { if !items.contains(&"dcr.toml".to_string()) {
return Err("dcr.toml file not found".to_string()); return Err("dcr.toml file not found".to_string());
@@ -530,7 +485,7 @@ fn build_project_at(
let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?; let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?;
let project_name = get_config_str(&config, "package.name"); let project_name = get_config_str(&config, "package.name");
let project_version = get_config_str(&config, "package.version"); let project_version = get_config_str(&config, "package.version");
let build_target_config = get_string_with_profile(&config, "target", profile); let build_target_config = get_build_string_with_profile(&config, "target", profile);
let build_target = target.or(if build_target_config.is_empty() { let build_target = target.or(if build_target_config.is_empty() {
None None
} else { } else {
@@ -544,6 +499,11 @@ fn build_project_at(
let build_kind = get_string_with_profile_and_target(&config, "kind", profile, build_target); let build_kind = get_string_with_profile_and_target(&config, "kind", profile, build_target);
let build_platform = let build_platform =
get_string_with_profile_and_target(&config, "platform", profile, build_target); get_string_with_profile_and_target(&config, "platform", profile, build_target);
let mut build_type =
get_string_with_profile_and_target(&config, "type", profile, build_target);
if build_type.is_empty() {
build_type = get_config_str(&config, "package.type");
}
let tc_cc = get_config_value(&config, "toolchain", "cc", profile, build_target) let tc_cc = get_config_value(&config, "toolchain", "cc", profile, build_target)
.or_else(|| get_config_opt(&config, "toolchain.cc")); .or_else(|| get_config_opt(&config, "toolchain.cc"));
let tc_cxx = get_config_value(&config, "toolchain", "cxx", profile, build_target) let tc_cxx = get_config_value(&config, "toolchain", "cxx", profile, build_target)
@@ -560,10 +520,32 @@ fn build_project_at(
.or_else(|| get_config_opt(&config, "toolchain.moc")); .or_else(|| get_config_opt(&config, "toolchain.moc"));
let tc_rcc = get_config_value(&config, "toolchain", "rcc", profile, build_target) let tc_rcc = get_config_value(&config, "toolchain", "rcc", profile, build_target)
.or_else(|| get_config_opt(&config, "toolchain.rcc")); .or_else(|| get_config_opt(&config, "toolchain.rcc"));
let build_cflags = let mut build_cflags =
get_list_with_profile_and_target(&config, "cflags", profile, build_target)?; get_list_with_profile_and_target(&config, "cflags", profile, build_target)?;
let build_ldflags = if let Some(t) = build_target
&& !t.trim().is_empty()
{
let target_flag = format!("--target={}", t.trim());
if !build_cflags
.iter()
.any(|f| f == &target_flag || f.starts_with("--target="))
{
build_cflags.insert(0, target_flag);
}
}
let mut build_ldflags =
get_list_with_profile_and_target(&config, "ldflags", profile, build_target)?; get_list_with_profile_and_target(&config, "ldflags", profile, build_target)?;
let build_ldscript =
get_string_with_profile_and_target(&config, "ldscript", profile, build_target);
if !build_ldscript.is_empty() {
build_ldflags.push(format!("-T{}", build_ldscript));
}
// Новые поля: filename и extension
let output_filename =
get_string_with_profile_and_target(&config, "filename", profile, build_target);
let output_extension =
get_string_with_profile_and_target(&config, "extension", profile, build_target);
let build_excludes = let build_excludes =
get_list_with_profile_and_target(&config, "exclude", profile, build_target)?; get_list_with_profile_and_target(&config, "exclude", profile, build_target)?;
let build_includes = let build_includes =
@@ -593,7 +575,61 @@ fn build_project_at(
let target_dir = build_target.map(|t| format!("target/{t}/{profile}")); let target_dir = build_target.map(|t| format!("target/{t}/{profile}"));
ensure_target_dirs(&items, profile, target_dir); ensure_target_dirs(&items, profile, target_dir);
let deps_table = config.get("dependencies").and_then(|v| v.as_table());
let resolved = resolve_deps(&config, profile, build_target, project_root)?; let resolved = resolve_deps(&config, profile, build_target, project_root)?;
// Registry dependencies are cached under the DCR registry root. Build
// them as normal DCR projects before the current project is linked.
if let Some(deps) = deps_table {
for (name, value) in deps {
if register::is_registry_dep(value) {
let pkg_info = register::resolve_package_from_registry(name)?;
let version = pkg_info
.get("latest_version")
.or_else(|| pkg_info.get("version"))
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let dep_root = register::package_root_from_registry_info(&pkg_info)?;
let include_dir = dep_root.join("target").join("include");
let lib_dir = dep_root.join("target").join("lib");
if !include_dir.exists() || !lib_dir.exists() {
print!(
"\r{:100}\r {} {} v{}",
"",
colored("Building", BOLD_GREEN),
name,
version
);
std::io::Write::flush(&mut std::io::stdout()).unwrap();
if !dep_root.join("dcr.toml").is_file() {
return Err(format!(
"Registry dependency `{}` is missing dcr.toml at {}",
name,
dep_root.display()
));
}
build_project_at(&dep_root, profile, build_target, &[], force, verbose)?;
print!(
"\r{:100}\r {} {} v{}",
"",
colored("Ready", BOLD_GREEN),
name,
version
);
println!();
} else {
println!(
" {} {} v{}",
colored("Ready", BOLD_GREEN),
name,
version
);
}
}
}
}
let (resolved_cflags, resolved_ldflags) = let (resolved_cflags, resolved_ldflags) =
resolve_pkg_config_flags(&pkg_configs, &build_cflags, &build_ldflags)?; resolve_pkg_config_flags(&pkg_configs, &build_cflags, &build_ldflags)?;
let mut combined_excludes = Vec::new(); let mut combined_excludes = Vec::new();
@@ -675,6 +711,11 @@ fn build_project_at(
platform: normalize_platform(&build_platform), platform: normalize_platform(&build_platform),
linker: resolved_linker.as_deref(), linker: resolved_linker.as_deref(),
archiver: resolved_archiver.as_deref(), archiver: resolved_archiver.as_deref(),
package_type: if build_type.is_empty() {
None
} else {
Some(build_type.as_str())
},
source_roots: &source_roots, source_roots: &source_roots,
exclude_dirs: &combined_excludes, exclude_dirs: &combined_excludes,
include_paths: &combined_includes, include_paths: &combined_includes,
@@ -683,6 +724,17 @@ fn build_project_at(
libs: &resolved.libs, libs: &resolved.libs,
cflags: &resolved_cflags, cflags: &resolved_cflags,
ldflags: &resolved_ldflags, ldflags: &resolved_ldflags,
output_filename: if output_filename.is_empty() {
None
} else {
Some(output_filename.as_str())
},
output_extension: if output_extension.is_empty() {
None
} else {
Some(output_extension.as_str())
},
verbose,
}; };
if std::env::var("DCR_DEBUG").is_ok() { if std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] debug: compiler={}", ctx.compiler); eprintln!("[dcr] debug: compiler={}", ctx.compiler);
@@ -732,8 +784,12 @@ fn build_project_at(
); );
if !skip { if !skip {
run_build(&ctx)?; run_build(&ctx)?;
check_interrupted()?;
write_build_fingerprint(&ctx, &fingerprint)?; write_build_fingerprint(&ctx, &fingerprint)?;
} }
if ctx.package_type == Some("lib") {
package_library(&ctx, &headers)?;
}
let post_steps_dirty = build_steps_need_run(&build_post_steps, &step_vars)?; let post_steps_dirty = build_steps_need_run(&build_post_steps, &step_vars)?;
if post_steps_dirty { if post_steps_dirty {
run_build_steps(&build_post_steps, &tool_execs, &step_flags, &step_vars)?; run_build_steps(&build_post_steps, &tool_execs, &step_flags, &step_vars)?;
@@ -743,31 +799,57 @@ fn build_project_at(
}) })
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String> fn package_library(ctx: &BuildContext, headers: &[PathBuf]) -> Result<(), String> {
where let target_root = if let Some(dir) = ctx.target_dir {
F: FnOnce() -> Result<T, String>, Path::new(dir)
{ .parent()
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?; .and_then(|p| p.parent())
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?; .unwrap_or_else(|| Path::new("target"))
let result = f(); } else {
let _ = std::env::set_current_dir(prev); Path::new("target")
result };
}
pub fn normalize_target_os(target: &str) -> &str { let include_dir = target_root.join("include");
match target { let lib_dir = target_root.join("lib");
"linux" => "x86_64-unknown-linux-gnu",
"macos" => "x86_64-apple-darwin", fs::create_dir_all(&include_dir).map_err(|e| e.to_string())?;
"windows" => "x86_64-pc-windows-msvc", fs::create_dir_all(&lib_dir).map_err(|e| e.to_string())?;
_ if target.contains('-') => target, // Assume valid triple
_ => { for header in headers {
warn(&format!( if let Some(name) = header.file_name() {
"Unknown target '{}', using as-is. Supported short names: linux, macos, windows", let dest = include_dir.join(name);
target fs::copy(header, dest)
)); .map_err(|e| format!("Failed to copy header {:?}: {}", header, e))?;
target
} }
} }
let mut outputs = Vec::new();
if ctx.kind == "staticlib" || ctx.kind == "any" {
outputs.push(crate::platform::lib_path(
ctx.profile,
ctx.project_name,
ctx.target_dir,
));
}
if ctx.kind == "sharedlib" || ctx.kind == "any" {
outputs.push(crate::platform::shared_lib_path(
ctx.profile,
ctx.project_name,
ctx.target_dir,
));
}
for output in outputs {
let path = Path::new(&output);
if path.exists()
&& let Some(name) = path.file_name()
{
let dest = lib_dir.join(name);
fs::copy(path, dest).map_err(|e| format!("Failed to copy lib {:?}: {}", path, e))?;
}
}
Ok(())
} }
pub fn normalize_target(target: &str, profile: &str) -> Option<String> { pub fn normalize_target(target: &str, profile: &str) -> Option<String> {
@@ -793,176 +875,6 @@ fn normalize_platform(platform: &str) -> Option<&str> {
} }
} }
fn resolve_compiler(
language: &str,
compiler: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> String {
let lang = primary_language(language);
env_override_compiler(&lang)
.or_else(|| toolchain_override_compiler(&lang, tc_cc, tc_cxx, tc_as))
.unwrap_or_else(|| compiler.to_string())
}
fn env_override_compiler(lang: &str) -> Option<String> {
if let Ok(value) = std::env::var("DCR_COMPILER") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
if lang == "asm" {
if let Ok(value) = std::env::var("DCR_AS") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
return None;
}
if (lang == "c++" || lang == "cpp" || lang == "cxx")
&& let Ok(value) = std::env::var("DCR_CXX")
{
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
if let Ok(value) = std::env::var("DCR_CC") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
None
}
fn toolchain_override_compiler(
lang: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> Option<String> {
if lang == "asm" {
return tc_as.map(|v| v.to_string());
}
if (lang == "c++" || lang == "cpp" || lang == "cxx")
&& let Some(v) = tc_cxx
{
return Some(v.to_string());
}
tc_cc.map(|v| v.to_string())
}
fn primary_language(language: &str) -> String {
let parts: Vec<String> = language
.split('+')
.map(|p| p.trim().to_lowercase())
.filter(|p| !p.is_empty())
.collect();
for p in &parts {
if p == "c++" || p == "cpp" || p == "cxx" {
return p.clone();
}
}
if parts.iter().any(|p| p == "c") {
return "c".to_string();
}
if parts.iter().any(|p| p == "asm") {
return "asm".to_string();
}
language.to_lowercase()
}
fn resolve_tool(env_key: &str, fallback: Option<&str>) -> Option<String> {
if let Ok(value) = std::env::var(env_key) {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
fallback.map(|v| v.to_string())
}
fn resolve_pkg_config_flags(
pkgs: &[String],
base_cflags: &[String],
base_ldflags: &[String],
) -> Result<(Vec<String>, Vec<String>), String> {
let mut cflags = base_cflags.to_vec();
let mut ldflags = base_ldflags.to_vec();
if pkgs.is_empty() {
return Ok((cflags, ldflags));
}
for pkg in pkgs {
let c_out = run_pkg_config(pkg, "--cflags")?;
let l_out = run_pkg_config(pkg, "--libs")?;
cflags.extend(split_flags(&c_out));
ldflags.extend(split_flags(&l_out));
}
Ok((cflags, ldflags))
}
fn run_pkg_config(pkg: &str, arg: &str) -> Result<String, String> {
let output = std::process::Command::new("pkg-config")
.arg(arg)
.arg(pkg)
.output()
.map_err(|err| format!("Failed to run pkg-config: {err}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("pkg-config failed for {pkg}: {stderr}"));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
fn split_flags(value: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
let mut chars = value.chars().peekable();
let mut quote: Option<char> = None;
while let Some(ch) = chars.next() {
if let Some(q) = quote {
if ch == q {
quote = None;
continue;
}
if ch == '\\' {
if let Some(next) = chars.next() {
current.push(next);
}
continue;
}
current.push(ch);
continue;
}
if ch == '"' || ch == '\'' {
quote = Some(ch);
continue;
}
if ch.is_whitespace() {
if !current.is_empty() {
out.push(current.clone());
current.clear();
}
continue;
}
if ch == '\\' {
if let Some(next) = chars.next() {
current.push(next);
}
continue;
}
current.push(ch);
}
if !current.is_empty() {
out.push(current);
}
out
}
struct ToolchainExecs { struct ToolchainExecs {
uic: String, uic: String,
moc: String, moc: String,
@@ -1322,44 +1234,6 @@ fn expand_step_value(template: &str, stem: &str, vars: &StepVars) -> String {
.replace("{version_suffix_dash}", vars.version_suffix_dash) .replace("{version_suffix_dash}", vars.version_suffix_dash)
} }
struct VersionInfo {
full: String,
major: String,
minor: String,
patch: String,
suffix: String,
suffix_dash: String,
}
fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}
struct StepVars<'a> { struct StepVars<'a> {
profile: &'a str, profile: &'a str,
version: &'a str, version: &'a str,
@@ -1449,18 +1323,35 @@ fn write_build_fingerprint(ctx: &BuildContext, fingerprint: &str) -> Result<(),
} }
fn build_cache_path(profile: &str, target_dir: Option<&str>) -> std::path::PathBuf { fn build_cache_path(profile: &str, target_dir: Option<&str>) -> std::path::PathBuf {
let _ = target_dir; match target_dir {
Path::new("./target").join(profile).join(".dcr-build.hash") Some(dir) => Path::new(dir).join(".dcr-build.hash"),
None => Path::new("./target").join(profile).join(".dcr-build.hash"),
}
} }
fn build_output_path(ctx: &BuildContext) -> String { fn build_output_path(ctx: &BuildContext) -> String {
let name = ctx.output_filename.unwrap_or(ctx.project_name);
let ext = ctx.output_extension.unwrap_or("");
let final_name = if ext.is_empty() {
name.to_string()
} else {
format!("{}.{}", name, ext)
};
if ctx.kind == "staticlib" { if ctx.kind == "staticlib" {
return crate::platform::lib_path(ctx.profile, ctx.project_name, ctx.target_dir); return crate::platform::lib_path(ctx.profile, &final_name, ctx.target_dir);
} }
if ctx.kind == "sharedlib" { if ctx.kind == "sharedlib" {
return crate::platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir); return crate::platform::shared_lib_path(ctx.profile, &final_name, ctx.target_dir);
} }
crate::platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir) if ctx.kind == "efi" {
return crate::platform::efi_path(ctx.profile, &final_name, ctx.target_dir);
}
if ctx.kind == "elf" {
return crate::platform::elf_path(ctx.profile, &final_name, ctx.target_dir);
}
crate::platform::bin_path(ctx.profile, &final_name, ctx.target_dir)
} }
fn collect_header_files( fn collect_header_files(

View File

@@ -1,7 +1,8 @@
use crate::config::flags; use crate::config::flags;
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::workspace::parse_workspace; use crate::core::workspace::parse_workspace;
use crate::utils::fs::{check_dir, find_project_root}; use crate::utils::build::parse_version_info;
use crate::utils::fs::{check_dir, find_project_root, with_dir};
use crate::utils::log::{error, warn}; use crate::utils::log::{error, warn};
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
use glob::glob; use glob::glob;
@@ -90,17 +91,27 @@ fn parse_clean_flags(args: &[String]) -> Result<CleanFlags, String> {
fn clean_from_root(root: &Path, flags: &CleanFlags) -> Result<(), String> { fn clean_from_root(root: &Path, flags: &CleanFlags) -> Result<(), String> {
let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?; let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?;
let target = flags.target.clone().or_else(|| { let target = flags
Some(if cfg!(target_os = "linux") { .target
"x86_64-unknown-linux-gnu".to_string() .clone()
} else if cfg!(target_os = "macos") { .or_else(|| {
"x86_64-apple-darwin".to_string() config
} else if cfg!(target_os = "windows") { .get("build.target")
"x86_64-pc-windows-msvc".to_string() .and_then(|v| v.as_str())
} else { .map(|s| s.trim().to_string())
"unknown".to_string() .filter(|s| !s.is_empty())
}) })
}); .or_else(|| {
Some(if cfg!(target_os = "linux") {
"x86_64-unknown-linux-gnu".to_string()
} else if cfg!(target_os = "macos") {
"x86_64-apple-darwin".to_string()
} else if cfg!(target_os = "windows") {
"x86_64-pc-windows-msvc".to_string()
} else {
"unknown".to_string()
})
});
if flags.all if flags.all
&& let Some(workspace) = parse_workspace( && let Some(workspace) = parse_workspace(
@@ -182,17 +193,6 @@ fn clean_project_at(
}) })
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}
fn clean_custom_paths(config: &Config, profile: &str) -> Result<(), String> { fn clean_custom_paths(config: &Config, profile: &str) -> Result<(), String> {
let patterns = match config.get("build.clean") { let patterns = match config.get("build.clean") {
Some(v) => v Some(v) => v
@@ -237,41 +237,3 @@ fn substitute_version_vars(value: &str, config: &Config) -> String {
.replace("{version_suffix}", &info.suffix) .replace("{version_suffix}", &info.suffix)
.replace("{version_suffix_dash}", &info.suffix_dash) .replace("{version_suffix_dash}", &info.suffix_dash)
} }
struct VersionInfo {
full: String,
major: String,
minor: String,
patch: String,
suffix: String,
suffix_dash: String,
}
fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}

View File

@@ -3,6 +3,7 @@ use reqwest::blocking::Client;
use serde::Deserialize; use serde::Deserialize;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[cfg(target_os = "linux")]
use std::process::Command; use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -137,8 +138,8 @@ fn download_asset(client: &Client, url: &str) -> Result<Vec<u8>, String> {
fn asset_candidates(target: &str) -> Vec<String> { fn asset_candidates(target: &str) -> Vec<String> {
let mut names = vec![format!("dcr-{target}")]; let mut names = vec![format!("dcr-{target}")];
if target == "x86_64-pc-windows-msvc" { if target.contains("-windows-") || target.ends_with("-windows") {
names.push("dcr-x86_64-pc-windows-msvc.exe".to_string()); names.push(format!("dcr-{target}.exe"));
} }
names names
@@ -156,14 +157,14 @@ fn temp_binary_path(current_exe: &Path) -> PathBuf {
current_exe.with_extension(extension) current_exe.with_extension(extension)
} }
fn set_executable_permissions(path: &Path) { fn set_executable_permissions(_path: &Path) {
#[cfg(unix)] #[cfg(unix)]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
if let Ok(meta) = fs::metadata(path) { if let Ok(meta) = fs::metadata(_path) {
let mut perms = meta.permissions(); let mut perms = meta.permissions();
perms.set_mode(0o755); perms.set_mode(0o755);
let _ = fs::set_permissions(path, perms); let _ = fs::set_permissions(_path, perms);
} }
} }
} }

View File

@@ -6,6 +6,7 @@ pub struct BuildRunFlags {
pub target: Option<String>, pub target: Option<String>,
pub force: bool, pub force: bool,
pub clean: bool, pub clean: bool,
pub verbose: bool,
} }
pub fn parse_build_run_flags(args: &[String]) -> Result<BuildRunFlags, i32> { pub fn parse_build_run_flags(args: &[String]) -> Result<BuildRunFlags, i32> {
@@ -13,6 +14,7 @@ pub fn parse_build_run_flags(args: &[String]) -> Result<BuildRunFlags, i32> {
let mut target = None; let mut target = None;
let mut force = false; let mut force = false;
let mut clean = false; let mut clean = false;
let mut verbose = false;
let mut iter = args.iter(); let mut iter = args.iter();
while let Some(arg) = iter.next() { while let Some(arg) = iter.next() {
@@ -29,6 +31,10 @@ pub fn parse_build_run_flags(args: &[String]) -> Result<BuildRunFlags, i32> {
clean = true; clean = true;
continue; continue;
} }
if candidate == "verbose" {
verbose = true;
continue;
}
if candidate == "target" { if candidate == "target" {
if let Some(t) = iter.next() { if let Some(t) = iter.next() {
target = Some(t.clone()); target = Some(t.clone());
@@ -55,5 +61,6 @@ pub fn parse_build_run_flags(args: &[String]) -> Result<BuildRunFlags, i32> {
target, target,
force, force,
clean, clean,
verbose,
}) })
} }

View File

@@ -3,181 +3,15 @@ use crate::core::builder::collect_sources;
use crate::core::builder::common; use crate::core::builder::common;
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::workspace::parse_workspace; use crate::core::workspace::parse_workspace;
use crate::utils::build::{
get_bool_with_profile, get_config_opt, get_config_str, get_language_with_profile_or_default,
get_list_with_profile, get_string_with_profile, normalize_target_os, resolve_compiler,
resolve_pkg_config_flags_lossy,
};
use crate::utils::fs::find_project_root; use crate::utils::fs::find_project_root;
use crate::utils::log::{error, warn}; use crate::utils::log::error;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
// ── helpers copied from cli::build (private there) ─────────────────────────
fn get_config_str(config: &Config, key: &str) -> String {
config
.get(key)
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string()
}
fn profile_table<'a>(config: &'a Config, profile: &str) -> Option<&'a toml::value::Table> {
config
.get("build")
.and_then(|v| v.as_table())
.and_then(|b| b.get(profile))
.and_then(|v| v.as_table())
}
fn get_string_with_profile(config: &Config, field: &str, profile: &str) -> String {
let base = get_config_str(config, &format!("build.{field}"));
let Some(table) = profile_table(config, profile) else {
return base;
};
let value = table.get(field).and_then(|v| v.as_str()).unwrap_or("");
let trimmed = value.trim();
if trimmed.is_empty() {
base
} else {
trimmed.to_string()
}
}
fn get_config_list(config: &Config, key: &str) -> Vec<String> {
config
.get(key)
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str())
.map(|s| s.to_string())
.collect()
})
.unwrap_or_default()
}
fn get_list_with_profile(config: &Config, field: &str, profile: &str) -> Vec<String> {
let mut out = get_config_list(config, &format!("build.{field}"));
if let Some(table) = profile_table(config, profile)
&& let Some(extra) = table.get(field).and_then(|v| v.as_array())
{
out.extend(
extra
.iter()
.filter_map(|v| v.as_str())
.map(|s| s.to_string()),
);
}
out
}
fn get_bool_with_profile(config: &Config, field: &str, profile: &str, default: bool) -> bool {
let base = config
.get(&format!("build.{field}"))
.and_then(|v| v.as_bool());
let profile_val =
profile_table(config, profile).and_then(|t| t.get(field).and_then(|v| v.as_bool()));
profile_val.or(base).unwrap_or(default)
}
fn get_language_with_profile(config: &Config, profile: &str) -> String {
if let Some(table) = profile_table(config, profile)
&& let Some(value) = table.get("language")
{
return parse_language_value(value);
}
let value = config.get("build.language");
match value {
Some(v) => parse_language_value(v),
None => "c".to_string(),
}
}
fn parse_language_value(value: &toml::Value) -> String {
if let Some(s) = value.as_str() {
return s.trim().to_string();
}
if let Some(arr) = value.as_array() {
let parts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
return parts.join("+");
}
"c".to_string()
}
fn get_config_opt(config: &Config, key: &str) -> Option<String> {
let value = config.get(key)?.as_str()?;
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
fn resolve_compiler(
language: &str,
compiler: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> String {
let lang = primary_language(language);
if let Ok(v) = std::env::var("DCR_COMPILER") {
let t = v.trim().to_string();
if !t.is_empty() {
return t;
}
}
if lang == "asm" {
if let Ok(v) = std::env::var("DCR_AS") {
let t = v.trim().to_string();
if !t.is_empty() {
return t;
}
}
if let Some(v) = tc_as {
return v.to_string();
}
}
if lang == "c++" || lang == "cpp" || lang == "cxx" {
if let Ok(v) = std::env::var("DCR_CXX") {
let t = v.trim().to_string();
if !t.is_empty() {
return t;
}
}
if let Some(v) = tc_cxx {
return v.to_string();
}
}
if let Ok(v) = std::env::var("DCR_CC") {
let t = v.trim().to_string();
if !t.is_empty() {
return t;
}
}
if let Some(v) = tc_cc {
return v.to_string();
}
compiler.to_string()
}
fn primary_language(language: &str) -> String {
let parts: Vec<String> = language
.split('+')
.map(|p| p.trim().to_lowercase())
.filter(|p| !p.is_empty())
.collect();
for p in &parts {
if p == "c++" || p == "cpp" || p == "cxx" {
return p.clone();
}
}
if parts.iter().any(|p| p == "c") {
return "c".to_string();
}
if parts.iter().any(|p| p == "asm") {
return "asm".to_string();
}
language.to_lowercase()
}
/// Like `deps::resolve_deps` but does NOT require lib directories to exist. /// Like `deps::resolve_deps` but does NOT require lib directories to exist.
/// Used by `gen` commands where the project may not have been built yet. /// Used by `gen` commands where the project may not have been built yet.
struct GenDeps { struct GenDeps {
@@ -310,53 +144,6 @@ fn resolve_deps_for_gen(config: &Config, profile: &str, project_root: &Path) ->
} }
} }
fn resolve_pkg_config_flags(
pkgs: &[String],
base_cflags: &[String],
base_ldflags: &[String],
) -> (Vec<String>, Vec<String>) {
let mut cflags = base_cflags.to_vec();
let mut ldflags = base_ldflags.to_vec();
for pkg in pkgs {
match std::process::Command::new("pkg-config")
.arg("--cflags")
.arg(pkg)
.output()
{
Ok(out) if out.status.success() => {
let s = String::from_utf8_lossy(&out.stdout);
cflags.extend(s.split_whitespace().map(|v| v.to_string()));
}
Ok(out) => {
let err = String::from_utf8_lossy(&out.stderr);
eprintln!("Warning: pkg-config --cflags {pkg} failed: {err}");
}
Err(e) => {
eprintln!("Warning: pkg-config --cflags {pkg} error: {e}");
}
}
match std::process::Command::new("pkg-config")
.arg("--libs")
.arg(pkg)
.output()
{
Ok(out) if out.status.success() => {
let s = String::from_utf8_lossy(&out.stdout);
ldflags.extend(s.split_whitespace().map(|v| v.to_string()));
}
Ok(out) => {
let err = String::from_utf8_lossy(&out.stderr);
eprintln!("Warning: pkg-config --libs {pkg} failed: {err}");
}
Err(e) => {
eprintln!("Warning: pkg-config --libs {pkg} error: {e}");
}
}
}
(cflags, ldflags)
}
// ── public API ─────────────────────────────────────────────────────────────── // ── public API ───────────────────────────────────────────────────────────────
/// Everything needed to generate output for one project member. /// Everything needed to generate output for one project member.
@@ -422,7 +209,7 @@ fn collect_project_info_inner(root: &Path, profile: &str) -> Result<ProjectInfo,
let name = get_config_str(&config, "package.name"); let name = get_config_str(&config, "package.name");
let version = get_config_str(&config, "package.version"); let version = get_config_str(&config, "package.version");
let language = get_language_with_profile(&config, profile); let language = get_language_with_profile_or_default(&config, profile);
let standard = get_string_with_profile(&config, "standard", profile); let standard = get_string_with_profile(&config, "standard", profile);
let compiler_s = get_string_with_profile(&config, "compiler", profile); let compiler_s = get_string_with_profile(&config, "compiler", profile);
let kind = get_string_with_profile(&config, "kind", profile); let kind = get_string_with_profile(&config, "kind", profile);
@@ -464,7 +251,7 @@ fn collect_project_info_inner(root: &Path, profile: &str) -> Result<ProjectInfo,
let resolved = resolve_deps_for_gen(&config, profile, root); let resolved = resolve_deps_for_gen(&config, profile, root);
let (resolved_cflags, resolved_ldflags) = let (resolved_cflags, resolved_ldflags) =
resolve_pkg_config_flags(&pkg_configs, &base_cflags, &base_ldflags); resolve_pkg_config_flags_lossy(&pkg_configs, &base_cflags, &base_ldflags);
// Build exclude/include pattern lists (same logic as cli::build) // Build exclude/include pattern lists (same logic as cli::build)
let mut combined_excludes: Vec<PathBuf> = Vec::new(); let mut combined_excludes: Vec<PathBuf> = Vec::new();
@@ -541,6 +328,7 @@ fn collect_project_info_inner(root: &Path, profile: &str) -> Result<ProjectInfo,
platform: normalize_platform(&platform), platform: normalize_platform(&platform),
linker: resolved_linker.as_deref(), linker: resolved_linker.as_deref(),
archiver: resolved_archiver.as_deref(), archiver: resolved_archiver.as_deref(),
package_type: None,
source_roots: &source_roots, source_roots: &source_roots,
exclude_dirs: &combined_excludes, exclude_dirs: &combined_excludes,
include_paths: &combined_includes, include_paths: &combined_includes,
@@ -549,6 +337,9 @@ fn collect_project_info_inner(root: &Path, profile: &str) -> Result<ProjectInfo,
libs: &resolved.libs, libs: &resolved.libs,
cflags: &resolved_cflags, cflags: &resolved_cflags,
ldflags: &resolved_ldflags, ldflags: &resolved_ldflags,
output_filename: None,
output_extension: None,
verbose: false,
}; };
let sources = collect_sources(&ctx).map_err(|e| format!("Failed to collect sources: {e}"))?; let sources = collect_sources(&ctx).map_err(|e| format!("Failed to collect sources: {e}"))?;
@@ -1394,22 +1185,6 @@ fn parse_gen_args(args: &[String]) -> Result<(PathBuf, String), i32> {
Ok((root, profile)) Ok((root, profile))
} }
fn normalize_target_os(s: &str) -> &str {
match s {
"linux" => "x86_64-unknown-linux-gnu",
"macos" => "x86_64-apple-darwin",
"windows" => "x86_64-pc-windows-msvc",
_ if s.contains('-') => s, // Assume valid triple
_ => {
warn(&format!(
"Unknown target '{}', using as-is. Supported short names: linux, macos, windows",
s
));
s
}
}
}
fn normalize_target(s: &str, profile: &str) -> Option<String> { fn normalize_target(s: &str, profile: &str) -> Option<String> {
let trimmed = normalize_target_os(s.trim()); let trimmed = normalize_target_os(s.trim());
if trimmed.is_empty() { if trimmed.is_empty() {

View File

@@ -12,6 +12,7 @@ pub fn help() -> i32 {
println!(" init Initialize the current directory as a project"); println!(" init Initialize the current directory as a project");
println!(" build [--profile] Build the project (default: --debug)"); println!(" build [--profile] Build the project (default: --debug)");
println!(" run [--profile] Build and run the project (default: --debug)"); println!(" run [--profile] Build and run the project (default: --debug)");
println!(" tree Display the dependency tree");
println!(" test Run project tests (alias: tests)"); println!(" test Run project tests (alias: tests)");
println!(" clean Remove the target directory"); println!(" clean Remove the target directory");
println!(" gen <subcommand> Generate IDE integration files"); println!(" gen <subcommand> Generate IDE integration files");

View File

@@ -8,4 +8,6 @@ pub mod help;
pub mod init; pub mod init;
pub mod new; pub mod new;
pub mod run; pub mod run;
pub mod setup;
pub mod test; pub mod test;
pub mod tree;

View File

@@ -2,10 +2,11 @@ use crate::cli::build::build;
use crate::cli::flags::parse_build_run_flags; use crate::cli::flags::parse_build_run_flags;
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::runner::run_binary; use crate::core::runner::run_binary;
use crate::utils::build::{normalize_target_os, parse_version_info};
use crate::utils::fs::find_project_root; use crate::utils::fs::find_project_root;
use crate::utils::fs::with_dir;
use crate::utils::log::error; use crate::utils::log::error;
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
use std::path::Path;
use std::process::Command; use std::process::Command;
fn get_run_cmd( fn get_run_cmd(
@@ -36,15 +37,6 @@ fn get_run_cmd(
} }
} }
fn normalize_target_os(s: &str) -> &str {
match s {
"linux" => "x86_64-unknown-linux-gnu",
"macos" => "x86_64-apple-darwin",
"windows" => "x86_64-pc-windows-msvc",
_ => s,
}
}
pub fn run(args: &[String]) -> i32 { pub fn run(args: &[String]) -> i32 {
let start_dir = match std::env::current_dir() { let start_dir = match std::env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
@@ -77,15 +69,6 @@ pub fn run(args: &[String]) -> i32 {
.get("package.name") .get("package.name")
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.unwrap_or(""); .unwrap_or("");
let build_kind = config
.get("build.kind")
.and_then(|v| v.as_str())
.unwrap_or("");
let target_dir = config
.get("build.target")
.and_then(|v| v.as_str())
.map(|s| s.trim())
.filter(|s| !s.is_empty());
let mut flags = match parse_build_run_flags(args) { let mut flags = match parse_build_run_flags(args) {
Ok(v) => v, Ok(v) => v,
@@ -106,6 +89,12 @@ pub fn run(args: &[String]) -> i32 {
flags.target = Some(default_target.to_string()); flags.target = Some(default_target.to_string());
} }
let build_kind = config
.get(&format!("build.{}.kind", flags.profile))
.and_then(|v| v.as_str())
.or_else(|| config.get("build.kind").and_then(|v| v.as_str()))
.unwrap_or("");
let normalized_target_dir = flags let normalized_target_dir = flags
.target .target
.as_ref() .as_ref()
@@ -118,7 +107,9 @@ pub fn run(args: &[String]) -> i32 {
let run_cmd = get_run_cmd(&config, &flags.profile, flags.target.as_deref(), version); let run_cmd = get_run_cmd(&config, &flags.profile, flags.target.as_deref(), version);
let kind = build_kind.trim(); let kind = build_kind.trim();
if run_cmd.is_none() && (kind == "staticlib" || kind == "sharedlib") { if run_cmd.is_none()
&& (kind == "staticlib" || kind == "sharedlib" || kind == "efi" || kind == "elf")
{
error("Cannot run library build"); error("Cannot run library build");
return 1; return 1;
} }
@@ -136,13 +127,21 @@ pub fn run(args: &[String]) -> i32 {
} }
println!("\n {} {}", colored("Running", BOLD_GREEN), bin_path); println!("\n {} {}", colored("Running", BOLD_GREEN), bin_path);
println!("--------------------------------"); println!("--------------------------------");
return run_binary(project_name, &flags.profile, target_dir); return run_binary(
project_name,
&flags.profile,
normalized_target_dir.as_deref(),
);
} }
let fallback_code = if let Some(cmd) = run_cmd { let fallback_code = if let Some(cmd) = run_cmd {
run_shell(&cmd) run_shell(&cmd)
} else { } else {
run_binary(project_name, &flags.profile, target_dir) run_binary(
project_name,
&flags.profile,
normalized_target_dir.as_deref(),
)
}; };
if fallback_code != 1 { if fallback_code != 1 {
return fallback_code; return fallback_code;
@@ -152,17 +151,6 @@ pub fn run(args: &[String]) -> i32 {
1 1
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}
fn run_shell(cmd: &str) -> i32 { fn run_shell(cmd: &str) -> i32 {
let status = if cfg!(target_os = "windows") { let status = if cfg!(target_os = "windows") {
Command::new("cmd").arg("/C").arg(cmd).status() Command::new("cmd").arg("/C").arg(cmd).status()
@@ -186,41 +174,3 @@ fn substitute_run_vars(cmd: &str, profile: &str, version: &str) -> String {
.replace("{version_suffix}", &info.suffix) .replace("{version_suffix}", &info.suffix)
.replace("{version_suffix_dash}", &info.suffix_dash) .replace("{version_suffix_dash}", &info.suffix_dash)
} }
struct VersionInfo {
full: String,
major: String,
minor: String,
patch: String,
suffix: String,
suffix_dash: String,
}
fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}

16
src/cli/setup.rs Normal file
View File

@@ -0,0 +1,16 @@
pub fn setup(_args: &[String]) -> i32 {
println!("Setting up DCR registries...");
match crate::core::registry::RegistryManager::load() {
Ok(manager) => {
println!("Loaded {} registries.", manager.config.registry.len());
for (name, reg) in manager.config.registry {
println!("- {}: {} (priority {})", name, reg.url, reg.priority);
}
0
}
Err(e) => {
println!("Error: {}", e);
1
}
}
}

View File

@@ -1,22 +1,26 @@
use crate::cli::build; use crate::cli::build;
use crate::config::{FILE_DCR_TEST_H, FILE_TEST_C, flags}; use crate::config::{FILE_DCR_TEST_H, FILE_TEST_C, flags};
use crate::core::config::Config; use crate::core::config::Config;
use crate::utils::fs::find_project_root; use crate::utils::build::{
get_config_opt, get_config_str, get_language_with_profile, get_list_with_profile,
get_string_with_profile, resolve_compiler, resolve_pkg_config_flags,
};
use crate::utils::fs::{find_project_root, with_dir};
use crate::utils::log::error; use crate::utils::log::error;
use crate::utils::text::{BOLD_GREEN, BOLD_RED, RESET, colored}; use crate::utils::text::{BOLD_GREEN, BOLD_RED, RESET, colored};
use std::env;
use std::fs; use std::fs;
use std::path::Path; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
const BOLD_BLUE: &str = "\x1b[1m\x1b[94m"; const BOLD_BLUE: &str = "\x1b[1m\x1b[94m";
pub fn test(args: &[String]) -> i32 { pub fn test(args: &[String]) -> i32 {
let mut init_header = false; let mut init_header = false;
let mut profile = "debug";
for arg in args { for arg in args {
if arg == "--help" { if arg == "--help" {
println!("USAGE:"); println!("USAGE:");
println!(" dcr test [--init]"); println!(" dcr test [--init] [--debug | --release]");
println!(); println!();
println!("ALIASES:"); println!("ALIASES:");
println!(" dcr tests"); println!(" dcr tests");
@@ -26,12 +30,18 @@ pub fn test(args: &[String]) -> i32 {
println!(); println!();
println!("OPTIONS:"); println!("OPTIONS:");
println!(" --init Create tests/dcr_test.h in current project"); println!(" --init Create tests/dcr_test.h in current project");
println!(" --debug Build and run tests with debug profile (default)");
println!(" --release Build and run tests with release profile");
return 0; return 0;
} }
if arg == "--init" { if arg == "--init" {
init_header = true; init_header = true;
continue; continue;
} }
if arg == "--debug" || arg == "--release" {
profile = arg.trim_start_matches("--");
continue;
}
error("Unknown argument"); error("Unknown argument");
return 1; return 1;
} }
@@ -65,7 +75,7 @@ pub fn test(args: &[String]) -> i32 {
} }
} }
match with_dir(&root, run_testsuite) { match with_dir(&root, || run_testsuite(profile)) {
Ok(code) => code, Ok(code) => code,
Err(msg) => { Err(msg) => {
error(&msg); error(&msg);
@@ -74,73 +84,84 @@ pub fn test(args: &[String]) -> i32 {
} }
} }
fn run_testsuite() -> Result<i32, String> { fn run_testsuite(profile: &str) -> Result<i32, String> {
if build::build(&[String::from("--release")]) != 0 { if build::build(&[format!("--{profile}")]) != 0 {
return Ok(1); return Ok(1);
} }
let config = Config::open("./dcr.toml").map_err(|_| "Failed to read dcr.toml".to_string())?; let config = Config::open("./dcr.toml").map_err(|_| "Failed to read dcr.toml".to_string())?;
let name = config let name = get_config_str(&config, "package.name");
.get("package.name") let language = get_language_with_profile(&config, profile)?;
.and_then(|v| v.as_str()) let compiler_cfg = get_string_with_profile(&config, "compiler", profile);
.ok_or("package.name not found in dcr.toml")?; let standard = get_string_with_profile(&config, "standard", profile);
let kind = config let package_type = get_config_str(&config, "package.type");
.get("package.kind") let build_kind = get_string_with_profile(&config, "kind", profile);
.and_then(|v| v.as_str()) let tc_cc = get_config_opt(&config, "toolchain.cc");
.unwrap_or("bin"); let tc_cxx = get_config_opt(&config, "toolchain.cxx");
let tc_as = get_config_opt(&config, "toolchain.as");
let compiler = resolve_compiler(
&language,
&compiler_cfg,
tc_cc.as_deref(),
tc_cxx.as_deref(),
tc_as.as_deref(),
);
let compiler = env::var("DCR_CC").unwrap_or_else(|_| "cc".to_string()); let mut cflags: Vec<String> = flags(profile)
let profile = "release"; .unwrap_or(&[])
let flags_vec = flags(profile).unwrap_or(&[]); .iter()
let flags_str = flags_vec.join(" "); .map(|v| v.to_string())
.collect();
let test_c = "./tests/test.c"; cflags.extend(get_list_with_profile(&config, "cflags", profile));
if !Path::new(test_c).exists() { let ldflags = get_list_with_profile(&config, "ldflags", profile);
let pkg_configs = get_list_with_profile(&config, "pkg_config", profile);
let (cflags, ldflags) = resolve_pkg_config_flags(&pkg_configs, &cflags, &ldflags)?;
let includes = test_include_dirs(&config, profile);
let test_sources = collect_test_sources()?;
if test_sources.is_empty() {
return Err("tests/test.c not found; run 'dcr test --init' first".to_string()); return Err("tests/test.c not found; run 'dcr test --init' first".to_string());
} }
// Compile test.c to object let link_project_lib =
let obj_path = "./tests/test.o"; package_type == "lib" || build_kind == "staticlib" || build_kind == "sharedlib";
let compile_cmd = format!("{} -c {} -o {} {}", compiler, test_c, obj_path, flags_str); let mut stdout = String::new();
let compile_status = Command::new("sh") let mut declared = Vec::new();
.arg("-c") let mut suite_success = true;
.arg(&compile_cmd)
.status() fs::create_dir_all("./tests/target")
.map_err(|_| format!("Failed to compile {}", test_c))?; .map_err(|e| format!("Failed to create tests/target: {e}"))?;
if !compile_status.success() { for source in &test_sources {
return Err(format!("Compilation of {} failed", test_c)); declared.extend(extract_test_names_path(source));
let stem = source
.file_stem()
.and_then(|v| v.to_str())
.unwrap_or("test");
let obj_path = Path::new("./tests/target").join(format!("{stem}.o"));
let bin_path =
Path::new("./tests/target").join(format!("{stem}{}", std::env::consts::EXE_SUFFIX));
compile_test_source(&compiler, &standard, &cflags, &includes, source, &obj_path)?;
link_test_binary(
&compiler,
&ldflags,
link_project_lib.then_some(name.as_str()),
&obj_path,
&bin_path,
)?;
let out = Command::new(&bin_path)
.output()
.map_err(|_| format!("Failed to run `{}`", bin_path.display()))?;
stdout.push_str(&String::from_utf8_lossy(&out.stdout));
let stderr = String::from_utf8_lossy(&out.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
if !out.status.success() {
suite_success = false;
}
} }
// Link
let bin_path = format!("./tests/test{}", std::env::consts::EXE_SUFFIX);
let link_cmd = if kind == "lib" {
format!(
"{} {} -o {} -Ltarget/release -l{}",
compiler, obj_path, bin_path, name
)
} else {
format!("{} {} -o {}", compiler, obj_path, bin_path)
};
let link_status = Command::new("sh")
.arg("-c")
.arg(&link_cmd)
.status()
.map_err(|_| format!("Failed to link {}", bin_path))?;
if !link_status.success() {
return Err(format!("Linking of {} failed", bin_path));
}
let out = Command::new(&bin_path)
.output()
.map_err(|_| format!("Failed to run `{bin_path}`"))?;
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
let declared = extract_test_names("./tests/test.c");
let mut pass = 0; let mut pass = 0;
let mut skip = 0; let mut skip = 0;
let mut fail = 0; let mut fail = 0;
@@ -189,7 +210,7 @@ fn run_testsuite() -> Result<i32, String> {
} }
if !parsed_any { if !parsed_any {
if out.status.success() { if suite_success {
for name in &declared { for name in &declared {
println!("{} {}", colored("[PASS]", BOLD_GREEN), name); println!("{} {}", colored("[PASS]", BOLD_GREEN), name);
} }
@@ -216,12 +237,104 @@ fn run_testsuite() -> Result<i32, String> {
print_field("FAIL", fail, BOLD_RED); print_field("FAIL", fail, BOLD_RED);
println!("{}", colored("=====================", BOLD_GREEN)); println!("{}", colored("=====================", BOLD_GREEN));
if fail > 0 || !out.status.success() { if fail > 0 || !suite_success {
return Ok(1); return Ok(1);
} }
Ok(0) Ok(0)
} }
fn collect_test_sources() -> Result<Vec<PathBuf>, String> {
let tests_dir = Path::new("./tests");
if !tests_dir.is_dir() {
return Ok(Vec::new());
}
let mut sources = Vec::new();
for entry in fs::read_dir(tests_dir).map_err(|e| format!("Failed to read tests/: {e}"))? {
let path = entry
.map_err(|e| format!("Failed to read tests/: {e}"))?
.path();
if path.extension().and_then(|v| v.to_str()) == Some("c") {
sources.push(path);
}
}
sources.sort();
Ok(sources)
}
fn test_include_dirs(config: &Config, profile: &str) -> Vec<String> {
let mut dirs = vec![
"./tests".to_string(),
"./src".to_string(),
"./target/include".to_string(),
];
dirs.extend(get_list_with_profile(config, "include", profile));
dirs
}
fn compile_test_source(
compiler: &str,
standard: &str,
cflags: &[String],
includes: &[String],
source: &Path,
obj_path: &Path,
) -> Result<(), String> {
let mut cmd = Command::new(compiler);
cmd.arg("-c").arg(source).arg("-o").arg(obj_path);
if !standard.trim().is_empty() {
cmd.arg(format!("-std={}", standard.trim()));
}
for flag in cflags {
cmd.arg(flag);
}
for dir in includes {
cmd.arg(format!("-I{dir}"));
}
let output = cmd
.output()
.map_err(|e| format!("Failed to compile {}: {e}", source.display()))?;
print_command_output(&output);
if !output.status.success() {
return Err(format!("Compilation of {} failed", source.display()));
}
Ok(())
}
fn link_test_binary(
compiler: &str,
ldflags: &[String],
project_lib: Option<&str>,
obj_path: &Path,
bin_path: &Path,
) -> Result<(), String> {
let mut cmd = Command::new(compiler);
cmd.arg(obj_path);
if let Some(name) = project_lib {
cmd.arg("-Ltarget/lib").arg(format!("-l{name}"));
}
for flag in ldflags {
cmd.arg(flag);
}
cmd.arg("-o").arg(bin_path);
let output = cmd
.output()
.map_err(|e| format!("Failed to link {}: {e}", bin_path.display()))?;
print_command_output(&output);
if !output.status.success() {
return Err(format!("Linking of {} failed", bin_path.display()));
}
Ok(())
}
fn print_command_output(output: &std::process::Output) {
if !output.stdout.is_empty() {
print!("{}", String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
eprint!("{}", String::from_utf8_lossy(&output.stderr));
}
}
fn ensure_test_header() -> Result<(), String> { fn ensure_test_header() -> Result<(), String> {
fs::create_dir_all("./tests").map_err(|_| "Failed to create tests/".to_string())?; fs::create_dir_all("./tests").map_err(|_| "Failed to create tests/".to_string())?;
fs::write("./tests/dcr_test.h", FILE_DCR_TEST_H) fs::write("./tests/dcr_test.h", FILE_DCR_TEST_H)
@@ -233,7 +346,7 @@ fn ensure_test_header() -> Result<(), String> {
Ok(()) Ok(())
} }
fn extract_test_names(path: &str) -> Vec<String> { fn extract_test_names_path(path: &Path) -> Vec<String> {
let Ok(content) = fs::read_to_string(path) else { let Ok(content) = fs::read_to_string(path) else {
return Vec::new(); return Vec::new();
}; };
@@ -256,14 +369,3 @@ fn print_field(label: &str, value: i32, color: &str) {
println!("{}{}: {}{}", color, label, value, RESET); println!("{}{}: {}{}", color, label, value, RESET);
} }
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}

118
src/cli/tree.rs Normal file
View File

@@ -0,0 +1,118 @@
use crate::core::config::Config;
use crate::utils::log::error;
use crate::utils::text::{BOLD_CYAN, printc};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use toml::Value;
pub fn tree(_args: &[String]) -> i32 {
let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let config = match Config::open("dcr.toml") {
Ok(c) => c,
Err(_) => {
error("dcr.toml not found in current directory");
return 1;
}
};
let name = config
.get("package.name")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let version = config
.get("package.version")
.and_then(|v| v.as_str())
.unwrap_or("0.0.0");
printc(&format!("{} v{}", name, version), BOLD_CYAN);
let mut seen = HashSet::new();
seen.insert(name.to_string());
if let Some(deps) = config.get("dependencies").and_then(|v| v.as_table()) {
print_deps(deps, &current_dir, "", &mut seen);
}
0
}
fn print_deps(
deps: &toml::value::Table,
base_path: &Path,
prefix: &str,
seen: &mut HashSet<String>,
) {
let mut dep_list: Vec<_> = deps.iter().collect();
dep_list.sort_by_key(|(name, _)| *name);
for (i, (name, value)) in dep_list.iter().enumerate() {
let is_last = i == dep_list.len() - 1;
let connector = if is_last { "└── " } else { "├── " };
let child_prefix = if is_last { " " } else { "│ " };
let dep_path = resolve_dep_path(value, base_path);
let mut version = String::new();
let mut sub_deps = None;
let mut resolved_path = None;
if let Some(path) = &dep_path {
let dcr_toml = path.join("dcr.toml");
if dcr_toml.exists()
&& let Ok(config) = Config::open(&dcr_toml.to_string_lossy())
{
if let Some(v) = config.get("package.version").and_then(|v| v.as_str()) {
version = format!(" v{}", v);
}
sub_deps = config
.get("dependencies")
.and_then(|v| v.as_table())
.cloned();
resolved_path = Some(path.clone());
}
}
if version.is_empty() {
version = match value {
Value::String(s) if s.starts_with("git:") || s.starts_with("github:") => {
format!(" ({})", s)
}
Value::Table(t) => {
if let Some(v) = t.get("version").and_then(|v| v.as_str()) {
format!(" v{}", v)
} else if let Some(git) = t.get("git").and_then(|v| v.as_str()) {
format!(" ({})", git)
} else {
"".to_string()
}
}
_ => "".to_string(),
};
}
println!("{}{}{}{}", prefix, connector, name, version);
if let Some(s_deps) = sub_deps
&& !seen.contains(*name)
{
seen.insert(name.to_string());
let new_prefix = format!("{}{}", prefix, child_prefix);
if let Some(path) = resolved_path {
print_deps(&s_deps, &path, &new_prefix, seen);
}
seen.remove(*name);
}
}
}
fn resolve_dep_path(value: &Value, base_path: &Path) -> Option<PathBuf> {
match value {
Value::String(s) => s
.strip_prefix("path:")
.map(|stripped| base_path.join(stripped)),
Value::Table(t) => t
.get("path")
.and_then(|v| v.as_str())
.map(|path| base_path.join(path)),
_ => None,
}
}

View File

@@ -1,5 +1,13 @@
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, OnceLock};
static OUTPUT_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
pub fn get_output_lock() -> &'static Mutex<()> {
OUTPUT_MUTEX.get_or_init(|| Mutex::new(()))
}
pub fn collect_sources( pub fn collect_sources(
roots: &[PathBuf], roots: &[PathBuf],
@@ -153,6 +161,65 @@ pub fn has_glob_magic(value: &str) -> bool {
value.chars().any(|c| matches!(c, '*' | '?' | '[')) value.chars().any(|c| matches!(c, '*' | '?' | '['))
} }
pub fn parallel_build<F>(total_tasks: usize, task_fn: F) -> Result<(), String>
where
F: Fn(usize) -> Result<(), String> + Sync + Send,
{
let num_threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
let counter = std::sync::atomic::AtomicUsize::new(0);
let err_msg = std::sync::Mutex::new(None);
std::thread::scope(|s| {
for _ in 0..num_threads {
s.spawn(|| {
loop {
if err_msg.lock().unwrap().is_some() {
break;
}
let i = counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if i >= total_tasks {
break;
}
if let Err(e) = task_fn(i) {
let mut err = err_msg.lock().unwrap();
if err.is_none() {
*err = Some(e);
}
break;
}
}
});
}
});
if let Some(err) = err_msg.into_inner().unwrap() {
return Err(err);
}
Ok(())
}
pub fn run_command_sync_output(cmd: &mut Command) -> Result<(), String> {
let output = cmd.output().map_err(|err| format!("Build failed: {err}"))?;
let _guard = OUTPUT_MUTEX.get_or_init(|| Mutex::new(())).lock().unwrap();
if !output.stdout.is_empty() {
print!("{}", String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
eprint!("{}", String::from_utf8_lossy(&output.stderr));
}
if output.status.success() {
Ok(())
} else {
Err("Build failed".to_string())
}
}
pub fn normalize_source_path(path: &Path) -> String { pub fn normalize_source_path(path: &Path) -> String {
if !path.is_absolute() { if !path.is_absolute() {
return path.to_string_lossy().to_string(); return path.to_string_lossy().to_string();
@@ -167,10 +234,16 @@ pub fn normalize_source_path(path: &Path) -> String {
pub fn object_path(obj_dir: &Path, source: &str, obj_ext: &str) -> String { pub fn object_path(obj_dir: &Path, source: &str, obj_ext: &str) -> String {
let src_path = Path::new(source); let src_path = Path::new(source);
let rel = src_path let stripped = src_path.strip_prefix("./").unwrap_or(src_path);
.strip_prefix("./src") let rel = stripped
.or_else(|_| src_path.strip_prefix("src")) .components()
.unwrap_or(src_path); .skip(1)
.collect::<std::path::PathBuf>();
let rel = if rel.components().next().is_some() {
rel
} else {
stripped.to_path_buf()
};
let mut out = obj_dir.join(rel); let mut out = obj_dir.join(rel);
out.set_extension(obj_ext.trim_start_matches('.')); out.set_extension(obj_ext.trim_start_matches('.'));
out.to_string_lossy().to_string() out.to_string_lossy().to_string()

View File

@@ -18,7 +18,10 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
}; };
let start_time = Instant::now(); let start_time = Instant::now();
let sources = collect_sources(ctx)?; let sources = collect_sources(ctx)?;
let obj_dir = Path::new("./target").join(ctx.profile).join("obj"); let obj_dir = match ctx.target_dir {
Some(dir) => Path::new(dir).join("obj"),
None => Path::new("./target").join(ctx.profile).join("obj"),
};
let objects = build_objects(assembler, &sources, &obj_dir, ctx, "o")?; let objects = build_objects(assembler, &sources, &obj_dir, ctx, "o")?;
if ctx.kind == "staticlib" { if ctx.kind == "staticlib" {
@@ -37,7 +40,7 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for obj in &objects { for obj in &objects {
cmd.arg(obj); cmd.arg(obj);
} }
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -70,14 +73,24 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for flag in ctx.ldflags { for flag in ctx.ldflags {
cmd.arg(flag); cmd.arg(flag);
} }
let out_path = if ctx.kind == "sharedlib" { let name = ctx.output_filename.unwrap_or(ctx.project_name);
platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir) let ext = ctx.output_extension.unwrap_or("");
let final_name = if ext.is_empty() {
name.to_string()
} else { } else {
platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir) format!("{}.{}", name, ext)
};
let out_path = if ctx.kind == "sharedlib" {
platform::shared_lib_path(ctx.profile, &final_name, ctx.target_dir)
} else if ctx.kind == "elf" {
platform::elf_path(ctx.profile, &final_name, ctx.target_dir)
} else {
platform::bin_path(ctx.profile, &final_name, ctx.target_dir)
}; };
cmd.arg("-o").arg(out_path); cmd.arg("-o").arg(out_path);
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -107,25 +120,38 @@ fn build_objects(
ctx: &BuildContext, ctx: &BuildContext,
obj_ext: &str, obj_ext: &str,
) -> Result<Vec<String>, String> { ) -> Result<Vec<String>, String> {
let mut objects = Vec::new(); let objects: Vec<String> = sources
for source in sources { .iter()
let obj_path = common::object_path(obj_dir, source, obj_ext); .map(|s| common::object_path(obj_dir, s, obj_ext))
if let Some(parent) = Path::new(&obj_path).parent() { .collect();
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
} common::parallel_build(sources.len(), |i| {
if common::needs_rebuild(source, &obj_path) { build_object(assembler, &sources[i], &objects[i], ctx)
let mut cmd = Command::new(assembler); })?;
cmd.arg(source).arg("-o").arg(&obj_path);
for flag in ctx.cflags {
cmd.arg(flag);
}
match cmd.status() {
Ok(status) if status.success() => {}
Ok(_) => return Err("Build failed".to_string()),
Err(err) => return Err(format!("Build failed: {err}")),
}
}
objects.push(obj_path);
}
Ok(objects) Ok(objects)
} }
fn build_object(
assembler: &str,
source: &str,
obj_path: &str,
ctx: &BuildContext,
) -> Result<(), String> {
if let Some(parent) = Path::new(obj_path).parent() {
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
}
if !common::needs_rebuild(source, obj_path) {
return Ok(());
}
let mut cmd = Command::new(assembler);
cmd.arg(source).arg("-o").arg(obj_path);
for flag in ctx.cflags {
cmd.arg(flag);
}
common::run_command_sync_output(&mut cmd)
}

View File

@@ -17,6 +17,7 @@ pub struct BuildContext<'a> {
pub platform: Option<&'a str>, pub platform: Option<&'a str>,
pub linker: Option<&'a str>, pub linker: Option<&'a str>,
pub archiver: Option<&'a str>, pub archiver: Option<&'a str>,
pub package_type: Option<&'a str>,
pub source_roots: &'a [std::path::PathBuf], pub source_roots: &'a [std::path::PathBuf],
pub exclude_dirs: &'a [std::path::PathBuf], pub exclude_dirs: &'a [std::path::PathBuf],
pub include_paths: &'a [String], pub include_paths: &'a [String],
@@ -25,10 +26,19 @@ pub struct BuildContext<'a> {
pub libs: &'a [String], pub libs: &'a [String],
pub cflags: &'a [String], pub cflags: &'a [String],
pub ldflags: &'a [String], pub ldflags: &'a [String],
pub output_filename: Option<&'a str>,
pub output_extension: Option<&'a str>,
pub verbose: bool,
} }
pub fn build(ctx: &BuildContext) -> Result<f64, String> { pub fn build(ctx: &BuildContext) -> Result<f64, String> {
let compiler = ctx.compiler.to_lowercase(); let compiler = ctx.compiler.to_lowercase();
if !check_compiler_exists(ctx.compiler) {
return Err(format!(
"Compiler not found: {}. Make sure it is installed and available in PATH.",
ctx.compiler
));
}
if compiler.contains("clang-cl") { if compiler.contains("clang-cl") {
return msvc::build(ctx); return msvc::build(ctx);
} }
@@ -44,6 +54,14 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
unix_cc::build(ctx) unix_cc::build(ctx)
} }
fn check_compiler_exists(compiler: &str) -> bool {
let name = if compiler.is_empty() { "cc" } else { compiler };
std::process::Command::new(name)
.arg("--version")
.output()
.is_ok()
}
pub fn collect_sources(ctx: &BuildContext) -> Result<Vec<String>, String> { pub fn collect_sources(ctx: &BuildContext) -> Result<Vec<String>, String> {
let compiler = ctx.compiler.to_lowercase(); let compiler = ctx.compiler.to_lowercase();
if compiler.contains("clang-cl") || compiler == "cl" || compiler.contains("msvc") { if compiler.contains("clang-cl") || compiler == "cl" || compiler.contains("msvc") {

View File

@@ -18,7 +18,10 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
} }
let start_time = Instant::now(); let start_time = Instant::now();
let sources = collect_sources(ctx)?; let sources = collect_sources(ctx)?;
let obj_dir = Path::new("./target").join(ctx.profile).join("obj"); let obj_dir = match ctx.target_dir {
Some(dir) => Path::new(dir).join("obj"),
None => Path::new("./target").join(ctx.profile).join("obj"),
};
let objects = build_objects(compiler, &sources, &obj_dir, ctx, "obj")?; let objects = build_objects(compiler, &sources, &obj_dir, ctx, "obj")?;
if ctx.kind == "staticlib" { if ctx.kind == "staticlib" {
@@ -28,7 +31,7 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for obj in &objects { for obj in &objects {
cmd.arg(obj); cmd.arg(obj);
} }
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -92,12 +95,14 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
} }
let out_path = if ctx.kind == "sharedlib" { let out_path = if ctx.kind == "sharedlib" {
platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir) platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir)
} else if ctx.kind == "elf" {
platform::elf_path(ctx.profile, ctx.project_name, ctx.target_dir)
} else { } else {
platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir) platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir)
}; };
cmd.arg(format!("/Fe:{out_path}")); cmd.arg(format!("/Fe:{out_path}"));
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -192,96 +197,124 @@ fn build_objects(
ctx: &BuildContext, ctx: &BuildContext,
obj_ext: &str, obj_ext: &str,
) -> Result<Vec<String>, String> { ) -> Result<Vec<String>, String> {
let mut objects = Vec::new(); let objects: Vec<String> = sources
for source in sources { .iter()
let obj_path = common::object_path(obj_dir, source, obj_ext); .map(|s| common::object_path(obj_dir, s, obj_ext))
if let Some(parent) = Path::new(&obj_path).parent() { .collect();
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
}
if common::needs_rebuild(source, &obj_path) {
let mut cmd = Command::new(compiler);
cmd.arg("/nologo");
match ctx.language.to_lowercase().as_str() {
"c" => {
cmd.arg("/TC");
}
"c++" | "cpp" | "cxx" => {
cmd.arg("/TP");
}
_ => {
return Err("Unsupported language".to_string());
}
}
if !ctx.standard.is_empty() && ctx.language.to_lowercase() != "asm" {
let std_flag = msvc_standard_flag(ctx.language, ctx.standard)?;
cmd.arg(std_flag);
}
if let Some(flag) = msvc_arch_flag(ctx.platform) {
cmd.arg(flag);
}
if ctx.cflags.is_empty() {
for flag in default_flags(ctx.profile) {
cmd.arg(flag);
}
}
for flag in ctx.cflags {
cmd.arg(flag);
}
for dir in ctx.include_dirs {
cmd.arg(format!("/I{dir}"));
}
cmd.arg("/c").arg(source).arg(format!("/Fo:{}", obj_path));
cmd.arg("/showIncludes");
if std::env::var("DCR_DEBUG").is_ok() { common::parallel_build(sources.len(), |i| {
eprintln!("[dcr] {:?}", cmd); build_object(compiler, &sources[i], &objects[i], ctx)
} })?;
let output = cmd.output().map_err(|err| format!("Build failed: {err}"))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let mut headers = Vec::new();
let mut clean_stdout = String::new();
for line in stdout.lines() {
if let Some(stripped) = line.strip_prefix("Note: including file:") {
headers.push(stripped.trim().to_string());
} else if let Some(stripped) = line.strip_prefix("Примечание: включение файла:")
{
headers.push(stripped.trim().to_string());
} else {
clean_stdout.push_str(line);
clean_stdout.push('\n');
}
}
if !output.status.success() {
eprint!("{}", clean_stdout);
eprint!("{}", stderr);
return Err("Build failed".to_string());
} else {
let trimmed_out = clean_stdout.trim();
let trimmed_err = stderr.trim();
let src_filename = Path::new(source)
.file_name()
.and_then(|v| v.to_str())
.unwrap_or("");
if !trimmed_out.is_empty() && trimmed_out != src_filename {
print!("{}", clean_stdout);
}
if !trimmed_err.is_empty() {
eprintln!("{}", trimmed_err);
}
}
let d_path = Path::new(&obj_path).with_extension("d");
let mut d_content = format!("{}: \\\n", obj_path.replace('\\', "/"));
for h in headers {
let escaped = h.replace('\\', "/").replace(" ", "\\ ");
d_content.push_str(&format!(" {} \\\n", escaped));
}
std::fs::write(&d_path, d_content).map_err(|err| format!("d file error: {err}"))?;
}
objects.push(obj_path);
}
Ok(objects) Ok(objects)
} }
fn build_object(
compiler: &str,
source: &str,
obj_path: &str,
ctx: &BuildContext,
) -> Result<(), String> {
if let Some(parent) = Path::new(obj_path).parent() {
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
}
if !common::needs_rebuild(source, obj_path) {
return Ok(());
}
let mut cmd = Command::new(compiler);
cmd.arg("/nologo");
match ctx.language.to_lowercase().as_str() {
"c" => {
cmd.arg("/TC");
}
"c++" | "cpp" | "cxx" => {
cmd.arg("/TP");
}
_ => return Err("Unsupported language".to_string()),
}
if !ctx.standard.is_empty() && ctx.language.to_lowercase() != "asm" {
let std_flag = msvc_standard_flag(ctx.language, ctx.standard)?;
cmd.arg(std_flag);
}
if let Some(flag) = msvc_arch_flag(ctx.platform) {
cmd.arg(flag);
}
if ctx.cflags.is_empty() {
for flag in default_flags(ctx.profile) {
cmd.arg(flag);
}
}
for flag in ctx.cflags {
cmd.arg(flag);
}
for dir in ctx.include_dirs {
cmd.arg(format!("/I{dir}"));
}
cmd.arg("/c").arg(source).arg(format!("/Fo:{}", obj_path));
cmd.arg("/showIncludes");
if std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd);
}
let output = cmd.output().map_err(|err| format!("Build failed: {err}"))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let mut headers = Vec::new();
let mut clean_stdout = String::new();
for line in stdout.lines() {
if let Some(stripped) = line.strip_prefix("Note: including file:") {
headers.push(stripped.trim().to_string());
} else if let Some(stripped) = line.strip_prefix("Примечание: включение файла:")
{
headers.push(stripped.trim().to_string());
} else {
clean_stdout.push_str(line);
clean_stdout.push('\n');
}
}
let _lock = common::get_output_lock().lock().unwrap();
if !output.status.success() {
eprint!("{}", clean_stdout);
eprint!("{}", stderr);
return Err("Build failed".to_string());
}
let trimmed_out = clean_stdout.trim();
let trimmed_err = stderr.trim();
let src_filename = Path::new(source)
.file_name()
.and_then(|v| v.to_str())
.unwrap_or("");
if !trimmed_out.is_empty() && trimmed_out != src_filename {
print!("{}", clean_stdout);
}
if !trimmed_err.is_empty() {
eprintln!("{}", trimmed_err);
}
let d_path = Path::new(obj_path).with_extension("d");
let mut d_content = format!("{}: \\\n", obj_path.replace('\\', "/"));
for h in headers {
let escaped = h.replace('\\', "/").replace(" ", "\\ ");
d_content.push_str(&format!(" {} \\\n", escaped));
}
fs::write(&d_path, d_content).map_err(|err| format!("d file error: {err}"))?;
Ok(())
}

View File

@@ -18,7 +18,10 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
}; };
let start_time = Instant::now(); let start_time = Instant::now();
let sources = collect_sources(ctx)?; let sources = collect_sources(ctx)?;
let obj_dir = Path::new("./target").join(ctx.profile).join("obj"); let obj_dir = match ctx.target_dir {
Some(dir) => Path::new(dir).join("obj"),
None => Path::new("./target").join(ctx.profile).join("obj"),
};
let objects = build_objects(assembler, &sources, &obj_dir, ctx, "o")?; let objects = build_objects(assembler, &sources, &obj_dir, ctx, "o")?;
if ctx.kind == "staticlib" { if ctx.kind == "staticlib" {
@@ -37,7 +40,7 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for obj in &objects { for obj in &objects {
cmd.arg(obj); cmd.arg(obj);
} }
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -70,14 +73,24 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for flag in ctx.ldflags { for flag in ctx.ldflags {
cmd.arg(flag); cmd.arg(flag);
} }
let out_path = if ctx.kind == "sharedlib" { let name = ctx.output_filename.unwrap_or(ctx.project_name);
platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir) let ext = ctx.output_extension.unwrap_or("");
let final_name = if ext.is_empty() {
name.to_string()
} else { } else {
platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir) format!("{}.{}", name, ext)
};
let out_path = if ctx.kind == "sharedlib" {
platform::shared_lib_path(ctx.profile, &final_name, ctx.target_dir)
} else if ctx.kind == "elf" {
platform::elf_path(ctx.profile, &final_name, ctx.target_dir)
} else {
platform::bin_path(ctx.profile, &final_name, ctx.target_dir)
}; };
cmd.arg("-o").arg(out_path); cmd.arg("-o").arg(out_path);
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -107,37 +120,53 @@ fn build_objects(
ctx: &BuildContext, ctx: &BuildContext,
obj_ext: &str, obj_ext: &str,
) -> Result<Vec<String>, String> { ) -> Result<Vec<String>, String> {
let mut objects = Vec::new(); let objects: Vec<String> = sources
.iter()
.map(|s| common::object_path(obj_dir, s, obj_ext))
.collect();
let format = nasm_format(ctx.platform); let format = nasm_format(ctx.platform);
for source in sources {
let obj_path = common::object_path(obj_dir, source, obj_ext); common::parallel_build(sources.len(), |i| {
if let Some(parent) = Path::new(&obj_path).parent() { build_object(assembler, &sources[i], &objects[i], format, ctx)
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?; })?;
}
if common::needs_rebuild(source, &obj_path) {
let mut cmd = Command::new(assembler);
cmd.arg("-f")
.arg(format)
.arg(source)
.arg("-o")
.arg(&obj_path);
for flag in ctx.cflags {
cmd.arg(flag);
}
if std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd);
}
match cmd.status() {
Ok(status) if status.success() => {}
Ok(_) => return Err("Build failed".to_string()),
Err(err) => return Err(format!("Build failed: {err}")),
}
}
objects.push(obj_path);
}
Ok(objects) Ok(objects)
} }
fn build_object(
assembler: &str,
source: &str,
obj_path: &str,
format: &str,
ctx: &BuildContext,
) -> Result<(), String> {
if let Some(parent) = Path::new(obj_path).parent() {
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
}
if !common::needs_rebuild(source, obj_path) {
return Ok(());
}
let mut cmd = Command::new(assembler);
cmd.arg("-f")
.arg(format)
.arg(source)
.arg("-o")
.arg(obj_path);
for flag in ctx.cflags {
cmd.arg(flag);
}
if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd);
}
common::run_command_sync_output(&mut cmd)
}
fn nasm_format(platform: Option<&str>) -> &'static str { fn nasm_format(platform: Option<&str>) -> &'static str {
if let Some(p) = platform { if let Some(p) = platform {
let p = p.to_lowercase().replace('-', "_"); let p = p.to_lowercase().replace('-', "_");

View File

@@ -20,7 +20,10 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
ctx.exclude_dirs, ctx.exclude_dirs,
ctx.include_paths, ctx.include_paths,
)?; )?;
let obj_dir = Path::new("./target").join(ctx.profile).join("obj"); let obj_dir = match ctx.target_dir {
Some(dir) => Path::new(dir).join("obj"),
None => Path::new("./target").join(ctx.profile).join("obj"),
};
let objects = build_objects(compiler, &sources, &obj_dir, ctx, "o")?; let objects = build_objects(compiler, &sources, &obj_dir, ctx, "o")?;
if ctx.kind == "staticlib" { if ctx.kind == "staticlib" {
@@ -30,7 +33,7 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for obj in &objects { for obj in &objects {
cmd.arg(obj); cmd.arg(obj);
} }
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -51,6 +54,12 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
cmd.arg("-shared"); cmd.arg("-shared");
} }
} }
if ctx.kind == "efi" {
cmd.arg("-shared");
cmd.arg("-nostdlib");
cmd.arg("-Wl,-dll");
cmd.arg("-Wl,--subsystem,10");
}
for obj in &objects { for obj in &objects {
cmd.arg(obj); cmd.arg(obj);
} }
@@ -63,14 +72,26 @@ pub fn build(ctx: &BuildContext) -> Result<f64, String> {
for flag in ctx.ldflags { for flag in ctx.ldflags {
cmd.arg(flag); cmd.arg(flag);
} }
let out_path = if ctx.kind == "sharedlib" { let name = ctx.output_filename.unwrap_or(ctx.project_name);
platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir) let ext = ctx.output_extension.unwrap_or("");
let final_name = if ext.is_empty() {
name.to_string()
} else { } else {
platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir) format!("{}.{}", name, ext)
};
let out_path = if ctx.kind == "sharedlib" {
platform::shared_lib_path(ctx.profile, &final_name, ctx.target_dir)
} else if ctx.kind == "efi" {
platform::efi_path(ctx.profile, &final_name, ctx.target_dir)
} else if ctx.kind == "elf" {
platform::elf_path(ctx.profile, &final_name, ctx.target_dir)
} else {
platform::bin_path(ctx.profile, &final_name, ctx.target_dir)
}; };
cmd.arg("-o").arg(out_path); cmd.arg("-o").arg(out_path);
if std::env::var("DCR_DEBUG").is_ok() { if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { match cmd.status() {
@@ -125,6 +146,19 @@ fn default_flags(profile: &str) -> &'static [&'static str] {
} }
} }
fn is_bare_metal_target(target: Option<&str>) -> bool {
if let Some(t) = target {
let lower = t.to_lowercase();
lower.contains("none")
|| lower.contains("-elf")
|| lower.contains("eabi")
|| lower.contains("baremetal")
|| lower.contains("bare-metal")
} else {
false
}
}
fn build_objects( fn build_objects(
compiler: &str, compiler: &str,
sources: &[String], sources: &[String],
@@ -132,56 +166,78 @@ fn build_objects(
ctx: &BuildContext, ctx: &BuildContext,
obj_ext: &str, obj_ext: &str,
) -> Result<Vec<String>, String> { ) -> Result<Vec<String>, String> {
let mut objects = Vec::new(); let objects: Vec<String> = sources
for source in sources { .iter()
let obj_path = common::object_path(obj_dir, source, obj_ext); .map(|s| common::object_path(obj_dir, s, obj_ext))
if let Some(parent) = Path::new(&obj_path).parent() { .collect();
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
} common::parallel_build(sources.len(), |i| {
if common::needs_rebuild(source, &obj_path) { build_object(compiler, &sources[i], &objects[i], ctx)
let mut cmd = Command::new(compiler); })?;
cmd.arg("-c").arg(source).arg("-o").arg(&obj_path);
if ctx.kind == "sharedlib" {
cmd.arg("-fPIC");
}
if let Some(flag) = asm_lang_flag(source) {
cmd.arg("-x").arg(flag);
}
if let Some(platform) = ctx.platform
&& !platform.trim().is_empty()
{
cmd.arg(format!("-march={}", platform));
}
if !ctx.standard.is_empty() && ctx.language.to_lowercase() != "asm" {
cmd.arg(format!("-std={}", ctx.standard));
}
if ctx.cflags.is_empty() {
for flag in default_flags(ctx.profile) {
cmd.arg(flag);
}
}
for flag in ctx.cflags {
cmd.arg(flag);
}
for dir in ctx.include_dirs {
cmd.arg(format!("-I{dir}"));
}
let d_path = Path::new(&obj_path).with_extension("d");
cmd.arg("-MMD").arg("-MF").arg(&d_path);
if std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd);
}
match cmd.status() {
Ok(status) if status.success() => {}
Ok(_) => return Err("Build failed".to_string()),
Err(err) => return Err(format!("Build failed: {err}")),
}
}
objects.push(obj_path);
}
Ok(objects) Ok(objects)
} }
fn build_object(
compiler: &str,
source: &str,
obj_path: &str,
ctx: &BuildContext,
) -> Result<(), String> {
if let Some(parent) = Path::new(obj_path).parent() {
fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
}
if !common::needs_rebuild(source, obj_path) {
return Ok(());
}
let mut cmd = Command::new(compiler);
cmd.arg("-c").arg(source).arg("-o").arg(obj_path);
if ctx.kind == "sharedlib" {
cmd.arg("-fPIC");
}
if let Some(flag) = asm_lang_flag(source) {
cmd.arg("-x").arg(flag);
}
if let Some(platform) = ctx.platform
&& !platform.trim().is_empty()
{
cmd.arg(format!("-march={}", platform));
}
if !ctx.standard.is_empty() && ctx.language.to_lowercase() != "asm" {
cmd.arg(format!("-std={}", ctx.standard));
}
let use_dcr_defaults = ctx.cflags.is_empty() && !is_bare_metal_target(ctx.target);
if use_dcr_defaults {
for flag in default_flags(ctx.profile) {
cmd.arg(flag);
}
}
for flag in ctx.cflags {
cmd.arg(flag);
}
for dir in ctx.include_dirs {
cmd.arg(format!("-I{dir}"));
}
let d_path = Path::new(obj_path).with_extension("d");
cmd.arg("-MMD").arg("-MF").arg(&d_path);
if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
eprintln!("[dcr] {:?}", cmd);
}
common::run_command_sync_output(&mut cmd)
}
fn asm_lang_flag(source: &str) -> Option<&'static str> { fn asm_lang_flag(source: &str) -> Option<&'static str> {
let ext = Path::new(source).extension().and_then(|v| v.to_str())?; let ext = Path::new(source).extension().and_then(|v| v.to_str())?;
match ext { match ext {

View File

@@ -1,3 +1,5 @@
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use toml::Value; use toml::Value;
@@ -8,6 +10,7 @@ const DEFAULT_LANGUAGE: &str = "c";
const DEFAULT_STANDARD: &str = "c11"; const DEFAULT_STANDARD: &str = "c11";
const DEFAULT_COMPILER: &str = "clang"; const DEFAULT_COMPILER: &str = "clang";
const DEFAULT_KIND: &str = "bin"; const DEFAULT_KIND: &str = "bin";
const VALID_KINDS: &[&str] = &["bin", "staticlib", "sharedlib", "efi", "elf"];
#[derive(Debug)] #[derive(Debug)]
pub enum ConfigError { pub enum ConfigError {
@@ -51,6 +54,98 @@ impl From<toml::ser::Error> for ConfigError {
pub struct Config { pub struct Config {
path: PathBuf, path: PathBuf,
data: Value, data: Value,
typed: DcrConfig,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct DcrConfig {
pub package: PackageConfig,
pub build: BuildConfig,
#[serde(default)]
pub dependencies: BTreeMap<String, DependencyConfig>,
#[serde(default)]
pub toolchain: Option<ToolchainConfig>,
#[serde(default)]
pub workspace: BTreeMap<String, WorkspaceMemberConfig>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct PackageConfig {
pub name: String,
pub version: String,
#[serde(default, rename = "type")]
pub pkg_type: Option<String>,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct BuildConfig {
pub language: LanguageConfig,
pub standard: String,
pub compiler: String,
#[serde(default)]
pub kind: Option<String>,
#[serde(default)]
pub target: Option<String>,
#[serde(default)]
pub platform: Option<String>,
#[serde(default)]
pub cflags: Vec<String>,
#[serde(default)]
pub ldflags: Vec<String>,
#[serde(default)]
pub exclude: Vec<String>,
#[serde(default)]
pub include: Vec<String>,
#[serde(default)]
pub roots: Vec<String>,
#[serde(default)]
pub clean: Vec<String>,
#[serde(default)]
pub src_disable: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum LanguageConfig {
One(String),
Many(Vec<String>),
}
impl LanguageConfig {
fn values(&self) -> Vec<&str> {
match self {
LanguageConfig::One(value) => vec![value.as_str()],
LanguageConfig::Many(values) => values.iter().map(String::as_str).collect(),
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum DependencyConfig {
Version(String),
Table(BTreeMap<String, Value>),
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ToolchainConfig {
pub cc: Option<String>,
pub cxx: Option<String>,
#[serde(rename = "as")]
pub assembler: Option<String>,
pub ar: Option<String>,
pub ld: Option<String>,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct WorkspaceMemberConfig {
pub path: String,
#[serde(default)]
pub deps: Vec<String>,
} }
impl Config { impl Config {
@@ -63,7 +158,8 @@ impl Config {
write_toml(&path, &default_value)?; write_toml(&path, &default_value)?;
default_value default_value
}; };
let cfg = Self { path, data }; let typed = parse_typed_config(&data)?;
let cfg = Self { path, data, typed };
cfg.validate()?; cfg.validate()?;
Ok(cfg) Ok(cfg)
} }
@@ -74,11 +170,27 @@ impl Config {
return Err(ConfigError::Invalid("dcr.toml not found".into())); return Err(ConfigError::Invalid("dcr.toml not found".into()));
} }
let data = read_toml(&path)?; let data = read_toml(&path)?;
let cfg = Self { path, data }; let typed = parse_typed_config(&data)?;
let cfg = Self { path, data, typed };
cfg.validate()?; cfg.validate()?;
Ok(cfg) Ok(cfg)
} }
#[allow(dead_code)]
pub fn typed(&self) -> &DcrConfig {
&self.typed
}
#[allow(dead_code)]
pub fn package(&self) -> &PackageConfig {
&self.typed.package
}
#[allow(dead_code)]
pub fn build_config(&self) -> &BuildConfig {
&self.typed.build
}
pub fn get(&self, key: &str) -> Option<&Value> { pub fn get(&self, key: &str) -> Option<&Value> {
let parts: Vec<&str> = key.split('.').collect(); let parts: Vec<&str> = key.split('.').collect();
get_path(&self.data, &parts) get_path(&self.data, &parts)
@@ -98,118 +210,59 @@ impl Config {
} }
pub fn validate(&self) -> Result<(), ConfigError> { pub fn validate(&self) -> Result<(), ConfigError> {
let package = self if self.typed.package.name.trim().is_empty() {
.get("package") return Err(ConfigError::Invalid("package.name is empty".into()));
.and_then(|v| v.as_table()) }
.ok_or_else(|| ConfigError::Invalid("missing [package]".into()))?; if self.typed.package.version.trim().is_empty() {
return Err(ConfigError::Invalid("package.version is empty".into()));
}
validate_package_name(&self.typed.package.name)?;
for key in ["name", "version"] { if let Some(pkg_type) = &self.typed.package.pkg_type {
let value = package.get(key).and_then(|v| v.as_str()).unwrap_or(""); let pkg_type = pkg_type.trim();
if value.trim().is_empty() { if !pkg_type.is_empty() && pkg_type != "lib" && pkg_type != "app" && pkg_type != "none"
return Err(ConfigError::Invalid(format!("package.{key} is empty"))); {
return Err(ConfigError::Invalid(
"package.type must be 'lib', 'app', or 'none'".into(),
));
} }
} }
let build = self validate_language_config(&self.typed.build.language, "build.language")?;
.get("build") if self.typed.build.standard.trim().is_empty() {
.and_then(|v| v.as_table()) return Err(ConfigError::Invalid("build.standard is empty".into()));
.ok_or_else(|| ConfigError::Invalid("missing [build]".into()))?;
if let Some(language) = build.get("language") {
self.validate_language(language)?;
} else {
return Err(ConfigError::Invalid("build.language is empty".into()));
} }
for key in ["standard", "compiler"] { if self.typed.build.compiler.trim().is_empty() {
let value = build.get(key).and_then(|v| v.as_str()).unwrap_or(""); return Err(ConfigError::Invalid("build.compiler is empty".into()));
if value.trim().is_empty() {
return Err(ConfigError::Invalid(format!("build.{key} is empty")));
}
} }
if let Some(platform) = build.get("platform") if let Some(platform) = &self.typed.build.platform
&& !platform && platform.trim().is_empty()
.as_str()
.map(|v| !v.trim().is_empty())
.unwrap_or(false)
{ {
return Err(ConfigError::Invalid("build.platform is empty".into())); return Err(ConfigError::Invalid("build.platform is empty".into()));
} }
if let Some(toolchain) = self.get("toolchain").and_then(|v| v.as_table()) { validate_toolchain(self.typed.toolchain.as_ref())?;
for key in ["cc", "cxx", "as", "ar", "ld"] { if let Some(kind) = &self.typed.build.kind {
if let Some(v) = toolchain.get(key)
&& !v.as_str().map(|s| !s.trim().is_empty()).unwrap_or(false)
{
return Err(ConfigError::Invalid(format!("toolchain.{key} is invalid")));
}
}
}
if let Some(kind) = build.get("kind").and_then(|v| v.as_str()) {
let kind = kind.trim(); let kind = kind.trim();
if !kind.is_empty() && kind != "bin" && kind != "staticlib" && kind != "sharedlib" { if !kind.is_empty() && !VALID_KINDS.contains(&kind) {
return Err(ConfigError::Invalid("build.kind is invalid".into())); return Err(ConfigError::Invalid("build.kind is invalid".into()));
} }
} }
if let Some(exclude) = build.get("exclude") { validate_string_list(&self.typed.build.exclude, "build.exclude")?;
let arr = exclude.as_array().ok_or_else(|| { validate_string_list(&self.typed.build.include, "build.include")?;
ConfigError::Invalid("build.exclude must be an array of strings".into()) validate_string_list(&self.typed.build.roots, "build.roots")?;
})?; validate_string_list(&self.typed.build.clean, "build.clean")?;
for item in arr { validate_string_list(&self.typed.build.cflags, "build.cflags")?;
let s = item.as_str().unwrap_or(""); validate_string_list(&self.typed.build.ldflags, "build.ldflags")?;
if s.trim().is_empty() { if let Some(target) = &self.typed.build.target {
return Err(ConfigError::Invalid( validate_non_empty_string(target, "build.target")?;
"build.exclude contains empty value".into(),
));
}
}
}
if let Some(include) = build.get("include") {
let arr = include.as_array().ok_or_else(|| {
ConfigError::Invalid("build.include must be an array of strings".into())
})?;
for item in arr {
let s = item.as_str().unwrap_or("");
if s.trim().is_empty() {
return Err(ConfigError::Invalid(
"build.include contains empty value".into(),
));
}
}
}
if let Some(roots) = build.get("roots") {
let arr = roots.as_array().ok_or_else(|| {
ConfigError::Invalid("build.roots must be an array of strings".into())
})?;
for item in arr {
let s = item.as_str().unwrap_or("");
if s.trim().is_empty() {
return Err(ConfigError::Invalid(
"build.roots contains empty value".into(),
));
}
}
}
if let Some(src_disable) = build.get("src_disable")
&& !src_disable.is_bool()
{
return Err(ConfigError::Invalid(
"build.src_disable must be a boolean".into(),
));
}
if let Some(clean) = build.get("clean") {
let arr = clean.as_array().ok_or_else(|| {
ConfigError::Invalid("build.clean must be an array of strings".into())
})?;
for item in arr {
let s = item.as_str().unwrap_or("");
if s.trim().is_empty() {
return Err(ConfigError::Invalid(
"build.clean contains empty value".into(),
));
}
}
} }
for profile in ["release", "debug"] { for profile in ["release", "debug"] {
if let Some(section) = build.get(profile) { if let Some(section) = self
.data
.get("build")
.and_then(|v| v.as_table())
.and_then(|build| build.get(profile))
{
let table = section.as_table().ok_or_else(|| { let table = section.as_table().ok_or_else(|| {
ConfigError::Invalid(format!("build.{profile} must be a table")) ConfigError::Invalid(format!("build.{profile} must be a table"))
})?; })?;
@@ -226,12 +279,93 @@ impl Config {
fn set(&mut self, key: &str, value: Value) -> Result<(), ConfigError> { fn set(&mut self, key: &str, value: Value) -> Result<(), ConfigError> {
let parts: Vec<&str> = key.split('.').collect(); let parts: Vec<&str> = key.split('.').collect();
let previous = self.data.clone();
set_path(&mut self.data, &parts, value)?; set_path(&mut self.data, &parts, value)?;
self.typed = match parse_typed_config(&self.data) {
Ok(typed) => typed,
Err(err) => {
self.data = previous;
return Err(err);
}
};
if let Err(err) = self.validate() {
self.data = previous;
self.typed = parse_typed_config(&self.data)?;
return Err(err);
}
self.save()?; self.save()?;
Ok(()) Ok(())
} }
} }
fn parse_typed_config(value: &Value) -> Result<DcrConfig, ConfigError> {
value.clone().try_into().map_err(ConfigError::TomlDe)
}
fn validate_package_name(name: &str) -> Result<(), ConfigError> {
let trimmed = name.trim();
if trimmed != name {
return Err(ConfigError::Invalid(
"package.name must not contain leading or trailing whitespace".into(),
));
}
if trimmed == "." || trimmed == ".." || trimmed.contains("..") {
return Err(ConfigError::Invalid("package.name is invalid".into()));
}
if !trimmed
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(ConfigError::Invalid(
"package.name must contain only ASCII letters, digits, '_' or '-'".into(),
));
}
Ok(())
}
fn validate_language_config(language: &LanguageConfig, key: &str) -> Result<(), ConfigError> {
let values = language.values();
if values.is_empty() {
return Err(ConfigError::Invalid(format!("{key} is empty")));
}
for value in values {
validate_non_empty_string(value, key)?;
}
Ok(())
}
fn validate_toolchain(toolchain: Option<&ToolchainConfig>) -> Result<(), ConfigError> {
let Some(toolchain) = toolchain else {
return Ok(());
};
for (key, value) in [
("cc", toolchain.cc.as_deref()),
("cxx", toolchain.cxx.as_deref()),
("as", toolchain.assembler.as_deref()),
("ar", toolchain.ar.as_deref()),
("ld", toolchain.ld.as_deref()),
] {
if let Some(value) = value {
validate_non_empty_string(value, &format!("toolchain.{key}"))?;
}
}
Ok(())
}
fn validate_string_list(values: &[String], key: &str) -> Result<(), ConfigError> {
for value in values {
validate_non_empty_string(value, key)?;
}
Ok(())
}
fn validate_non_empty_string(value: &str, key: &str) -> Result<(), ConfigError> {
if value.trim().is_empty() {
return Err(ConfigError::Invalid(format!("{key} contains empty value")));
}
Ok(())
}
impl Config { impl Config {
fn validate_language(&self, value: &Value) -> Result<(), ConfigError> { fn validate_language(&self, value: &Value) -> Result<(), ConfigError> {
if let Some(s) = value.as_str() { if let Some(s) = value.as_str() {
@@ -277,7 +411,7 @@ impl Config {
} }
if let Some(kind) = table.get("kind").and_then(|v| v.as_str()) { if let Some(kind) = table.get("kind").and_then(|v| v.as_str()) {
let kind = kind.trim(); let kind = kind.trim();
if !kind.is_empty() && kind != "bin" && kind != "staticlib" && kind != "sharedlib" { if !kind.is_empty() && !VALID_KINDS.contains(&kind) {
return Err(ConfigError::Invalid(format!( return Err(ConfigError::Invalid(format!(
"build.{profile}.kind is invalid" "build.{profile}.kind is invalid"
))); )));
@@ -398,6 +532,11 @@ fn default_toml() -> Result<Value, ConfigError> {
"version".to_string(), "version".to_string(),
Value::String(DEFAULT_VERSION.to_string()), Value::String(DEFAULT_VERSION.to_string()),
); );
package.insert("type".to_string(), Value::String("none".to_string()));
package.insert("description".to_string(), Value::String("".to_string()));
package.insert("author".to_string(), Value::String("".to_string()));
package.insert("license".to_string(), Value::String("MIT".to_string()));
let mut build = Map::new(); let mut build = Map::new();
build.insert( build.insert(
"language".to_string(), "language".to_string(),
@@ -458,7 +597,29 @@ fn format_toml(value: &Value) -> Result<String, ConfigError> {
let mut out = String::new(); let mut out = String::new();
out.push_str("[package]\n"); out.push_str("[package]\n");
out.push_str(&format!("name = \"{name}\"\n")); out.push_str(&format!("name = \"{name}\"\n"));
out.push_str(&format!("version = \"{version}\"\n\n")); out.push_str(&format!("version = \"{version}\"\n"));
for key in [
"type",
"description",
"author",
"authors",
"homepage",
"license",
"repository",
"readme",
"keywords",
"categories",
] {
if let Some(val) = package.get(key) {
match val {
Value::String(s) => out.push_str(&format!("{key} = \"{s}\"\n")),
Value::Array(_) => out.push_str(&format!("{key} = {}\n", format_string_array(val))),
_ => {}
}
}
}
out.push('\n');
out.push_str("[build]\n"); out.push_str("[build]\n");
if language.starts_with('[') { if language.starts_with('[') {
@@ -522,6 +683,9 @@ fn format_dep_value(value: &Value) -> String {
Value::String(s) => format!("\"{s}\""), Value::String(s) => format!("\"{s}\""),
Value::Table(tbl) => { Value::Table(tbl) => {
let mut parts = Vec::new(); let mut parts = Vec::new();
if let Some(v) = tbl.get("version").and_then(|v| v.as_str()) {
parts.push(format!("version = \"{v}\""));
}
if let Some(v) = tbl.get("path").and_then(|v| v.as_str()) { if let Some(v) = tbl.get("path").and_then(|v| v.as_str()) {
parts.push(format!("path = \"{v}\"")); parts.push(format!("path = \"{v}\""));
} }
@@ -537,18 +701,18 @@ fn format_dep_value(value: &Value) -> String {
if let Some(v) = tbl.get("rev").and_then(|v| v.as_str()) { if let Some(v) = tbl.get("rev").and_then(|v| v.as_str()) {
parts.push(format!("rev = \"{v}\"")); parts.push(format!("rev = \"{v}\""));
} }
if let Some(v) = tbl.get("default-features").and_then(|v| v.as_bool()) {
parts.push(format!(
"default-features = {}",
if v { "true" } else { "false" }
));
}
if let Some(v) = tbl.get("features") {
parts.push(format!("features = {}", format_string_array(v)));
}
if let Some(v) = tbl.get("system").and_then(|v| v.as_bool()) { if let Some(v) = tbl.get("system").and_then(|v| v.as_bool()) {
parts.push(format!("system = {}", if v { "true" } else { "false" })); parts.push(format!("system = {}", if v { "true" } else { "false" }));
} }
if let Some(v) = tbl.get("include") {
parts.push(format!("include = {}", format_string_array(v)));
}
if let Some(v) = tbl.get("lib") {
parts.push(format!("lib = {}", format_string_array(v)));
}
if let Some(v) = tbl.get("libs") {
parts.push(format!("libs = {}", format_string_array(v)));
}
format!("{{ {} }}", parts.join(", ")) format!("{{ {} }}", parts.join(", "))
} }
_ => "\"\"".to_string(), _ => "\"\"".to_string(),
@@ -630,6 +794,21 @@ mod tests {
assert!(config.is_ok(), "should open valid toml"); assert!(config.is_ok(), "should open valid toml");
} }
#[test]
fn exposes_typed_config() {
let dir = temp_dir("typed_config");
let path = write_toml_file(
&dir,
"[package]\nname = \"typed\"\nversion = \"1.2.3\"\ntype = \"lib\"\n\n[build]\nlanguage = [\"c\", \"c++\"]\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"staticlib\"\ncflags = [\"-Wall\"]\n\n[dependencies]\nfoo = \"1.0.0\"\n",
);
let config = Config::open(&path.to_string_lossy()).unwrap();
assert_eq!(config.package().name, "typed");
assert_eq!(config.typed().package.version, "1.2.3");
assert_eq!(config.build_config().compiler, "clang");
assert_eq!(config.build_config().cflags, ["-Wall"]);
assert!(config.typed().dependencies.contains_key("foo"));
}
#[test] #[test]
fn open_invalid_toml_syntax() { fn open_invalid_toml_syntax() {
let dir = temp_dir("open_invalid"); let dir = temp_dir("open_invalid");
@@ -666,6 +845,35 @@ mod tests {
assert!(result.is_err(), "missing [build] should fail validation"); assert!(result.is_err(), "missing [build] should fail validation");
} }
#[test]
fn validate_wrong_field_type_fails() {
let dir = temp_dir("wrong_type");
let path = write_toml_file(
&dir,
"[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = [\"clang\"]\nkind = \"bin\"\n\n[dependencies]\n",
);
let result = Config::open(&path.to_string_lossy());
assert!(
result.is_err(),
"typed config should reject wrong field types"
);
}
#[test]
fn validate_invalid_package_names_fail() {
for name in [
"../evil", "bad/name", "bad name", "", " name", "name ", "a.b",
] {
let dir = temp_dir("bad_name");
let content = format!(
"[package]\nname = \"{name}\"\nversion = \"0.1.0\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"bin\"\n\n[dependencies]\n"
);
let path = write_toml_file(&dir, &content);
let result = Config::open(&path.to_string_lossy());
assert!(result.is_err(), "package name `{name}` should fail");
}
}
#[test] #[test]
fn validate_empty_language_fails() { fn validate_empty_language_fails() {
let dir = temp_dir("empty_lang"); let dir = temp_dir("empty_lang");
@@ -712,14 +920,16 @@ mod tests {
#[test] #[test]
fn validate_valid_kinds() { fn validate_valid_kinds() {
for kind in ["bin", "staticlib", "sharedlib"] { for &kind in VALID_KINDS {
let dir = temp_dir(&format!("kind_{kind}")); let dir = temp_dir("valid_kind");
let content = format!( let toml = format!(
"[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"{kind}\"\n\n[dependencies]\n" "[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"{kind}\"\n\n[dependencies]\n"
); );
let path = write_toml_file(&dir, &content); let path = write_toml_file(&dir, &toml);
let result = Config::open(&path.to_string_lossy()); assert!(
assert!(result.is_ok(), "kind '{kind}' should be valid"); Config::open(&path.to_string_lossy()).is_ok(),
"kind '{kind}' should be valid"
);
} }
} }

View File

@@ -1,7 +1,9 @@
#[allow(dead_code)]
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum DepSource { pub enum DepSource {
Path(String), Path(String),
Git { Git {
@@ -10,8 +12,13 @@ pub enum DepSource {
tag: Option<String>, tag: Option<String>,
rev: Option<String>, rev: Option<String>,
}, },
Registry {
version: String,
features: Option<Vec<String>>,
},
} }
#[allow(dead_code)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct DepSpec { pub struct DepSpec {
pub name: String, pub name: String,
@@ -21,13 +28,14 @@ pub struct DepSpec {
pub libs_raw: Option<Vec<String>>, pub libs_raw: Option<Vec<String>>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, Default)]
pub struct ResolvedDeps { pub struct ResolvedDeps {
pub include_dirs: Vec<String>, pub include_dirs: Vec<String>,
pub lib_dirs: Vec<String>, pub lib_dirs: Vec<String>,
pub libs: Vec<String>, pub libs: Vec<String>,
} }
#[allow(dead_code)]
pub fn resolve_path(project_root: &Path, raw: &str) -> Result<PathBuf, String> { pub fn resolve_path(project_root: &Path, raw: &str) -> Result<PathBuf, String> {
let p = Path::new(raw); let p = Path::new(raw);
let full = if p.is_absolute() { let full = if p.is_absolute() {
@@ -38,6 +46,7 @@ pub fn resolve_path(project_root: &Path, raw: &str) -> Result<PathBuf, String> {
Ok(full) Ok(full)
} }
#[allow(dead_code)]
pub fn resolve_paths( pub fn resolve_paths(
base: &Path, base: &Path,
raw: Option<&[String]>, raw: Option<&[String]>,
@@ -71,10 +80,12 @@ pub fn resolve_paths(
Ok(out) Ok(out)
} }
#[allow(dead_code)]
pub fn expand_profile(raw: &str, profile: &str) -> String { pub fn expand_profile(raw: &str, profile: &str) -> String {
raw.replace("{profile}", profile) raw.replace("{profile}", profile)
} }
#[allow(dead_code)]
pub fn sync_dep_dir(src: &Path, dst: &Path) -> std::io::Result<()> { pub fn sync_dep_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
if dst.exists() { if dst.exists() {
fs::remove_dir_all(dst)?; fs::remove_dir_all(dst)?;
@@ -82,6 +93,7 @@ pub fn sync_dep_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
copy_dir_all(src, dst) copy_dir_all(src, dst)
} }
#[allow(dead_code)]
pub fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> { pub fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
fs::create_dir_all(dst)?; fs::create_dir_all(dst)?;
for entry in fs::read_dir(src)? { for entry in fs::read_dir(src)? {

View File

@@ -1,5 +1,6 @@
use std::path::Path; use std::path::Path;
#[allow(dead_code)]
pub fn fetch_git_dep( pub fn fetch_git_dep(
url: &str, url: &str,
target_dir: &Path, target_dir: &Path,
@@ -29,6 +30,7 @@ pub fn fetch_git_dep(
Ok(()) Ok(())
} }
#[allow(dead_code)]
fn checkout_ref(repo: &git2::Repository, reference_str: &str) -> Result<(), String> { fn checkout_ref(repo: &git2::Repository, reference_str: &str) -> Result<(), String> {
let (object, reference) = repo let (object, reference) = repo
.revparse_ext(reference_str) .revparse_ext(reference_str)

View File

@@ -18,18 +18,20 @@ pub fn write_lock(
packages: &[DepLock], packages: &[DepLock],
) -> Result<(), String> { ) -> Result<(), String> {
let mut out = String::new(); let mut out = String::new();
out.push_str("[[package]]\n");
out.push_str(&format!("name = \"{}\"\n", escape_value(project_name)));
out.push_str(&format!(
"version = \"{}\"\n",
escape_value(project_version)
));
if !packages.is_empty() { if !packages.is_empty() {
out.push_str("[[package]]\n");
out.push_str(&format!("name = \"{}\"\n", escape_value(project_name)));
out.push_str(&format!( out.push_str(&format!(
"version = \"{}\"\n", "dependencies = [{}]\n",
escape_value(project_version)
));
out.push_str(&format!(
"dependencies = [{}]\n\n",
quote_list(&packages.iter().map(|p| p.name.clone()).collect::<Vec<_>>()) quote_list(&packages.iter().map(|p| p.name.clone()).collect::<Vec<_>>())
)); ));
} }
out.push('\n');
for pkg in packages { for pkg in packages {
out.push_str("[[package]]\n"); out.push_str("[[package]]\n");
out.push_str(&format!("name = \"{}\"\n", escape_value(&pkg.name))); out.push_str(&format!("name = \"{}\"\n", escape_value(&pkg.name)));
@@ -55,6 +57,7 @@ fn escape_value(input: &str) -> String {
input.replace('\\', "\\\\").replace('"', "\\\"") input.replace('\\', "\\\\").replace('"', "\\\"")
} }
#[allow(dead_code)]
pub fn read_dep_version(dep_path: &Path) -> Option<String> { pub fn read_dep_version(dep_path: &Path) -> Option<String> {
let path = dep_path.join("dcr.toml"); let path = dep_path.join("dcr.toml");
let content = fs::read_to_string(path).ok()?; let content = fs::read_to_string(path).ok()?;
@@ -67,6 +70,7 @@ pub fn read_dep_version(dep_path: &Path) -> Option<String> {
.map(|s| s.to_string()) .map(|s| s.to_string())
} }
#[allow(dead_code)]
pub fn compute_checksum(root: &Path) -> Result<String, String> { pub fn compute_checksum(root: &Path) -> Result<String, String> {
let mut files = Vec::new(); let mut files = Vec::new();
collect_files(root, root, &mut files)?; collect_files(root, root, &mut files)?;
@@ -82,6 +86,7 @@ pub fn compute_checksum(root: &Path) -> Result<String, String> {
Ok(to_hex(&hash)) Ok(to_hex(&hash))
} }
#[allow(dead_code)]
fn collect_files(root: &Path, dir: &Path, out: &mut Vec<String>) -> Result<(), String> { fn collect_files(root: &Path, dir: &Path, out: &mut Vec<String>) -> Result<(), String> {
for entry in fs::read_dir(dir).map_err(|err| format!("read_dir failed: {err}"))? { for entry in fs::read_dir(dir).map_err(|err| format!("read_dir failed: {err}"))? {
let entry = entry.map_err(|err| format!("read_dir failed: {err}"))?; let entry = entry.map_err(|err| format!("read_dir failed: {err}"))?;
@@ -105,6 +110,7 @@ fn collect_files(root: &Path, dir: &Path, out: &mut Vec<String>) -> Result<(), S
Ok(()) Ok(())
} }
#[allow(dead_code)]
fn to_hex(bytes: &[u8]) -> String { fn to_hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2); let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes { for b in bytes {

View File

@@ -1,23 +1,31 @@
pub mod common; pub mod common;
pub mod git; pub mod git;
pub mod lock; pub mod lock;
pub mod register;
use crate::core::config::Config; use crate::core::config::Config;
use std::fs; use crate::core::deps::common::ResolvedDeps;
use crate::core::deps::lock::{DepLock, write_lock};
use std::path::Path; use std::path::Path;
use toml::Value;
pub use common::{DepSource, DepSpec, ResolvedDeps}; fn dep_version(path: &Path) -> String {
use common::{expand_profile, resolve_path, resolve_paths, sync_dep_dir}; Config::open(&path.join("dcr.toml").to_string_lossy())
use git::fetch_git_dep; .ok()
use lock::{DepLock, compute_checksum, read_dep_version, write_lock}; .and_then(|c| {
c.get("package.version")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
.unwrap_or_default()
}
pub fn resolve_deps( pub fn resolve_deps(
config: &Config, config: &Config,
profile: &str, _profile: &str,
target: Option<&str>, _target: Option<&str>,
project_root: &Path, project_root: &Path,
) -> Result<ResolvedDeps, String> { ) -> Result<ResolvedDeps, String> {
let mut resolved = ResolvedDeps::default();
let project_name = config let project_name = config
.get("package.name") .get("package.name")
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
@@ -28,132 +36,101 @@ pub fn resolve_deps(
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.unwrap_or("") .unwrap_or("")
.to_string(); .to_string();
let deps = parse_dependencies(config, profile, target)?;
if deps.is_empty() {
return Ok(ResolvedDeps {
include_dirs: Vec::new(),
lib_dirs: Vec::new(),
libs: Vec::new(),
});
}
let mut include_dirs = Vec::new(); let deps_table = config.get("dependencies").and_then(|v| v.as_table());
let mut lib_dirs = Vec::new(); let mut lock_packages: Vec<DepLock> = Vec::new();
let mut libs = Vec::new();
let mut lock_packages = Vec::new();
for dep in deps { if let Some(deps) = deps_table {
let (dep_path, is_git) = match &dep.source { for (name, value) in deps {
DepSource::Path(path_raw) => { if register::is_registry_dep(value) {
let expanded = expand_profile(path_raw, profile); let pkg_info = register::resolve_package_from_registry(name)?;
(resolve_path(project_root, &expanded)?, false) let dep_root = register::package_root_from_registry_info(&pkg_info)?;
}
DepSource::Git {
url,
branch,
tag,
rev,
} => {
let git_deps_dir = project_root
.join("target")
.join(profile)
.join("deps")
.join("git");
fs::create_dir_all(&git_deps_dir)
.map_err(|e| format!("failed to create target/{}/deps/git: {}", profile, e))?;
let dep_dir = git_deps_dir.join(&dep.name);
if !dep_dir.exists() {
use crate::utils::text::{BOLD_GREEN, colored};
use std::io::{self, Write};
print!(
" {} dependency `{}` from {}...",
colored("Fetching", BOLD_GREEN),
dep.name,
url
);
io::stdout().flush().ok();
fetch_git_dep( resolved.include_dirs.push(
url, register::registry_include_dir(&dep_root)
&dep_dir, .to_string_lossy()
branch.as_deref(), .to_string(),
tag.as_deref(), );
rev.as_deref(), resolved.lib_dirs.push(
)?; register::registry_lib_dir(&dep_root)
.to_string_lossy()
.to_string(),
);
resolved.libs.push(name.clone());
print!( lock_packages.push(DepLock {
"\r\x1B[2K {} dependency `{}`\n", name: name.clone(),
colored("Fetched", BOLD_GREEN), version: pkg_info
dep.name .get("version")
); .and_then(|v| v.as_str())
io::stdout().flush().ok(); .unwrap_or("")
.to_string(),
checksum: String::new(),
source: format!(
"registry+{}",
pkg_info
.get("registry_url")
.and_then(|v| v.as_str())
.unwrap_or("https://dcr-registry.pages.dev")
),
});
} else if let Some(path) = path_dep_path(value) {
let dep_root = project_root.join(path);
if let Some(table) = value.as_table() {
if let Some(includes) = table.get("include").and_then(|v| v.as_array()) {
for inc in includes {
if let Some(inc_str) = inc.as_str() {
resolved
.include_dirs
.push(dep_root.join(inc_str).to_string_lossy().to_string());
}
}
} else {
push_if_exists(&mut resolved.include_dirs, &dep_root.join("include"));
}
if let Some(lib_dirs) = table.get("lib").and_then(|v| v.as_array()) {
for lib_dir in lib_dirs {
if let Some(lib_dir_str) = lib_dir.as_str() {
resolved
.lib_dirs
.push(dep_root.join(lib_dir_str).to_string_lossy().to_string());
}
}
} else {
push_default_lib_dirs(&mut resolved.lib_dirs, &dep_root);
}
if let Some(libs) = table.get("libs").and_then(|v| v.as_array()) {
for lib in libs {
if let Some(lib_str) = lib.as_str() {
resolved.libs.push(lib_str.to_string());
}
}
} else {
resolved.libs.push(name.clone());
}
} else { } else {
fetch_git_dep( push_if_exists(&mut resolved.include_dirs, &dep_root.join("include"));
url, push_default_lib_dirs(&mut resolved.lib_dirs, &dep_root);
&dep_dir, resolved.libs.push(name.clone());
branch.as_deref(),
tag.as_deref(),
rev.as_deref(),
)?;
} }
(dep_dir, true)
lock_packages.push(DepLock {
name: name.clone(),
version: dep_version(&dep_root),
checksum: String::new(),
source: format!("path+{}", dep_root.display()),
});
} else if let Some(git_info) = git_dep(value) {
lock_packages.push(DepLock {
name: name.clone(),
version: git_info.version.unwrap_or_default(),
checksum: String::new(),
source: format!("git+{}", git_info.url),
});
} }
};
if !dep_path.is_dir() {
return Err(format!(
"Dependency '{}' path is not a directory: {}",
dep.name,
dep_path.display()
));
} }
let include = resolve_paths(&dep_path, dep.include_raw.as_deref(), &["include"], profile)?;
let lib = resolve_paths(
&dep_path,
dep.lib_raw.as_deref(),
&["lib", "lib64"],
profile,
)?;
let libs_list = dep
.libs_raw
.clone()
.unwrap_or_else(|| vec![dep.name.clone()]);
if include.is_empty() || lib.is_empty() {
return Err(format!(
"Dependency '{}' missing include/lib dirs. Add include/lib in dcr.toml.",
dep.name
));
}
include_dirs.extend(include.iter().map(|p| p.to_string_lossy().to_string()));
lib_dirs.extend(lib.iter().map(|p| p.to_string_lossy().to_string()));
libs.extend(libs_list.iter().cloned());
if !is_git {
let dep_cache = project_root
.join("target")
.join(profile)
.join("deps")
.join(&dep.name);
sync_dep_dir(&dep_path, &dep_cache)
.map_err(|err| format!("Failed to sync dep {}: {err}", dep.name))?;
}
let dep_version = read_dep_version(&dep_path).unwrap_or_else(|| "0.0.0".to_string());
let dep_checksum = compute_checksum(&dep_path)
.map_err(|err| format!("Failed to hash dep {}: {err}", dep.name))?;
let source_str = match &dep.source {
DepSource::Path(p) => format!("path+{}", p),
DepSource::Git { url, .. } => format!("git+{}", url),
};
lock_packages.push(DepLock {
name: dep.name.clone(),
version: dep_version,
checksum: dep_checksum,
source: source_str,
});
} }
write_lock( write_lock(
@@ -163,124 +140,88 @@ pub fn resolve_deps(
&lock_packages, &lock_packages,
)?; )?;
Ok(ResolvedDeps { Ok(resolved)
include_dirs,
lib_dirs,
libs,
})
} }
fn parse_dependencies( struct GitDep<'a> {
config: &Config, url: &'a str,
profile: &str, version: Option<String>,
target: Option<&str>,
) -> Result<Vec<DepSpec>, String> {
let mut deps_table = None;
let combinations = if let Some(t) = target {
let normalized_t = crate::cli::build::normalize_target_os(t);
vec![
format!("dependencies.{}.{}", normalized_t, profile),
format!("dependencies.{}.{}", profile, normalized_t),
format!("dependencies.{}", normalized_t),
format!("dependencies.{}", profile),
"dependencies".to_string(),
]
} else {
vec![
format!("dependencies.{}", profile),
"dependencies".to_string(),
]
};
for key in combinations {
if let Some(val) = config.get(&key).and_then(|v| v.as_table()) {
deps_table = Some(val);
break;
}
}
let deps_table = match deps_table {
Some(t) => t,
None => return Ok(Vec::new()),
};
let mut deps = Vec::new();
for (name, value) in deps_table {
match value {
Value::String(path) => {
deps.push(DepSpec {
name: name.to_string(),
source: DepSource::Path(path.to_string()),
include_raw: None,
lib_raw: None,
libs_raw: None,
});
}
Value::Table(tbl) => {
if tbl.get("system").and_then(|v| v.as_bool()).unwrap_or(false) {
return Err(format!(
"Dependency '{}' uses system=true, which is not supported yet",
name
));
}
let source = if let Some(git_url) = tbl.get("git").and_then(|v| v.as_str()) {
DepSource::Git {
url: git_url.to_string(),
branch: tbl
.get("branch")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
tag: tbl
.get("tag")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
rev: tbl
.get("rev")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
}
} else if let Some(path) = tbl.get("path").and_then(|v| v.as_str()) {
DepSource::Path(path.to_string())
} else {
return Err(format!("Dependency '{}' missing path or git", name));
};
let include = parse_string_list(tbl.get("include"), name, "include")?;
let lib = parse_string_list(tbl.get("lib"), name, "lib")?;
let libs = parse_string_list(tbl.get("libs"), name, "libs")?;
deps.push(DepSpec {
name: name.to_string(),
source,
include_raw: include,
lib_raw: lib,
libs_raw: libs,
});
}
_ => {
return Err(format!("Dependency '{}' must be a string or a table", name));
}
}
}
deps.sort_by(|a, b| a.name.cmp(&b.name));
Ok(deps)
} }
fn parse_string_list( fn git_dep(value: &toml::Value) -> Option<GitDep<'_>> {
value: Option<&Value>, if let Some(table) = value.as_table()
dep_name: &str, && let Some(url) = table.get("git").and_then(|v| v.as_str())
key: &str, {
) -> Result<Option<Vec<String>>, String> { let version = table
let Some(value) = value else { return Ok(None) }; .get("version")
let list = value.as_array().ok_or_else(|| { .and_then(|v| v.as_str())
format!( .map(|s| s.to_string());
"Dependency '{}' field '{}' must be an array of strings", return Some(GitDep { url, version });
dep_name, key }
) None
})?; }
let mut out = Vec::new();
for item in list { fn path_dep_path(value: &toml::Value) -> Option<&str> {
let s = item if let Some(table) = value.as_table() {
.as_str() return table.get("path").and_then(|v| v.as_str());
.ok_or_else(|| format!("Dependency '{}' field '{}' must be strings", dep_name, key))?; }
out.push(s.to_string()); register::path_from_string_dep(value)
}
fn push_if_exists(paths: &mut Vec<String>, path: &Path) {
if path.exists() {
paths.push(path.to_string_lossy().to_string());
}
}
fn push_default_lib_dirs(paths: &mut Vec<String>, dep_root: &Path) {
for dir in ["lib", "lib64"] {
push_if_exists(paths, &dep_root.join(dir));
}
push_if_exists(paths, &dep_root.join("target").join("lib"));
}
#[cfg(test)]
mod tests {
use super::*;
use toml::Value;
#[test]
fn path_dep_path_supports_table_and_legacy_strings() {
let table = Value::Table(
[(
"path".to_string(),
Value::String("./libs/mylib".to_string()),
)]
.into_iter()
.collect(),
);
assert_eq!(path_dep_path(&table), Some("./libs/mylib"));
assert_eq!(
path_dep_path(&Value::String("path:./libs/mylib".to_string())),
Some("./libs/mylib")
);
assert_eq!(
path_dep_path(&Value::String("./libs/mylib".to_string())),
Some("./libs/mylib")
);
assert_eq!(path_dep_path(&Value::String("1.2.3".to_string())), None);
}
#[test]
fn default_lib_dirs_include_packaged_library_output() {
let root = std::env::temp_dir().join(format!(
"dcr_default_lib_dirs_{}_{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(root.join("target/lib")).unwrap();
let mut paths = Vec::new();
push_default_lib_dirs(&mut paths, &root);
assert!(paths.iter().any(|p| p.ends_with("target/lib")));
let _ = std::fs::remove_dir_all(root);
} }
Ok(Some(out))
} }

223
src/core/deps/register.rs Normal file
View File

@@ -0,0 +1,223 @@
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::fs;
use std::path::{Path, PathBuf};
use toml::Value as TomlValue;
#[derive(Debug, Serialize, Deserialize)]
pub struct Registry {
pub url: String,
pub priority: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DcrConfig {
pub registry: std::collections::HashMap<String, Registry>,
}
fn home_dir() -> Option<PathBuf> {
if let Ok(home) = std::env::var("HOME") {
return Some(PathBuf::from(home));
}
if let Ok(profile) = std::env::var("USERPROFILE") {
return Some(PathBuf::from(profile));
}
None
}
fn dcr_config_dir() -> Option<PathBuf> {
home_dir().map(|h| h.join(".dcr"))
}
pub fn get_registry_config() -> Option<DcrConfig> {
let home = home_dir()?;
let config_path = home.join(".dcr/config.toml");
if !config_path.exists() {
return None;
}
let content = fs::read_to_string(config_path).ok()?;
toml::from_str(&content).ok()
}
pub fn get_index_path() -> PathBuf {
std::env::var("DCR_INDEX_PATH")
.map(PathBuf::from)
.unwrap_or_else(|_| {
dcr_config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("index.json")
})
}
pub fn get_registry_cache_root() -> PathBuf {
let index_path = get_index_path();
if let Some(parent) = index_path.parent() {
if parent.exists() {
return parent.to_path_buf();
}
if let Err(e) = std::fs::create_dir_all(parent) {
eprintln!("Warning: failed to create registry cache directory: {e}");
}
parent.to_path_buf()
} else {
PathBuf::from(".")
}
}
pub fn package_root_from_registry_info(pkg_info: &JsonValue) -> Result<PathBuf, String> {
let raw_path = pkg_info
.get("path")
.and_then(|v| v.as_str())
.ok_or("Registry package is missing path")?;
if raw_path.trim().is_empty() {
return Err("Registry package path is empty".to_string());
}
let path = Path::new(raw_path);
let full_path = if path.is_absolute() {
path.to_path_buf()
} else {
get_registry_cache_root().join(path)
};
if full_path.file_name().and_then(|v| v.to_str()) == Some("dcr.toml") {
return full_path
.parent()
.map(Path::to_path_buf)
.ok_or_else(|| format!("Invalid registry package path: {}", full_path.display()));
}
Ok(full_path)
}
pub fn registry_include_dir(dep_root: &Path) -> PathBuf {
dep_root.join("target").join("include")
}
pub fn registry_lib_dir(dep_root: &Path) -> PathBuf {
dep_root.join("target").join("lib")
}
pub fn resolve_package_from_registry(name: &str) -> Result<JsonValue, String> {
let config = get_registry_config().ok_or("No registry config found")?;
let mut registries: Vec<(&String, &Registry)> = config.registry.iter().collect();
registries.sort_by_key(|b| std::cmp::Reverse(b.1.priority));
for (_name_reg, _reg) in registries {
let index_path = get_index_path();
if index_path.exists() {
let index_content = fs::read_to_string(&index_path).map_err(|e| e.to_string())?;
let index: JsonValue =
serde_json::from_str(&index_content).map_err(|e| e.to_string())?;
if let Some(pkgs) = index.get("packages").and_then(|v| v.as_array()) {
for pkg in pkgs {
if pkg.get("name").and_then(|v| v.as_str()) == Some(name) {
return Ok(pkg.clone());
}
}
}
}
}
Err(format!(
"Package {} not found in registry (checked: {:?})",
name,
get_index_path()
))
}
pub fn is_registry_dep(value: &TomlValue) -> bool {
if let Some(raw) = value.as_str() {
let raw = raw.trim();
return !is_path_like_string(raw) && !is_git_like_string(raw);
}
if let Some(table) = value.as_table() {
if table.contains_key("git") || table.contains_key("path") || table.contains_key("url") {
return false;
}
table.contains_key("version")
|| table.contains_key("features")
|| table.contains_key("optional")
|| table.contains_key("registry")
} else {
false
}
}
pub fn path_from_string_dep(value: &TomlValue) -> Option<&str> {
let raw = value.as_str()?.trim();
if let Some(path) = raw.strip_prefix("path:") {
return Some(path);
}
if is_path_like_string(raw) {
return Some(raw);
}
None
}
fn is_path_like_string(raw: &str) -> bool {
raw.starts_with("path:")
|| raw.starts_with("./")
|| raw.starts_with("../")
|| raw.starts_with('/')
|| raw.starts_with("~/")
|| raw.contains('\\')
}
fn is_git_like_string(raw: &str) -> bool {
raw.starts_with("git:")
|| raw.starts_with("github:")
|| raw.starts_with("gitlab:")
|| raw.starts_with("http://")
|| raw.starts_with("https://")
|| raw.starts_with("git@")
}
#[cfg(test)]
mod tests {
use super::*;
use toml::map::Map;
#[test]
fn registry_dep_detection_excludes_local_and_git_strings() {
assert!(is_registry_dep(&TomlValue::String("1.2.3".to_string())));
assert!(!is_registry_dep(&TomlValue::String(
"path:./libs/mylib".to_string()
)));
assert!(!is_registry_dep(&TomlValue::String(
"./libs/mylib".to_string()
)));
assert!(!is_registry_dep(&TomlValue::String(
"git:https://example.com/repo.git".to_string()
)));
}
#[test]
fn registry_dep_detection_excludes_source_tables() {
let mut path_table = Map::new();
path_table.insert(
"path".to_string(),
TomlValue::String("./libs/mylib".to_string()),
);
assert!(!is_registry_dep(&TomlValue::Table(path_table)));
let mut registry_table = Map::new();
registry_table.insert("features".to_string(), TomlValue::Array(Vec::new()));
assert!(is_registry_dep(&TomlValue::Table(registry_table)));
}
#[test]
fn registry_package_root_accepts_package_dir_or_manifest_path() {
let pkg = serde_json::json!({ "path": "/tmp/pkg" });
assert_eq!(
package_root_from_registry_info(&pkg).unwrap(),
PathBuf::from("/tmp/pkg")
);
let pkg = serde_json::json!({ "path": "/tmp/pkg/dcr.toml" });
assert_eq!(
package_root_from_registry_info(&pkg).unwrap(),
PathBuf::from("/tmp/pkg")
);
}
}

View File

@@ -1,5 +1,6 @@
pub mod builder; pub mod builder;
pub mod config; pub mod config;
pub mod deps; pub mod deps;
pub mod registry;
pub mod runner; pub mod runner;
pub mod workspace; pub mod workspace;

52
src/core/registry.rs Normal file
View File

@@ -0,0 +1,52 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
#[derive(Debug, Serialize, Deserialize)]
pub struct Registry {
pub url: String,
pub priority: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub registry: HashMap<String, Registry>,
}
pub struct RegistryManager {
pub config: Config,
#[allow(dead_code)]
pub path: PathBuf,
}
fn home_dir() -> Option<PathBuf> {
if let Ok(home) = std::env::var("HOME") {
return Some(PathBuf::from(home));
}
if let Ok(profile) = std::env::var("USERPROFILE") {
return Some(PathBuf::from(profile));
}
None
}
impl RegistryManager {
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
let dcr_dir = home_dir()
.ok_or("Cannot determine home directory")?
.join(".dcr");
let config_path = dcr_dir.join("config.toml");
if !config_path.exists() {
return Err("Config file ~/.dcr/config.toml not found".into());
}
let content = fs::read_to_string(&config_path)?;
let config: Config = toml::from_str(&content)?;
Ok(Self {
config,
path: dcr_dir,
})
}
}

View File

@@ -1,44 +1,21 @@
use crate::platform; use crate::platform;
use crate::utils::fs::check_dir;
use crate::utils::log::warn;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
pub fn run_binary(project_name: &str, profile: &str, target_dir: Option<&str>) -> i32 { pub fn run_binary(project_name: &str, profile: &str, target_dir: Option<&str>) -> i32 {
let bin_path = platform::bin_path(profile, project_name, target_dir); let bin_path = platform::bin_path(profile, project_name, target_dir);
if Path::new(&bin_path).exists() { if Path::new(&bin_path).exists() {
let output = Command::new(&bin_path) let output = Command::new(&bin_path).output();
.output() match output {
.unwrap_or_else(|_| panic!("Failed to run {}", bin_path)); Ok(o) => {
print!("{}", String::from_utf8_lossy(&output.stdout)); print!("{}", String::from_utf8_lossy(&o.stdout));
eprint!("{}", String::from_utf8_lossy(&output.stderr)); eprint!("{}", String::from_utf8_lossy(&o.stderr));
return output.status.code().unwrap_or(1); return o.status.code().unwrap_or(0);
}
Err(_) => {
return 1;
}
}
} }
if target_dir.is_none()
&& check_dir(Some(&format!("target/{profile}")))
.unwrap_or_default()
.contains(&profile.to_string())
{
warn("Launch of the latest release");
let bin_path = platform::bin_path(profile, project_name, target_dir);
let output = Command::new(&bin_path)
.output()
.unwrap_or_else(|_| panic!("Failed to run {}", &bin_path));
print!("{}", String::from_utf8_lossy(&output.stdout));
eprint!("{}", String::from_utf8_lossy(&output.stderr));
return output.status.code().unwrap_or(1);
}
if target_dir.is_some() && Path::new(&bin_path).exists() {
warn("Launch of the latest release");
let output = Command::new(&bin_path)
.output()
.unwrap_or_else(|_| panic!("Failed to run {}", &bin_path));
print!("{}", String::from_utf8_lossy(&output.stdout));
eprint!("{}", String::from_utf8_lossy(&output.stderr));
return output.status.code().unwrap_or(1);
}
1 1
} }

View File

@@ -1,4 +1,5 @@
use crate::core::config::Config; use crate::core::config::Config;
use crate::utils::build::normalize_target_os;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use toml::Value; use toml::Value;
@@ -24,7 +25,7 @@ pub fn parse_workspace(
let mut table = None; let mut table = None;
// Order: workspace.target.profile, workspace.profile.target, workspace.target, workspace.profile, workspace // Order: workspace.target.profile, workspace.profile.target, workspace.target, workspace.profile, workspace
let combinations = if let Some(t) = target { let combinations = if let Some(t) = target {
let normalized_t = crate::cli::build::normalize_target_os(t); let normalized_t = normalize_target_os(t);
vec![ vec![
format!("workspace.{}.{}", normalized_t, profile), format!("workspace.{}.{}", normalized_t, profile),
format!("workspace.{}.{}", profile, normalized_t), format!("workspace.{}.{}", profile, normalized_t),

View File

@@ -18,9 +18,11 @@ fn main() {
let code = match cmd { let code = match cmd {
"new" => cli::r#new::new(rest), "new" => cli::r#new::new(rest),
"init" => cli::init::init(rest), "init" => cli::init::init(rest),
"setup" => cli::setup::setup(rest),
"add" => cli::add::add(rest), "add" => cli::add::add(rest),
"build" => cli::build::build(rest), "build" => cli::build::build(rest),
"run" => cli::run::run(rest), "run" => cli::run::run(rest),
"tree" => cli::tree::tree(rest),
"test" | "tests" => cli::test::test(rest), "test" | "tests" => cli::test::test(rest),
"clean" => cli::clean::clean(rest), "clean" => cli::clean::clean(rest),
"gen" => cli::r#gen::r#gen(rest), "gen" => cli::r#gen::r#gen(rest),

View File

@@ -1,21 +1,55 @@
pub fn bin_path(profile: &str, name: &str, target_dir: Option<&str>) -> String { pub fn bin_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir { match target_dir {
Some(dir) => format!("{}/{}", dir.trim_end_matches('/'), name), Some(dir) => format!("{}/{}", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}"), None => {
let arch = std::env::consts::ARCH;
let target = format!("{arch}-unknown-linux-gnu");
format!("./target/{target}/{profile}/{name}")
}
} }
} }
pub fn lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String { pub fn lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir { match target_dir {
Some(dir) => format!("{}/lib{}.a", dir.trim_end_matches('/'), name), Some(dir) => format!("{}/lib{}.a", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/lib{name}.a"), None => {
let arch = std::env::consts::ARCH;
let target = format!("{arch}-unknown-linux-gnu");
format!("./target/{target}/{profile}/lib{name}.a")
}
}
}
pub fn elf_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir {
Some(dir) => format!("{}/{}", dir.trim_end_matches('/'), name),
None => {
let arch = std::env::consts::ARCH;
let target = format!("{arch}-unknown-linux-gnu");
format!("./target/{target}/{profile}/{name}")
}
}
}
pub fn efi_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir {
Some(dir) => format!("{}/{}.efi", dir.trim_end_matches('/'), name),
None => {
let arch = std::env::consts::ARCH;
let target = format!("{arch}-unknown-linux-gnu");
format!("./target/{target}/{profile}/{name}.efi")
}
} }
} }
pub fn shared_lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String { pub fn shared_lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir { match target_dir {
Some(dir) => format!("{}/lib{}.so", dir.trim_end_matches('/'), name), Some(dir) => format!("{}/lib{}.so", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/lib{name}.so"), None => {
let arch = std::env::consts::ARCH;
let target = format!("{arch}-unknown-linux-gnu");
format!("./target/{target}/{profile}/lib{name}.so")
}
} }
} }
@@ -25,12 +59,16 @@ mod tests {
#[test] #[test]
fn bin_path_default() { fn bin_path_default() {
assert_eq!(bin_path("debug", "hello", None), "./target/debug/hello"); let arch = std::env::consts::ARCH;
let expected = format!("./target/{arch}-unknown-linux-gnu/debug/hello");
assert_eq!(bin_path("debug", "hello", None), expected);
} }
#[test] #[test]
fn bin_path_release() { fn bin_path_release() {
assert_eq!(bin_path("release", "hello", None), "./target/release/hello"); let arch = std::env::consts::ARCH;
let expected = format!("./target/{arch}-unknown-linux-gnu/release/hello");
assert_eq!(bin_path("release", "hello", None), expected);
} }
#[test] #[test]
@@ -45,10 +83,9 @@ mod tests {
#[test] #[test]
fn lib_path_default() { fn lib_path_default() {
assert_eq!( let arch = std::env::consts::ARCH;
lib_path("debug", "mylib", None), let expected = format!("./target/{arch}-unknown-linux-gnu/debug/libmylib.a");
"./target/debug/libmylib.a" assert_eq!(lib_path("debug", "mylib", None), expected);
);
} }
#[test] #[test]
@@ -58,10 +95,9 @@ mod tests {
#[test] #[test]
fn shared_lib_path_default() { fn shared_lib_path_default() {
assert_eq!( let arch = std::env::consts::ARCH;
shared_lib_path("debug", "mylib", None), let expected = format!("./target/{arch}-unknown-linux-gnu/debug/libmylib.so");
"./target/debug/libmylib.so" assert_eq!(shared_lib_path("debug", "mylib", None), expected);
);
} }
#[test] #[test]

View File

@@ -12,6 +12,20 @@ pub fn lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
} }
} }
pub fn elf_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir {
Some(dir) => format!("{}/{}", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}"),
}
}
pub fn efi_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir {
Some(dir) => format!("{}/{}.efi", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}.efi"),
}
}
pub fn shared_lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String { pub fn shared_lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir { match target_dir {
Some(dir) => format!("{}/lib{}.dylib", dir.trim_end_matches('/'), name), Some(dir) => format!("{}/lib{}.dylib", dir.trim_end_matches('/'), name),

View File

@@ -27,6 +27,50 @@ pub fn bin_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
} }
} }
pub fn elf_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
#[cfg(target_os = "linux")]
{
linux::elf_path(profile, name, target_dir)
}
#[cfg(target_os = "macos")]
{
return macos::elf_path(profile, name, target_dir);
}
#[cfg(target_os = "windows")]
{
return windows::elf_path(profile, name, target_dir);
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
match target_dir {
Some(dir) => format!("{}/{}", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}"),
}
}
}
pub fn efi_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
#[cfg(target_os = "linux")]
{
linux::efi_path(profile, name, target_dir)
}
#[cfg(target_os = "macos")]
{
return macos::efi_path(profile, name, target_dir);
}
#[cfg(target_os = "windows")]
{
return windows::efi_path(profile, name, target_dir);
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
match target_dir {
Some(dir) => format!("{}/{}.efi", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}.efi"),
}
}
}
pub fn lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String { pub fn lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {

View File

@@ -12,6 +12,20 @@ pub fn lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
} }
} }
pub fn elf_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir {
Some(dir) => format!("{}/{}.exe", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}.exe"),
}
}
pub fn efi_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir {
Some(dir) => format!("{}/{}.efi", dir.trim_end_matches('/'), name),
None => format!("./target/{profile}/{name}.efi"),
}
}
pub fn shared_lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String { pub fn shared_lib_path(profile: &str, name: &str, target_dir: Option<&str>) -> String {
match target_dir { match target_dir {
Some(dir) => format!("{}/{}.dll", dir.trim_end_matches('/'), name), Some(dir) => format!("{}/{}.dll", dir.trim_end_matches('/'), name),

376
src/utils/build.rs Normal file
View File

@@ -0,0 +1,376 @@
use crate::core::config::Config;
use crate::utils::log::warn;
pub struct VersionInfo {
pub full: String,
pub major: String,
pub minor: String,
pub patch: String,
pub suffix: String,
pub suffix_dash: String,
}
pub fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}
pub fn normalize_target_os(target: &str) -> &str {
match target {
"linux" => "x86_64-unknown-linux-gnu",
"macos" => "x86_64-apple-darwin",
"windows" => "x86_64-pc-windows-msvc",
_ if target.contains('-') => target,
_ => {
warn(&format!(
"Unknown target '{}', using as-is. Supported short names: linux, macos, windows",
target
));
target
}
}
}
pub fn get_config_str(config: &Config, key: &str) -> String {
config
.get(key)
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string()
}
pub fn profile_table<'a>(config: &'a Config, profile: &str) -> Option<&'a toml::value::Table> {
config
.get("build")
.and_then(|v| v.as_table())
.and_then(|b| b.get(profile))
.and_then(|v| v.as_table())
}
pub fn get_config_opt(config: &Config, key: &str) -> Option<String> {
let value = config.get(key)?.as_str()?;
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
pub fn get_string_with_profile(config: &Config, field: &str, profile: &str) -> String {
let base = get_config_str(config, &format!("build.{field}"));
let Some(table) = profile_table(config, profile) else {
return base;
};
let value = table.get(field).and_then(|v| v.as_str()).unwrap_or("");
let trimmed = value.trim();
if trimmed.is_empty() {
base
} else {
trimmed.to_string()
}
}
pub fn get_config_list(config: &Config, key: &str) -> Vec<String> {
config
.get(key)
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str())
.map(|s| s.to_string())
.collect()
})
.unwrap_or_default()
}
pub fn get_list_with_profile(config: &Config, field: &str, profile: &str) -> Vec<String> {
let mut out = get_config_list(config, &format!("build.{field}"));
if let Some(table) = profile_table(config, profile)
&& let Some(extra) = table.get(field).and_then(|v| v.as_array())
{
out.extend(
extra
.iter()
.filter_map(|v| v.as_str())
.map(|s| s.to_string()),
);
}
out
}
pub fn get_bool_with_profile(config: &Config, field: &str, profile: &str, default: bool) -> bool {
let base = config
.get(&format!("build.{field}"))
.and_then(|v| v.as_bool());
let profile_val =
profile_table(config, profile).and_then(|t| t.get(field).and_then(|v| v.as_bool()));
profile_val.or(base).unwrap_or(default)
}
pub fn get_language_with_profile(config: &Config, profile: &str) -> Result<String, String> {
if let Some(table) = profile_table(config, profile)
&& let Some(value) = table.get("language")
{
return parse_language_value(value, "build.language");
}
match config.get("build.language") {
Some(v) => parse_language_value(v, "build.language"),
None => Err("build.language is missing".to_string()),
}
}
pub fn get_language_with_profile_or_default(config: &Config, profile: &str) -> String {
get_language_with_profile(config, profile).unwrap_or_else(|_| "c".to_string())
}
pub fn parse_language_value(value: &toml::Value, key: &str) -> Result<String, String> {
if let Some(s) = value.as_str() {
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} is empty"));
}
return Ok(trimmed.to_string());
}
let arr = value
.as_array()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let mut parts = Vec::new();
for item in arr {
let s = item
.as_str()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} contains empty value"));
}
parts.push(trimmed.to_string());
}
if parts.is_empty() {
return Err(format!("{key} is empty"));
}
Ok(parts.join("+"))
}
pub fn resolve_compiler(
language: &str,
compiler: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> String {
let lang = primary_language(language);
env_override_compiler(&lang)
.or_else(|| toolchain_override_compiler(&lang, tc_cc, tc_cxx, tc_as))
.unwrap_or_else(|| compiler.to_string())
}
fn env_override_compiler(lang: &str) -> Option<String> {
if let Ok(value) = std::env::var("DCR_COMPILER") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
if lang == "asm" {
if let Ok(value) = std::env::var("DCR_AS") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
return None;
}
if (lang == "c++" || lang == "cpp" || lang == "cxx")
&& let Ok(value) = std::env::var("DCR_CXX")
{
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
if let Ok(value) = std::env::var("DCR_CC") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
None
}
fn toolchain_override_compiler(
lang: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> Option<String> {
if lang == "asm" {
return tc_as.map(|v| v.to_string());
}
if (lang == "c++" || lang == "cpp" || lang == "cxx")
&& let Some(v) = tc_cxx
{
return Some(v.to_string());
}
tc_cc.map(|v| v.to_string())
}
pub fn primary_language(language: &str) -> String {
let parts: Vec<String> = language
.split('+')
.map(|p| p.trim().to_lowercase())
.filter(|p| !p.is_empty())
.collect();
for p in &parts {
if p == "c++" || p == "cpp" || p == "cxx" {
return p.clone();
}
}
if parts.iter().any(|p| p == "c") {
return "c".to_string();
}
if parts.iter().any(|p| p == "asm") {
return "asm".to_string();
}
language.to_lowercase()
}
pub fn resolve_tool(env_key: &str, fallback: Option<&str>) -> Option<String> {
if let Ok(value) = std::env::var(env_key) {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
fallback.map(|v| v.to_string())
}
pub fn resolve_pkg_config_flags(
pkgs: &[String],
base_cflags: &[String],
base_ldflags: &[String],
) -> Result<(Vec<String>, Vec<String>), String> {
let mut cflags = base_cflags.to_vec();
let mut ldflags = base_ldflags.to_vec();
for pkg in pkgs {
let c_out = run_pkg_config(pkg, "--cflags")?;
let l_out = run_pkg_config(pkg, "--libs")?;
cflags.extend(split_flags(&c_out));
ldflags.extend(split_flags(&l_out));
}
Ok((cflags, ldflags))
}
pub fn resolve_pkg_config_flags_lossy(
pkgs: &[String],
base_cflags: &[String],
base_ldflags: &[String],
) -> (Vec<String>, Vec<String>) {
match resolve_pkg_config_flags(pkgs, base_cflags, base_ldflags) {
Ok(flags) => flags,
Err(err) => {
eprintln!("Warning: {err}");
(base_cflags.to_vec(), base_ldflags.to_vec())
}
}
}
fn run_pkg_config(pkg: &str, arg: &str) -> Result<String, String> {
let output = std::process::Command::new("pkg-config")
.arg(arg)
.arg(pkg)
.output()
.map_err(|err| format!("Failed to run pkg-config: {err}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("pkg-config failed for {pkg}: {stderr}"));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
fn split_flags(value: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
let mut chars = value.chars().peekable();
let mut quote: Option<char> = None;
while let Some(ch) = chars.next() {
if let Some(q) = quote {
if ch == q {
quote = None;
} else {
current.push(ch);
}
continue;
}
match ch {
'\'' | '"' => quote = Some(ch),
'\\' => {
if let Some(next) = chars.next() {
current.push(next);
}
}
c if c.is_whitespace() => {
if !current.is_empty() {
out.push(std::mem::take(&mut current));
}
}
c => current.push(c),
}
}
if !current.is_empty() {
out.push(current);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_target_short_names() {
assert_eq!(normalize_target_os("linux"), "x86_64-unknown-linux-gnu");
assert_eq!(normalize_target_os("macos"), "x86_64-apple-darwin");
assert_eq!(normalize_target_os("windows"), "x86_64-pc-windows-msvc");
assert_eq!(
normalize_target_os("x86_64-unknown-linux-gnu"),
"x86_64-unknown-linux-gnu"
);
assert_eq!(normalize_target_os("unknown"), "unknown");
}
#[test]
fn parse_version_parts() {
let info = parse_version_info("1.2.3-beta");
assert_eq!(info.full, "1.2.3-beta");
assert_eq!(info.major, "1");
assert_eq!(info.minor, "2");
assert_eq!(info.patch, "3");
assert_eq!(info.suffix, "beta");
assert_eq!(info.suffix_dash, "-beta");
}
}

View File

@@ -29,3 +29,14 @@ pub fn find_project_root(start: &Path) -> io::Result<Option<PathBuf>> {
} }
Ok(None) Ok(None)
} }
pub fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}

View File

@@ -1,3 +1,4 @@
pub mod build;
pub mod fs; pub mod fs;
pub mod log; pub mod log;
pub mod text; pub mod text;

View File

@@ -232,7 +232,7 @@ fn dcr_add_dependencies() {
assert!(out.status.success(), "dcr add path should succeed"); assert!(out.status.success(), "dcr add path should succeed");
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap(); let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
assert!( assert!(
toml.contains("mylib = \"./libs/mylib\""), toml.contains("mylib = { path = \"./libs/mylib\" }"),
"path dep not found in toml" "path dep not found in toml"
); );
@@ -280,6 +280,121 @@ fn dcr_add_dependencies() {
assert!(!out.status.success(), "dcr add without prefix should fail"); assert!(!out.status.success(), "dcr add without prefix should fail");
} }
#[test]
fn dcr_builds_lib_package() {
let Some(compiler) = available_compiler() else {
eprintln!("no compiler found; skipping lib package test");
return;
};
let dir = unique_sandbox_dir("lib_package");
let out = run_dcr(&["init"], &dir);
assert!(out.status.success(), "dcr init should succeed");
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
let updated_toml = toml
.replace("kind = \"bin\"", "kind = \"staticlib\"")
.replace("type = \"none\"", "type = \"lib\"");
std::fs::write(dir.join("dcr.toml"), updated_toml).expect("failed to write toml");
std::fs::write(dir.join("src").join("my_lib.h"), "void hello();")
.expect("failed to write header");
let envs = [("DCR_COMPILER", compiler)];
let out = run_dcr_env(&["build"], &dir, &envs);
if !out.status.success() {
eprintln!("stdout: {}", String::from_utf8_lossy(&out.stdout));
eprintln!("stderr: {}", String::from_utf8_lossy(&out.stderr));
}
assert!(out.status.success(), "dcr build should succeed");
let target_dir = dir.join("target");
assert!(
target_dir.join("include").join("my_lib.h").is_file(),
"include/my_lib.h missing"
);
assert!(target_dir.join("lib").exists(), "lib directory missing");
}
#[test]
fn registry_dependency_is_built_from_cache() {
let Some(compiler) = available_compiler() else {
eprintln!("no compiler found; skipping registry dependency build test");
return;
};
let root = unique_sandbox_dir("registry_dep");
let home = root.join("home");
let dcr_home = home.join(".dcr");
let dep = root.join("cache").join("mylib");
let app = root.join("app");
std::fs::create_dir_all(dcr_home.as_path()).expect("failed to create dcr home");
std::fs::create_dir_all(dep.join("src")).expect("failed to create dep src");
std::fs::create_dir_all(app.join("src")).expect("failed to create app src");
std::fs::write(
dcr_home.join("config.toml"),
"[registry.local]\nurl = \"file://local\"\npriority = 1\n",
)
.expect("failed to write registry config");
std::fs::write(
dcr_home.join("index.json"),
format!(
"{{\"packages\":[{{\"name\":\"mylib\",\"latest_version\":\"0.1.0\",\"path\":\"{}\"}}]}}",
dep.display()
),
)
.expect("failed to write registry index");
std::fs::write(
dep.join("dcr.toml"),
"[package]\nname = \"mylib\"\nversion = \"0.1.0\"\ntype = \"lib\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"staticlib\"\n\n[dependencies]\n",
)
.expect("failed to write dep dcr.toml");
std::fs::write(dep.join("src").join("mylib.h"), "int answer(void);\n")
.expect("failed to write header");
std::fs::write(
dep.join("src").join("mylib.c"),
"int answer(void) { return 42; }\n",
)
.expect("failed to write dep source");
std::fs::write(
app.join("dcr.toml"),
"[package]\nname = \"app\"\nversion = \"0.1.0\"\ntype = \"none\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"bin\"\n\n[dependencies]\nmylib = \"0.1.0\"\n",
)
.expect("failed to write app dcr.toml");
std::fs::write(
app.join("src").join("main.c"),
"#include \"mylib.h\"\nint main(void) { return answer() == 42 ? 0 : 1; }\n",
)
.expect("failed to write app source");
let index_path = dcr_home.join("index.json");
let envs = [
("DCR_COMPILER", compiler),
("HOME", home.to_str().unwrap()),
("DCR_INDEX_PATH", index_path.to_str().unwrap()),
];
let out = run_dcr_env(&["build"], &app, &envs);
if !out.status.success() {
eprintln!("stdout: {}", String::from_utf8_lossy(&out.stdout));
eprintln!("stderr: {}", String::from_utf8_lossy(&out.stderr));
}
assert!(
out.status.success(),
"registry dependency build should succeed"
);
assert!(
dep.join("target").join("include").join("mylib.h").is_file(),
"registry dependency headers were not packaged"
);
assert!(
dep.join("target").join("lib").exists(),
"registry dependency library directory missing"
);
}
#[test] #[test]
fn dcr_test_runs_without_sandbox_dependency() { fn dcr_test_runs_without_sandbox_dependency() {
let Some(compiler) = available_compiler() else { let Some(compiler) = available_compiler() else {