mirror of
https://github.com/dexoron/dcr.git
synced 2026-10-21 16:49:37 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2de836a421 | |||
| ed85f801e9 | |||
| 9d8dcda366 | |||
| 0193834bfd | |||
| debc5d2044 | |||
| 00ed418291 |
57
.github/workflows/release.yml
vendored
57
.github/workflows/release.yml
vendored
@@ -42,19 +42,68 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
|
# GNU/Linux
|
||||||
|
# x86_64
|
||||||
- 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
|
asset_name: dcr-x86_64-unknown-linux-gnu
|
||||||
|
|
||||||
|
# ARM64
|
||||||
|
- os: ubuntu-latest
|
||||||
|
target: aarch64-unknown-linux-gnu
|
||||||
|
asset_name: dcr-aarch64-unknown-linux-gnu
|
||||||
|
|
||||||
|
# Musl/Linux
|
||||||
|
# x86_64
|
||||||
|
- os: ubuntu-latest
|
||||||
|
target: x86_64-unknown-linux-musl
|
||||||
|
asset_name: dcr-x86_64-unknown-linux-musl
|
||||||
|
|
||||||
|
# ARM64
|
||||||
|
- os: ubuntu-latest
|
||||||
|
target: aarch64-unknown-linux-musl
|
||||||
|
asset_name: dcr-aarch64-unknown-linux-musl
|
||||||
|
|
||||||
|
# MacOS
|
||||||
|
# x86_64 (Intel Mac, macOS 10.12+)
|
||||||
- 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
|
asset_name: dcr-x86_64-apple-darwin
|
||||||
- os: macos-15
|
|
||||||
|
# ARM64 (Apple Silicon Mac, macOS 11+)
|
||||||
|
- os: macos-latest
|
||||||
target: aarch64-apple-darwin
|
target: aarch64-apple-darwin
|
||||||
asset_name: dcr-aarch64-apple-darwin
|
asset_name: dcr-aarch64-apple-darwin
|
||||||
|
|
||||||
|
# Windows MSVC
|
||||||
|
# x86_64
|
||||||
- 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
|
asset_name: dcr-x86_64-pc-windows-msvc.exe
|
||||||
|
|
||||||
|
# ARM64
|
||||||
|
- os: windows-latest
|
||||||
|
target: aarch64-pc-windows-msvc
|
||||||
|
asset_name: dcr-aarch64-pc-windows-msvc.exe
|
||||||
|
|
||||||
|
# Windows GNU
|
||||||
|
# x86_64
|
||||||
|
- os: windows-latest
|
||||||
|
target: x86_64-pc-windows-gnu
|
||||||
|
asset_name: dcr-x86_64-pc-windows-gnu.exe
|
||||||
|
|
||||||
|
# Windows LLVM
|
||||||
|
# x86_64
|
||||||
|
- os: windows-latest
|
||||||
|
target: x86_64-pc-windows-gnullvm
|
||||||
|
asset_name: dcr-x86_64-pc-windows-gnullvm.exe
|
||||||
|
|
||||||
|
|
||||||
|
# ARM64
|
||||||
|
- os: windows-latest
|
||||||
|
target: aarch64-pc-windows-gnullvm
|
||||||
|
asset_name: dcr-aarch64-pc-windows-gnullvm.exe
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
needs: notes
|
needs: notes
|
||||||
steps:
|
steps:
|
||||||
@@ -65,6 +114,12 @@ jobs:
|
|||||||
name: release-notes
|
name: release-notes
|
||||||
path: .github
|
path: .github
|
||||||
|
|
||||||
|
- name: Install Linux Cross Compilation Tools
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu musl-tools
|
||||||
|
|
||||||
- name: Setup Rust
|
- name: Setup Rust
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
|
|||||||
121
AGENT.md
121
AGENT.md
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
**DCR (Dexoron Cargo Realization)** — CLI-утилита для управления C/C++/ASM проектами в стиле Cargo.
|
**DCR (Dexoron Cargo Realization)** — CLI tool for managing C/C++/ASM projects in a Cargo-style.
|
||||||
|
|
||||||
- **Язык реализации**: Rust (edition 2024)
|
- **Implementation Language**: Rust (edition 2024)
|
||||||
- **Лицензия**: MIT
|
- **License**: MIT
|
||||||
- **Репозиторий**: [github.com/dexoron/dcr](https://github.com/dexoron/dcr)
|
- **Repository**: [github.com/dexoron/dcr](https://github.com/dexoron/dcr)
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -14,47 +14,35 @@
|
|||||||
|
|
||||||
```
|
```
|
||||||
src/
|
src/
|
||||||
├── main.rs # Точка входа, маршрутизация CLI-команд
|
├── main.rs # Entry point, CLI command routing
|
||||||
├── config.rs # Глобальные константы: профили сборки, шаблон main.c
|
├── config.rs # Global constants
|
||||||
├── cli/ # Реализация CLI-команд
|
├── cli/ # CLI command implementation
|
||||||
│ ├── new.rs # dcr new <name>
|
│ ├── new.rs # dcr new <name>
|
||||||
│ ├── init.rs # dcr init
|
│ ├── init.rs # dcr init
|
||||||
│ ├── build.rs # dcr build [--debug|--release]
|
│ ├── setup.rs # dcr setup (registry initialization)
|
||||||
│ ├── run.rs # dcr run [--debug|--release]
|
│ ├── add.rs # dcr add <name>
|
||||||
│ ├── clean.rs # dcr clean [--all]
|
│ ├── build.rs # dcr build
|
||||||
|
│ ├── run.rs # dcr run
|
||||||
|
│ ├── clean.rs # dcr clean
|
||||||
│ ├── help.rs # dcr --help
|
│ ├── help.rs # dcr --help
|
||||||
│ └── flag_update.rs # dcr --update (self-update через GitHub Releases)
|
│ └── flag_update.rs # dcr --update
|
||||||
├── core/ # Бизнес-логика
|
├── core/ # Business logic
|
||||||
│ ├── config.rs # Парсинг/валидация/форматирование dcr.toml (struct Config)
|
│ ├── config.rs # dcr.toml parsing
|
||||||
│ ├── deps.rs # Разрешение path-зависимостей, генерация dcr.lock
|
│ ├── registry.rs # Package index management (RegistryManager)
|
||||||
│ ├── runner.rs # Запуск скомпилированного бинарника
|
│ ├── deps/ # Dependency resolution (path, git)
|
||||||
│ ├── workspace.rs # Поддержка [workspace] и упорядочивание сборки
|
│ ├── runner.rs # Binary execution
|
||||||
│ └── builder/ # Бэкенды компиляторов/ассемблеров
|
│ ├── workspace.rs # [workspace] support
|
||||||
│ ├── mod.rs # Общий интерфейс сборки
|
│ └── builder/ # Compiler backends (gcc, clang, msvc, nasm, gas)
|
||||||
│ ├── gcc.rs # GCC backend
|
├── platform/ # Platform-specific logic
|
||||||
│ ├── clang.rs # Clang backend
|
└── utils/ # Helper utilities
|
||||||
│ ├── 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
|
### Key Concepts
|
||||||
|
|
||||||
- **`dcr.toml`** — конфигурационный файл проекта (аналог `Cargo.toml`). Секции: `[package]`, `[build]`, `[toolchain]`, `[dependencies]`, `[workspace]`.
|
- **`~/.dcr/`**: Centralized storage for registries and configurations.
|
||||||
- **Профили сборки**: `debug` (по умолчанию) и `release`. Встроенные флаги зависят от компилятора. Пользовательские флаги через `build.cflags` / `build.ldflags`.
|
- **`config.toml`**: File in `~/.dcr/` defining available package indices and their priorities.
|
||||||
- **Инкрементальная сборка**: объектные файлы кешируются по mtime. Отслеживание заголовков пока не реализовано (см. `TODO.md`).
|
- **`dcr.toml`**: Local project configuration.
|
||||||
- **Workspace**: корневой `dcr.toml` с секцией `[workspace]` описывает member-проекты и их зависимости; сборка происходит в топологическом порядке.
|
- **Registry System**: `RegistryManager` handles package discovery across multiple indices based on priority.
|
||||||
- **Path dependencies**: зависимости по путям автоматически добавляют include/lib-пути; генерируется `dcr.lock`.
|
|
||||||
- **Build kinds**: `bin` (бинарник), `staticlib` (`.a`), `sharedlib` (`.so`/`.dylib`/`.dll`).
|
|
||||||
|
|
||||||
## Supported Platforms
|
## Supported Platforms
|
||||||
|
|
||||||
@@ -69,58 +57,21 @@ src/
|
|||||||
|
|
||||||
| Crate | Purpose |
|
| Crate | Purpose |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `reqwest` | HTTP-запросы для `--update` (blocking, rustls-tls) |
|
| `reqwest` | HTTP requests |
|
||||||
| `serde` | Сериализация/десериализация |
|
| `serde` | Serialization |
|
||||||
| `toml` | Парсинг `dcr.toml` |
|
| `toml` | Configuration parsing |
|
||||||
| `sha2` | Хеширование при обновлении |
|
| `git2` | Git dependency handling |
|
||||||
| `self-replace` | Замена бинарника при `--update` |
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
### Build & Run
|
### Build & Run
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo build # debug build
|
cargo build --release
|
||||||
cargo build --release # release build
|
./target/release/dcr setup
|
||||||
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
|
## Code Conventions
|
||||||
|
- Rust stable edition 2024.
|
||||||
- Rust stable edition 2024
|
- `cargo fmt` and `cargo clippy -- -D warnings`.
|
||||||
- Форматирование: `cargo fmt`
|
- CLI output in English.
|
||||||
- Линтинг: `cargo clippy` без warnings
|
- Use `utils::log` for messaging.
|
||||||
- Функции — маленькие и сфокусированные
|
|
||||||
- Имена — понятные и описательные
|
|
||||||
- Пользовательские сообщения 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)
|
|
||||||
|
|||||||
31
CHANGELOG.md
31
CHANGELOG.md
@@ -1,5 +1,36 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
Added:
|
||||||
|
|
||||||
|
- Full Git dependency support in `dcr.toml`
|
||||||
|
- Support for `git`, `branch`, `tag`, and `rev` fields
|
||||||
|
- Automatic cloning and checkout via `git2`
|
||||||
|
- Dependencies are stored in `target/<profile>/deps/git/`
|
||||||
|
- New `dcr add` command for easy dependency management
|
||||||
|
- Short syntax: `github:user/repo`, `gitlab:user/repo`, `path:/to/lib`
|
||||||
|
- Automatic GitHub resolution for `git:user/repo`
|
||||||
|
- Visual feedback for dependency fetching with in-place status updates ("Fetching" → "Fetched")
|
||||||
|
- Modular dependency management architecture in `src/core/deps/`
|
||||||
|
|
||||||
## [0.5.1] - 2026-04-12
|
## [0.5.1] - 2026-04-12
|
||||||
|
|
||||||
Fixed:
|
Fixed:
|
||||||
|
|||||||
152
Cargo.lock
generated
152
Cargo.lock
generated
@@ -54,6 +54,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2"
|
checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"find-msvc-tools",
|
"find-msvc-tools",
|
||||||
|
"jobserver",
|
||||||
|
"libc",
|
||||||
"shlex",
|
"shlex",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -69,6 +71,18 @@ 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"
|
||||||
@@ -90,12 +104,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dcr"
|
name = "dcr"
|
||||||
version = "0.5.1"
|
version = "0.6.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"console",
|
||||||
|
"git2",
|
||||||
"glob",
|
"glob",
|
||||||
|
"indicatif",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"self-replace",
|
"self-replace",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"toml",
|
"toml",
|
||||||
]
|
]
|
||||||
@@ -121,6 +139,12 @@ 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"
|
||||||
@@ -263,6 +287,21 @@ dependencies = [
|
|||||||
"wasip3",
|
"wasip3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "git2"
|
||||||
|
version = "0.20.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7b88256088d75a56f8ecfa070513a775dd9107f6530ef14919dac831af9cfe2b"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"libc",
|
||||||
|
"libgit2-sys",
|
||||||
|
"log",
|
||||||
|
"openssl-probe",
|
||||||
|
"openssl-sys",
|
||||||
|
"url",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "glob"
|
name = "glob"
|
||||||
version = "0.3.3"
|
version = "0.3.3"
|
||||||
@@ -510,6 +549,19 @@ 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"
|
||||||
@@ -532,6 +584,16 @@ version = "1.0.17"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jobserver"
|
||||||
|
version = "0.1.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.3.4",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "js-sys"
|
name = "js-sys"
|
||||||
version = "0.3.85"
|
version = "0.3.85"
|
||||||
@@ -554,6 +616,46 @@ version = "0.2.182"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
|
checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libgit2-sys"
|
||||||
|
version = "0.18.4+1.9.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9b26f66f35e1871b22efcf7191564123d2a446ca0538cde63c23adfefa9b15b7"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"libssh2-sys",
|
||||||
|
"libz-sys",
|
||||||
|
"openssl-sys",
|
||||||
|
"pkg-config",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libssh2-sys"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "220e4f05ad4a218192533b300327f5150e809b54c4ec83b5a1d91833601811b9"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"libz-sys",
|
||||||
|
"openssl-sys",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libz-sys"
|
||||||
|
version = "1.1.28"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fc3a226e576f50782b3305c5ccf458698f92798987f551c6a02efe8276721e22"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "linux-raw-sys"
|
name = "linux-raw-sys"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -601,6 +703,24 @@ 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-probe"
|
||||||
|
version = "0.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-sys"
|
||||||
|
version = "0.9.115"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "158fe5b292746440aa6e7a7e690e55aeb72d41505e2804c23c6973ad0e9c9781"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "percent-encoding"
|
name = "percent-encoding"
|
||||||
version = "2.3.2"
|
version = "2.3.2"
|
||||||
@@ -619,6 +739,18 @@ version = "0.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pkg-config"
|
||||||
|
version = "0.3.33"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
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"
|
||||||
@@ -1241,12 +1373,24 @@ 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"
|
||||||
@@ -1271,6 +1415,12 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "vcpkg"
|
||||||
|
version = "0.2.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "version_check"
|
name = "version_check"
|
||||||
version = "0.9.5"
|
version = "0.9.5"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dcr"
|
name = "dcr"
|
||||||
version = "0.5.1"
|
version = "0.6.5"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
@@ -11,3 +11,7 @@ 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"
|
||||||
|
serde_json = "1"
|
||||||
|
|||||||
39
README.md
39
README.md
@@ -17,17 +17,20 @@ The current implementation is written in Rust.
|
|||||||
- 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 and shared libraries
|
||||||
|
- 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
|
||||||
|
|
||||||
@@ -106,6 +109,15 @@ 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>`
|
||||||
|
Adds a dependency to `dcr.toml`.
|
||||||
|
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.
|
||||||
|
|
||||||
### `dcr build [profile]`
|
### `dcr build [profile]`
|
||||||
Builds the project. If no profile is specified, `--debug` is used.
|
Builds the project. If no profile is specified, `--debug` is used.
|
||||||
Use `--force` to rebuild without cache, `--clean` to clean before build.
|
Use `--force` to rebuild without cache, `--clean` to clean before build.
|
||||||
@@ -177,6 +189,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`:
|
||||||
|
|
||||||
@@ -184,11 +197,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"
|
||||||
# Optional platform hint
|
# Optional platform hint
|
||||||
# platform = "x86_64"
|
# platform = "x86_64"
|
||||||
# Optional custom flags
|
# Optional custom flags
|
||||||
@@ -211,20 +226,22 @@ ldflags = ["-lm"]
|
|||||||
# rcc = "rcc"
|
# rcc = "rcc"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
my_lib = "path:./libs/my_lib"
|
||||||
|
cool_lib = { git = "https://github.com/user/cool_lib", tag = "v1.0" }
|
||||||
```
|
```
|
||||||
|
|
||||||
Workspace example:
|
Workspace example:
|
||||||
|
...
|
||||||
```toml
|
|
||||||
[workspace]
|
[workspace]
|
||||||
kernel = { path = "src/kernel", deps = ["core", "userspace"] }
|
kernel = { path = "src/kernel", deps = ["core", "userspace"] }
|
||||||
core = { path = "src/core", deps = ["userspace"] }
|
core = { path = "src/core", deps = ["userspace"] }
|
||||||
userspace = { path = "src/userspace" }
|
userspace = { path = "src/userspace" }
|
||||||
```
|
```
|
||||||
|
|
||||||
Path dependencies are supported. DCR will resolve them on build and generate `dcr.lock`.
|
Git and Path dependencies are supported. DCR will resolve them on build and generate `dcr.lock`.
|
||||||
|
|
||||||
|
Incremental build note: object files are rebuilt when source `.c/.cpp` or included header files change.
|
||||||
|
|
||||||
Incremental build note: object files are rebuilt when source `.c/.cpp` files change. Header dependency tracking is not implemented yet.
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
- Rust toolchain (`rustc`, `cargo`) - for building DCR from source
|
- Rust toolchain (`rustc`, `cargo`) - for building DCR from source
|
||||||
|
|||||||
74
TODO.md
74
TODO.md
@@ -1,9 +1,67 @@
|
|||||||
# TODO
|
# DCR TODO.md
|
||||||
|
|
||||||
- Add external package managers (Conan, vcpkg)
|
Priority list of tasks to turn DCR into a true Cargo killer for C/C++ developers.
|
||||||
- Linker script + direct linker control
|
|
||||||
- Custom targets/steps
|
## 🔥 High Priority (Next Releases)
|
||||||
- Cross-compilation and freestanding targets (-nostdinc, -nostdlib, custom target triple like i686-elf)
|
|
||||||
- Mixed C + ASM in one project (compile .c and .s/.S sources together)
|
- [x] **Git dependencies support**
|
||||||
- Per-member include directories in workspace (e.g. include paths for subprojects)
|
`git = "https://github.com/user/repo.git#branch"` and `git = "..."@tag`
|
||||||
- Build-time code generation (auto-generated headers, pre-build scripts)
|
- [ ] **Conan and vcpkg integration**
|
||||||
|
Automatic download, installation and linking of packages
|
||||||
|
- [ ] **Full freestanding / embedded support**
|
||||||
|
`-nostdlib`, linker scripts, bare-metal targets (i686-elf, aarch64-none-elf, etc.)
|
||||||
|
- [ ] **EFI support**
|
||||||
|
Dedicated platform configuration for EFI targets
|
||||||
|
- [ ] **Custom project name**
|
||||||
|
Override binary name in `dcr.toml`
|
||||||
|
- [ ] **Custom build steps / targets**
|
||||||
|
Ability to define custom pre-build, post-build, codegen steps in `dcr.toml`
|
||||||
|
- [ ] **Improved mixed C/C++/ASM projects**
|
||||||
|
Better handling of `.S` and `.asm` files with correct flags
|
||||||
|
- [ ] **dcr publish + official package registry**
|
||||||
|
Publish and fetch your own libraries easily
|
||||||
|
|
||||||
|
## ✅ Medium Priority
|
||||||
|
|
||||||
|
- [ ] **Static analysis** (`dcr check`)
|
||||||
|
Integration with clang-tidy, cppcheck, include-what-you-use
|
||||||
|
- [ ] **Linter + Formatter** (`dcr fmt`, `dcr lint`)
|
||||||
|
- [ ] **Hot reload / Live reload** for applications (raylib, SFML, SDL, etc.)
|
||||||
|
- [ ] **Better cross-compilation experience**
|
||||||
|
Ready-to-use toolchains + automatic download
|
||||||
|
- [ ] **Linker script support** + direct linker control
|
||||||
|
- [ ] **Workspaces improvements**
|
||||||
|
Per-member include directories, selective builds, better dependency graph
|
||||||
|
- [ ] **Build-time code generation**
|
||||||
|
Support for protobuf, flatbuffers, Qt moc, custom generators
|
||||||
|
|
||||||
|
## 📌 Low Priority / Nice to Have
|
||||||
|
|
||||||
|
- [ ] Support for Meson and Ninja as alternative backends
|
||||||
|
- [ ] Dockerfile generation (`dcr docker init`)
|
||||||
|
- [ ] First-class Windows MSVC support (currently works but rough)
|
||||||
|
- [ ] Documentation generation (`dcr doc`)
|
||||||
|
- [ ] Sanitizers integration (`dcr sanitize`)
|
||||||
|
- [ ] Benchmarks and comparison with CMake/Meson
|
||||||
|
- [ ] C++20 modules support (when it becomes stable)
|
||||||
|
|
||||||
|
## 🧠 Future Ideas
|
||||||
|
|
||||||
|
- Official DCR package registry (dcrhub)
|
||||||
|
- GUI wrapper (dcr-gui)
|
||||||
|
- Plugin system
|
||||||
|
- Toolchain manager (like rustup)
|
||||||
|
- Zig as alternative compiler
|
||||||
|
- deb/rpm/flatpak/AppImage packaging support
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Currently in progress:**
|
||||||
|
- ...
|
||||||
|
|
||||||
|
**Completed in recent releases:**
|
||||||
|
- Workspaces
|
||||||
|
- Cross-compilation
|
||||||
|
- IDE config generation (VS Code, CLion, compile_commands.json)
|
||||||
|
- Self-update (`dcr --update`)
|
||||||
|
- Header tracking
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
|
|
||||||
* [Global options](commands/global-options.md)
|
* [Global options](commands/global-options.md)
|
||||||
* [dcr init/new](commands/dcr-init-or-new.md)
|
* [dcr init/new](commands/dcr-init-or-new.md)
|
||||||
|
* [dcr add](commands/dcr-add.md)
|
||||||
* [dcr build](commands/dcr-build.md)
|
* [dcr build](commands/dcr-build.md)
|
||||||
* [dcr run](commands/dcr-run.md)
|
* [dcr run](commands/dcr-run.md)
|
||||||
* [dcr clean](commands/dcr-clean.md)
|
* [dcr clean](commands/dcr-clean.md)
|
||||||
|
|||||||
32
docs/commands/dcr-add.md
Normal file
32
docs/commands/dcr-add.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# dcr add
|
||||||
|
|
||||||
|
Add a dependency to `dcr.toml`.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dcr add <name> <source> [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
- `path:./path/to/lib`: Local directory.
|
||||||
|
- `github:user/repo`: GitHub repository.
|
||||||
|
- `gitlab:user/repo`: GitLab repository.
|
||||||
|
- `git:host.com/user/repo`: Generic Git repository (HTTPS).
|
||||||
|
- `https://...`: Full Git URL.
|
||||||
|
|
||||||
|
## Options
|
||||||
|
|
||||||
|
- `--branch <name>`: Use a specific branch.
|
||||||
|
- `--tag <name>`: Use a specific tag.
|
||||||
|
- `--rev <sha>`: Use a specific commit hash.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dcr add my_lib path:./libs/my_lib
|
||||||
|
dcr add cool_lib github:user/cool_lib
|
||||||
|
dcr add shared_lib gitlab:org/shared --branch develop
|
||||||
|
dcr add custom_lib git:git.internal.com/r/lib --tag v1.0.0
|
||||||
|
```
|
||||||
@@ -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.
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -2,25 +2,39 @@
|
|||||||
|
|
||||||
Dependencies are defined in `dcr.toml` under `[dependencies]`.
|
Dependencies are defined in `dcr.toml` under `[dependencies]`.
|
||||||
|
|
||||||
## Full example
|
## Full example (Path)
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
fmt = { path = "./third_party/fmt", include = ["include"], lib = ["lib"], libs = ["fmt"] }
|
fmt = { path = "./third_party/fmt", include = ["include"], lib = ["lib"], libs = ["fmt"] }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Full example (Git)
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
json = { git = "https://github.com/nlohmann/json", tag = "v3.11.2" }
|
||||||
|
```
|
||||||
|
|
||||||
## Field reference
|
## Field reference
|
||||||
|
|
||||||
- `path`: required dependency root path.
|
- `path`: local path to dependency root.
|
||||||
|
- `git`: URL of Git repository.
|
||||||
|
- `branch`: Git branch name.
|
||||||
|
- `tag`: Git tag name.
|
||||||
|
- `rev`: Git commit SHA.
|
||||||
- `include`: optional include subpaths (absolute or relative to dep root).
|
- `include`: optional include subpaths (absolute or relative to dep root).
|
||||||
- `lib`: optional library subpaths (absolute or relative to dep root).
|
- `lib`: optional library subpaths (absolute or relative to dep root).
|
||||||
- `libs`: optional linker library names.
|
- `libs`: optional linker library names.
|
||||||
|
|
||||||
## Common valid compact form
|
## Common valid compact forms
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
mylib = { path = "./libs/mylib" }
|
mylib = { path = "./libs/mylib" }
|
||||||
|
gitlib = { git = "https://github.com/user/repo" }
|
||||||
|
# Shortest form for path
|
||||||
|
simple = "./libs/simple"
|
||||||
```
|
```
|
||||||
|
|
||||||
In this form DCR will try defaults for include/lib dirs and use `mylib` as the linker library name.
|
In these forms DCR will try defaults for include/lib dirs and use the dependency name as the linker library name.
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
```text
|
```text
|
||||||
dcr new <name>
|
dcr new <name>
|
||||||
dcr init
|
dcr init
|
||||||
|
dcr setup
|
||||||
|
dcr add <name> <source>(optional)
|
||||||
dcr build [--debug|--release]
|
dcr build [--debug|--release]
|
||||||
dcr run [--debug|--release]
|
dcr run [--debug|--release]
|
||||||
dcr clean [--debug|--release] [--all]
|
dcr clean [--debug|--release] [--all]
|
||||||
|
|||||||
199
src/cli/add.rs
Normal file
199
src/cli/add.rs
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
use crate::core::config::Config;
|
||||||
|
use crate::utils::fs::find_project_root;
|
||||||
|
use crate::utils::log::error;
|
||||||
|
use crate::utils::text::{BOLD_GREEN, colored};
|
||||||
|
use toml::Value;
|
||||||
|
use toml::map::Map;
|
||||||
|
|
||||||
|
pub struct AddArgs {
|
||||||
|
pub name: String,
|
||||||
|
pub path: Option<String>,
|
||||||
|
pub git: Option<String>,
|
||||||
|
pub branch: Option<String>,
|
||||||
|
pub tag: Option<String>,
|
||||||
|
pub rev: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(args: &[String]) -> i32 {
|
||||||
|
let add_args = match parse_add_args(args) {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(code) => return code,
|
||||||
|
};
|
||||||
|
|
||||||
|
let start_dir = match std::env::current_dir() {
|
||||||
|
Ok(dir) => dir,
|
||||||
|
Err(_) => {
|
||||||
|
error("Failed to determine current directory");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let root = match find_project_root(&start_dir) {
|
||||||
|
Ok(Some(dir)) => dir,
|
||||||
|
Ok(None) => {
|
||||||
|
error("dcr.toml file not found");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
error("Failed to find project root");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut config = match Config::open(&root.join("dcr.toml").to_string_lossy()) {
|
||||||
|
Ok(cfg) => cfg,
|
||||||
|
Err(err) => {
|
||||||
|
error(&err.to_string());
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let dep_value = if let Some(git_url) = add_args.git {
|
||||||
|
if add_args.branch.is_none() && add_args.tag.is_none() && add_args.rev.is_none() {
|
||||||
|
let mut table = Map::new();
|
||||||
|
table.insert("git".to_string(), Value::String(git_url));
|
||||||
|
Value::Table(table)
|
||||||
|
} else {
|
||||||
|
let mut table = Map::new();
|
||||||
|
table.insert("git".to_string(), Value::String(git_url));
|
||||||
|
if let Some(b) = add_args.branch {
|
||||||
|
table.insert("branch".to_string(), Value::String(b));
|
||||||
|
}
|
||||||
|
if let Some(t) = add_args.tag {
|
||||||
|
table.insert("tag".to_string(), Value::String(t));
|
||||||
|
}
|
||||||
|
if let Some(r) = add_args.rev {
|
||||||
|
table.insert("rev".to_string(), Value::String(r));
|
||||||
|
}
|
||||||
|
Value::Table(table)
|
||||||
|
}
|
||||||
|
} else if let Some(path) = add_args.path {
|
||||||
|
Value::String(path)
|
||||||
|
} else {
|
||||||
|
error("Dependency source (path or git) must be provided");
|
||||||
|
return 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
let key = format!("dependencies.{}", add_args.name);
|
||||||
|
if let Err(err) = config.edit(&key, dep_value) {
|
||||||
|
error(&format!("Failed to update dcr.toml: {}", err));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
println!(
|
||||||
|
" {} dependency `{}` to dcr.toml",
|
||||||
|
colored("Added", BOLD_GREEN),
|
||||||
|
add_args.name
|
||||||
|
);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_add_args(args: &[String]) -> Result<AddArgs, i32> {
|
||||||
|
if args.is_empty() {
|
||||||
|
error("Usage: dcr add <name> <source> [--branch <branch> | --tag <tag> | --rev <rev>]");
|
||||||
|
error("Sources:");
|
||||||
|
error(" user/repo -> github.com/user/repo");
|
||||||
|
error(" github:user/repo -> github.com/user/repo");
|
||||||
|
error(" gitlab:user/repo -> gitlab.com/user/repo");
|
||||||
|
error(" git:host.com/user/repo -> host.com/user/repo");
|
||||||
|
error(" path:./path/to/lib -> local path");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut name = String::new();
|
||||||
|
let source_spec: String;
|
||||||
|
let mut branch = None;
|
||||||
|
let mut tag = None;
|
||||||
|
let mut rev = None;
|
||||||
|
|
||||||
|
let mut iter = args.iter();
|
||||||
|
if let Some(n) = iter.next() {
|
||||||
|
if n.starts_with("--") {
|
||||||
|
error("First argument must be the dependency name");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
name = n.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(s) = iter.next() {
|
||||||
|
if s.starts_with("--") {
|
||||||
|
error("Second argument must be the dependency source");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
source_spec = s.clone();
|
||||||
|
} else {
|
||||||
|
error("Dependency source is required");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(arg) = iter.next() {
|
||||||
|
match arg.as_str() {
|
||||||
|
"--branch" => {
|
||||||
|
branch = iter.next().cloned();
|
||||||
|
if branch.is_none() {
|
||||||
|
error("--branch requires a value");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--tag" => {
|
||||||
|
tag = iter.next().cloned();
|
||||||
|
if tag.is_none() {
|
||||||
|
error("--tag requires a value");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--rev" => {
|
||||||
|
rev = iter.next().cloned();
|
||||||
|
if rev.is_none() {
|
||||||
|
error("--rev requires a value");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
error(&format!("Unknown argument: {}", arg));
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut path = None;
|
||||||
|
let mut git = None;
|
||||||
|
|
||||||
|
if let Some(p) = source_spec.strip_prefix("path:") {
|
||||||
|
path = Some(p.to_string());
|
||||||
|
} else if let Some(g) = source_spec.strip_prefix("github:") {
|
||||||
|
git = Some(format!("https://github.com/{}", g));
|
||||||
|
} else if let Some(g) = source_spec.strip_prefix("gitlab:") {
|
||||||
|
git = Some(format!("https://gitlab.com/{}", g));
|
||||||
|
} else if let Some(g) = source_spec.strip_prefix("git:") {
|
||||||
|
if g.contains('/') && !g.contains('.') {
|
||||||
|
// git:user/repo -> default to github
|
||||||
|
git = Some(format!("https://github.com/{}", g));
|
||||||
|
} else {
|
||||||
|
// git:host.com/user/repo
|
||||||
|
let url = if g.starts_with("http") || g.starts_with("git@") {
|
||||||
|
g.to_string()
|
||||||
|
} else {
|
||||||
|
format!("https://{}", g)
|
||||||
|
};
|
||||||
|
git = Some(url);
|
||||||
|
}
|
||||||
|
} else if source_spec.starts_with("http://")
|
||||||
|
|| source_spec.starts_with("https://")
|
||||||
|
|| source_spec.starts_with("git@")
|
||||||
|
{
|
||||||
|
git = Some(source_spec);
|
||||||
|
} else {
|
||||||
|
error("Source must have a prefix (path:, git:, github:, gitlab:) or be a full URL");
|
||||||
|
return Err(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(AddArgs {
|
||||||
|
name,
|
||||||
|
path,
|
||||||
|
git,
|
||||||
|
branch,
|
||||||
|
tag,
|
||||||
|
rev,
|
||||||
|
})
|
||||||
|
}
|
||||||
133
src/cli/build.rs
133
src/cli/build.rs
@@ -3,7 +3,7 @@ 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::fs::{check_dir, find_project_root};
|
||||||
use crate::utils::log::{error, warn};
|
use crate::utils::log::{error, warn};
|
||||||
@@ -476,7 +476,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(
|
||||||
@@ -544,6 +544,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)
|
||||||
@@ -593,7 +598,68 @@ 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 resolved = resolve_deps(&config, profile, build_target, project_root)?;
|
let deps_table = config.get("dependencies").and_then(|v| v.as_table());
|
||||||
|
let mut resolved = resolve_deps(&config, profile, build_target, project_root)?;
|
||||||
|
|
||||||
|
// Process dependencies
|
||||||
|
if let Some(deps) = deps_table {
|
||||||
|
for (name, _) in deps {
|
||||||
|
if register::is_registry_dep(config.get(&format!("dependencies.{name}")).unwrap()) {
|
||||||
|
let pkg_info = register::resolve_package_from_registry(name)?;
|
||||||
|
let _version = pkg_info
|
||||||
|
.get("latest_version")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("unknown");
|
||||||
|
|
||||||
|
let pkg_path = pkg_info.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
let dep_root = register::get_index_path()
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.join(Path::new(pkg_path).parent().unwrap());
|
||||||
|
let include_dir = dep_root.join("target").join("include");
|
||||||
|
|
||||||
|
if !include_dir.exists() {
|
||||||
|
print!(
|
||||||
|
"\r{:100}\r {} {} v{}",
|
||||||
|
"",
|
||||||
|
colored("Building", BOLD_GREEN),
|
||||||
|
name,
|
||||||
|
_version
|
||||||
|
);
|
||||||
|
std::io::Write::flush(&mut std::io::stdout()).unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||||
|
print!(
|
||||||
|
"\r{:100}\r {} {} v{}",
|
||||||
|
"",
|
||||||
|
colored("Ready", BOLD_GREEN),
|
||||||
|
name,
|
||||||
|
_version
|
||||||
|
);
|
||||||
|
println!();
|
||||||
|
} else {
|
||||||
|
println!(
|
||||||
|
" {} {} v{}",
|
||||||
|
colored("Ready", BOLD_GREEN),
|
||||||
|
name,
|
||||||
|
_version
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
resolved
|
||||||
|
.include_dirs
|
||||||
|
.push(include_dir.to_string_lossy().to_string());
|
||||||
|
resolved.lib_dirs.push(
|
||||||
|
dep_root
|
||||||
|
.join("target")
|
||||||
|
.join("lib")
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
resolved.libs.push(name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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 +741,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,
|
||||||
@@ -734,6 +805,9 @@ fn build_project_at(
|
|||||||
run_build(&ctx)?;
|
run_build(&ctx)?;
|
||||||
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,6 +817,59 @@ fn build_project_at(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn package_library(ctx: &BuildContext, headers: &[PathBuf]) -> Result<(), String> {
|
||||||
|
let target_root = if let Some(dir) = ctx.target_dir {
|
||||||
|
Path::new(dir)
|
||||||
|
.parent()
|
||||||
|
.and_then(|p| p.parent())
|
||||||
|
.unwrap_or_else(|| Path::new("target"))
|
||||||
|
} else {
|
||||||
|
Path::new("target")
|
||||||
|
};
|
||||||
|
|
||||||
|
let include_dir = target_root.join("include");
|
||||||
|
let lib_dir = target_root.join("lib");
|
||||||
|
|
||||||
|
fs::create_dir_all(&include_dir).map_err(|e| e.to_string())?;
|
||||||
|
fs::create_dir_all(&lib_dir).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
for header in headers {
|
||||||
|
if let Some(name) = header.file_name() {
|
||||||
|
let dest = include_dir.join(name);
|
||||||
|
fs::copy(header, dest)
|
||||||
|
.map_err(|e| format!("Failed to copy header {:?}: {}", header, e))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
|
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
|
||||||
where
|
where
|
||||||
F: FnOnce() -> Result<T, String>,
|
F: FnOnce() -> Result<T, String>,
|
||||||
|
|||||||
@@ -541,6 +541,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,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod add;
|
||||||
pub mod build;
|
pub mod build;
|
||||||
pub mod clean;
|
pub mod clean;
|
||||||
pub mod flag_update;
|
pub mod flag_update;
|
||||||
@@ -7,4 +8,5 @@ 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;
|
||||||
|
|||||||
16
src/cli/setup.rs
Normal file
16
src/cli/setup.rs
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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],
|
||||||
|
|||||||
@@ -110,6 +110,16 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(pkg_type) = package.get("type").and_then(|v| v.as_str()) {
|
||||||
|
let pkg_type = pkg_type.trim();
|
||||||
|
if !pkg_type.is_empty() && pkg_type != "lib" && pkg_type != "app" && pkg_type != "none"
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"package.type must be 'lib', 'app', or 'none'".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let build = self
|
let build = self
|
||||||
.get("build")
|
.get("build")
|
||||||
.and_then(|v| v.as_table())
|
.and_then(|v| v.as_table())
|
||||||
@@ -398,6 +408,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 +473,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,21 +559,36 @@ 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}\""));
|
||||||
}
|
}
|
||||||
|
if let Some(v) = tbl.get("git").and_then(|v| v.as_str()) {
|
||||||
|
parts.push(format!("git = \"{v}\""));
|
||||||
|
}
|
||||||
|
if let Some(v) = tbl.get("branch").and_then(|v| v.as_str()) {
|
||||||
|
parts.push(format!("branch = \"{v}\""));
|
||||||
|
}
|
||||||
|
if let Some(v) = tbl.get("tag").and_then(|v| v.as_str()) {
|
||||||
|
parts.push(format!("tag = \"{v}\""));
|
||||||
|
}
|
||||||
|
if let Some(v) = tbl.get("rev").and_then(|v| v.as_str()) {
|
||||||
|
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(),
|
||||||
|
|||||||
390
src/core/deps.rs
390
src/core/deps.rs
@@ -1,390 +0,0 @@
|
|||||||
use crate::core::config::Config;
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use std::fs;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use toml::Value;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct DepSpec {
|
|
||||||
pub name: String,
|
|
||||||
pub path_raw: String,
|
|
||||||
pub include_raw: Option<Vec<String>>,
|
|
||||||
pub lib_raw: Option<Vec<String>>,
|
|
||||||
pub libs_raw: Option<Vec<String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ResolvedDeps {
|
|
||||||
pub include_dirs: Vec<String>,
|
|
||||||
pub lib_dirs: Vec<String>,
|
|
||||||
pub libs: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve_deps(
|
|
||||||
config: &Config,
|
|
||||||
profile: &str,
|
|
||||||
target: Option<&str>,
|
|
||||||
project_root: &Path,
|
|
||||||
) -> Result<ResolvedDeps, String> {
|
|
||||||
let project_name = config
|
|
||||||
.get("package.name")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_string();
|
|
||||||
let project_version = config
|
|
||||||
.get("package.version")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.unwrap_or("")
|
|
||||||
.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 mut lib_dirs = Vec::new();
|
|
||||||
let mut libs = Vec::new();
|
|
||||||
let mut lock_packages = Vec::new();
|
|
||||||
|
|
||||||
for dep in deps {
|
|
||||||
let dep_path_raw = expand_profile(&dep.path_raw, profile);
|
|
||||||
let dep_path = resolve_path(project_root, &dep_path_raw)?;
|
|
||||||
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());
|
|
||||||
|
|
||||||
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))?;
|
|
||||||
lock_packages.push(DepLock {
|
|
||||||
name: dep.name.clone(),
|
|
||||||
version: dep_version,
|
|
||||||
checksum: dep_checksum,
|
|
||||||
source: format!("path+{}", dep.path_raw),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
write_lock(
|
|
||||||
project_root,
|
|
||||||
&project_name,
|
|
||||||
&project_version,
|
|
||||||
&lock_packages,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(ResolvedDeps {
|
|
||||||
include_dirs,
|
|
||||||
lib_dirs,
|
|
||||||
libs,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
struct DepLock {
|
|
||||||
name: String,
|
|
||||||
version: String,
|
|
||||||
checksum: String,
|
|
||||||
source: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_dependencies(
|
|
||||||
config: &Config,
|
|
||||||
profile: &str,
|
|
||||||
target: Option<&str>,
|
|
||||||
) -> Result<Vec<DepSpec>, String> {
|
|
||||||
let mut deps_table = None;
|
|
||||||
// Order: dependencies.target.profile, dependencies.profile.target, dependencies.target, dependencies.profile, dependencies
|
|
||||||
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::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 path = tbl
|
|
||||||
.get("path")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.ok_or_else(|| format!("Dependency '{}' missing path", name))?
|
|
||||||
.to_string();
|
|
||||||
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(),
|
|
||||||
path_raw: path,
|
|
||||||
include_raw: include,
|
|
||||||
lib_raw: lib,
|
|
||||||
libs_raw: libs,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
return Err(format!(
|
|
||||||
"Dependency '{}' must be a table with path/include/lib",
|
|
||||||
name
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
deps.sort_by(|a, b| a.name.cmp(&b.name));
|
|
||||||
Ok(deps)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_string_list(
|
|
||||||
value: Option<&Value>,
|
|
||||||
dep_name: &str,
|
|
||||||
key: &str,
|
|
||||||
) -> Result<Option<Vec<String>>, String> {
|
|
||||||
let Some(value) = value else { return Ok(None) };
|
|
||||||
let list = value.as_array().ok_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"Dependency '{}' field '{}' must be an array of strings",
|
|
||||||
dep_name, key
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
let mut out = Vec::new();
|
|
||||||
for item in list {
|
|
||||||
let s = item
|
|
||||||
.as_str()
|
|
||||||
.ok_or_else(|| format!("Dependency '{}' field '{}' must be strings", dep_name, key))?;
|
|
||||||
out.push(s.to_string());
|
|
||||||
}
|
|
||||||
Ok(Some(out))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_path(project_root: &Path, raw: &str) -> Result<PathBuf, String> {
|
|
||||||
let p = Path::new(raw);
|
|
||||||
let full = if p.is_absolute() {
|
|
||||||
p.to_path_buf()
|
|
||||||
} else {
|
|
||||||
project_root.join(p)
|
|
||||||
};
|
|
||||||
Ok(full)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_paths(
|
|
||||||
base: &Path,
|
|
||||||
raw: Option<&[String]>,
|
|
||||||
defaults: &[&str],
|
|
||||||
profile: &str,
|
|
||||||
) -> Result<Vec<PathBuf>, String> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
if let Some(raw) = raw {
|
|
||||||
for r in raw {
|
|
||||||
let expanded = expand_profile(r, profile);
|
|
||||||
let p = Path::new(&expanded);
|
|
||||||
let full = if p.is_absolute() {
|
|
||||||
p.to_path_buf()
|
|
||||||
} else {
|
|
||||||
base.join(p)
|
|
||||||
};
|
|
||||||
if !full.exists() {
|
|
||||||
return Err(format!("Path does not exist: {}", full.display()));
|
|
||||||
}
|
|
||||||
out.push(full);
|
|
||||||
}
|
|
||||||
return Ok(out);
|
|
||||||
}
|
|
||||||
|
|
||||||
for d in defaults {
|
|
||||||
let candidate = base.join(d);
|
|
||||||
if candidate.exists() {
|
|
||||||
out.push(candidate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expand_profile(raw: &str, profile: &str) -> String {
|
|
||||||
raw.replace("{profile}", profile)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sync_dep_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
|
|
||||||
if dst.exists() {
|
|
||||||
fs::remove_dir_all(dst)?;
|
|
||||||
}
|
|
||||||
copy_dir_all(src, dst)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
|
|
||||||
fs::create_dir_all(dst)?;
|
|
||||||
for entry in fs::read_dir(src)? {
|
|
||||||
let entry = entry?;
|
|
||||||
let ty = entry.file_type()?;
|
|
||||||
let from = entry.path();
|
|
||||||
let to = dst.join(entry.file_name());
|
|
||||||
if ty.is_dir() {
|
|
||||||
copy_dir_all(&from, &to)?;
|
|
||||||
} else {
|
|
||||||
fs::copy(&from, &to)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_lock(
|
|
||||||
project_root: &Path,
|
|
||||||
project_name: &str,
|
|
||||||
project_version: &str,
|
|
||||||
packages: &[DepLock],
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut out = String::new();
|
|
||||||
if !packages.is_empty() {
|
|
||||||
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)
|
|
||||||
));
|
|
||||||
out.push_str(&format!(
|
|
||||||
"dependencies = [{}]\n\n",
|
|
||||||
quote_list(&packages.iter().map(|p| p.name.clone()).collect::<Vec<_>>())
|
|
||||||
));
|
|
||||||
}
|
|
||||||
for pkg in packages {
|
|
||||||
out.push_str("[[package]]\n");
|
|
||||||
out.push_str(&format!("name = \"{}\"\n", escape_value(&pkg.name)));
|
|
||||||
out.push_str(&format!("version = \"{}\"\n", escape_value(&pkg.version)));
|
|
||||||
out.push_str(&format!("source = \"{}\"\n", escape_value(&pkg.source)));
|
|
||||||
out.push_str(&format!("checksum = \"{}\"\n", escape_value(&pkg.checksum)));
|
|
||||||
out.push('\n');
|
|
||||||
}
|
|
||||||
fs::write(project_root.join("dcr.lock"), out)
|
|
||||||
.map_err(|err| format!("Failed to write dcr.lock: {err}"))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn quote_list(items: &[String]) -> String {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.map(|s| format!("\"{}\"", escape_value(s)))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(", ")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn escape_value(input: &str) -> String {
|
|
||||||
input.replace('\\', "\\\\").replace('"', "\\\"")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_dep_version(dep_path: &Path) -> Option<String> {
|
|
||||||
let path = dep_path.join("dcr.toml");
|
|
||||||
let content = fs::read_to_string(path).ok()?;
|
|
||||||
let value: Value = content.parse().ok()?;
|
|
||||||
value
|
|
||||||
.get("package")
|
|
||||||
.and_then(|v| v.as_table())
|
|
||||||
.and_then(|t| t.get("version"))
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.map(|s| s.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compute_checksum(root: &Path) -> Result<String, String> {
|
|
||||||
let mut files = Vec::new();
|
|
||||||
collect_files(root, root, &mut files)?;
|
|
||||||
files.sort();
|
|
||||||
let mut hasher = Sha256::new();
|
|
||||||
for rel in files {
|
|
||||||
hasher.update(rel.as_bytes());
|
|
||||||
let data =
|
|
||||||
fs::read(root.join(&rel)).map_err(|err| format!("failed to read {}: {err}", rel))?;
|
|
||||||
hasher.update(&data);
|
|
||||||
}
|
|
||||||
let hash = hasher.finalize();
|
|
||||||
Ok(to_hex(&hash))
|
|
||||||
}
|
|
||||||
|
|
||||||
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}"))? {
|
|
||||||
let entry = entry.map_err(|err| format!("read_dir failed: {err}"))?;
|
|
||||||
let path = entry.path();
|
|
||||||
let name = entry.file_name();
|
|
||||||
let name_str = name.to_string_lossy();
|
|
||||||
if name_str == "target" {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if path.is_dir() {
|
|
||||||
collect_files(root, &path, out)?;
|
|
||||||
} else if path.is_file() {
|
|
||||||
let rel = path
|
|
||||||
.strip_prefix(root)
|
|
||||||
.unwrap_or(&path)
|
|
||||||
.to_string_lossy()
|
|
||||||
.to_string();
|
|
||||||
out.push(rel);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_hex(bytes: &[u8]) -> String {
|
|
||||||
let mut out = String::with_capacity(bytes.len() * 2);
|
|
||||||
for b in bytes {
|
|
||||||
out.push_str(&format!("{:02x}", b));
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
111
src/core/deps/common.rs
Normal file
111
src/core/deps/common.rs
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
#[allow(dead_code)]
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub enum DepSource {
|
||||||
|
Path(String),
|
||||||
|
Git {
|
||||||
|
url: String,
|
||||||
|
branch: Option<String>,
|
||||||
|
tag: Option<String>,
|
||||||
|
rev: Option<String>,
|
||||||
|
},
|
||||||
|
Registry {
|
||||||
|
version: String,
|
||||||
|
features: Option<Vec<String>>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DepSpec {
|
||||||
|
pub name: String,
|
||||||
|
pub source: DepSource,
|
||||||
|
pub include_raw: Option<Vec<String>>,
|
||||||
|
pub lib_raw: Option<Vec<String>>,
|
||||||
|
pub libs_raw: Option<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct ResolvedDeps {
|
||||||
|
pub include_dirs: Vec<String>,
|
||||||
|
pub lib_dirs: Vec<String>,
|
||||||
|
pub libs: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn resolve_path(project_root: &Path, raw: &str) -> Result<PathBuf, String> {
|
||||||
|
let p = Path::new(raw);
|
||||||
|
let full = if p.is_absolute() {
|
||||||
|
p.to_path_buf()
|
||||||
|
} else {
|
||||||
|
project_root.join(p)
|
||||||
|
};
|
||||||
|
Ok(full)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn resolve_paths(
|
||||||
|
base: &Path,
|
||||||
|
raw: Option<&[String]>,
|
||||||
|
defaults: &[&str],
|
||||||
|
profile: &str,
|
||||||
|
) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if let Some(raw) = raw {
|
||||||
|
for r in raw {
|
||||||
|
let expanded = expand_profile(r, profile);
|
||||||
|
let p = Path::new(&expanded);
|
||||||
|
let full = if p.is_absolute() {
|
||||||
|
p.to_path_buf()
|
||||||
|
} else {
|
||||||
|
base.join(p)
|
||||||
|
};
|
||||||
|
if !full.exists() {
|
||||||
|
return Err(format!("Path does not exist: {}", full.display()));
|
||||||
|
}
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
for d in defaults {
|
||||||
|
let candidate = base.join(d);
|
||||||
|
if candidate.exists() {
|
||||||
|
out.push(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn expand_profile(raw: &str, profile: &str) -> String {
|
||||||
|
raw.replace("{profile}", profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn sync_dep_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
|
||||||
|
if dst.exists() {
|
||||||
|
fs::remove_dir_all(dst)?;
|
||||||
|
}
|
||||||
|
copy_dir_all(src, dst)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
|
||||||
|
fs::create_dir_all(dst)?;
|
||||||
|
for entry in fs::read_dir(src)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let ty = entry.file_type()?;
|
||||||
|
let from = entry.path();
|
||||||
|
let to = dst.join(entry.file_name());
|
||||||
|
if ty.is_dir() {
|
||||||
|
copy_dir_all(&from, &to)?;
|
||||||
|
} else {
|
||||||
|
fs::copy(&from, &to)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
54
src/core/deps/git.rs
Normal file
54
src/core/deps/git.rs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn fetch_git_dep(
|
||||||
|
url: &str,
|
||||||
|
target_dir: &Path,
|
||||||
|
branch: Option<&str>,
|
||||||
|
tag: Option<&str>,
|
||||||
|
rev: Option<&str>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if target_dir.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut builder = git2::build::RepoBuilder::new();
|
||||||
|
if let Some(b) = branch {
|
||||||
|
builder.branch(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
let repo = builder
|
||||||
|
.clone(url, target_dir)
|
||||||
|
.map_err(|e| format!("failed to clone {}: {}", url, e))?;
|
||||||
|
|
||||||
|
if let Some(t) = tag {
|
||||||
|
checkout_ref(&repo, &format!("refs/tags/{}", t))?;
|
||||||
|
} else if let Some(r) = rev {
|
||||||
|
checkout_ref(&repo, r)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn checkout_ref(repo: &git2::Repository, reference_str: &str) -> Result<(), String> {
|
||||||
|
let (object, reference) = repo
|
||||||
|
.revparse_ext(reference_str)
|
||||||
|
.map_err(|e| format!("failed to find ref {}: {}", reference_str, e))?;
|
||||||
|
|
||||||
|
repo.checkout_tree(&object, None).map_err(|e| {
|
||||||
|
let ref_name = reference.as_ref().and_then(|r| r.name()).unwrap_or("HEAD");
|
||||||
|
format!("failed to checkout {}: {}", ref_name, e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
match reference {
|
||||||
|
Some(gref) => {
|
||||||
|
let ref_name = gref.name().unwrap_or("HEAD");
|
||||||
|
repo.set_head(ref_name)
|
||||||
|
}
|
||||||
|
None => repo.set_head_detached(object.id()),
|
||||||
|
}
|
||||||
|
.map_err(|e| format!("failed to set HEAD: {}", e))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
120
src/core/deps/lock.rs
Normal file
120
src/core/deps/lock.rs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use toml::Value;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DepLock {
|
||||||
|
pub name: String,
|
||||||
|
pub version: String,
|
||||||
|
pub checksum: String,
|
||||||
|
pub source: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_lock(
|
||||||
|
project_root: &Path,
|
||||||
|
project_name: &str,
|
||||||
|
project_version: &str,
|
||||||
|
packages: &[DepLock],
|
||||||
|
) -> Result<(), String> {
|
||||||
|
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() {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"dependencies = [{}]\n",
|
||||||
|
quote_list(&packages.iter().map(|p| p.name.clone()).collect::<Vec<_>>())
|
||||||
|
));
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
|
||||||
|
for pkg in packages {
|
||||||
|
out.push_str("[[package]]\n");
|
||||||
|
out.push_str(&format!("name = \"{}\"\n", escape_value(&pkg.name)));
|
||||||
|
out.push_str(&format!("version = \"{}\"\n", escape_value(&pkg.version)));
|
||||||
|
out.push_str(&format!("source = \"{}\"\n", escape_value(&pkg.source)));
|
||||||
|
out.push_str(&format!("checksum = \"{}\"\n", escape_value(&pkg.checksum)));
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
fs::write(project_root.join("dcr.lock"), out)
|
||||||
|
.map_err(|err| format!("Failed to write dcr.lock: {err}"))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote_list(items: &[String]) -> String {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.map(|s| format!("\"{}\"", escape_value(s)))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn escape_value(input: &str) -> String {
|
||||||
|
input.replace('\\', "\\\\").replace('"', "\\\"")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn read_dep_version(dep_path: &Path) -> Option<String> {
|
||||||
|
let path = dep_path.join("dcr.toml");
|
||||||
|
let content = fs::read_to_string(path).ok()?;
|
||||||
|
let value: Value = content.parse().ok()?;
|
||||||
|
value
|
||||||
|
.get("package")
|
||||||
|
.and_then(|v| v.as_table())
|
||||||
|
.and_then(|t| t.get("version"))
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn compute_checksum(root: &Path) -> Result<String, String> {
|
||||||
|
let mut files = Vec::new();
|
||||||
|
collect_files(root, root, &mut files)?;
|
||||||
|
files.sort();
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
for rel in files {
|
||||||
|
hasher.update(rel.as_bytes());
|
||||||
|
let data =
|
||||||
|
fs::read(root.join(&rel)).map_err(|err| format!("failed to read {}: {err}", rel))?;
|
||||||
|
hasher.update(&data);
|
||||||
|
}
|
||||||
|
let hash = hasher.finalize();
|
||||||
|
Ok(to_hex(&hash))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
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}"))? {
|
||||||
|
let entry = entry.map_err(|err| format!("read_dir failed: {err}"))?;
|
||||||
|
let path = entry.path();
|
||||||
|
let name = entry.file_name();
|
||||||
|
let name_str = name.to_string_lossy();
|
||||||
|
if name_str == "target" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if path.is_dir() {
|
||||||
|
collect_files(root, &path, out)?;
|
||||||
|
} else if path.is_file() {
|
||||||
|
let rel = path
|
||||||
|
.strip_prefix(root)
|
||||||
|
.unwrap_or(&path)
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string();
|
||||||
|
out.push(rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn to_hex(bytes: &[u8]) -> String {
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
|
for b in bytes {
|
||||||
|
out.push_str(&format!("{:02x}", b));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
93
src/core/deps/mod.rs
Normal file
93
src/core/deps/mod.rs
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
pub mod common;
|
||||||
|
pub mod git;
|
||||||
|
pub mod lock;
|
||||||
|
pub mod register;
|
||||||
|
|
||||||
|
use crate::core::config::Config;
|
||||||
|
use crate::core::deps::common::ResolvedDeps;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub fn resolve_deps(
|
||||||
|
config: &Config,
|
||||||
|
_profile: &str,
|
||||||
|
_target: Option<&str>,
|
||||||
|
project_root: &Path,
|
||||||
|
) -> Result<ResolvedDeps, String> {
|
||||||
|
let mut resolved = ResolvedDeps::default();
|
||||||
|
let project_name = config
|
||||||
|
.get("package.name")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
let project_version = config
|
||||||
|
.get("package.version")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let deps_table = config.get("dependencies").and_then(|v| v.as_table());
|
||||||
|
let lock_packages = Vec::new();
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
// Используем путь относительно project_root или системный путь, если нужно
|
||||||
|
let dep_root = project_root.join("dcr-index");
|
||||||
|
|
||||||
|
resolved.include_dirs.push(
|
||||||
|
dep_root
|
||||||
|
.join("target")
|
||||||
|
.join("include")
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
resolved.lib_dirs.push(
|
||||||
|
dep_root
|
||||||
|
.join("target")
|
||||||
|
.join("lib")
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
resolved.libs.push(name.clone());
|
||||||
|
} else if let Some(table) = value.as_table()
|
||||||
|
&& let Some(path) = table.get("path").and_then(|v| v.as_str())
|
||||||
|
{
|
||||||
|
let dep_root = project_root.join(path);
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let lib_path = dep_root.join("target").join("lib");
|
||||||
|
if lib_path.exists() {
|
||||||
|
resolved
|
||||||
|
.lib_dirs
|
||||||
|
.push(lib_path.to_string_lossy().to_string());
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
crate::core::deps::lock::write_lock(
|
||||||
|
project_root,
|
||||||
|
&project_name,
|
||||||
|
&project_version,
|
||||||
|
&lock_packages,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(resolved)
|
||||||
|
}
|
||||||
76
src/core/deps/register.rs
Normal file
76
src/core/deps/register.rs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_registry_config() -> Option<DcrConfig> {
|
||||||
|
let home = std::env::var("HOME").ok()?;
|
||||||
|
let config_path = Path::new(&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(|_| {
|
||||||
|
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
|
||||||
|
Path::new(&home).join(".dcr").join("index.json")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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 value.is_str() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if let Some(table) = value.as_table() {
|
||||||
|
return !table.contains_key("git")
|
||||||
|
&& !table.contains_key("path")
|
||||||
|
&& !table.contains_key("url")
|
||||||
|
&& !table.contains_key("version");
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|||||||
41
src/core/registry.rs
Normal file
41
src/core/registry.rs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RegistryManager {
|
||||||
|
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
|
let home = std::env::var("HOME")?;
|
||||||
|
let dcr_dir = PathBuf::from(home).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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ 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),
|
||||||
"build" => cli::build::build(rest),
|
"build" => cli::build::build(rest),
|
||||||
"run" => cli::run::run(rest),
|
"run" => cli::run::run(rest),
|
||||||
"test" | "tests" => cli::test::test(rest),
|
"test" | "tests" => cli::test::test(rest),
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
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}")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,12 +29,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]
|
||||||
|
|||||||
@@ -221,6 +221,101 @@ fn workspace_build_and_clean_all() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dcr_add_dependencies() {
|
||||||
|
let dir = unique_sandbox_dir("add_dep");
|
||||||
|
let out = run_dcr(&["init"], &dir);
|
||||||
|
assert!(out.status.success(), "dcr init should succeed");
|
||||||
|
|
||||||
|
// Test path: prefix
|
||||||
|
let out = run_dcr(&["add", "mylib", "path:./libs/mylib"], &dir);
|
||||||
|
assert!(out.status.success(), "dcr add path should succeed");
|
||||||
|
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
|
||||||
|
assert!(
|
||||||
|
toml.contains("mylib = \"./libs/mylib\""),
|
||||||
|
"path dep not found in toml"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test github: prefix
|
||||||
|
let out = run_dcr(&["add", "gh_lib", "github:user/repo"], &dir);
|
||||||
|
assert!(out.status.success(), "dcr add github should succeed");
|
||||||
|
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
|
||||||
|
assert!(
|
||||||
|
toml.contains("gh_lib = { git = \"https://github.com/user/repo\" }"),
|
||||||
|
"github dep not found in toml"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test git: prefix (generic)
|
||||||
|
let out = run_dcr(&["add", "custom_git", "git:host.com/user/repo"], &dir);
|
||||||
|
assert!(out.status.success(), "dcr add custom git should succeed");
|
||||||
|
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
|
||||||
|
assert!(
|
||||||
|
toml.contains("custom_git = { git = \"https://host.com/user/repo\" }"),
|
||||||
|
"custom git dep not found in toml"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test git: prefix (github default)
|
||||||
|
let out = run_dcr(&["add", "git_short", "git:user/repo"], &dir);
|
||||||
|
assert!(out.status.success(), "dcr add git short should succeed");
|
||||||
|
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
|
||||||
|
assert!(
|
||||||
|
toml.contains("git_short = { git = \"https://github.com/user/repo\" }"),
|
||||||
|
"git short dep not found in toml"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test flags (branch)
|
||||||
|
let out = run_dcr(
|
||||||
|
&["add", "branch_lib", "github:user/repo", "--branch", "dev"],
|
||||||
|
&dir,
|
||||||
|
);
|
||||||
|
assert!(out.status.success(), "dcr add with branch should succeed");
|
||||||
|
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
|
||||||
|
assert!(
|
||||||
|
toml.contains("branch_lib = { git = \"https://github.com/user/repo\", branch = \"dev\" }"),
|
||||||
|
"branch lib not found in toml"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Test failure on no prefix
|
||||||
|
let out = run_dcr(&["add", "fail_lib", "user/repo"], &dir);
|
||||||
|
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]
|
#[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 {
|
||||||
|
|||||||
Reference in New Issue
Block a user