This commit is contained in:
Nilton Constantino
2026-02-02 13:54:01 +00:00
parent 99d3dc38a1
commit 6732111328
15 changed files with 571 additions and 167 deletions
@@ -0,0 +1,61 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::fs;
use anyhow::Result;
#[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)
}
+30 -45
View File
@@ -2,6 +2,7 @@ use std::path::{Path, PathBuf};
use std::fs;
use std::process::Command;
use crate::manifest::DependencySpec;
use crate::deps::cache::{CacheManifest, get_cache_root, get_git_worktree_path, GitCacheEntry};
#[derive(Debug)]
pub enum FetchError {
@@ -12,6 +13,7 @@ pub enum FetchError {
},
MissingManifest(PathBuf),
InvalidPath(PathBuf),
CacheError(String),
}
impl std::fmt::Display for FetchError {
@@ -27,10 +29,13 @@ impl std::fmt::Display for FetchError {
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)
@@ -42,6 +47,7 @@ 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),
@@ -50,7 +56,7 @@ pub fn fetch_dependency(
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)
fetch_git(url, version, root_project_dir)
} else {
Err(FetchError::InvalidPath(PathBuf::from(alias)))
}
@@ -72,10 +78,11 @@ pub fn fetch_path(path_str: &str, base_dir: &Path) -> Result<PathBuf, FetchError
Ok(canonical)
}
pub fn fetch_git(url: &str, version: &str) -> Result<PathBuf, FetchError> {
let cache_dir = get_cache_dir();
let hash = fnv1a_hash(url);
let target_dir = cache_dir.join("git").join(format!("{:016x}", hash));
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)?;
@@ -113,6 +120,15 @@ pub fn fetch_git(url: &str, version: &str) -> Result<PathBuf, FetchError> {
});
}
}
// 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() {
@@ -122,24 +138,6 @@ pub fn fetch_git(url: &str, version: &str) -> Result<PathBuf, FetchError> {
Ok(target_dir)
}
fn get_cache_dir() -> PathBuf {
if let Ok(override_dir) = std::env::var("PROMETEU_CACHE_DIR") {
return PathBuf::from(override_dir);
}
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
Path::new(&home).join(".prometeu").join("cache")
}
fn fnv1a_hash(s: &str) -> u64 {
let mut hash = 0xcbf29ce484222325;
for b in s.as_bytes() {
hash ^= *b as u64;
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
@@ -159,19 +157,12 @@ mod tests {
assert_eq!(fetched.canonicalize().unwrap(), dep.canonicalize().unwrap());
}
#[test]
fn test_cache_path_generation_is_deterministic() {
let url = "https://github.com/prometeu/core.git";
let h1 = fnv1a_hash(url);
let h2 = fnv1a_hash(url);
assert_eq!(h1, h2);
assert_eq!(h1, 7164662596401709514); // Deterministic FNV-1a
}
#[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
@@ -183,25 +174,19 @@ mod tests {
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 cache_dir = tmp.path().join("cache");
std::env::set_var("PROMETEU_CACHE_DIR", &cache_dir);
let url = format!("file://{}", remote_dir.display());
let fetched = fetch_git(&url, "latest");
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));
}
std::env::remove_var("PROMETEU_CACHE_DIR");
}
#[test]
fn test_get_cache_dir_override() {
std::env::set_var("PROMETEU_CACHE_DIR", "/tmp/prometeu-cache");
assert_eq!(get_cache_dir(), PathBuf::from("/tmp/prometeu-cache"));
std::env::remove_var("PROMETEU_CACHE_DIR");
}
}
+1
View File
@@ -1,2 +1,3 @@
pub mod resolver;
pub mod fetch;
pub mod cache;
+118 -14
View File
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use crate::manifest::{Manifest, load_manifest};
use crate::deps::fetch::{fetch_dependency, FetchError};
use crate::sources::{ProjectSources, discover, SourceError};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProjectId {
@@ -14,6 +15,7 @@ pub struct ResolvedNode {
pub id: ProjectId,
pub path: PathBuf,
pub manifest: Manifest,
pub sources: ProjectSources,
}
#[derive(Debug)]
@@ -29,6 +31,35 @@ pub struct ResolvedGraph {
pub root_id: Option<ProjectId>,
}
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
}
}
#[derive(Debug)]
pub enum ResolveError {
CycleDetected(Vec<String>),
@@ -45,6 +76,7 @@ pub enum ResolveError {
},
ManifestError(crate::manifest::ManifestError),
FetchError(FetchError),
SourceError(SourceError),
IoError {
path: PathBuf,
source: std::io::Error,
@@ -64,6 +96,7 @@ impl std::fmt::Display for ResolveError {
}
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),
}
}
@@ -83,6 +116,19 @@ impl From<FetchError> for ResolveError {
}
}
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();
@@ -93,7 +139,7 @@ pub fn resolve_graph(root_dir: &Path) -> Result<ResolvedGraph, ResolveError> {
source: e,
})?;
let root_id = resolve_recursive(&root_path, &mut graph, &mut visited, &mut stack)?;
let root_id = resolve_recursive(&root_path, &root_path, &mut graph, &mut visited, &mut stack)?;
graph.root_id = Some(root_id);
Ok(graph)
@@ -101,11 +147,13 @@ pub fn resolve_graph(root_dir: &Path) -> Result<ResolvedGraph, ResolveError> {
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(),
@@ -149,8 +197,8 @@ fn resolve_recursive(
let mut edges = Vec::new();
for (alias, spec) in &manifest.dependencies {
let dep_path = fetch_dependency(alias, spec, project_path)?;
let dep_id = resolve_recursive(&dep_path, graph, visited, stack)?;
let dep_path = fetch_dependency(alias, spec, project_path, root_project_dir)?;
let dep_id = resolve_recursive(&dep_path, root_project_dir, graph, visited, stack)?;
edges.push(ResolvedEdge {
alias: alias.clone(),
@@ -165,6 +213,7 @@ fn resolve_recursive(
id: project_id.clone(),
path: project_path.to_path_buf(),
manifest,
sources,
});
graph.edges.insert(project_id.clone(), edges);
@@ -188,12 +237,14 @@ mod tests {
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"
"version": "1.0.0",
"kind": "lib"
}"#).unwrap();
let graph = resolve_graph(&root).unwrap();
@@ -218,12 +269,14 @@ mod tests {
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();
@@ -247,12 +300,14 @@ mod tests {
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"
"version": "1.0.0",
"kind": "lib"
}"#).unwrap();
let graph = resolve_graph(&root).unwrap();
@@ -280,29 +335,34 @@ mod tests {
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"
"version": "1.0.0",
"kind": "lib"
}"#).unwrap();
fs::write(shared2.join("prometeu.json"), r#"{
"name": "shared",
"version": "2.0.0"
"version": "2.0.0",
"kind": "lib"
}"#).unwrap();
let err = resolve_graph(&root).unwrap_err();
@@ -331,30 +391,35 @@ mod tests {
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"
"version": "1.0.0",
"kind": "lib"
}"#).unwrap();
fs::write(p2.join("prometeu.json"), r#"{
"name": "collision",
"version": "1.0.0"
"version": "1.0.0",
"kind": "lib"
}"#).unwrap();
let err = resolve_graph(&root).unwrap_err();
@@ -378,17 +443,15 @@ mod tests {
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"}"#).unwrap();
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
let cache_dir = tmp.path().join("cache");
std::env::set_var("PROMETEU_CACHE_DIR", &cache_dir);
fs::write(root.join("prometeu.json"), format!(r#"{{
"name": "root",
"version": "0.1.0",
"kind": "lib",
"dependencies": {{
"rem": {{ "git": "file://{}" }}
}}
@@ -400,8 +463,49 @@ mod tests {
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());
}
}
std::env::remove_var("PROMETEU_CACHE_DIR");
#[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);
}
}