3 Commits

Author SHA1 Message Date
3b54500d4d Merge branch 'master' into dev 2026-05-18 16:15:22 +08:00
933fae749d Fixed:
- Path dependencies now work correctly: `dcr add` stores them as `{ path =
"./..." }` tables, `is_registry_dep` properly distinguishes registry strings
from path/git strings, and `deps/mod.rs` resolves both table-form and
legacy string-form path dependencies
- Registry dependency paths no longer hardcoded to `project_root/dcr-index`;
now use `package_root_from_registry_info()` which resolves relative to the
registry cache root (`~/.dcr/`)
- Registry dependencies are now actually built: `build_project_at()` is
called when `include_dir` or `lib_dir` is missing

Added:

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

Removed:

- Removed unused dependencies `indicatif` and `console` from `Cargo.toml`
2026-05-18 16:13:33 +08:00
441c9f4df3 update: add dev release support and update cross build 2026-05-15 11:40:17 +08:00
26 changed files with 1597 additions and 1116 deletions

View File

@@ -15,6 +15,8 @@ permissions:
jobs: jobs:
publish-aur: publish-aur:
# Не публикуем dev/pre-release теги в AUR
if: "!contains(github.ref_name, '-')"
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment: aur environment: aur
steps: steps:

View File

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

View File

@@ -1,5 +1,41 @@
# Changelog # Changelog
## [0.6.6] - 2026-05-18
Fixed:
- Path dependencies now work correctly: `dcr add` stores them as `{ path =
"./..." }` tables, `is_registry_dep` properly distinguishes registry strings
from path/git strings, and `deps/mod.rs` resolves both table-form and
legacy string-form path dependencies
- Registry dependency paths no longer hardcoded to `project_root/dcr-index`;
now use `package_root_from_registry_info()` which resolves relative to the
registry cache root (`~/.dcr/`)
- Registry dependencies are now actually built: `build_project_at()` is
called when `include_dir` or `lib_dir` is missing
Added:
- `SIGINT`/`Ctrl+C` handler via `ctrlc` crate — `dcr build` now checks
`BUILD_INTERRUPTED` flag at key points and aborts cleanly
- `utils/build.rs` — extracted shared utilities: `parse_version_info`,
`normalize_target_os`, `resolve_compiler`, `primary_language`,
`resolve_pkg_config_flags` and config helpers. Eliminates code duplication
between `cli/build.rs`, `cli/run.rs`, `cli/clean.rs`, `cli/gen.rs`
- `utils/fs.rs::with_dir` — extracted common directory-scoped execution
- `run_command_sync_output` in `builder/common.rs` with global `OUTPUT_MUTEX`
— synchronized compiler output across all backends (unix_cc, gas, nasm, msvc)
- New helper functions in `deps/register.rs`: `get_registry_cache_root`,
`package_root_from_registry_info`, `registry_include_dir`, `registry_lib_dir`,
`path_from_string_dep`
- Unit tests for `register.rs` (`is_registry_dep`, `package_root_from_registry_info`),
`deps/mod.rs` (`path_dep_path`, `push_default_lib_dirs`),
`utils/build.rs` (`normalize_target_os`, `parse_version_info`)
Removed:
- Removed unused dependencies `indicatif` and `console` from `Cargo.toml`
## [0.6.5] - 2026-05-13 ## [0.6.5] - 2026-05-13
Added: Added:

115
Cargo.lock generated
View File

@@ -35,6 +35,15 @@ dependencies = [
"generic-array", "generic-array",
] ]
[[package]]
name = "block2"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [
"objc2",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.19.1" version = "3.19.1"
@@ -71,18 +80,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "console"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
dependencies = [
"encode_unicode",
"libc",
"unicode-width",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.17" version = "0.2.17"
@@ -103,13 +100,23 @@ dependencies = [
] ]
[[package]] [[package]]
name = "dcr" name = "ctrlc"
version = "0.6.5" version = "3.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162"
dependencies = [ dependencies = [
"console", "dispatch2",
"nix",
"windows-sys 0.61.2",
]
[[package]]
name = "dcr"
version = "0.6.6"
dependencies = [
"ctrlc",
"git2", "git2",
"glob", "glob",
"indicatif",
"reqwest", "reqwest",
"self-replace", "self-replace",
"serde", "serde",
@@ -128,6 +135,18 @@ dependencies = [
"crypto-common", "crypto-common",
] ]
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags",
"block2",
"libc",
"objc2",
]
[[package]] [[package]]
name = "displaydoc" name = "displaydoc"
version = "0.2.5" version = "0.2.5"
@@ -139,12 +158,6 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "encode_unicode"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@@ -549,19 +562,6 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "indicatif"
version = "0.18.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25470f23803092da7d239834776d653104d551bc4d7eacaf31e6837854b8e9eb"
dependencies = [
"console",
"portable-atomic",
"unicode-width",
"unit-prefix",
"web-time",
]
[[package]] [[package]]
name = "ipnet" name = "ipnet"
version = "2.11.0" version = "2.11.0"
@@ -697,6 +697,33 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "nix"
version = "0.31.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d6d0705320c1e6ba1d912b5e37cf18071b6c2e9b7fa8215a1e8a7651966f5d3"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "objc2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.3" version = "1.21.3"
@@ -745,12 +772,6 @@ version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "portable-atomic"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.4" version = "0.1.4"
@@ -1373,24 +1394,12 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.6" version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "unit-prefix"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
[[package]] [[package]]
name = "untrusted" name = "untrusted"
version = "0.9.0" version = "0.9.0"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "dcr" name = "dcr"
version = "0.6.5" version = "0.6.6"
edition = "2024" edition = "2024"
build = "build.rs" build = "build.rs"
@@ -11,7 +11,6 @@ serde = { version = "1", features = ["derive"] }
self-replace = "1" self-replace = "1"
sha2 = "0.10" sha2 = "0.10"
toml = "1.0.3" toml = "1.0.3"
indicatif = "0.18.4"
console = "0.16.3"
git2 = "0.20.4" git2 = "0.20.4"
serde_json = "1" serde_json = "1"
ctrlc = "3"

View File

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

View File

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

View File

@@ -68,7 +68,9 @@ pub fn add(args: &[String]) -> i32 {
Value::Table(table) Value::Table(table)
} }
} else if let Some(path) = add_args.path { } else if let Some(path) = add_args.path {
Value::String(path) let mut table = Map::new();
table.insert("path".to_string(), Value::String(path));
Value::Table(table)
} else { } else {
error("Dependency source (path or git) must be provided"); error("Dependency source (path or git) must be provided");
return 1; return 1;

View File

@@ -5,16 +5,28 @@ 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::{register, resolve_deps}; use crate::core::deps::{register, resolve_deps};
use crate::core::workspace::parse_workspace; use crate::core::workspace::parse_workspace;
use crate::utils::fs::{check_dir, find_project_root}; use crate::utils::build::{
use crate::utils::log::{error, warn}; get_bool_with_profile, get_config_opt, get_config_str, get_language_with_profile,
normalize_target_os, parse_version_info, profile_table, resolve_compiler,
resolve_pkg_config_flags, resolve_tool,
};
use crate::utils::fs::{check_dir, find_project_root, with_dir};
use crate::utils::log::error;
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
use glob::glob; use glob::glob;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Once;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant; use std::time::Instant;
static BUILD_INTERRUPTED: AtomicBool = AtomicBool::new(false);
static SIGNAL_HANDLER: Once = Once::new();
pub fn build(args: &[String]) -> i32 { pub fn build(args: &[String]) -> i32 {
install_signal_handler();
BUILD_INTERRUPTED.store(false, Ordering::SeqCst);
let start_dir = match std::env::current_dir() { let start_dir = match std::env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
Err(_) => { Err(_) => {
@@ -67,77 +79,20 @@ pub fn build(args: &[String]) -> i32 {
} }
} }
fn get_config_str(config: &Config, key: &str) -> String { fn install_signal_handler() {
config SIGNAL_HANDLER.call_once(|| {
.get(key) let _ = ctrlc::set_handler(|| {
.and_then(|v| v.as_str()) BUILD_INTERRUPTED.store(true, Ordering::SeqCst);
.unwrap_or("") });
.to_string() });
} }
fn get_config_language(config: &Config, key: &str) -> Result<String, String> { fn check_interrupted() -> Result<(), String> {
let value = config.get(key).ok_or_else(|| format!("{key} is missing"))?; if BUILD_INTERRUPTED.load(Ordering::SeqCst) {
if let Some(s) = value.as_str() { Err("Build interrupted".to_string())
let trimmed = s.trim(); } else {
if trimmed.is_empty() { Ok(())
return Err(format!("{key} is empty"));
} }
return Ok(trimmed.to_string());
}
let arr = value
.as_array()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let mut parts = Vec::new();
for item in arr {
let s = item
.as_str()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} contains empty value"));
}
parts.push(trimmed.to_string());
}
if parts.is_empty() {
return Err(format!("{key} is empty"));
}
Ok(parts.join("+"))
}
fn parse_language_value(value: &toml::Value, key: &str) -> Result<String, String> {
if let Some(s) = value.as_str() {
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} is empty"));
}
return Ok(trimmed.to_string());
}
let arr = value
.as_array()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let mut parts = Vec::new();
for item in arr {
let s = item
.as_str()
.ok_or_else(|| format!("{key} must be string or array of strings"))?;
let trimmed = s.trim();
if trimmed.is_empty() {
return Err(format!("{key} contains empty value"));
}
parts.push(trimmed.to_string());
}
if parts.is_empty() {
return Err(format!("{key} is empty"));
}
Ok(parts.join("+"))
}
fn profile_table<'a>(config: &'a Config, profile: &str) -> Option<&'a toml::value::Table> {
config
.get("build")
.and_then(|v| v.as_table())
.and_then(|b| b.get(profile))
.and_then(|v| v.as_table())
} }
fn get_config_value_raw( fn get_config_value_raw(
@@ -211,7 +166,7 @@ fn get_string_with_profile_and_target(
} }
} }
fn get_string_with_profile(config: &Config, field: &str, profile: &str) -> String { fn get_build_string_with_profile(config: &Config, field: &str, profile: &str) -> String {
get_string_with_profile_and_target(config, field, profile, None) get_string_with_profile_and_target(config, field, profile, None)
} }
@@ -275,22 +230,18 @@ fn get_list_with_profile_and_target(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::utils::build::normalize_target_os;
#[test] #[test]
fn test_normalize_target_os() { fn test_normalize_target_os() {
assert_eq!(normalize_target_os("linux"), "x86_64-unknown-linux-gnu");
assert_eq!(normalize_target_os("macos"), "x86_64-apple-darwin");
assert_eq!(normalize_target_os("windows"), "x86_64-pc-windows-msvc");
assert_eq!( assert_eq!(
super::normalize_target_os("linux"), normalize_target_os("x86_64-unknown-linux-gnu"),
"x86_64-unknown-linux-gnu" "x86_64-unknown-linux-gnu"
); );
assert_eq!(super::normalize_target_os("macos"), "x86_64-apple-darwin"); assert_eq!(normalize_target_os("unknown"), "unknown");
assert_eq!(
super::normalize_target_os("windows"),
"x86_64-pc-windows-msvc"
);
assert_eq!(
super::normalize_target_os("x86_64-unknown-linux-gnu"),
"x86_64-unknown-linux-gnu"
);
assert_eq!(super::normalize_target_os("unknown"), "unknown");
} }
} }
@@ -306,34 +257,6 @@ fn get_targets(config: &Config, profile: &str) -> Result<Vec<String>, String> {
get_list_with_profile(config, "targets", profile) get_list_with_profile(config, "targets", profile)
} }
fn get_bool_with_profile(config: &Config, field: &str, profile: &str, default: bool) -> bool {
let base = config
.get(&format!("build.{field}"))
.and_then(|v| v.as_bool());
let profile_val = profile_table(config, profile)
.and_then(|table| table.get(field).and_then(|value| value.as_bool()));
profile_val.or(base).unwrap_or(default)
}
fn get_language_with_profile(config: &Config, profile: &str) -> Result<String, String> {
if let Some(table) = profile_table(config, profile)
&& let Some(value) = table.get("language")
{
return parse_language_value(value, &format!("build.{profile}.language"));
}
get_config_language(config, "build.language")
}
fn get_config_opt(config: &Config, key: &str) -> Option<String> {
let value = config.get(key)?.as_str()?;
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
fn get_config_list(config: &Config, key: &str) -> Result<Vec<String>, String> { fn get_config_list(config: &Config, key: &str) -> Result<Vec<String>, String> {
let value = match config.get(key) { let value = match config.get(key) {
Some(v) => v, Some(v) => v,
@@ -467,6 +390,7 @@ fn build_from_root(
let start_time = Instant::now(); let start_time = Instant::now();
for (i, build_target) in targets_to_build.iter().enumerate() { for (i, build_target) in targets_to_build.iter().enumerate() {
check_interrupted()?;
if targets_to_build.len() > 1 { if targets_to_build.len() > 1 {
println!( println!(
" Building target {} of {}: {}", " Building target {} of {}: {}",
@@ -523,6 +447,7 @@ fn build_project_at(
force: bool, force: bool,
) -> Result<(), String> { ) -> Result<(), String> {
with_dir(project_root, || { with_dir(project_root, || {
check_interrupted()?;
let items = check_dir(None).map_err(|_| "Failed to read project directory".to_string())?; let items = check_dir(None).map_err(|_| "Failed to read project directory".to_string())?;
if !items.contains(&"dcr.toml".to_string()) { if !items.contains(&"dcr.toml".to_string()) {
return Err("dcr.toml file not found".to_string()); return Err("dcr.toml file not found".to_string());
@@ -530,7 +455,7 @@ fn build_project_at(
let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?; let config = Config::open("./dcr.toml").map_err(|err| err.to_string())?;
let project_name = get_config_str(&config, "package.name"); let project_name = get_config_str(&config, "package.name");
let project_version = get_config_str(&config, "package.version"); let project_version = get_config_str(&config, "package.version");
let build_target_config = get_string_with_profile(&config, "target", profile); let build_target_config = get_build_string_with_profile(&config, "target", profile);
let build_target = target.or(if build_target_config.is_empty() { let build_target = target.or(if build_target_config.is_empty() {
None None
} else { } else {
@@ -599,41 +524,46 @@ fn build_project_at(
ensure_target_dirs(&items, profile, target_dir); ensure_target_dirs(&items, profile, target_dir);
let deps_table = config.get("dependencies").and_then(|v| v.as_table()); let deps_table = config.get("dependencies").and_then(|v| v.as_table());
let mut resolved = resolve_deps(&config, profile, build_target, project_root)?; let resolved = resolve_deps(&config, profile, build_target, project_root)?;
// Process dependencies // Registry dependencies are cached under the DCR registry root. Build
// them as normal DCR projects before the current project is linked.
if let Some(deps) = deps_table { if let Some(deps) = deps_table {
for (name, _) in deps { for (name, value) in deps {
if register::is_registry_dep(config.get(&format!("dependencies.{name}")).unwrap()) { if register::is_registry_dep(value) {
let pkg_info = register::resolve_package_from_registry(name)?; let pkg_info = register::resolve_package_from_registry(name)?;
let _version = pkg_info let version = pkg_info
.get("latest_version") .get("latest_version")
.or_else(|| pkg_info.get("version"))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.unwrap_or("unknown"); .unwrap_or("unknown");
let dep_root = register::package_root_from_registry_info(&pkg_info)?;
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"); let include_dir = dep_root.join("target").join("include");
let lib_dir = dep_root.join("target").join("lib");
if !include_dir.exists() { if !include_dir.exists() || !lib_dir.exists() {
print!( print!(
"\r{:100}\r {} {} v{}", "\r{:100}\r {} {} v{}",
"", "",
colored("Building", BOLD_GREEN), colored("Building", BOLD_GREEN),
name, name,
_version version
); );
std::io::Write::flush(&mut std::io::stdout()).unwrap(); std::io::Write::flush(&mut std::io::stdout()).unwrap();
std::thread::sleep(std::time::Duration::from_millis(300)); if !dep_root.join("dcr.toml").is_file() {
return Err(format!(
"Registry dependency `{}` is missing dcr.toml at {}",
name,
dep_root.display()
));
}
build_project_at(&dep_root, profile, build_target, &[], force)?;
print!( print!(
"\r{:100}\r {} {} v{}", "\r{:100}\r {} {} v{}",
"", "",
colored("Ready", BOLD_GREEN), colored("Ready", BOLD_GREEN),
name, name,
_version version
); );
println!(); println!();
} else { } else {
@@ -641,21 +571,9 @@ fn build_project_at(
" {} {} v{}", " {} {} v{}",
colored("Ready", BOLD_GREEN), colored("Ready", BOLD_GREEN),
name, name,
_version 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());
} }
} }
} }
@@ -803,6 +721,7 @@ fn build_project_at(
); );
if !skip { if !skip {
run_build(&ctx)?; run_build(&ctx)?;
check_interrupted()?;
write_build_fingerprint(&ctx, &fingerprint)?; write_build_fingerprint(&ctx, &fingerprint)?;
} }
if ctx.package_type == Some("lib") { if ctx.package_type == Some("lib") {
@@ -870,33 +789,6 @@ fn package_library(ctx: &BuildContext, headers: &[PathBuf]) -> Result<(), String
Ok(()) Ok(())
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}
pub fn normalize_target_os(target: &str) -> &str {
match target {
"linux" => "x86_64-unknown-linux-gnu",
"macos" => "x86_64-apple-darwin",
"windows" => "x86_64-pc-windows-msvc",
_ if target.contains('-') => target, // Assume valid triple
_ => {
warn(&format!(
"Unknown target '{}', using as-is. Supported short names: linux, macos, windows",
target
));
target
}
}
}
pub fn normalize_target(target: &str, profile: &str) -> Option<String> { pub fn normalize_target(target: &str, profile: &str) -> Option<String> {
let trimmed = normalize_target_os(target.trim()); let trimmed = normalize_target_os(target.trim());
if trimmed.is_empty() { if trimmed.is_empty() {
@@ -920,176 +812,6 @@ fn normalize_platform(platform: &str) -> Option<&str> {
} }
} }
fn resolve_compiler(
language: &str,
compiler: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> String {
let lang = primary_language(language);
env_override_compiler(&lang)
.or_else(|| toolchain_override_compiler(&lang, tc_cc, tc_cxx, tc_as))
.unwrap_or_else(|| compiler.to_string())
}
fn env_override_compiler(lang: &str) -> Option<String> {
if let Ok(value) = std::env::var("DCR_COMPILER") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
if lang == "asm" {
if let Ok(value) = std::env::var("DCR_AS") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
return None;
}
if (lang == "c++" || lang == "cpp" || lang == "cxx")
&& let Ok(value) = std::env::var("DCR_CXX")
{
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
if let Ok(value) = std::env::var("DCR_CC") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
None
}
fn toolchain_override_compiler(
lang: &str,
tc_cc: Option<&str>,
tc_cxx: Option<&str>,
tc_as: Option<&str>,
) -> Option<String> {
if lang == "asm" {
return tc_as.map(|v| v.to_string());
}
if (lang == "c++" || lang == "cpp" || lang == "cxx")
&& let Some(v) = tc_cxx
{
return Some(v.to_string());
}
tc_cc.map(|v| v.to_string())
}
fn primary_language(language: &str) -> String {
let parts: Vec<String> = language
.split('+')
.map(|p| p.trim().to_lowercase())
.filter(|p| !p.is_empty())
.collect();
for p in &parts {
if p == "c++" || p == "cpp" || p == "cxx" {
return p.clone();
}
}
if parts.iter().any(|p| p == "c") {
return "c".to_string();
}
if parts.iter().any(|p| p == "asm") {
return "asm".to_string();
}
language.to_lowercase()
}
fn resolve_tool(env_key: &str, fallback: Option<&str>) -> Option<String> {
if let Ok(value) = std::env::var(env_key) {
let trimmed = value.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
fallback.map(|v| v.to_string())
}
fn resolve_pkg_config_flags(
pkgs: &[String],
base_cflags: &[String],
base_ldflags: &[String],
) -> Result<(Vec<String>, Vec<String>), String> {
let mut cflags = base_cflags.to_vec();
let mut ldflags = base_ldflags.to_vec();
if pkgs.is_empty() {
return Ok((cflags, ldflags));
}
for pkg in pkgs {
let c_out = run_pkg_config(pkg, "--cflags")?;
let l_out = run_pkg_config(pkg, "--libs")?;
cflags.extend(split_flags(&c_out));
ldflags.extend(split_flags(&l_out));
}
Ok((cflags, ldflags))
}
fn run_pkg_config(pkg: &str, arg: &str) -> Result<String, String> {
let output = std::process::Command::new("pkg-config")
.arg(arg)
.arg(pkg)
.output()
.map_err(|err| format!("Failed to run pkg-config: {err}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("pkg-config failed for {pkg}: {stderr}"));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
fn split_flags(value: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
let mut chars = value.chars().peekable();
let mut quote: Option<char> = None;
while let Some(ch) = chars.next() {
if let Some(q) = quote {
if ch == q {
quote = None;
continue;
}
if ch == '\\' {
if let Some(next) = chars.next() {
current.push(next);
}
continue;
}
current.push(ch);
continue;
}
if ch == '"' || ch == '\'' {
quote = Some(ch);
continue;
}
if ch.is_whitespace() {
if !current.is_empty() {
out.push(current.clone());
current.clear();
}
continue;
}
if ch == '\\' {
if let Some(next) = chars.next() {
current.push(next);
}
continue;
}
current.push(ch);
}
if !current.is_empty() {
out.push(current);
}
out
}
struct ToolchainExecs { struct ToolchainExecs {
uic: String, uic: String,
moc: String, moc: String,
@@ -1449,44 +1171,6 @@ fn expand_step_value(template: &str, stem: &str, vars: &StepVars) -> String {
.replace("{version_suffix_dash}", vars.version_suffix_dash) .replace("{version_suffix_dash}", vars.version_suffix_dash)
} }
struct VersionInfo {
full: String,
major: String,
minor: String,
patch: String,
suffix: String,
suffix_dash: String,
}
fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}
struct StepVars<'a> { struct StepVars<'a> {
profile: &'a str, profile: &'a str,
version: &'a str, version: &'a str,

View File

@@ -1,7 +1,8 @@
use crate::config::flags; use crate::config::flags;
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::workspace::parse_workspace; use crate::core::workspace::parse_workspace;
use crate::utils::fs::{check_dir, find_project_root}; use crate::utils::build::parse_version_info;
use crate::utils::fs::{check_dir, find_project_root, with_dir};
use crate::utils::log::{error, warn}; use crate::utils::log::{error, warn};
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
use glob::glob; use glob::glob;
@@ -182,17 +183,6 @@ fn clean_project_at(
}) })
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}
fn clean_custom_paths(config: &Config, profile: &str) -> Result<(), String> { fn clean_custom_paths(config: &Config, profile: &str) -> Result<(), String> {
let patterns = match config.get("build.clean") { let patterns = match config.get("build.clean") {
Some(v) => v Some(v) => v
@@ -237,41 +227,3 @@ fn substitute_version_vars(value: &str, config: &Config) -> String {
.replace("{version_suffix}", &info.suffix) .replace("{version_suffix}", &info.suffix)
.replace("{version_suffix_dash}", &info.suffix_dash) .replace("{version_suffix_dash}", &info.suffix_dash)
} }
struct VersionInfo {
full: String,
major: String,
minor: String,
patch: String,
suffix: String,
suffix_dash: String,
}
fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}

View File

@@ -3,6 +3,7 @@ use reqwest::blocking::Client;
use serde::Deserialize; use serde::Deserialize;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[cfg(target_os = "linux")]
use std::process::Command; use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -156,14 +157,14 @@ fn temp_binary_path(current_exe: &Path) -> PathBuf {
current_exe.with_extension(extension) current_exe.with_extension(extension)
} }
fn set_executable_permissions(path: &Path) { fn set_executable_permissions(_path: &Path) {
#[cfg(unix)] #[cfg(unix)]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
if let Ok(meta) = fs::metadata(path) { if let Ok(meta) = fs::metadata(_path) {
let mut perms = meta.permissions(); let mut perms = meta.permissions();
perms.set_mode(0o755); perms.set_mode(0o755);
let _ = fs::set_permissions(path, perms); let _ = fs::set_permissions(_path, perms);
} }
} }
} }

View File

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

View File

@@ -2,10 +2,11 @@ use crate::cli::build::build;
use crate::cli::flags::parse_build_run_flags; use crate::cli::flags::parse_build_run_flags;
use crate::core::config::Config; use crate::core::config::Config;
use crate::core::runner::run_binary; use crate::core::runner::run_binary;
use crate::utils::build::{normalize_target_os, parse_version_info};
use crate::utils::fs::find_project_root; use crate::utils::fs::find_project_root;
use crate::utils::fs::with_dir;
use crate::utils::log::error; use crate::utils::log::error;
use crate::utils::text::{BOLD_GREEN, colored}; use crate::utils::text::{BOLD_GREEN, colored};
use std::path::Path;
use std::process::Command; use std::process::Command;
fn get_run_cmd( fn get_run_cmd(
@@ -36,15 +37,6 @@ fn get_run_cmd(
} }
} }
fn normalize_target_os(s: &str) -> &str {
match s {
"linux" => "x86_64-unknown-linux-gnu",
"macos" => "x86_64-apple-darwin",
"windows" => "x86_64-pc-windows-msvc",
_ => s,
}
}
pub fn run(args: &[String]) -> i32 { pub fn run(args: &[String]) -> i32 {
let start_dir = match std::env::current_dir() { let start_dir = match std::env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
@@ -152,17 +144,6 @@ pub fn run(args: &[String]) -> i32 {
1 1
} }
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
let result = f();
let _ = std::env::set_current_dir(prev);
result
}
fn run_shell(cmd: &str) -> i32 { fn run_shell(cmd: &str) -> i32 {
let status = if cfg!(target_os = "windows") { let status = if cfg!(target_os = "windows") {
Command::new("cmd").arg("/C").arg(cmd).status() Command::new("cmd").arg("/C").arg(cmd).status()
@@ -186,41 +167,3 @@ fn substitute_run_vars(cmd: &str, profile: &str, version: &str) -> String {
.replace("{version_suffix}", &info.suffix) .replace("{version_suffix}", &info.suffix)
.replace("{version_suffix_dash}", &info.suffix_dash) .replace("{version_suffix_dash}", &info.suffix_dash)
} }
struct VersionInfo {
full: String,
major: String,
minor: String,
patch: String,
suffix: String,
suffix_dash: String,
}
fn parse_version_info(version: &str) -> VersionInfo {
let mut full = version.trim().to_string();
if full.is_empty() {
full = "0.0.0".to_string();
}
let full_clone = full.clone();
let (base, suffix) = match full_clone.split_once('-') {
Some((head, tail)) => (head, tail),
None => (full_clone.as_str(), ""),
};
let mut parts = base.split('.');
let major = parts.next().unwrap_or("0").to_string();
let minor = parts.next().unwrap_or("0").to_string();
let patch = parts.next().unwrap_or("0").to_string();
let suffix_dash = if suffix.is_empty() {
"".to_string()
} else {
format!("-{suffix}")
};
VersionInfo {
full,
major,
minor,
patch,
suffix: suffix.to_string(),
suffix_dash,
}
}

View File

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

View File

@@ -1,5 +1,9 @@
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, OnceLock};
static OUTPUT_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
pub fn collect_sources( pub fn collect_sources(
roots: &[PathBuf], roots: &[PathBuf],
@@ -196,6 +200,22 @@ where
Ok(()) Ok(())
} }
pub fn run_command_sync_output(cmd: &mut Command) -> Result<(), String> {
let output = cmd.output().map_err(|err| format!("Build failed: {err}"))?;
let _guard = OUTPUT_MUTEX.get_or_init(|| Mutex::new(())).lock().unwrap();
if !output.stdout.is_empty() {
print!("{}", String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
eprint!("{}", String::from_utf8_lossy(&output.stderr));
}
if output.status.success() {
Ok(())
} else {
Err("Build failed".to_string())
}
}
pub fn normalize_source_path(path: &Path) -> String { pub fn normalize_source_path(path: &Path) -> String {
if !path.is_absolute() { if !path.is_absolute() {
return path.to_string_lossy().to_string(); return path.to_string_lossy().to_string();

View File

@@ -140,9 +140,5 @@ fn build_object(
cmd.arg(flag); cmd.arg(flag);
} }
match cmd.status() { common::run_command_sync_output(&mut cmd)
Ok(status) if status.success() => Ok(()),
Ok(_) => Err("Build failed".to_string()),
Err(err) => Err(format!("Build failed: {err}")),
}
} }

View File

@@ -151,11 +151,7 @@ fn build_object(
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { common::run_command_sync_output(&mut cmd)
Ok(status) if status.success() => Ok(()),
Ok(_) => Err("Build failed".to_string()),
Err(err) => Err(format!("Build failed: {err}")),
}
} }
fn nasm_format(platform: Option<&str>) -> &'static str { fn nasm_format(platform: Option<&str>) -> &'static str {

View File

@@ -200,11 +200,7 @@ fn build_object(
eprintln!("[dcr] {:?}", cmd); eprintln!("[dcr] {:?}", cmd);
} }
match cmd.status() { common::run_command_sync_output(&mut cmd)
Ok(status) if status.success() => Ok(()),
Ok(_) => Err("Build failed".to_string()),
Err(err) => Err(format!("Build failed: {err}")),
}
} }
fn asm_lang_flag(source: &str) -> Option<&'static str> { fn asm_lang_flag(source: &str) -> Option<&'static str> {

View File

@@ -1,3 +1,5 @@
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use toml::Value; use toml::Value;
@@ -51,6 +53,98 @@ impl From<toml::ser::Error> for ConfigError {
pub struct Config { pub struct Config {
path: PathBuf, path: PathBuf,
data: Value, data: Value,
typed: DcrConfig,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct DcrConfig {
pub package: PackageConfig,
pub build: BuildConfig,
#[serde(default)]
pub dependencies: BTreeMap<String, DependencyConfig>,
#[serde(default)]
pub toolchain: Option<ToolchainConfig>,
#[serde(default)]
pub workspace: BTreeMap<String, WorkspaceMemberConfig>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct PackageConfig {
pub name: String,
pub version: String,
#[serde(default, rename = "type")]
pub pkg_type: Option<String>,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct BuildConfig {
pub language: LanguageConfig,
pub standard: String,
pub compiler: String,
#[serde(default)]
pub kind: Option<String>,
#[serde(default)]
pub target: Option<String>,
#[serde(default)]
pub platform: Option<String>,
#[serde(default)]
pub cflags: Vec<String>,
#[serde(default)]
pub ldflags: Vec<String>,
#[serde(default)]
pub exclude: Vec<String>,
#[serde(default)]
pub include: Vec<String>,
#[serde(default)]
pub roots: Vec<String>,
#[serde(default)]
pub clean: Vec<String>,
#[serde(default)]
pub src_disable: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum LanguageConfig {
One(String),
Many(Vec<String>),
}
impl LanguageConfig {
fn values(&self) -> Vec<&str> {
match self {
LanguageConfig::One(value) => vec![value.as_str()],
LanguageConfig::Many(values) => values.iter().map(String::as_str).collect(),
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum DependencyConfig {
Version(String),
Table(BTreeMap<String, Value>),
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ToolchainConfig {
pub cc: Option<String>,
pub cxx: Option<String>,
#[serde(rename = "as")]
pub assembler: Option<String>,
pub ar: Option<String>,
pub ld: Option<String>,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct WorkspaceMemberConfig {
pub path: String,
#[serde(default)]
pub deps: Vec<String>,
} }
impl Config { impl Config {
@@ -63,7 +157,8 @@ impl Config {
write_toml(&path, &default_value)?; write_toml(&path, &default_value)?;
default_value default_value
}; };
let cfg = Self { path, data }; let typed = parse_typed_config(&data)?;
let cfg = Self { path, data, typed };
cfg.validate()?; cfg.validate()?;
Ok(cfg) Ok(cfg)
} }
@@ -74,11 +169,27 @@ impl Config {
return Err(ConfigError::Invalid("dcr.toml not found".into())); return Err(ConfigError::Invalid("dcr.toml not found".into()));
} }
let data = read_toml(&path)?; let data = read_toml(&path)?;
let cfg = Self { path, data }; let typed = parse_typed_config(&data)?;
let cfg = Self { path, data, typed };
cfg.validate()?; cfg.validate()?;
Ok(cfg) Ok(cfg)
} }
#[allow(dead_code)]
pub fn typed(&self) -> &DcrConfig {
&self.typed
}
#[allow(dead_code)]
pub fn package(&self) -> &PackageConfig {
&self.typed.package
}
#[allow(dead_code)]
pub fn build_config(&self) -> &BuildConfig {
&self.typed.build
}
pub fn get(&self, key: &str) -> Option<&Value> { pub fn get(&self, key: &str) -> Option<&Value> {
let parts: Vec<&str> = key.split('.').collect(); let parts: Vec<&str> = key.split('.').collect();
get_path(&self.data, &parts) get_path(&self.data, &parts)
@@ -98,19 +209,15 @@ impl Config {
} }
pub fn validate(&self) -> Result<(), ConfigError> { pub fn validate(&self) -> Result<(), ConfigError> {
let package = self if self.typed.package.name.trim().is_empty() {
.get("package") return Err(ConfigError::Invalid("package.name is empty".into()));
.and_then(|v| v.as_table())
.ok_or_else(|| ConfigError::Invalid("missing [package]".into()))?;
for key in ["name", "version"] {
let value = package.get(key).and_then(|v| v.as_str()).unwrap_or("");
if value.trim().is_empty() {
return Err(ConfigError::Invalid(format!("package.{key} is empty")));
} }
if self.typed.package.version.trim().is_empty() {
return Err(ConfigError::Invalid("package.version is empty".into()));
} }
validate_package_name(&self.typed.package.name)?;
if let Some(pkg_type) = package.get("type").and_then(|v| v.as_str()) { if let Some(pkg_type) = &self.typed.package.pkg_type {
let pkg_type = pkg_type.trim(); let pkg_type = pkg_type.trim();
if !pkg_type.is_empty() && pkg_type != "lib" && pkg_type != "app" && pkg_type != "none" if !pkg_type.is_empty() && pkg_type != "lib" && pkg_type != "app" && pkg_type != "none"
{ {
@@ -120,106 +227,41 @@ impl Config {
} }
} }
let build = self validate_language_config(&self.typed.build.language, "build.language")?;
.get("build") if self.typed.build.standard.trim().is_empty() {
.and_then(|v| v.as_table()) return Err(ConfigError::Invalid("build.standard is empty".into()));
.ok_or_else(|| ConfigError::Invalid("missing [build]".into()))?;
if let Some(language) = build.get("language") {
self.validate_language(language)?;
} else {
return Err(ConfigError::Invalid("build.language is empty".into()));
} }
for key in ["standard", "compiler"] { if self.typed.build.compiler.trim().is_empty() {
let value = build.get(key).and_then(|v| v.as_str()).unwrap_or(""); return Err(ConfigError::Invalid("build.compiler is empty".into()));
if value.trim().is_empty() {
return Err(ConfigError::Invalid(format!("build.{key} is empty")));
} }
} if let Some(platform) = &self.typed.build.platform
if let Some(platform) = build.get("platform") && platform.trim().is_empty()
&& !platform
.as_str()
.map(|v| !v.trim().is_empty())
.unwrap_or(false)
{ {
return Err(ConfigError::Invalid("build.platform is empty".into())); return Err(ConfigError::Invalid("build.platform is empty".into()));
} }
if let Some(toolchain) = self.get("toolchain").and_then(|v| v.as_table()) { validate_toolchain(self.typed.toolchain.as_ref())?;
for key in ["cc", "cxx", "as", "ar", "ld"] { if let Some(kind) = &self.typed.build.kind {
if let Some(v) = toolchain.get(key)
&& !v.as_str().map(|s| !s.trim().is_empty()).unwrap_or(false)
{
return Err(ConfigError::Invalid(format!("toolchain.{key} is invalid")));
}
}
}
if let Some(kind) = build.get("kind").and_then(|v| v.as_str()) {
let kind = kind.trim(); let kind = kind.trim();
if !kind.is_empty() && kind != "bin" && kind != "staticlib" && kind != "sharedlib" { if !kind.is_empty() && kind != "bin" && kind != "staticlib" && kind != "sharedlib" {
return Err(ConfigError::Invalid("build.kind is invalid".into())); return Err(ConfigError::Invalid("build.kind is invalid".into()));
} }
} }
if let Some(exclude) = build.get("exclude") { validate_string_list(&self.typed.build.exclude, "build.exclude")?;
let arr = exclude.as_array().ok_or_else(|| { validate_string_list(&self.typed.build.include, "build.include")?;
ConfigError::Invalid("build.exclude must be an array of strings".into()) validate_string_list(&self.typed.build.roots, "build.roots")?;
})?; validate_string_list(&self.typed.build.clean, "build.clean")?;
for item in arr { validate_string_list(&self.typed.build.cflags, "build.cflags")?;
let s = item.as_str().unwrap_or(""); validate_string_list(&self.typed.build.ldflags, "build.ldflags")?;
if s.trim().is_empty() { if let Some(target) = &self.typed.build.target {
return Err(ConfigError::Invalid( validate_non_empty_string(target, "build.target")?;
"build.exclude contains empty value".into(),
));
}
}
}
if let Some(include) = build.get("include") {
let arr = include.as_array().ok_or_else(|| {
ConfigError::Invalid("build.include must be an array of strings".into())
})?;
for item in arr {
let s = item.as_str().unwrap_or("");
if s.trim().is_empty() {
return Err(ConfigError::Invalid(
"build.include contains empty value".into(),
));
}
}
}
if let Some(roots) = build.get("roots") {
let arr = roots.as_array().ok_or_else(|| {
ConfigError::Invalid("build.roots must be an array of strings".into())
})?;
for item in arr {
let s = item.as_str().unwrap_or("");
if s.trim().is_empty() {
return Err(ConfigError::Invalid(
"build.roots contains empty value".into(),
));
}
}
}
if let Some(src_disable) = build.get("src_disable")
&& !src_disable.is_bool()
{
return Err(ConfigError::Invalid(
"build.src_disable must be a boolean".into(),
));
}
if let Some(clean) = build.get("clean") {
let arr = clean.as_array().ok_or_else(|| {
ConfigError::Invalid("build.clean must be an array of strings".into())
})?;
for item in arr {
let s = item.as_str().unwrap_or("");
if s.trim().is_empty() {
return Err(ConfigError::Invalid(
"build.clean contains empty value".into(),
));
}
}
} }
for profile in ["release", "debug"] { for profile in ["release", "debug"] {
if let Some(section) = build.get(profile) { if let Some(section) = self
.data
.get("build")
.and_then(|v| v.as_table())
.and_then(|build| build.get(profile))
{
let table = section.as_table().ok_or_else(|| { let table = section.as_table().ok_or_else(|| {
ConfigError::Invalid(format!("build.{profile} must be a table")) ConfigError::Invalid(format!("build.{profile} must be a table"))
})?; })?;
@@ -236,12 +278,93 @@ impl Config {
fn set(&mut self, key: &str, value: Value) -> Result<(), ConfigError> { fn set(&mut self, key: &str, value: Value) -> Result<(), ConfigError> {
let parts: Vec<&str> = key.split('.').collect(); let parts: Vec<&str> = key.split('.').collect();
let previous = self.data.clone();
set_path(&mut self.data, &parts, value)?; set_path(&mut self.data, &parts, value)?;
self.typed = match parse_typed_config(&self.data) {
Ok(typed) => typed,
Err(err) => {
self.data = previous;
return Err(err);
}
};
if let Err(err) = self.validate() {
self.data = previous;
self.typed = parse_typed_config(&self.data)?;
return Err(err);
}
self.save()?; self.save()?;
Ok(()) Ok(())
} }
} }
fn parse_typed_config(value: &Value) -> Result<DcrConfig, ConfigError> {
value.clone().try_into().map_err(ConfigError::TomlDe)
}
fn validate_package_name(name: &str) -> Result<(), ConfigError> {
let trimmed = name.trim();
if trimmed != name {
return Err(ConfigError::Invalid(
"package.name must not contain leading or trailing whitespace".into(),
));
}
if trimmed == "." || trimmed == ".." || trimmed.contains("..") {
return Err(ConfigError::Invalid("package.name is invalid".into()));
}
if !trimmed
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(ConfigError::Invalid(
"package.name must contain only ASCII letters, digits, '_' or '-'".into(),
));
}
Ok(())
}
fn validate_language_config(language: &LanguageConfig, key: &str) -> Result<(), ConfigError> {
let values = language.values();
if values.is_empty() {
return Err(ConfigError::Invalid(format!("{key} is empty")));
}
for value in values {
validate_non_empty_string(value, key)?;
}
Ok(())
}
fn validate_toolchain(toolchain: Option<&ToolchainConfig>) -> Result<(), ConfigError> {
let Some(toolchain) = toolchain else {
return Ok(());
};
for (key, value) in [
("cc", toolchain.cc.as_deref()),
("cxx", toolchain.cxx.as_deref()),
("as", toolchain.assembler.as_deref()),
("ar", toolchain.ar.as_deref()),
("ld", toolchain.ld.as_deref()),
] {
if let Some(value) = value {
validate_non_empty_string(value, &format!("toolchain.{key}"))?;
}
}
Ok(())
}
fn validate_string_list(values: &[String], key: &str) -> Result<(), ConfigError> {
for value in values {
validate_non_empty_string(value, key)?;
}
Ok(())
}
fn validate_non_empty_string(value: &str, key: &str) -> Result<(), ConfigError> {
if value.trim().is_empty() {
return Err(ConfigError::Invalid(format!("{key} contains empty value")));
}
Ok(())
}
impl Config { impl Config {
fn validate_language(&self, value: &Value) -> Result<(), ConfigError> { fn validate_language(&self, value: &Value) -> Result<(), ConfigError> {
if let Some(s) = value.as_str() { if let Some(s) = value.as_str() {
@@ -670,6 +793,21 @@ mod tests {
assert!(config.is_ok(), "should open valid toml"); assert!(config.is_ok(), "should open valid toml");
} }
#[test]
fn exposes_typed_config() {
let dir = temp_dir("typed_config");
let path = write_toml_file(
&dir,
"[package]\nname = \"typed\"\nversion = \"1.2.3\"\ntype = \"lib\"\n\n[build]\nlanguage = [\"c\", \"c++\"]\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"staticlib\"\ncflags = [\"-Wall\"]\n\n[dependencies]\nfoo = \"1.0.0\"\n",
);
let config = Config::open(&path.to_string_lossy()).unwrap();
assert_eq!(config.package().name, "typed");
assert_eq!(config.typed().package.version, "1.2.3");
assert_eq!(config.build_config().compiler, "clang");
assert_eq!(config.build_config().cflags, ["-Wall"]);
assert!(config.typed().dependencies.contains_key("foo"));
}
#[test] #[test]
fn open_invalid_toml_syntax() { fn open_invalid_toml_syntax() {
let dir = temp_dir("open_invalid"); let dir = temp_dir("open_invalid");
@@ -706,6 +844,35 @@ mod tests {
assert!(result.is_err(), "missing [build] should fail validation"); assert!(result.is_err(), "missing [build] should fail validation");
} }
#[test]
fn validate_wrong_field_type_fails() {
let dir = temp_dir("wrong_type");
let path = write_toml_file(
&dir,
"[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = [\"clang\"]\nkind = \"bin\"\n\n[dependencies]\n",
);
let result = Config::open(&path.to_string_lossy());
assert!(
result.is_err(),
"typed config should reject wrong field types"
);
}
#[test]
fn validate_invalid_package_names_fail() {
for name in [
"../evil", "bad/name", "bad name", "", " name", "name ", "a.b",
] {
let dir = temp_dir("bad_name");
let content = format!(
"[package]\nname = \"{name}\"\nversion = \"0.1.0\"\n\n[build]\nlanguage = \"c\"\nstandard = \"c11\"\ncompiler = \"clang\"\nkind = \"bin\"\n\n[dependencies]\n"
);
let path = write_toml_file(&dir, &content);
let result = Config::open(&path.to_string_lossy());
assert!(result.is_err(), "package name `{name}` should fail");
}
}
#[test] #[test]
fn validate_empty_language_fails() { fn validate_empty_language_fails() {
let dir = temp_dir("empty_lang"); let dir = temp_dir("empty_lang");

View File

@@ -31,29 +31,23 @@ pub fn resolve_deps(
if let Some(deps) = deps_table { if let Some(deps) = deps_table {
for (name, value) in deps { for (name, value) in deps {
if register::is_registry_dep(value) { if register::is_registry_dep(value) {
let _pkg_info = register::resolve_package_from_registry(name)?; let pkg_info = register::resolve_package_from_registry(name)?;
// Используем путь относительно project_root или системный путь, если нужно let dep_root = register::package_root_from_registry_info(&pkg_info)?;
let dep_root = project_root.join("dcr-index");
resolved.include_dirs.push( resolved.include_dirs.push(
dep_root register::registry_include_dir(&dep_root)
.join("target")
.join("include")
.to_string_lossy() .to_string_lossy()
.to_string(), .to_string(),
); );
resolved.lib_dirs.push( resolved.lib_dirs.push(
dep_root register::registry_lib_dir(&dep_root)
.join("target")
.join("lib")
.to_string_lossy() .to_string_lossy()
.to_string(), .to_string(),
); );
resolved.libs.push(name.clone()); resolved.libs.push(name.clone());
} else if let Some(table) = value.as_table() } else if let Some(path) = path_dep_path(value) {
&& let Some(path) = table.get("path").and_then(|v| v.as_str())
{
let dep_root = project_root.join(path); let dep_root = project_root.join(path);
if let Some(table) = value.as_table() {
if let Some(includes) = table.get("include").and_then(|v| v.as_array()) { if let Some(includes) = table.get("include").and_then(|v| v.as_array()) {
for inc in includes { for inc in includes {
if let Some(inc_str) = inc.as_str() { if let Some(inc_str) = inc.as_str() {
@@ -62,13 +56,22 @@ pub fn resolve_deps(
.push(dep_root.join(inc_str).to_string_lossy().to_string()); .push(dep_root.join(inc_str).to_string_lossy().to_string());
} }
} }
} else {
push_if_exists(&mut resolved.include_dirs, &dep_root.join("include"));
} }
let lib_path = dep_root.join("target").join("lib");
if lib_path.exists() { if let Some(lib_dirs) = table.get("lib").and_then(|v| v.as_array()) {
for lib_dir in lib_dirs {
if let Some(lib_dir_str) = lib_dir.as_str() {
resolved resolved
.lib_dirs .lib_dirs
.push(lib_path.to_string_lossy().to_string()); .push(dep_root.join(lib_dir_str).to_string_lossy().to_string());
} }
}
} else {
push_default_lib_dirs(&mut resolved.lib_dirs, &dep_root);
}
if let Some(libs) = table.get("libs").and_then(|v| v.as_array()) { if let Some(libs) = table.get("libs").and_then(|v| v.as_array()) {
for lib in libs { for lib in libs {
if let Some(lib_str) = lib.as_str() { if let Some(lib_str) = lib.as_str() {
@@ -78,6 +81,11 @@ pub fn resolve_deps(
} else { } else {
resolved.libs.push(name.clone()); resolved.libs.push(name.clone());
} }
} else {
push_if_exists(&mut resolved.include_dirs, &dep_root.join("include"));
push_default_lib_dirs(&mut resolved.lib_dirs, &dep_root);
resolved.libs.push(name.clone());
}
} }
} }
} }
@@ -91,3 +99,68 @@ pub fn resolve_deps(
Ok(resolved) Ok(resolved)
} }
fn path_dep_path(value: &toml::Value) -> Option<&str> {
if let Some(table) = value.as_table() {
return table.get("path").and_then(|v| v.as_str());
}
register::path_from_string_dep(value)
}
fn push_if_exists(paths: &mut Vec<String>, path: &Path) {
if path.exists() {
paths.push(path.to_string_lossy().to_string());
}
}
fn push_default_lib_dirs(paths: &mut Vec<String>, dep_root: &Path) {
for dir in ["lib", "lib64"] {
push_if_exists(paths, &dep_root.join(dir));
}
push_if_exists(paths, &dep_root.join("target").join("lib"));
}
#[cfg(test)]
mod tests {
use super::*;
use toml::Value;
#[test]
fn path_dep_path_supports_table_and_legacy_strings() {
let table = Value::Table(
[(
"path".to_string(),
Value::String("./libs/mylib".to_string()),
)]
.into_iter()
.collect(),
);
assert_eq!(path_dep_path(&table), Some("./libs/mylib"));
assert_eq!(
path_dep_path(&Value::String("path:./libs/mylib".to_string())),
Some("./libs/mylib")
);
assert_eq!(
path_dep_path(&Value::String("./libs/mylib".to_string())),
Some("./libs/mylib")
);
assert_eq!(path_dep_path(&Value::String("1.2.3".to_string())), None);
}
#[test]
fn default_lib_dirs_include_packaged_library_output() {
let root = std::env::temp_dir().join(format!(
"dcr_default_lib_dirs_{}_{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(root.join("target/lib")).unwrap();
let mut paths = Vec::new();
push_default_lib_dirs(&mut paths, &root);
assert!(paths.iter().any(|p| p.ends_with("target/lib")));
let _ = std::fs::remove_dir_all(root);
}
}

View File

@@ -35,6 +35,47 @@ pub fn get_index_path() -> PathBuf {
}) })
} }
pub fn get_registry_cache_root() -> PathBuf {
get_index_path()
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."))
}
pub fn package_root_from_registry_info(pkg_info: &JsonValue) -> Result<PathBuf, String> {
let raw_path = pkg_info
.get("path")
.and_then(|v| v.as_str())
.ok_or("Registry package is missing path")?;
if raw_path.trim().is_empty() {
return Err("Registry package path is empty".to_string());
}
let path = Path::new(raw_path);
let full_path = if path.is_absolute() {
path.to_path_buf()
} else {
get_registry_cache_root().join(path)
};
if full_path.file_name().and_then(|v| v.to_str()) == Some("dcr.toml") {
return full_path
.parent()
.map(Path::to_path_buf)
.ok_or_else(|| format!("Invalid registry package path: {}", full_path.display()));
}
Ok(full_path)
}
pub fn registry_include_dir(dep_root: &Path) -> PathBuf {
dep_root.join("target").join("include")
}
pub fn registry_lib_dir(dep_root: &Path) -> PathBuf {
dep_root.join("target").join("lib")
}
pub fn resolve_package_from_registry(name: &str) -> Result<JsonValue, String> { pub fn resolve_package_from_registry(name: &str) -> Result<JsonValue, String> {
let config = get_registry_config().ok_or("No registry config found")?; let config = get_registry_config().ok_or("No registry config found")?;
let mut registries: Vec<(&String, &Registry)> = config.registry.iter().collect(); let mut registries: Vec<(&String, &Registry)> = config.registry.iter().collect();
@@ -63,8 +104,9 @@ pub fn resolve_package_from_registry(name: &str) -> Result<JsonValue, String> {
} }
pub fn is_registry_dep(value: &TomlValue) -> bool { pub fn is_registry_dep(value: &TomlValue) -> bool {
if value.is_str() { if let Some(raw) = value.as_str() {
return true; let raw = raw.trim();
return !is_path_like_string(raw) && !is_git_like_string(raw);
} }
if let Some(table) = value.as_table() { if let Some(table) = value.as_table() {
return !table.contains_key("git") return !table.contains_key("git")
@@ -74,3 +116,81 @@ pub fn is_registry_dep(value: &TomlValue) -> bool {
} }
false false
} }
pub fn path_from_string_dep(value: &TomlValue) -> Option<&str> {
let raw = value.as_str()?.trim();
if let Some(path) = raw.strip_prefix("path:") {
return Some(path);
}
if is_path_like_string(raw) {
return Some(raw);
}
None
}
fn is_path_like_string(raw: &str) -> bool {
raw.starts_with("path:")
|| raw.starts_with("./")
|| raw.starts_with("../")
|| raw.starts_with('/')
|| raw.starts_with("~/")
|| raw.contains('\\')
}
fn is_git_like_string(raw: &str) -> bool {
raw.starts_with("git:")
|| raw.starts_with("github:")
|| raw.starts_with("gitlab:")
|| raw.starts_with("http://")
|| raw.starts_with("https://")
|| raw.starts_with("git@")
}
#[cfg(test)]
mod tests {
use super::*;
use toml::map::Map;
#[test]
fn registry_dep_detection_excludes_local_and_git_strings() {
assert!(is_registry_dep(&TomlValue::String("1.2.3".to_string())));
assert!(!is_registry_dep(&TomlValue::String(
"path:./libs/mylib".to_string()
)));
assert!(!is_registry_dep(&TomlValue::String(
"./libs/mylib".to_string()
)));
assert!(!is_registry_dep(&TomlValue::String(
"git:https://example.com/repo.git".to_string()
)));
}
#[test]
fn registry_dep_detection_excludes_source_tables() {
let mut path_table = Map::new();
path_table.insert(
"path".to_string(),
TomlValue::String("./libs/mylib".to_string()),
);
assert!(!is_registry_dep(&TomlValue::Table(path_table)));
let mut registry_table = Map::new();
registry_table.insert("features".to_string(), TomlValue::Array(Vec::new()));
assert!(is_registry_dep(&TomlValue::Table(registry_table)));
}
#[test]
fn registry_package_root_accepts_package_dir_or_manifest_path() {
let pkg = serde_json::json!({ "path": "/tmp/pkg" });
assert_eq!(
package_root_from_registry_info(&pkg).unwrap(),
PathBuf::from("/tmp/pkg")
);
let pkg = serde_json::json!({ "path": "/tmp/pkg/dcr.toml" });
assert_eq!(
package_root_from_registry_info(&pkg).unwrap(),
PathBuf::from("/tmp/pkg")
);
}
}

View File

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

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

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

View File

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

View File

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

View File

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