feat: Enhance dependency management and project setup

- Added support for registry-based dependencies in the dependencies section.
- Updated the package section to include a project type field.
- Introduced a new CLI command `dcr setup` to load and display registry configurations.
- Implemented a new module for handling registry operations, including loading and resolving packages from registries.
- Enhanced the build process to handle library packaging, including copying headers and libraries to the appropriate target directories.
- Updated the CLI to support building library packages and added tests for library package builds.
- Improved error handling and output messages during dependency resolution and package fetching.
This commit is contained in:
2026-05-13 19:24:53 +08:00
parent debc5d2044
commit 0193834bfd
26 changed files with 610 additions and 410 deletions

View File

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

View File

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

View File

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

View File

@@ -1,23 +1,19 @@
pub mod common;
pub mod git;
pub mod lock;
pub mod register;
use crate::core::config::Config;
use std::fs;
use crate::core::deps::common::ResolvedDeps;
use std::path::Path;
use toml::Value;
pub use common::{DepSource, DepSpec, ResolvedDeps};
use common::{expand_profile, resolve_path, resolve_paths, sync_dep_dir};
use git::fetch_git_dep;
use lock::{DepLock, compute_checksum, read_dep_version, write_lock};
pub fn resolve_deps(
config: &Config,
profile: &str,
target: Option<&str>,
_profile: &str,
_target: Option<&str>,
project_root: &Path,
) -> Result<ResolvedDeps, String> {
let mut resolved = ResolvedDeps::default();
let project_name = config
.get("package.name")
.and_then(|v| v.as_str())
@@ -28,259 +24,70 @@ pub fn resolve_deps(
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let deps = parse_dependencies(config, profile, target)?;
if deps.is_empty() {
return Ok(ResolvedDeps {
include_dirs: Vec::new(),
lib_dirs: Vec::new(),
libs: Vec::new(),
});
}
let mut include_dirs = Vec::new();
let mut lib_dirs = Vec::new();
let mut libs = Vec::new();
let mut lock_packages = Vec::new();
let deps_table = config.get("dependencies").and_then(|v| v.as_table());
let lock_packages = Vec::new();
for dep in deps {
let (dep_path, is_git) = match &dep.source {
DepSource::Path(path_raw) => {
let expanded = expand_profile(path_raw, profile);
(resolve_path(project_root, &expanded)?, false)
}
DepSource::Git {
url,
branch,
tag,
rev,
} => {
let git_deps_dir = project_root
.join("target")
.join(profile)
.join("deps")
.join("git");
fs::create_dir_all(&git_deps_dir)
.map_err(|e| format!("failed to create target/{}/deps/git: {}", profile, e))?;
let dep_dir = git_deps_dir.join(&dep.name);
if !dep_dir.exists() {
use crate::utils::text::{BOLD_GREEN, colored};
use std::io::{self, Write};
print!(
" {} dependency `{}` from {}...",
colored("Fetching", BOLD_GREEN),
dep.name,
url
);
io::stdout().flush().ok();
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");
fetch_git_dep(
url,
&dep_dir,
branch.as_deref(),
tag.as_deref(),
rev.as_deref(),
)?;
print!(
"\r\x1B[2K {} dependency `{}`\n",
colored("Fetched", BOLD_GREEN),
dep.name
);
io::stdout().flush().ok();
} else {
fetch_git_dep(
url,
&dep_dir,
branch.as_deref(),
tag.as_deref(),
rev.as_deref(),
)?;
resolved.include_dirs.push(
dep_root
.join("target")
.join("include")
.to_string_lossy()
.to_string(),
);
resolved.lib_dirs.push(
dep_root
.join("target")
.join("lib")
.to_string_lossy()
.to_string(),
);
resolved.libs.push(name.clone());
} else if let Some(table) = value.as_table()
&& let Some(path) = table.get("path").and_then(|v| v.as_str())
{
let dep_root = project_root.join(path);
if let Some(includes) = table.get("include").and_then(|v| v.as_array()) {
for inc in includes {
if let Some(inc_str) = inc.as_str() {
resolved
.include_dirs
.push(dep_root.join(inc_str).to_string_lossy().to_string());
}
}
}
let lib_path = dep_root.join("target").join("lib");
if lib_path.exists() {
resolved
.lib_dirs
.push(lib_path.to_string_lossy().to_string());
}
if let Some(libs) = table.get("libs").and_then(|v| v.as_array()) {
for lib in libs {
if let Some(lib_str) = lib.as_str() {
resolved.libs.push(lib_str.to_string());
}
}
} else {
resolved.libs.push(name.clone());
}
(dep_dir, true)
}
};
if !dep_path.is_dir() {
return Err(format!(
"Dependency '{}' path is not a directory: {}",
dep.name,
dep_path.display()
));
}
let include = resolve_paths(&dep_path, dep.include_raw.as_deref(), &["include"], profile)?;
let lib = resolve_paths(
&dep_path,
dep.lib_raw.as_deref(),
&["lib", "lib64"],
profile,
)?;
let libs_list = dep
.libs_raw
.clone()
.unwrap_or_else(|| vec![dep.name.clone()]);
if include.is_empty() || lib.is_empty() {
return Err(format!(
"Dependency '{}' missing include/lib dirs. Add include/lib in dcr.toml.",
dep.name
));
}
include_dirs.extend(include.iter().map(|p| p.to_string_lossy().to_string()));
lib_dirs.extend(lib.iter().map(|p| p.to_string_lossy().to_string()));
libs.extend(libs_list.iter().cloned());
if !is_git {
let dep_cache = project_root
.join("target")
.join(profile)
.join("deps")
.join(&dep.name);
sync_dep_dir(&dep_path, &dep_cache)
.map_err(|err| format!("Failed to sync dep {}: {err}", dep.name))?;
}
let dep_version = read_dep_version(&dep_path).unwrap_or_else(|| "0.0.0".to_string());
let dep_checksum = compute_checksum(&dep_path)
.map_err(|err| format!("Failed to hash dep {}: {err}", dep.name))?;
let source_str = match &dep.source {
DepSource::Path(p) => format!("path+{}", p),
DepSource::Git { url, .. } => format!("git+{}", url),
};
lock_packages.push(DepLock {
name: dep.name.clone(),
version: dep_version,
checksum: dep_checksum,
source: source_str,
});
}
write_lock(
crate::core::deps::lock::write_lock(
project_root,
&project_name,
&project_version,
&lock_packages,
)?;
Ok(ResolvedDeps {
include_dirs,
lib_dirs,
libs,
})
}
fn parse_dependencies(
config: &Config,
profile: &str,
target: Option<&str>,
) -> Result<Vec<DepSpec>, String> {
let mut deps_table = None;
let combinations = if let Some(t) = target {
let normalized_t = crate::cli::build::normalize_target_os(t);
vec![
format!("dependencies.{}.{}", normalized_t, profile),
format!("dependencies.{}.{}", profile, normalized_t),
format!("dependencies.{}", normalized_t),
format!("dependencies.{}", profile),
"dependencies".to_string(),
]
} else {
vec![
format!("dependencies.{}", profile),
"dependencies".to_string(),
]
};
for key in combinations {
if let Some(val) = config.get(&key).and_then(|v| v.as_table()) {
deps_table = Some(val);
break;
}
}
let deps_table = match deps_table {
Some(t) => t,
None => return Ok(Vec::new()),
};
let mut deps = Vec::new();
for (name, value) in deps_table {
match value {
Value::String(path) => {
deps.push(DepSpec {
name: name.to_string(),
source: DepSource::Path(path.to_string()),
include_raw: None,
lib_raw: None,
libs_raw: None,
});
}
Value::Table(tbl) => {
if tbl.get("system").and_then(|v| v.as_bool()).unwrap_or(false) {
return Err(format!(
"Dependency '{}' uses system=true, which is not supported yet",
name
));
}
let source = if let Some(git_url) = tbl.get("git").and_then(|v| v.as_str()) {
DepSource::Git {
url: git_url.to_string(),
branch: tbl
.get("branch")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
tag: tbl
.get("tag")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
rev: tbl
.get("rev")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
}
} else if let Some(path) = tbl.get("path").and_then(|v| v.as_str()) {
DepSource::Path(path.to_string())
} else {
return Err(format!("Dependency '{}' missing path or git", name));
};
let include = parse_string_list(tbl.get("include"), name, "include")?;
let lib = parse_string_list(tbl.get("lib"), name, "lib")?;
let libs = parse_string_list(tbl.get("libs"), name, "libs")?;
deps.push(DepSpec {
name: name.to_string(),
source,
include_raw: include,
lib_raw: lib,
libs_raw: libs,
});
}
_ => {
return Err(format!("Dependency '{}' must be a string or a table", name));
}
}
}
deps.sort_by(|a, b| a.name.cmp(&b.name));
Ok(deps)
}
fn parse_string_list(
value: Option<&Value>,
dep_name: &str,
key: &str,
) -> Result<Option<Vec<String>>, String> {
let Some(value) = value else { return Ok(None) };
let list = value.as_array().ok_or_else(|| {
format!(
"Dependency '{}' field '{}' must be an array of strings",
dep_name, key
)
})?;
let mut out = Vec::new();
for item in list {
let s = item
.as_str()
.ok_or_else(|| format!("Dependency '{}' field '{}' must be strings", dep_name, key))?;
out.push(s.to_string());
}
Ok(Some(out))
Ok(resolved)
}

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

@@ -0,0 +1,76 @@
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::fs;
use std::path::{Path, PathBuf};
use toml::Value as TomlValue;
#[derive(Debug, Serialize, Deserialize)]
pub struct Registry {
pub url: String,
pub priority: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DcrConfig {
pub registry: std::collections::HashMap<String, Registry>,
}
pub fn get_registry_config() -> Option<DcrConfig> {
let home = std::env::var("HOME").ok()?;
let config_path = Path::new(&home).join(".dcr/config.toml");
if !config_path.exists() {
return None;
}
let content = fs::read_to_string(config_path).ok()?;
toml::from_str(&content).ok()
}
pub fn get_index_path() -> PathBuf {
std::env::var("DCR_INDEX_PATH")
.map(PathBuf::from)
.unwrap_or_else(|_| {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
Path::new(&home).join(".dcr").join("index.json")
})
}
pub fn resolve_package_from_registry(name: &str) -> Result<JsonValue, String> {
let config = get_registry_config().ok_or("No registry config found")?;
let mut registries: Vec<(&String, &Registry)> = config.registry.iter().collect();
registries.sort_by(|a, b| b.1.priority.cmp(&a.1.priority));
for (_name_reg, _reg) in registries {
let index_path = get_index_path();
if index_path.exists() {
let index_content = fs::read_to_string(&index_path).map_err(|e| e.to_string())?;
let index: JsonValue =
serde_json::from_str(&index_content).map_err(|e| e.to_string())?;
if let Some(pkgs) = index.get("packages").and_then(|v| v.as_array()) {
for pkg in pkgs {
if pkg.get("name").and_then(|v| v.as_str()) == Some(name) {
return Ok(pkg.clone());
}
}
}
}
}
Err(format!(
"Package {} not found in registry (checked: {:?})",
name,
get_index_path()
))
}
pub fn is_registry_dep(value: &TomlValue) -> bool {
if value.is_str() {
return true;
}
if let Some(table) = value.as_table() {
return !table.contains_key("git")
&& !table.contains_key("path")
&& !table.contains_key("url")
&& !table.contains_key("version");
}
false
}