mirror of
https://github.com/dexoron/dcr.git
synced 2026-10-21 22:29:32 +00:00
Compare commits
8 Commits
441c9f4df3
...
v0.6.6
| Author | SHA1 | Date | |
|---|---|---|---|
| fce9c44181 | |||
| 3b54500d4d | |||
| 933fae749d | |||
|
|
9ab7ce15db | ||
|
|
954f2870ba | ||
|
|
9a24a80d59 | ||
|
|
a123f647c8 | ||
|
|
8f04a37eb0 |
28
.github/workflows/release.yml
vendored
28
.github/workflows/release.yml
vendored
@@ -116,14 +116,30 @@ jobs:
|
||||
if: runner.os == 'Linux' && matrix.apt != ''
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ${{ matrix.apt }}
|
||||
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: Install musl.cc cross-toolchain
|
||||
if: matrix.musl_cross != ''
|
||||
- name: Setup LLVM + MinGW (gnullvm)
|
||||
if: contains(matrix.target, 'gnullvm')
|
||||
shell: pwsh
|
||||
run: |
|
||||
curl -fsSL "https://musl.cc/${{ matrix.musl_cross }}.tgz" | \
|
||||
sudo tar -xz -C /opt
|
||||
echo "/opt/${{ matrix.musl_cross }}/bin" >> "$GITHUB_PATH"
|
||||
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
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
36
CHANGELOG.md
36
CHANGELOG.md
@@ -1,5 +1,41 @@
|
||||
# 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
|
||||
|
||||
Added:
|
||||
|
||||
115
Cargo.lock
generated
115
Cargo.lock
generated
@@ -35,6 +35,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.19.1"
|
||||
@@ -71,18 +80,6 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -103,13 +100,23 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dcr"
|
||||
version = "0.6.5"
|
||||
name = "ctrlc"
|
||||
version = "3.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162"
|
||||
dependencies = [
|
||||
"console",
|
||||
"dispatch2",
|
||||
"nix",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dcr"
|
||||
version = "0.6.6"
|
||||
dependencies = [
|
||||
"ctrlc",
|
||||
"git2",
|
||||
"glob",
|
||||
"indicatif",
|
||||
"reqwest",
|
||||
"self-replace",
|
||||
"serde",
|
||||
@@ -128,6 +135,18 @@ dependencies = [
|
||||
"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]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.5"
|
||||
@@ -139,12 +158,6 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encode_unicode"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -549,19 +562,6 @@ dependencies = [
|
||||
"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]]
|
||||
name = "ipnet"
|
||||
version = "2.11.0"
|
||||
@@ -697,6 +697,33 @@ dependencies = [
|
||||
"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]]
|
||||
name = "once_cell"
|
||||
version = "1.21.3"
|
||||
@@ -745,12 +772,6 @@ version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.4"
|
||||
@@ -1373,24 +1394,12 @@ version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
|
||||
[[package]]
|
||||
name = "unit-prefix"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "dcr"
|
||||
version = "0.6.5"
|
||||
version = "0.6.6"
|
||||
edition = "2024"
|
||||
build = "build.rs"
|
||||
|
||||
@@ -11,7 +11,6 @@ serde = { version = "1", features = ["derive"] }
|
||||
self-replace = "1"
|
||||
sha2 = "0.10"
|
||||
toml = "1.0.3"
|
||||
indicatif = "0.18.4"
|
||||
console = "0.16.3"
|
||||
git2 = "0.20.4"
|
||||
serde_json = "1"
|
||||
ctrlc = "3"
|
||||
|
||||
@@ -68,7 +68,9 @@ pub fn add(args: &[String]) -> i32 {
|
||||
Value::Table(table)
|
||||
}
|
||||
} 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 {
|
||||
error("Dependency source (path or git) must be provided");
|
||||
return 1;
|
||||
|
||||
432
src/cli/build.rs
432
src/cli/build.rs
@@ -5,16 +5,28 @@ use crate::core::builder::{BuildContext, build as build_project, collect_sources
|
||||
use crate::core::config::Config;
|
||||
use crate::core::deps::{register, resolve_deps};
|
||||
use crate::core::workspace::parse_workspace;
|
||||
use crate::utils::fs::{check_dir, find_project_root};
|
||||
use crate::utils::log::{error, warn};
|
||||
use crate::utils::build::{
|
||||
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 glob::glob;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Once;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
static BUILD_INTERRUPTED: AtomicBool = AtomicBool::new(false);
|
||||
static SIGNAL_HANDLER: Once = Once::new();
|
||||
|
||||
pub fn build(args: &[String]) -> i32 {
|
||||
install_signal_handler();
|
||||
BUILD_INTERRUPTED.store(false, Ordering::SeqCst);
|
||||
let start_dir = match std::env::current_dir() {
|
||||
Ok(dir) => dir,
|
||||
Err(_) => {
|
||||
@@ -67,77 +79,20 @@ pub fn build(args: &[String]) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_config_str(config: &Config, key: &str) -> String {
|
||||
config
|
||||
.get(key)
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
fn install_signal_handler() {
|
||||
SIGNAL_HANDLER.call_once(|| {
|
||||
let _ = ctrlc::set_handler(|| {
|
||||
BUILD_INTERRUPTED.store(true, Ordering::SeqCst);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn get_config_language(config: &Config, key: &str) -> Result<String, String> {
|
||||
let value = config.get(key).ok_or_else(|| format!("{key} is missing"))?;
|
||||
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());
|
||||
fn check_interrupted() -> Result<(), String> {
|
||||
if BUILD_INTERRUPTED.load(Ordering::SeqCst) {
|
||||
Err("Build interrupted".to_string())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
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(
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -275,22 +230,18 @@ fn get_list_with_profile_and_target(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::build::normalize_target_os;
|
||||
|
||||
#[test]
|
||||
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!(
|
||||
super::normalize_target_os("linux"),
|
||||
normalize_target_os("x86_64-unknown-linux-gnu"),
|
||||
"x86_64-unknown-linux-gnu"
|
||||
);
|
||||
assert_eq!(super::normalize_target_os("macos"), "x86_64-apple-darwin");
|
||||
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");
|
||||
assert_eq!(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)
|
||||
}
|
||||
|
||||
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> {
|
||||
let value = match config.get(key) {
|
||||
Some(v) => v,
|
||||
@@ -467,6 +390,7 @@ fn build_from_root(
|
||||
|
||||
let start_time = Instant::now();
|
||||
for (i, build_target) in targets_to_build.iter().enumerate() {
|
||||
check_interrupted()?;
|
||||
if targets_to_build.len() > 1 {
|
||||
println!(
|
||||
" Building target {} of {}: {}",
|
||||
@@ -523,6 +447,7 @@ fn build_project_at(
|
||||
force: bool,
|
||||
) -> Result<(), String> {
|
||||
with_dir(project_root, || {
|
||||
check_interrupted()?;
|
||||
let items = check_dir(None).map_err(|_| "Failed to read project directory".to_string())?;
|
||||
if !items.contains(&"dcr.toml".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 project_name = get_config_str(&config, "package.name");
|
||||
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() {
|
||||
None
|
||||
} else {
|
||||
@@ -599,41 +524,46 @@ fn build_project_at(
|
||||
ensure_target_dirs(&items, profile, target_dir);
|
||||
|
||||
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 {
|
||||
for (name, _) in deps {
|
||||
if register::is_registry_dep(config.get(&format!("dependencies.{name}")).unwrap()) {
|
||||
for (name, value) in deps {
|
||||
if register::is_registry_dep(value) {
|
||||
let pkg_info = register::resolve_package_from_registry(name)?;
|
||||
let _version = pkg_info
|
||||
let version = pkg_info
|
||||
.get("latest_version")
|
||||
.or_else(|| pkg_info.get("version"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown");
|
||||
|
||||
let pkg_path = pkg_info.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let dep_root = register::get_index_path()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join(Path::new(pkg_path).parent().unwrap());
|
||||
let dep_root = register::package_root_from_registry_info(&pkg_info)?;
|
||||
let include_dir = dep_root.join("target").join("include");
|
||||
let lib_dir = dep_root.join("target").join("lib");
|
||||
|
||||
if !include_dir.exists() {
|
||||
if !include_dir.exists() || !lib_dir.exists() {
|
||||
print!(
|
||||
"\r{:100}\r {} {} v{}",
|
||||
"",
|
||||
colored("Building", BOLD_GREEN),
|
||||
name,
|
||||
_version
|
||||
version
|
||||
);
|
||||
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!(
|
||||
"\r{:100}\r {} {} v{}",
|
||||
"",
|
||||
colored("Ready", BOLD_GREEN),
|
||||
name,
|
||||
_version
|
||||
version
|
||||
);
|
||||
println!();
|
||||
} else {
|
||||
@@ -641,21 +571,9 @@ fn build_project_at(
|
||||
" {} {} v{}",
|
||||
colored("Ready", BOLD_GREEN),
|
||||
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 {
|
||||
run_build(&ctx)?;
|
||||
check_interrupted()?;
|
||||
write_build_fingerprint(&ctx, &fingerprint)?;
|
||||
}
|
||||
if ctx.package_type == Some("lib") {
|
||||
@@ -870,33 +789,6 @@ fn package_library(ctx: &BuildContext, headers: &[PathBuf]) -> Result<(), String
|
||||
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> {
|
||||
let trimmed = normalize_target_os(target.trim());
|
||||
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 {
|
||||
uic: 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)
|
||||
}
|
||||
|
||||
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> {
|
||||
profile: &'a str,
|
||||
version: &'a str,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::config::flags;
|
||||
use crate::core::config::Config;
|
||||
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::text::{BOLD_GREEN, colored};
|
||||
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> {
|
||||
let patterns = match config.get("build.clean") {
|
||||
Some(v) => v
|
||||
@@ -237,41 +227,3 @@ fn substitute_version_vars(value: &str, config: &Config) -> String {
|
||||
.replace("{version_suffix}", &info.suffix)
|
||||
.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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use reqwest::blocking::Client;
|
||||
use serde::Deserialize;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -156,14 +157,14 @@ fn temp_binary_path(current_exe: &Path) -> PathBuf {
|
||||
current_exe.with_extension(extension)
|
||||
}
|
||||
|
||||
fn set_executable_permissions(path: &Path) {
|
||||
fn set_executable_permissions(_path: &Path) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
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();
|
||||
perms.set_mode(0o755);
|
||||
let _ = fs::set_permissions(path, perms);
|
||||
let _ = fs::set_permissions(_path, perms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
245
src/cli/gen.rs
245
src/cli/gen.rs
@@ -3,181 +3,15 @@ use crate::core::builder::collect_sources;
|
||||
use crate::core::builder::common;
|
||||
use crate::core::config::Config;
|
||||
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::log::{error, warn};
|
||||
use crate::utils::log::error;
|
||||
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.
|
||||
/// Used by `gen` commands where the project may not have been built yet.
|
||||
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 ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// 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 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 compiler_s = get_string_with_profile(&config, "compiler", 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_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)
|
||||
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))
|
||||
}
|
||||
|
||||
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> {
|
||||
let trimmed = normalize_target_os(s.trim());
|
||||
if trimmed.is_empty() {
|
||||
|
||||
@@ -12,6 +12,7 @@ pub fn help() -> i32 {
|
||||
println!(" init Initialize the current directory as a project");
|
||||
println!(" build [--profile] Build the project (default: --debug)");
|
||||
println!(" run [--profile] Build and run the project (default: --debug)");
|
||||
println!(" tree Display the dependency tree");
|
||||
println!(" test Run project tests (alias: tests)");
|
||||
println!(" clean Remove the target directory");
|
||||
println!(" gen <subcommand> Generate IDE integration files");
|
||||
|
||||
@@ -10,3 +10,4 @@ pub mod new;
|
||||
pub mod run;
|
||||
pub mod setup;
|
||||
pub mod test;
|
||||
pub mod tree;
|
||||
|
||||
@@ -2,10 +2,11 @@ use crate::cli::build::build;
|
||||
use crate::cli::flags::parse_build_run_flags;
|
||||
use crate::core::config::Config;
|
||||
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::with_dir;
|
||||
use crate::utils::log::error;
|
||||
use crate::utils::text::{BOLD_GREEN, colored};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
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 {
|
||||
let start_dir = match std::env::current_dir() {
|
||||
Ok(dir) => dir,
|
||||
@@ -152,17 +144,6 @@ pub fn run(args: &[String]) -> i32 {
|
||||
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 {
|
||||
let status = if cfg!(target_os = "windows") {
|
||||
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_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,
|
||||
}
|
||||
}
|
||||
|
||||
238
src/cli/test.rs
238
src/cli/test.rs
@@ -1,12 +1,15 @@
|
||||
use crate::cli::build;
|
||||
use crate::config::{FILE_DCR_TEST_H, FILE_TEST_C, flags};
|
||||
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::text::{BOLD_GREEN, BOLD_RED, RESET, colored};
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
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 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 flags_vec = flags(profile).unwrap_or(&[]);
|
||||
let flags_str = flags_vec.join(" ");
|
||||
let name = get_config_str(&config, "package.name");
|
||||
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";
|
||||
if !Path::new(test_c).exists() {
|
||||
let mut cflags: Vec<String> = flags(profile)
|
||||
.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());
|
||||
}
|
||||
|
||||
// Compile test.c to object
|
||||
let obj_path = "./tests/test.o";
|
||||
let compile_cmd = format!("{} -c {} -o {} {}", compiler, test_c, obj_path, flags_str);
|
||||
let compile_status = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(&compile_cmd)
|
||||
.status()
|
||||
.map_err(|_| format!("Failed to compile {}", test_c))?;
|
||||
if !compile_status.success() {
|
||||
return Err(format!("Compilation of {} failed", test_c));
|
||||
let link_project_lib =
|
||||
package_type == "lib" || build_kind == "staticlib" || build_kind == "sharedlib";
|
||||
let mut stdout = String::new();
|
||||
let mut declared = Vec::new();
|
||||
let mut suite_success = true;
|
||||
|
||||
fs::create_dir_all("./tests/target")
|
||||
.map_err(|e| format!("Failed to create tests/target: {e}"))?;
|
||||
for source in &test_sources {
|
||||
declared.extend(extract_test_names_path(source));
|
||||
let stem = source
|
||||
.file_stem()
|
||||
.and_then(|v| v.to_str())
|
||||
.unwrap_or("test");
|
||||
let obj_path = Path::new("./tests/target").join(format!("{stem}.o"));
|
||||
let bin_path =
|
||||
Path::new("./tests/target").join(format!("{stem}{}", std::env::consts::EXE_SUFFIX));
|
||||
|
||||
compile_test_source(&compiler, &standard, &cflags, &includes, source, &obj_path)?;
|
||||
link_test_binary(
|
||||
&compiler,
|
||||
&ldflags,
|
||||
link_project_lib.then_some(name.as_str()),
|
||||
&obj_path,
|
||||
&bin_path,
|
||||
)?;
|
||||
|
||||
let out = Command::new(&bin_path)
|
||||
.output()
|
||||
.map_err(|_| format!("Failed to run `{}`", bin_path.display()))?;
|
||||
stdout.push_str(&String::from_utf8_lossy(&out.stdout));
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
if !out.status.success() {
|
||||
suite_success = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Link
|
||||
let bin_path = format!("./tests/test{}", std::env::consts::EXE_SUFFIX);
|
||||
let link_cmd = if kind == "lib" {
|
||||
format!(
|
||||
"{} {} -o {} -Ltarget/release -l{}",
|
||||
compiler, obj_path, bin_path, name
|
||||
)
|
||||
} else {
|
||||
format!("{} {} -o {}", compiler, obj_path, bin_path)
|
||||
};
|
||||
let link_status = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(&link_cmd)
|
||||
.status()
|
||||
.map_err(|_| format!("Failed to link {}", bin_path))?;
|
||||
if !link_status.success() {
|
||||
return Err(format!("Linking of {} failed", bin_path));
|
||||
}
|
||||
|
||||
let out = Command::new(&bin_path)
|
||||
.output()
|
||||
.map_err(|_| format!("Failed to run `{bin_path}`"))?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
|
||||
let declared = extract_test_names("./tests/test.c");
|
||||
let mut pass = 0;
|
||||
let mut skip = 0;
|
||||
let mut fail = 0;
|
||||
@@ -189,7 +204,7 @@ fn run_testsuite() -> Result<i32, String> {
|
||||
}
|
||||
|
||||
if !parsed_any {
|
||||
if out.status.success() {
|
||||
if suite_success {
|
||||
for name in &declared {
|
||||
println!("{} {}", colored("[PASS]", BOLD_GREEN), name);
|
||||
}
|
||||
@@ -216,12 +231,104 @@ fn run_testsuite() -> Result<i32, String> {
|
||||
print_field("FAIL", fail, BOLD_RED);
|
||||
println!("{}", colored("=====================", BOLD_GREEN));
|
||||
|
||||
if fail > 0 || !out.status.success() {
|
||||
if fail > 0 || !suite_success {
|
||||
return Ok(1);
|
||||
}
|
||||
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> {
|
||||
fs::create_dir_all("./tests").map_err(|_| "Failed to create tests/".to_string())?;
|
||||
fs::write("./tests/dcr_test.h", FILE_DCR_TEST_H)
|
||||
@@ -233,7 +340,7 @@ fn ensure_test_header() -> Result<(), String> {
|
||||
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 {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -256,14 +363,3 @@ fn print_field(label: &str, value: i32, color: &str) {
|
||||
println!("{}{}: {}{}", color, label, value, RESET);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_dir<F, T>(dir: &Path, f: F) -> Result<T, String>
|
||||
where
|
||||
F: FnOnce() -> Result<T, String>,
|
||||
{
|
||||
let prev = std::env::current_dir().map_err(|_| "Failed to get current dir".to_string())?;
|
||||
std::env::set_current_dir(dir).map_err(|_| "Failed to change directory".to_string())?;
|
||||
let result = f();
|
||||
let _ = std::env::set_current_dir(prev);
|
||||
result
|
||||
}
|
||||
|
||||
118
src/cli/tree.rs
Normal file
118
src/cli/tree.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
use crate::core::config::Config;
|
||||
use crate::utils::log::error;
|
||||
use crate::utils::text::{BOLD_CYAN, printc};
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use toml::Value;
|
||||
|
||||
pub fn tree(_args: &[String]) -> i32 {
|
||||
let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
|
||||
let config = match Config::open("dcr.toml") {
|
||||
Ok(c) => c,
|
||||
Err(_) => {
|
||||
error("dcr.toml not found in current directory");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
let name = config
|
||||
.get("package.name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown");
|
||||
let version = config
|
||||
.get("package.version")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("0.0.0");
|
||||
|
||||
printc(&format!("{} v{}", name, version), BOLD_CYAN);
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
seen.insert(name.to_string());
|
||||
|
||||
if let Some(deps) = config.get("dependencies").and_then(|v| v.as_table()) {
|
||||
print_deps(deps, ¤t_dir, "", &mut seen);
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
fn print_deps(
|
||||
deps: &toml::value::Table,
|
||||
base_path: &Path,
|
||||
prefix: &str,
|
||||
seen: &mut HashSet<String>,
|
||||
) {
|
||||
let mut dep_list: Vec<_> = deps.iter().collect();
|
||||
dep_list.sort_by_key(|(name, _)| *name);
|
||||
|
||||
for (i, (name, value)) in dep_list.iter().enumerate() {
|
||||
let is_last = i == dep_list.len() - 1;
|
||||
let connector = if is_last { "└── " } else { "├── " };
|
||||
let child_prefix = if is_last { " " } else { "│ " };
|
||||
|
||||
let dep_path = resolve_dep_path(value, base_path);
|
||||
let mut version = String::new();
|
||||
let mut sub_deps = None;
|
||||
let mut resolved_path = None;
|
||||
|
||||
if let Some(path) = &dep_path {
|
||||
let dcr_toml = path.join("dcr.toml");
|
||||
if dcr_toml.exists()
|
||||
&& let Ok(config) = Config::open(&dcr_toml.to_string_lossy())
|
||||
{
|
||||
if let Some(v) = config.get("package.version").and_then(|v| v.as_str()) {
|
||||
version = format!(" v{}", v);
|
||||
}
|
||||
sub_deps = config
|
||||
.get("dependencies")
|
||||
.and_then(|v| v.as_table())
|
||||
.cloned();
|
||||
resolved_path = Some(path.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if version.is_empty() {
|
||||
version = match value {
|
||||
Value::String(s) if s.starts_with("git:") || s.starts_with("github:") => {
|
||||
format!(" ({})", s)
|
||||
}
|
||||
Value::Table(t) => {
|
||||
if let Some(v) = t.get("version").and_then(|v| v.as_str()) {
|
||||
format!(" v{}", v)
|
||||
} else if let Some(git) = t.get("git").and_then(|v| v.as_str()) {
|
||||
format!(" ({})", git)
|
||||
} else {
|
||||
"".to_string()
|
||||
}
|
||||
}
|
||||
_ => "".to_string(),
|
||||
};
|
||||
}
|
||||
|
||||
println!("{}{}{}{}", prefix, connector, name, version);
|
||||
|
||||
if let Some(s_deps) = sub_deps
|
||||
&& !seen.contains(*name)
|
||||
{
|
||||
seen.insert(name.to_string());
|
||||
let new_prefix = format!("{}{}", prefix, child_prefix);
|
||||
if let Some(path) = resolved_path {
|
||||
print_deps(&s_deps, &path, &new_prefix, seen);
|
||||
}
|
||||
seen.remove(*name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_dep_path(value: &Value, base_path: &Path) -> Option<PathBuf> {
|
||||
match value {
|
||||
Value::String(s) => s
|
||||
.strip_prefix("path:")
|
||||
.map(|stripped| base_path.join(stripped)),
|
||||
Value::Table(t) => t
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|path| base_path.join(path)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
use std::fs;
|
||||
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(
|
||||
roots: &[PathBuf],
|
||||
@@ -196,6 +200,22 @@ where
|
||||
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 {
|
||||
if !path.is_absolute() {
|
||||
return path.to_string_lossy().to_string();
|
||||
|
||||
@@ -140,9 +140,5 @@ fn build_object(
|
||||
cmd.arg(flag);
|
||||
}
|
||||
|
||||
match cmd.status() {
|
||||
Ok(status) if status.success() => Ok(()),
|
||||
Ok(_) => Err("Build failed".to_string()),
|
||||
Err(err) => Err(format!("Build failed: {err}")),
|
||||
}
|
||||
common::run_command_sync_output(&mut cmd)
|
||||
}
|
||||
|
||||
@@ -151,11 +151,7 @@ fn build_object(
|
||||
eprintln!("[dcr] {:?}", cmd);
|
||||
}
|
||||
|
||||
match cmd.status() {
|
||||
Ok(status) if status.success() => Ok(()),
|
||||
Ok(_) => Err("Build failed".to_string()),
|
||||
Err(err) => Err(format!("Build failed: {err}")),
|
||||
}
|
||||
common::run_command_sync_output(&mut cmd)
|
||||
}
|
||||
|
||||
fn nasm_format(platform: Option<&str>) -> &'static str {
|
||||
|
||||
@@ -200,11 +200,7 @@ fn build_object(
|
||||
eprintln!("[dcr] {:?}", cmd);
|
||||
}
|
||||
|
||||
match cmd.status() {
|
||||
Ok(status) if status.success() => Ok(()),
|
||||
Ok(_) => Err("Build failed".to_string()),
|
||||
Err(err) => Err(format!("Build failed: {err}")),
|
||||
}
|
||||
common::run_command_sync_output(&mut cmd)
|
||||
}
|
||||
|
||||
fn asm_lang_flag(source: &str) -> Option<&'static str> {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use toml::Value;
|
||||
@@ -51,6 +53,98 @@ impl From<toml::ser::Error> for ConfigError {
|
||||
pub struct Config {
|
||||
path: PathBuf,
|
||||
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 {
|
||||
@@ -63,7 +157,8 @@ impl Config {
|
||||
write_toml(&path, &default_value)?;
|
||||
default_value
|
||||
};
|
||||
let cfg = Self { path, data };
|
||||
let typed = parse_typed_config(&data)?;
|
||||
let cfg = Self { path, data, typed };
|
||||
cfg.validate()?;
|
||||
Ok(cfg)
|
||||
}
|
||||
@@ -74,11 +169,27 @@ impl Config {
|
||||
return Err(ConfigError::Invalid("dcr.toml not found".into()));
|
||||
}
|
||||
let data = read_toml(&path)?;
|
||||
let cfg = Self { path, data };
|
||||
let typed = parse_typed_config(&data)?;
|
||||
let cfg = Self { path, data, typed };
|
||||
cfg.validate()?;
|
||||
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> {
|
||||
let parts: Vec<&str> = key.split('.').collect();
|
||||
get_path(&self.data, &parts)
|
||||
@@ -98,19 +209,15 @@ impl Config {
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||
let package = self
|
||||
.get("package")
|
||||
.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.name.trim().is_empty() {
|
||||
return Err(ConfigError::Invalid("package.name is empty".into()));
|
||||
}
|
||||
if self.typed.package.version.trim().is_empty() {
|
||||
return Err(ConfigError::Invalid("package.version is empty".into()));
|
||||
}
|
||||
validate_package_name(&self.typed.package.name)?;
|
||||
|
||||
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();
|
||||
if !pkg_type.is_empty() && pkg_type != "lib" && pkg_type != "app" && pkg_type != "none"
|
||||
{
|
||||
@@ -120,106 +227,41 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
let build = self
|
||||
.get("build")
|
||||
.and_then(|v| v.as_table())
|
||||
.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()));
|
||||
validate_language_config(&self.typed.build.language, "build.language")?;
|
||||
if self.typed.build.standard.trim().is_empty() {
|
||||
return Err(ConfigError::Invalid("build.standard is empty".into()));
|
||||
}
|
||||
for key in ["standard", "compiler"] {
|
||||
let value = build.get(key).and_then(|v| v.as_str()).unwrap_or("");
|
||||
if value.trim().is_empty() {
|
||||
return Err(ConfigError::Invalid(format!("build.{key} is empty")));
|
||||
}
|
||||
if self.typed.build.compiler.trim().is_empty() {
|
||||
return Err(ConfigError::Invalid("build.compiler is empty".into()));
|
||||
}
|
||||
if let Some(platform) = build.get("platform")
|
||||
&& !platform
|
||||
.as_str()
|
||||
.map(|v| !v.trim().is_empty())
|
||||
.unwrap_or(false)
|
||||
if let Some(platform) = &self.typed.build.platform
|
||||
&& platform.trim().is_empty()
|
||||
{
|
||||
return Err(ConfigError::Invalid("build.platform is empty".into()));
|
||||
}
|
||||
if let Some(toolchain) = self.get("toolchain").and_then(|v| v.as_table()) {
|
||||
for key in ["cc", "cxx", "as", "ar", "ld"] {
|
||||
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()) {
|
||||
validate_toolchain(self.typed.toolchain.as_ref())?;
|
||||
if let Some(kind) = &self.typed.build.kind {
|
||||
let kind = kind.trim();
|
||||
if !kind.is_empty() && kind != "bin" && kind != "staticlib" && kind != "sharedlib" {
|
||||
return Err(ConfigError::Invalid("build.kind is invalid".into()));
|
||||
}
|
||||
}
|
||||
if let Some(exclude) = build.get("exclude") {
|
||||
let arr = exclude.as_array().ok_or_else(|| {
|
||||
ConfigError::Invalid("build.exclude 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.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(),
|
||||
));
|
||||
}
|
||||
}
|
||||
validate_string_list(&self.typed.build.exclude, "build.exclude")?;
|
||||
validate_string_list(&self.typed.build.include, "build.include")?;
|
||||
validate_string_list(&self.typed.build.roots, "build.roots")?;
|
||||
validate_string_list(&self.typed.build.clean, "build.clean")?;
|
||||
validate_string_list(&self.typed.build.cflags, "build.cflags")?;
|
||||
validate_string_list(&self.typed.build.ldflags, "build.ldflags")?;
|
||||
if let Some(target) = &self.typed.build.target {
|
||||
validate_non_empty_string(target, "build.target")?;
|
||||
}
|
||||
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(|| {
|
||||
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> {
|
||||
let parts: Vec<&str> = key.split('.').collect();
|
||||
let previous = self.data.clone();
|
||||
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()?;
|
||||
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 {
|
||||
fn validate_language(&self, value: &Value) -> Result<(), ConfigError> {
|
||||
if let Some(s) = value.as_str() {
|
||||
@@ -670,6 +793,21 @@ mod tests {
|
||||
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]
|
||||
fn open_invalid_toml_syntax() {
|
||||
let dir = temp_dir("open_invalid");
|
||||
@@ -706,6 +844,35 @@ mod tests {
|
||||
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]
|
||||
fn validate_empty_language_fails() {
|
||||
let dir = temp_dir("empty_lang");
|
||||
|
||||
@@ -31,51 +31,59 @@ pub fn resolve_deps(
|
||||
if let Some(deps) = deps_table {
|
||||
for (name, value) in deps {
|
||||
if register::is_registry_dep(value) {
|
||||
let _pkg_info = register::resolve_package_from_registry(name)?;
|
||||
// Используем путь относительно project_root или системный путь, если нужно
|
||||
let dep_root = project_root.join("dcr-index");
|
||||
let pkg_info = register::resolve_package_from_registry(name)?;
|
||||
let dep_root = register::package_root_from_registry_info(&pkg_info)?;
|
||||
|
||||
resolved.include_dirs.push(
|
||||
dep_root
|
||||
.join("target")
|
||||
.join("include")
|
||||
register::registry_include_dir(&dep_root)
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
);
|
||||
resolved.lib_dirs.push(
|
||||
dep_root
|
||||
.join("target")
|
||||
.join("lib")
|
||||
register::registry_lib_dir(&dep_root)
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
);
|
||||
resolved.libs.push(name.clone());
|
||||
} else if let Some(table) = value.as_table()
|
||||
&& let Some(path) = table.get("path").and_then(|v| v.as_str())
|
||||
{
|
||||
} else if let Some(path) = path_dep_path(value) {
|
||||
let dep_root = project_root.join(path);
|
||||
if let Some(includes) = table.get("include").and_then(|v| v.as_array()) {
|
||||
for inc in includes {
|
||||
if let Some(inc_str) = inc.as_str() {
|
||||
resolved
|
||||
.include_dirs
|
||||
.push(dep_root.join(inc_str).to_string_lossy().to_string());
|
||||
if let Some(table) = value.as_table() {
|
||||
if let Some(includes) = table.get("include").and_then(|v| v.as_array()) {
|
||||
for inc in includes {
|
||||
if let Some(inc_str) = inc.as_str() {
|
||||
resolved
|
||||
.include_dirs
|
||||
.push(dep_root.join(inc_str).to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
push_if_exists(&mut resolved.include_dirs, &dep_root.join("include"));
|
||||
}
|
||||
}
|
||||
let lib_path = dep_root.join("target").join("lib");
|
||||
if lib_path.exists() {
|
||||
resolved
|
||||
.lib_dirs
|
||||
.push(lib_path.to_string_lossy().to_string());
|
||||
}
|
||||
if let Some(libs) = table.get("libs").and_then(|v| v.as_array()) {
|
||||
for lib in libs {
|
||||
if let Some(lib_str) = lib.as_str() {
|
||||
resolved.libs.push(lib_str.to_string());
|
||||
|
||||
if let Some(lib_dirs) = table.get("lib").and_then(|v| v.as_array()) {
|
||||
for lib_dir in lib_dirs {
|
||||
if let Some(lib_dir_str) = lib_dir.as_str() {
|
||||
resolved
|
||||
.lib_dirs
|
||||
.push(dep_root.join(lib_dir_str).to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
push_default_lib_dirs(&mut resolved.lib_dirs, &dep_root);
|
||||
}
|
||||
|
||||
if let Some(libs) = table.get("libs").and_then(|v| v.as_array()) {
|
||||
for lib in libs {
|
||||
if let Some(lib_str) = lib.as_str() {
|
||||
resolved.libs.push(lib_str.to_string());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resolved.libs.push(name.clone());
|
||||
}
|
||||
} else {
|
||||
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)
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
let config = get_registry_config().ok_or("No registry config found")?;
|
||||
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 {
|
||||
if value.is_str() {
|
||||
return true;
|
||||
if let Some(raw) = value.as_str() {
|
||||
let raw = raw.trim();
|
||||
return !is_path_like_string(raw) && !is_git_like_string(raw);
|
||||
}
|
||||
if let Some(table) = value.as_table() {
|
||||
return !table.contains_key("git")
|
||||
@@ -74,3 +116,81 @@ pub fn is_registry_dep(value: &TomlValue) -> bool {
|
||||
}
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::core::config::Config;
|
||||
use crate::utils::build::normalize_target_os;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use toml::Value;
|
||||
@@ -24,7 +25,7 @@ pub fn parse_workspace(
|
||||
let mut table = None;
|
||||
// Order: workspace.target.profile, workspace.profile.target, workspace.target, workspace.profile, workspace
|
||||
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![
|
||||
format!("workspace.{}.{}", normalized_t, profile),
|
||||
format!("workspace.{}.{}", profile, normalized_t),
|
||||
|
||||
@@ -22,6 +22,7 @@ fn main() {
|
||||
"add" => cli::add::add(rest),
|
||||
"build" => cli::build::build(rest),
|
||||
"run" => cli::run::run(rest),
|
||||
"tree" => cli::tree::tree(rest),
|
||||
"test" | "tests" => cli::test::test(rest),
|
||||
"clean" => cli::clean::clean(rest),
|
||||
"gen" => cli::r#gen::r#gen(rest),
|
||||
|
||||
376
src/utils/build.rs
Normal file
376
src/utils/build.rs
Normal 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");
|
||||
}
|
||||
}
|
||||
@@ -29,3 +29,14 @@ pub fn find_project_root(start: &Path) -> io::Result<Option<PathBuf>> {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod build;
|
||||
pub mod fs;
|
||||
pub mod log;
|
||||
pub mod text;
|
||||
|
||||
@@ -232,7 +232,7 @@ fn dcr_add_dependencies() {
|
||||
assert!(out.status.success(), "dcr add path should succeed");
|
||||
let toml = std::fs::read_to_string(dir.join("dcr.toml")).unwrap();
|
||||
assert!(
|
||||
toml.contains("mylib = \"./libs/mylib\""),
|
||||
toml.contains("mylib = { path = \"./libs/mylib\" }"),
|
||||
"path dep not found in toml"
|
||||
);
|
||||
|
||||
@@ -316,6 +316,85 @@ fn dcr_builds_lib_package() {
|
||||
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]
|
||||
fn dcr_test_runs_without_sandbox_dependency() {
|
||||
let Some(compiler) = available_compiler() else {
|
||||
|
||||
Reference in New Issue
Block a user