mirror of
https://github.com/dexoron/dcr.git
synced 2026-10-21 21:19:35 +00:00
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:
@@ -17,6 +17,7 @@ pub struct BuildContext<'a> {
|
||||
pub platform: Option<&'a str>,
|
||||
pub linker: Option<&'a str>,
|
||||
pub archiver: Option<&'a str>,
|
||||
pub package_type: Option<&'a str>,
|
||||
pub source_roots: &'a [std::path::PathBuf],
|
||||
pub exclude_dirs: &'a [std::path::PathBuf],
|
||||
pub include_paths: &'a [String],
|
||||
|
||||
@@ -110,6 +110,16 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(pkg_type) = package.get("type").and_then(|v| v.as_str()) {
|
||||
let pkg_type = pkg_type.trim();
|
||||
if !pkg_type.is_empty() && pkg_type != "lib" && pkg_type != "app" && pkg_type != "none"
|
||||
{
|
||||
return Err(ConfigError::Invalid(
|
||||
"package.type must be 'lib', 'app', or 'none'".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let build = self
|
||||
.get("build")
|
||||
.and_then(|v| v.as_table())
|
||||
@@ -398,6 +408,11 @@ fn default_toml() -> Result<Value, ConfigError> {
|
||||
"version".to_string(),
|
||||
Value::String(DEFAULT_VERSION.to_string()),
|
||||
);
|
||||
package.insert("type".to_string(), Value::String("none".to_string()));
|
||||
package.insert("description".to_string(), Value::String("".to_string()));
|
||||
package.insert("author".to_string(), Value::String("".to_string()));
|
||||
package.insert("license".to_string(), Value::String("MIT".to_string()));
|
||||
|
||||
let mut build = Map::new();
|
||||
build.insert(
|
||||
"language".to_string(),
|
||||
@@ -458,7 +473,29 @@ fn format_toml(value: &Value) -> Result<String, ConfigError> {
|
||||
let mut out = String::new();
|
||||
out.push_str("[package]\n");
|
||||
out.push_str(&format!("name = \"{name}\"\n"));
|
||||
out.push_str(&format!("version = \"{version}\"\n\n"));
|
||||
out.push_str(&format!("version = \"{version}\"\n"));
|
||||
|
||||
for key in [
|
||||
"type",
|
||||
"description",
|
||||
"author",
|
||||
"authors",
|
||||
"homepage",
|
||||
"license",
|
||||
"repository",
|
||||
"readme",
|
||||
"keywords",
|
||||
"categories",
|
||||
] {
|
||||
if let Some(val) = package.get(key) {
|
||||
match val {
|
||||
Value::String(s) => out.push_str(&format!("{key} = \"{s}\"\n")),
|
||||
Value::Array(_) => out.push_str(&format!("{key} = {}\n", format_string_array(val))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push('\n');
|
||||
|
||||
out.push_str("[build]\n");
|
||||
if language.starts_with('[') {
|
||||
@@ -522,6 +559,9 @@ fn format_dep_value(value: &Value) -> String {
|
||||
Value::String(s) => format!("\"{s}\""),
|
||||
Value::Table(tbl) => {
|
||||
let mut parts = Vec::new();
|
||||
if let Some(v) = tbl.get("version").and_then(|v| v.as_str()) {
|
||||
parts.push(format!("version = \"{v}\""));
|
||||
}
|
||||
if let Some(v) = tbl.get("path").and_then(|v| v.as_str()) {
|
||||
parts.push(format!("path = \"{v}\""));
|
||||
}
|
||||
@@ -537,18 +577,18 @@ fn format_dep_value(value: &Value) -> String {
|
||||
if let Some(v) = tbl.get("rev").and_then(|v| v.as_str()) {
|
||||
parts.push(format!("rev = \"{v}\""));
|
||||
}
|
||||
if let Some(v) = tbl.get("default-features").and_then(|v| v.as_bool()) {
|
||||
parts.push(format!(
|
||||
"default-features = {}",
|
||||
if v { "true" } else { "false" }
|
||||
));
|
||||
}
|
||||
if let Some(v) = tbl.get("features") {
|
||||
parts.push(format!("features = {}", format_string_array(v)));
|
||||
}
|
||||
if let Some(v) = tbl.get("system").and_then(|v| v.as_bool()) {
|
||||
parts.push(format!("system = {}", if v { "true" } else { "false" }));
|
||||
}
|
||||
if let Some(v) = tbl.get("include") {
|
||||
parts.push(format!("include = {}", format_string_array(v)));
|
||||
}
|
||||
if let Some(v) = tbl.get("lib") {
|
||||
parts.push(format!("lib = {}", format_string_array(v)));
|
||||
}
|
||||
if let Some(v) = tbl.get("libs") {
|
||||
parts.push(format!("libs = {}", format_string_array(v)));
|
||||
}
|
||||
format!("{{ {} }}", parts.join(", "))
|
||||
}
|
||||
_ => "\"\"".to_string(),
|
||||
|
||||
@@ -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)? {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
76
src/core/deps/register.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
pub url: String,
|
||||
pub priority: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct DcrConfig {
|
||||
pub registry: std::collections::HashMap<String, Registry>,
|
||||
}
|
||||
|
||||
pub fn get_registry_config() -> Option<DcrConfig> {
|
||||
let home = std::env::var("HOME").ok()?;
|
||||
let config_path = Path::new(&home).join(".dcr/config.toml");
|
||||
if !config_path.exists() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(config_path).ok()?;
|
||||
toml::from_str(&content).ok()
|
||||
}
|
||||
|
||||
pub fn get_index_path() -> PathBuf {
|
||||
std::env::var("DCR_INDEX_PATH")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| {
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
|
||||
Path::new(&home).join(".dcr").join("index.json")
|
||||
})
|
||||
}
|
||||
|
||||
pub fn resolve_package_from_registry(name: &str) -> Result<JsonValue, String> {
|
||||
let config = get_registry_config().ok_or("No registry config found")?;
|
||||
let mut registries: Vec<(&String, &Registry)> = config.registry.iter().collect();
|
||||
registries.sort_by(|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
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod builder;
|
||||
pub mod config;
|
||||
pub mod deps;
|
||||
pub mod registry;
|
||||
pub mod runner;
|
||||
pub mod workspace;
|
||||
|
||||
41
src/core/registry.rs
Normal file
41
src/core/registry.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
pub url: String,
|
||||
pub priority: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
pub registry: HashMap<String, Registry>,
|
||||
}
|
||||
|
||||
pub struct RegistryManager {
|
||||
pub config: Config,
|
||||
#[allow(dead_code)]
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl RegistryManager {
|
||||
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let home = std::env::var("HOME")?;
|
||||
let dcr_dir = PathBuf::from(home).join(".dcr");
|
||||
let config_path = dcr_dir.join("config.toml");
|
||||
|
||||
if !config_path.exists() {
|
||||
return Err("Config file ~/.dcr/config.toml not found".into());
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&config_path)?;
|
||||
let config: Config = toml::from_str(&content)?;
|
||||
|
||||
Ok(Self {
|
||||
config,
|
||||
path: dcr_dir,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,21 @@
|
||||
use crate::platform;
|
||||
use crate::utils::fs::check_dir;
|
||||
use crate::utils::log::warn;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
pub fn run_binary(project_name: &str, profile: &str, target_dir: Option<&str>) -> i32 {
|
||||
let bin_path = platform::bin_path(profile, project_name, target_dir);
|
||||
if Path::new(&bin_path).exists() {
|
||||
let output = Command::new(&bin_path)
|
||||
.output()
|
||||
.unwrap_or_else(|_| panic!("Failed to run {}", bin_path));
|
||||
print!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
eprint!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
return output.status.code().unwrap_or(1);
|
||||
let output = Command::new(&bin_path).output();
|
||||
match output {
|
||||
Ok(o) => {
|
||||
print!("{}", String::from_utf8_lossy(&o.stdout));
|
||||
eprint!("{}", String::from_utf8_lossy(&o.stderr));
|
||||
return o.status.code().unwrap_or(0);
|
||||
}
|
||||
Err(_) => {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if target_dir.is_none()
|
||||
&& check_dir(Some(&format!("target/{profile}")))
|
||||
.unwrap_or_default()
|
||||
.contains(&profile.to_string())
|
||||
{
|
||||
warn("Launch of the latest release");
|
||||
let bin_path = platform::bin_path(profile, project_name, target_dir);
|
||||
let output = Command::new(&bin_path)
|
||||
.output()
|
||||
.unwrap_or_else(|_| panic!("Failed to run {}", &bin_path));
|
||||
print!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
eprint!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
return output.status.code().unwrap_or(1);
|
||||
}
|
||||
|
||||
if target_dir.is_some() && Path::new(&bin_path).exists() {
|
||||
warn("Launch of the latest release");
|
||||
let output = Command::new(&bin_path)
|
||||
.output()
|
||||
.unwrap_or_else(|_| panic!("Failed to run {}", &bin_path));
|
||||
print!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
eprint!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
return output.status.code().unwrap_or(1);
|
||||
}
|
||||
|
||||
1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user