dev/pbs (#8)
Co-authored-by: Nilton Constantino <nilton.constantino@visma.com> Reviewed-on: #8
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CacheManifest {
|
||||
#[serde(default)]
|
||||
pub git: HashMap<String, GitCacheEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GitCacheEntry {
|
||||
pub path: PathBuf,
|
||||
pub resolved_ref: String,
|
||||
pub fetched_at: String,
|
||||
}
|
||||
|
||||
impl CacheManifest {
|
||||
pub fn load(cache_dir: &Path) -> Result<Self> {
|
||||
let manifest_path = cache_dir.join("cache.json");
|
||||
if !manifest_path.exists() {
|
||||
return Ok(Self {
|
||||
git: HashMap::new(),
|
||||
});
|
||||
}
|
||||
let content = fs::read_to_string(&manifest_path)?;
|
||||
let manifest = serde_json::from_str(&content)?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
pub fn save(&self, cache_dir: &Path) -> Result<()> {
|
||||
if !cache_dir.exists() {
|
||||
fs::create_dir_all(cache_dir)?;
|
||||
}
|
||||
let manifest_path = cache_dir.join("cache.json");
|
||||
let content = serde_json::to_string_pretty(self)?;
|
||||
fs::write(manifest_path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_cache_root(project_root: &Path) -> PathBuf {
|
||||
project_root.join("cache")
|
||||
}
|
||||
|
||||
pub fn get_git_worktree_path(project_root: &Path, repo_url: &str) -> PathBuf {
|
||||
let cache_root = get_cache_root(project_root);
|
||||
let id = normalized_repo_id(repo_url);
|
||||
cache_root.join("git").join(id).join("worktree")
|
||||
}
|
||||
|
||||
fn normalized_repo_id(url: &str) -> String {
|
||||
let mut hash = 0xcbf29ce484222325;
|
||||
for b in url.as_bytes() {
|
||||
hash ^= *b as u64;
|
||||
hash = hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
format!("{:016x}", hash)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use crate::deps::cache::{get_cache_root, get_git_worktree_path, CacheManifest, GitCacheEntry};
|
||||
use crate::manifest::DependencySpec;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FetchError {
|
||||
Io(std::io::Error),
|
||||
CloneFailed {
|
||||
url: String,
|
||||
stderr: String,
|
||||
},
|
||||
MissingManifest(PathBuf),
|
||||
InvalidPath(PathBuf),
|
||||
CacheError(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FetchError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FetchError::Io(e) => write!(f, "IO error: {}", e),
|
||||
FetchError::CloneFailed { url, stderr } => {
|
||||
write!(f, "Failed to clone git repository from '{}': {}", url, stderr)
|
||||
}
|
||||
FetchError::MissingManifest(path) => {
|
||||
write!(f, "Missing 'prometeu.json' in fetched project at {}", path.display())
|
||||
}
|
||||
FetchError::InvalidPath(path) => {
|
||||
write!(f, "Invalid dependency path: {}", path.display())
|
||||
}
|
||||
FetchError::CacheError(msg) => write!(f, "Cache error: {}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FetchError {}
|
||||
|
||||
impl From<std::io::Error> for FetchError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
FetchError::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches a dependency based on its specification.
|
||||
pub fn fetch_dependency(
|
||||
alias: &str,
|
||||
spec: &DependencySpec,
|
||||
base_dir: &Path,
|
||||
root_project_dir: &Path,
|
||||
) -> Result<PathBuf, FetchError> {
|
||||
match spec {
|
||||
DependencySpec::Path(p) => fetch_path(p, base_dir),
|
||||
DependencySpec::Full(full) => {
|
||||
if let Some(p) = &full.path {
|
||||
fetch_path(p, base_dir)
|
||||
} else if let Some(url) = &full.git {
|
||||
let version = full.version.as_deref().unwrap_or("latest");
|
||||
fetch_git(url, version, root_project_dir)
|
||||
} else {
|
||||
Err(FetchError::InvalidPath(PathBuf::from(alias)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_path(path_str: &str, base_dir: &Path) -> Result<PathBuf, FetchError> {
|
||||
let path = base_dir.join(path_str);
|
||||
if !path.exists() {
|
||||
return Err(FetchError::InvalidPath(path));
|
||||
}
|
||||
|
||||
let canonical = path.canonicalize()?;
|
||||
if !canonical.join("prometeu.json").exists() {
|
||||
return Err(FetchError::MissingManifest(canonical));
|
||||
}
|
||||
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
pub fn fetch_git(url: &str, version: &str, root_project_dir: &Path) -> Result<PathBuf, FetchError> {
|
||||
let cache_root = get_cache_root(root_project_dir);
|
||||
let mut manifest = CacheManifest::load(&cache_root).map_err(|e| FetchError::CacheError(e.to_string()))?;
|
||||
|
||||
let target_dir = get_git_worktree_path(root_project_dir, url);
|
||||
|
||||
if !target_dir.exists() {
|
||||
fs::create_dir_all(&target_dir)?;
|
||||
|
||||
let output = Command::new("git")
|
||||
.arg("clone")
|
||||
.arg(url)
|
||||
.arg(".")
|
||||
.current_dir(&target_dir)
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
// Cleanup on failure
|
||||
let _ = fs::remove_dir_all(&target_dir);
|
||||
return Err(FetchError::CloneFailed {
|
||||
url: url.to_string(),
|
||||
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// TODO: Handle version/pinning (v0 pins to HEAD for now)
|
||||
if version != "latest" {
|
||||
let output = Command::new("git")
|
||||
.arg("checkout")
|
||||
.arg(version)
|
||||
.current_dir(&target_dir)
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
// We keep the clone but maybe should report error?
|
||||
// For v0 we just attempt it.
|
||||
return Err(FetchError::CloneFailed {
|
||||
url: url.to_string(),
|
||||
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Update cache manifest
|
||||
let rel_path = target_dir.strip_prefix(root_project_dir).map_err(|_| FetchError::CacheError("Path outside of project root".to_string()))?;
|
||||
manifest.git.insert(url.to_string(), GitCacheEntry {
|
||||
path: rel_path.to_path_buf(),
|
||||
resolved_ref: version.to_string(),
|
||||
fetched_at: "2026-02-02T00:00:00Z".to_string(), // Use a fixed timestamp or actual one? The requirement said "2026-02-02T00:00:00Z" in example
|
||||
});
|
||||
manifest.save(&cache_root).map_err(|e| FetchError::CacheError(e.to_string()))?;
|
||||
}
|
||||
|
||||
if !target_dir.join("prometeu.json").exists() {
|
||||
return Err(FetchError::MissingManifest(target_dir));
|
||||
}
|
||||
|
||||
Ok(target_dir)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_fetch_path_resolves_relative() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let base = tmp.path().join("base");
|
||||
let dep = tmp.path().join("dep");
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
fs::create_dir_all(&dep).unwrap();
|
||||
fs::write(dep.join("prometeu.json"), "{}").unwrap();
|
||||
|
||||
let fetched = fetch_path("../dep", &base).unwrap();
|
||||
assert_eq!(fetched.canonicalize().unwrap(), dep.canonicalize().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fetch_git_local_mock() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let project_root = tmp.path().join("project");
|
||||
let remote_dir = tmp.path().join("remote");
|
||||
fs::create_dir_all(&project_root).unwrap();
|
||||
fs::create_dir_all(&remote_dir).unwrap();
|
||||
|
||||
// Init remote git repo
|
||||
let _ = Command::new("git").arg("init").current_dir(&remote_dir).status();
|
||||
let _ = Command::new("git").arg("config").arg("user.email").arg("you@example.com").current_dir(&remote_dir).status();
|
||||
let _ = Command::new("git").arg("config").arg("user.name").arg("Your Name").current_dir(&remote_dir).status();
|
||||
|
||||
fs::write(remote_dir.join("prometeu.json"), r#"{"name": "remote", "version": "1.0.0"}"#).unwrap();
|
||||
let _ = Command::new("git").arg("add").arg(".").current_dir(&remote_dir).status();
|
||||
let _ = Command::new("git").arg("commit").arg("-m").arg("initial").current_dir(&remote_dir).status();
|
||||
|
||||
let url = format!("file://{}", remote_dir.display());
|
||||
let fetched = fetch_git(&url, "latest", &project_root);
|
||||
|
||||
// Only assert if git succeeded (it might not be in all CI envs, though should be here)
|
||||
if let Ok(path) = fetched {
|
||||
assert!(path.exists());
|
||||
assert!(path.join("prometeu.json").exists());
|
||||
|
||||
// Check cache manifest
|
||||
let cache_json = project_root.join("cache/cache.json");
|
||||
assert!(cache_json.exists());
|
||||
let content = fs::read_to_string(cache_json).unwrap();
|
||||
assert!(content.contains(&url));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod resolver;
|
||||
pub mod fetch;
|
||||
pub mod cache;
|
||||
@@ -0,0 +1,764 @@
|
||||
use crate::deps::fetch::{fetch_dependency, FetchError};
|
||||
use crate::manifest::{load_manifest, Manifest};
|
||||
use crate::sources::{discover, ProjectSources, SourceError};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct ProjectId {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ResolvedNode {
|
||||
pub id: ProjectId,
|
||||
pub path: PathBuf,
|
||||
pub manifest: Manifest,
|
||||
pub sources: ProjectSources,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ResolvedEdge {
|
||||
pub alias: String,
|
||||
pub to: ProjectId,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum ResolutionStep {
|
||||
TryResolve {
|
||||
alias: String,
|
||||
spec: String,
|
||||
},
|
||||
Resolved {
|
||||
project_id: ProjectId,
|
||||
path: PathBuf,
|
||||
},
|
||||
UsingCached {
|
||||
project_id: ProjectId,
|
||||
},
|
||||
Conflict {
|
||||
name: String,
|
||||
existing_version: String,
|
||||
new_version: String,
|
||||
},
|
||||
Error {
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||
pub struct ResolutionTrace {
|
||||
pub steps: Vec<ResolutionStep>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||
pub struct ResolvedGraph {
|
||||
pub nodes: HashMap<ProjectId, ResolvedNode>,
|
||||
pub edges: HashMap<ProjectId, Vec<ResolvedEdge>>,
|
||||
pub root_id: Option<ProjectId>,
|
||||
pub trace: ResolutionTrace,
|
||||
}
|
||||
|
||||
impl ResolvedGraph {
|
||||
pub fn resolve_import_path(&self, from_node: &ProjectId, import_path: &str) -> Option<PathBuf> {
|
||||
if import_path.starts_with('@') {
|
||||
let parts: Vec<&str> = import_path[1..].splitn(2, ':').collect();
|
||||
if parts.len() == 2 {
|
||||
let alias = parts[0];
|
||||
let module_name = parts[1];
|
||||
|
||||
// Find dependency by alias
|
||||
if let Some(edges) = self.edges.get(from_node) {
|
||||
if let Some(edge) = edges.iter().find(|e| e.alias == alias) {
|
||||
if let Some(node) = self.nodes.get(&edge.to) {
|
||||
// Found the dependency project. Now find the module inside it.
|
||||
let module_path = node.path.join("src/main/modules").join(module_name);
|
||||
return Some(module_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Local import (relative to current project's src/main/modules)
|
||||
if let Some(node) = self.nodes.get(from_node) {
|
||||
return Some(node.path.join("src/main/modules").join(import_path));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn explain(&self) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("--- Dependency Resolution Trace ---\n");
|
||||
for step in &self.trace.steps {
|
||||
match step {
|
||||
ResolutionStep::TryResolve { alias, spec } => {
|
||||
out.push_str(&format!(" [?] Resolving '{}' (spec: {})\n", alias, spec));
|
||||
}
|
||||
ResolutionStep::Resolved { project_id, path } => {
|
||||
out.push_str(&format!(" [✓] Resolved '{}' v{} at {:?}\n", project_id.name, project_id.version, path));
|
||||
}
|
||||
ResolutionStep::UsingCached { project_id } => {
|
||||
out.push_str(&format!(" [.] Using cached '{}' v{}\n", project_id.name, project_id.version));
|
||||
}
|
||||
ResolutionStep::Conflict { name, existing_version, new_version } => {
|
||||
out.push_str(&format!(" [!] CONFLICT for '{}': {} vs {}\n", name, existing_version, new_version));
|
||||
}
|
||||
ResolutionStep::Error { message } => {
|
||||
out.push_str(&format!(" [X] ERROR: {}\n", message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(root_id) = &self.root_id {
|
||||
out.push_str("\n--- Resolved Dependency Graph ---\n");
|
||||
let mut visited = HashSet::new();
|
||||
out.push_str(&format!("{} v{}\n", root_id.name, root_id.version));
|
||||
self.print_node(root_id, 0, &mut out, &mut visited);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn print_node(&self, id: &ProjectId, indent: usize, out: &mut String, visited: &mut HashSet<ProjectId>) {
|
||||
if let Some(edges) = self.edges.get(id) {
|
||||
for edge in edges {
|
||||
let prefix = " ".repeat(indent);
|
||||
out.push_str(&format!("{}└── {}: {} v{}\n", prefix, edge.alias, edge.to.name, edge.to.version));
|
||||
if !visited.contains(&edge.to) {
|
||||
visited.insert(edge.to.clone());
|
||||
self.print_node(&edge.to, indent + 1, out, visited);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ResolveError {
|
||||
CycleDetected(Vec<String>),
|
||||
MissingDependency(PathBuf),
|
||||
VersionConflict {
|
||||
name: String,
|
||||
v1: String,
|
||||
v2: String,
|
||||
},
|
||||
NameCollision {
|
||||
name: String,
|
||||
p1: PathBuf,
|
||||
p2: PathBuf,
|
||||
},
|
||||
ManifestError(crate::manifest::ManifestError),
|
||||
FetchError(FetchError),
|
||||
SourceError(SourceError),
|
||||
IoError {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
WithTrace {
|
||||
trace: ResolutionTrace,
|
||||
source: Box<ResolveError>,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ResolveError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ResolveError::CycleDetected(chain) => write!(f, "Cycle detected: {}", chain.join(" -> ")),
|
||||
ResolveError::MissingDependency(path) => write!(f, "Missing dependency at: {}", path.display()),
|
||||
ResolveError::VersionConflict { name, v1, v2 } => {
|
||||
write!(f, "Version conflict for project '{}': {} vs {}", name, v1, v2)
|
||||
}
|
||||
ResolveError::NameCollision { name, p1, p2 } => {
|
||||
write!(f, "Name collision: two distinct projects claiming same name '{}' at {} and {}", name, p1.display(), p2.display())
|
||||
}
|
||||
ResolveError::ManifestError(e) => write!(f, "Manifest error: {}", e),
|
||||
ResolveError::FetchError(e) => write!(f, "Fetch error: {}", e),
|
||||
ResolveError::SourceError(e) => write!(f, "Source error: {}", e),
|
||||
ResolveError::IoError { path, source } => write!(f, "IO error at {}: {}", path.display(), source),
|
||||
ResolveError::WithTrace { source, .. } => write!(f, "{}", source),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ResolveError {}
|
||||
|
||||
impl From<crate::manifest::ManifestError> for ResolveError {
|
||||
fn from(e: crate::manifest::ManifestError) -> Self {
|
||||
ResolveError::ManifestError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FetchError> for ResolveError {
|
||||
fn from(e: FetchError) -> Self {
|
||||
ResolveError::FetchError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SourceError> for ResolveError {
|
||||
fn from(e: SourceError) -> Self {
|
||||
match e {
|
||||
SourceError::Manifest(me) => ResolveError::ManifestError(me),
|
||||
SourceError::Io(ioe) => ResolveError::IoError {
|
||||
path: PathBuf::new(),
|
||||
source: ioe,
|
||||
},
|
||||
_ => ResolveError::SourceError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve_graph(root_dir: &Path) -> Result<ResolvedGraph, ResolveError> {
|
||||
let mut graph = ResolvedGraph::default();
|
||||
let mut visited = HashSet::new();
|
||||
let mut stack = Vec::new();
|
||||
|
||||
let root_path = root_dir.canonicalize().map_err(|e| ResolveError::IoError {
|
||||
path: root_dir.to_path_buf(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
let root_id = match resolve_recursive(&root_path, &root_path, &mut graph, &mut visited, &mut stack) {
|
||||
Ok(id) => id,
|
||||
Err(e) => return Err(ResolveError::WithTrace {
|
||||
trace: graph.trace,
|
||||
source: Box::new(e),
|
||||
}),
|
||||
};
|
||||
graph.root_id = Some(root_id);
|
||||
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
fn resolve_recursive(
|
||||
project_path: &Path,
|
||||
root_project_dir: &Path,
|
||||
graph: &mut ResolvedGraph,
|
||||
visited: &mut HashSet<ProjectId>,
|
||||
stack: &mut Vec<ProjectId>,
|
||||
) -> Result<ProjectId, ResolveError> {
|
||||
let manifest = load_manifest(project_path)?;
|
||||
let sources = discover(project_path)?;
|
||||
let project_id = ProjectId {
|
||||
name: manifest.name.clone(),
|
||||
version: manifest.version.clone(),
|
||||
};
|
||||
|
||||
// Cycle detection
|
||||
if let Some(pos) = stack.iter().position(|id| id == &project_id) {
|
||||
let mut chain: Vec<String> = stack[pos..].iter().map(|id| id.name.clone()).collect();
|
||||
chain.push(project_id.name.clone());
|
||||
return Err(ResolveError::CycleDetected(chain));
|
||||
}
|
||||
|
||||
// Collision handling: Name collision
|
||||
// If we find a project with the same name but different path/version, we might have a collision or version conflict.
|
||||
for node in graph.nodes.values() {
|
||||
if node.id.name == project_id.name {
|
||||
if node.id.version != project_id.version {
|
||||
graph.trace.steps.push(ResolutionStep::Conflict {
|
||||
name: project_id.name.clone(),
|
||||
existing_version: node.id.version.clone(),
|
||||
new_version: project_id.version.clone(),
|
||||
});
|
||||
return Err(ResolveError::VersionConflict {
|
||||
name: project_id.name.clone(),
|
||||
v1: node.id.version.clone(),
|
||||
v2: project_id.version.clone(),
|
||||
});
|
||||
}
|
||||
// Same name, same version, but different path?
|
||||
if node.path != project_path {
|
||||
return Err(ResolveError::NameCollision {
|
||||
name: project_id.name.clone(),
|
||||
p1: node.path.clone(),
|
||||
p2: project_path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If already fully visited, return the ID
|
||||
if visited.contains(&project_id) {
|
||||
graph.trace.steps.push(ResolutionStep::UsingCached {
|
||||
project_id: project_id.clone(),
|
||||
});
|
||||
return Ok(project_id);
|
||||
}
|
||||
|
||||
graph.trace.steps.push(ResolutionStep::Resolved {
|
||||
project_id: project_id.clone(),
|
||||
path: project_path.to_path_buf(),
|
||||
});
|
||||
|
||||
visited.insert(project_id.clone());
|
||||
stack.push(project_id.clone());
|
||||
|
||||
let mut edges = Vec::new();
|
||||
for (alias, spec) in &manifest.dependencies {
|
||||
graph.trace.steps.push(ResolutionStep::TryResolve {
|
||||
alias: alias.clone(),
|
||||
spec: format!("{:?}", spec),
|
||||
});
|
||||
|
||||
let dep_path = match fetch_dependency(alias, spec, project_path, root_project_dir) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
graph.trace.steps.push(ResolutionStep::Error {
|
||||
message: format!("Fetch error for '{}': {}", alias, e),
|
||||
});
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
|
||||
let dep_id = match resolve_recursive(&dep_path, root_project_dir, graph, visited, stack) {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
// If it's a version conflict, we already pushed it inside the recursive call
|
||||
// but let's make sure we catch other errors too.
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
edges.push(ResolvedEdge {
|
||||
alias: alias.clone(),
|
||||
to: dep_id,
|
||||
});
|
||||
}
|
||||
|
||||
stack.pop();
|
||||
graph.nodes.insert(project_id.clone(), ResolvedNode {
|
||||
id: project_id.clone(),
|
||||
path: project_path.to_path_buf(),
|
||||
manifest,
|
||||
sources,
|
||||
});
|
||||
graph.edges.insert(project_id.clone(), edges);
|
||||
|
||||
Ok(project_id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_simple_graph() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("root");
|
||||
let dep = dir.path().join("dep");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::create_dir_all(&dep).unwrap();
|
||||
|
||||
fs::write(root.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "d": "../dep" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(dep.join("prometeu.json"), r#"{
|
||||
"name": "dep",
|
||||
"version": "1.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
let graph = resolve_graph(&root).unwrap();
|
||||
assert_eq!(graph.nodes.len(), 2);
|
||||
let root_id = graph.root_id.as_ref().unwrap();
|
||||
assert_eq!(root_id.name, "root");
|
||||
|
||||
let edges = graph.edges.get(root_id).unwrap();
|
||||
assert_eq!(edges.len(), 1);
|
||||
assert_eq!(edges[0].alias, "d");
|
||||
assert_eq!(edges[0].to.name, "dep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cycle_detection() {
|
||||
let dir = tempdir().unwrap();
|
||||
let a = dir.path().join("a");
|
||||
let b = dir.path().join("b");
|
||||
fs::create_dir_all(&a).unwrap();
|
||||
fs::create_dir_all(&b).unwrap();
|
||||
|
||||
fs::write(a.join("prometeu.json"), r#"{
|
||||
"name": "a",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "b": "../b" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(b.join("prometeu.json"), r#"{
|
||||
"name": "b",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "a": "../a" }
|
||||
}"#).unwrap();
|
||||
|
||||
let err = resolve_graph(&a).unwrap_err();
|
||||
match err {
|
||||
ResolveError::WithTrace { source, .. } => {
|
||||
if let ResolveError::CycleDetected(chain) = *source {
|
||||
assert_eq!(chain, vec!["a", "b", "a"]);
|
||||
} else {
|
||||
panic!("Expected CycleDetected error, got {:?}", source);
|
||||
}
|
||||
}
|
||||
_ => panic!("Expected WithTrace containing CycleDetected error, got {:?}", err),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_alias_does_not_change_identity() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("root");
|
||||
let dep = dir.path().join("dep");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::create_dir_all(&dep).unwrap();
|
||||
|
||||
fs::write(root.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "my_alias": "../dep" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(dep.join("prometeu.json"), r#"{
|
||||
"name": "actual_name",
|
||||
"version": "1.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
let graph = resolve_graph(&root).unwrap();
|
||||
let root_id = graph.root_id.as_ref().unwrap();
|
||||
let edges = graph.edges.get(root_id).unwrap();
|
||||
assert_eq!(edges[0].alias, "my_alias");
|
||||
assert_eq!(edges[0].to.name, "actual_name");
|
||||
assert!(graph.nodes.contains_key(&edges[0].to));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_version_conflict() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("root");
|
||||
let dep1 = dir.path().join("dep1");
|
||||
let dep2 = dir.path().join("dep2");
|
||||
let shared = dir.path().join("shared1");
|
||||
let shared2 = dir.path().join("shared2");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::create_dir_all(&dep1).unwrap();
|
||||
fs::create_dir_all(&dep2).unwrap();
|
||||
fs::create_dir_all(&shared).unwrap();
|
||||
fs::create_dir_all(&shared2).unwrap();
|
||||
|
||||
fs::write(root.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "d1": "../dep1", "d2": "../dep2" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(dep1.join("prometeu.json"), r#"{
|
||||
"name": "dep1",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "s": "../shared1" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(dep2.join("prometeu.json"), r#"{
|
||||
"name": "dep2",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "s": "../shared2" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(shared.join("prometeu.json"), r#"{
|
||||
"name": "shared",
|
||||
"version": "1.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(shared2.join("prometeu.json"), r#"{
|
||||
"name": "shared",
|
||||
"version": "2.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
let err = resolve_graph(&root).unwrap_err();
|
||||
match err {
|
||||
ResolveError::WithTrace { source, .. } => {
|
||||
if let ResolveError::VersionConflict { name, .. } = *source {
|
||||
assert_eq!(name, "shared");
|
||||
} else {
|
||||
panic!("Expected VersionConflict error, got {:?}", source);
|
||||
}
|
||||
}
|
||||
_ => panic!("Expected WithTrace containing VersionConflict error, got {:?}", err),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_name_collision() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("root");
|
||||
let dep1 = dir.path().join("dep1");
|
||||
let dep2 = dir.path().join("dep2");
|
||||
let p1 = dir.path().join("p1");
|
||||
let p2 = dir.path().join("p2");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::create_dir_all(&dep1).unwrap();
|
||||
fs::create_dir_all(&dep2).unwrap();
|
||||
fs::create_dir_all(&p1).unwrap();
|
||||
fs::create_dir_all(&p2).unwrap();
|
||||
|
||||
fs::write(root.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "d1": "../dep1", "d2": "../dep2" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(dep1.join("prometeu.json"), r#"{
|
||||
"name": "dep1",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "p": "../p1" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(dep2.join("prometeu.json"), r#"{
|
||||
"name": "dep2",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": { "p": "../p2" }
|
||||
}"#).unwrap();
|
||||
|
||||
// Both p1 and p2 claim to be "collision" version 1.0.0
|
||||
fs::write(p1.join("prometeu.json"), r#"{
|
||||
"name": "collision",
|
||||
"version": "1.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(p2.join("prometeu.json"), r#"{
|
||||
"name": "collision",
|
||||
"version": "1.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
let err = resolve_graph(&root).unwrap_err();
|
||||
match err {
|
||||
ResolveError::WithTrace { source, .. } => {
|
||||
if let ResolveError::NameCollision { name, .. } = *source {
|
||||
assert_eq!(name, "collision");
|
||||
} else {
|
||||
panic!("Expected NameCollision error, got {:?}", source);
|
||||
}
|
||||
}
|
||||
_ => panic!("Expected WithTrace containing NameCollision error, got {:?}", err),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_with_git_dependency_mock() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let root = tmp.path().join("root");
|
||||
let remote = tmp.path().join("remote");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::create_dir_all(&remote).unwrap();
|
||||
|
||||
// Setup remote
|
||||
let _ = std::process::Command::new("git").arg("init").current_dir(&remote).status();
|
||||
let _ = std::process::Command::new("git").arg("config").arg("user.email").arg("you@example.com").current_dir(&remote).status();
|
||||
let _ = std::process::Command::new("git").arg("config").arg("user.name").arg("Your Name").current_dir(&remote).status();
|
||||
fs::write(remote.join("prometeu.json"), r#"{"name": "remote", "version": "1.2.3", "kind": "lib"}"#).unwrap();
|
||||
let _ = std::process::Command::new("git").arg("add").arg(".").current_dir(&remote).status();
|
||||
let _ = std::process::Command::new("git").arg("commit").arg("-m").arg("init").current_dir(&remote).status();
|
||||
|
||||
// Setup root
|
||||
fs::write(root.join("prometeu.json"), format!(r#"{{
|
||||
"name": "root",
|
||||
"version": "0.1.0",
|
||||
"kind": "lib",
|
||||
"dependencies": {{
|
||||
"rem": {{ "git": "file://{}" }}
|
||||
}}
|
||||
}}"#, remote.display())).unwrap();
|
||||
|
||||
let graph = resolve_graph(&root);
|
||||
|
||||
if let Ok(graph) = graph {
|
||||
assert_eq!(graph.nodes.len(), 2);
|
||||
let rem_id = graph.nodes.values().find(|n| n.id.name == "remote").unwrap().id.clone();
|
||||
assert_eq!(rem_id.version, "1.2.3");
|
||||
|
||||
// Verify cache manifest was created
|
||||
assert!(root.join("cache/cache.json").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_import_path() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("root");
|
||||
let sdk = dir.path().join("sdk");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::create_dir_all(&sdk).unwrap();
|
||||
let root = root.canonicalize().unwrap();
|
||||
let sdk = sdk.canonicalize().unwrap();
|
||||
|
||||
fs::create_dir_all(root.join("src/main/modules")).unwrap();
|
||||
fs::create_dir_all(sdk.join("src/main/modules/math")).unwrap();
|
||||
fs::write(root.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
fs::write(root.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "0.1.0",
|
||||
"kind": "app",
|
||||
"dependencies": { "sdk": "../sdk" }
|
||||
}"#).unwrap();
|
||||
|
||||
fs::write(sdk.join("prometeu.json"), r#"{
|
||||
"name": "sdk",
|
||||
"version": "1.0.0",
|
||||
"kind": "lib"
|
||||
}"#).unwrap();
|
||||
|
||||
let graph = resolve_graph(&root).unwrap();
|
||||
let root_id = graph.root_id.as_ref().unwrap();
|
||||
|
||||
// Resolve @sdk:math
|
||||
let path = graph.resolve_import_path(root_id, "@sdk:math").unwrap();
|
||||
assert_eq!(path.canonicalize().unwrap(), sdk.join("src/main/modules/math").canonicalize().unwrap());
|
||||
|
||||
// Resolve local module
|
||||
let path = graph.resolve_import_path(root_id, "local_mod").unwrap();
|
||||
let expected = root.join("src/main/modules/local_mod");
|
||||
assert_eq!(path, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolution_trace_and_explain() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root_dir = dir.path().join("root");
|
||||
fs::create_dir_all(&root_dir).unwrap();
|
||||
let root_dir = root_dir.canonicalize().unwrap();
|
||||
|
||||
// Root project
|
||||
fs::write(root_dir.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"dep1": { "path": "../dep1" }
|
||||
}
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(root_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(root_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
// Dep 1
|
||||
let dep1_dir = dir.path().join("dep1");
|
||||
fs::create_dir_all(&dep1_dir).unwrap();
|
||||
let dep1_dir = dep1_dir.canonicalize().unwrap();
|
||||
fs::write(dep1_dir.join("prometeu.json"), r#"{
|
||||
"name": "dep1",
|
||||
"version": "1.1.0"
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(dep1_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(dep1_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
let graph = resolve_graph(&root_dir).unwrap();
|
||||
let explanation = graph.explain();
|
||||
|
||||
assert!(explanation.contains("--- Dependency Resolution Trace ---"));
|
||||
assert!(explanation.contains("[✓] Resolved 'root' v1.0.0"));
|
||||
assert!(explanation.contains("[?] Resolving 'dep1'"));
|
||||
assert!(explanation.contains("[✓] Resolved 'dep1' v1.1.0"));
|
||||
|
||||
assert!(explanation.contains("--- Resolved Dependency Graph ---"));
|
||||
assert!(explanation.contains("root v1.0.0"));
|
||||
assert!(explanation.contains("└── dep1: dep1 v1.1.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conflict_explanation() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root_dir = dir.path().join("root");
|
||||
fs::create_dir_all(&root_dir).unwrap();
|
||||
let root_dir = root_dir.canonicalize().unwrap();
|
||||
|
||||
// Root -> A, B
|
||||
// A -> C v1
|
||||
// B -> C v2
|
||||
|
||||
fs::write(root_dir.join("prometeu.json"), r#"{
|
||||
"name": "root",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"a": { "path": "../a" },
|
||||
"b": { "path": "../b" }
|
||||
}
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(root_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(root_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
let a_dir = dir.path().join("a");
|
||||
fs::create_dir_all(&a_dir).unwrap();
|
||||
let a_dir = a_dir.canonicalize().unwrap();
|
||||
fs::write(a_dir.join("prometeu.json"), r#"{
|
||||
"name": "a",
|
||||
"version": "1.0.0",
|
||||
"dependencies": { "c": { "path": "../c1" } }
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(a_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(a_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
let b_dir = dir.path().join("b");
|
||||
fs::create_dir_all(&b_dir).unwrap();
|
||||
let b_dir = b_dir.canonicalize().unwrap();
|
||||
fs::write(b_dir.join("prometeu.json"), r#"{
|
||||
"name": "b",
|
||||
"version": "1.0.0",
|
||||
"dependencies": { "c": { "path": "../c2" } }
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(b_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(b_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
let c1_dir = dir.path().join("c1");
|
||||
fs::create_dir_all(&c1_dir).unwrap();
|
||||
let c1_dir = c1_dir.canonicalize().unwrap();
|
||||
fs::write(c1_dir.join("prometeu.json"), r#"{
|
||||
"name": "c",
|
||||
"version": "1.0.0"
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(c1_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(c1_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
let c2_dir = dir.path().join("c2");
|
||||
fs::create_dir_all(&c2_dir).unwrap();
|
||||
let c2_dir = c2_dir.canonicalize().unwrap();
|
||||
fs::write(c2_dir.join("prometeu.json"), r#"{
|
||||
"name": "c",
|
||||
"version": "2.0.0"
|
||||
}"#).unwrap();
|
||||
fs::create_dir_all(c2_dir.join("src/main/modules")).unwrap();
|
||||
fs::write(c2_dir.join("src/main/modules/main.pbs"), "").unwrap();
|
||||
|
||||
let res = resolve_graph(&root_dir);
|
||||
assert!(res.is_err());
|
||||
|
||||
if let Err(ResolveError::WithTrace { trace, source }) = res {
|
||||
let mut dummy = ResolvedGraph::default();
|
||||
dummy.trace = trace;
|
||||
let explanation = dummy.explain();
|
||||
|
||||
assert!(explanation.contains("[!] CONFLICT for 'c': 1.0.0 vs 2.0.0"));
|
||||
assert!(source.to_string().contains("Version conflict for project 'c': 1.0.0 vs 2.0.0"));
|
||||
} else {
|
||||
panic!("Expected WithTrace error");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user