mirror of
https://github.com/dexoron/dcr.git
synced 2026-10-21 20:19:40 +00:00
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`
This commit is contained in:
@@ -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),
|
||||
|
||||
Reference in New Issue
Block a user