ryra_core/registry/
resolve.rs1use std::path::{Path, PathBuf};
2
3use crate::config::schema::Config;
4use crate::error::{Error, Result};
5use crate::paths::{DEFAULT_REGISTRY_URL, REGISTRY_DIR_ENV};
6use crate::registry;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ServiceRef {
16 Default(String),
18 Custom { registry: String, service: String },
20 Path { dir: PathBuf, name: String },
24}
25
26pub fn is_path_like(input: &str) -> bool {
36 input == "."
37 || input == ".."
38 || input.starts_with("./")
39 || input.starts_with("../")
40 || input.starts_with('/')
41 || input.starts_with('~')
42}
43
44pub fn path_ref(dir: &Path) -> Result<ServiceRef> {
48 let svc = registry::load_project_service(dir)?;
49 let abs = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
50 Ok(ServiceRef::Path {
51 dir: abs,
52 name: svc.def.service.name,
53 })
54}
55
56impl ServiceRef {
57 pub fn parse(input: &str) -> Result<Self> {
63 let parts: Vec<&str> = input.split('/').collect();
64 match parts.as_slice() {
65 [""] => Err(Error::InvalidServiceRef(
66 "service reference cannot be empty".to_string(),
67 )),
68 [name] => {
69 if name.is_empty() {
70 Err(Error::InvalidServiceRef(
71 "service reference cannot be empty".to_string(),
72 ))
73 } else {
74 Ok(ServiceRef::Default((*name).to_string()))
75 }
76 }
77 [registry, service] => {
78 if registry.is_empty() {
79 return Err(Error::InvalidServiceRef(format!(
80 "registry name cannot be empty in reference '{input}'"
81 )));
82 }
83 if service.is_empty() {
84 return Err(Error::InvalidServiceRef(format!(
85 "service name cannot be empty in reference '{input}'"
86 )));
87 }
88 Ok(ServiceRef::Custom {
89 registry: (*registry).to_string(),
90 service: (*service).to_string(),
91 })
92 }
93 _ => Err(Error::InvalidServiceRef(format!(
94 "invalid service reference '{input}': expected 'service' or 'registry/service'"
95 ))),
96 }
97 }
98
99 pub fn service_name(&self) -> &str {
101 match self {
102 ServiceRef::Default(name) => name,
103 ServiceRef::Custom { service, .. } => service,
104 ServiceRef::Path { name, .. } => name,
105 }
106 }
107
108 pub fn registry_name(&self) -> &str {
114 match self {
115 ServiceRef::Default(_) => crate::paths::REGISTRY_DEFAULT,
116 ServiceRef::Custom { registry, .. } => registry,
117 ServiceRef::Path { dir, .. } => dir.to_str().unwrap_or("local"),
118 }
119 }
120}
121
122pub async fn resolve_default_registry_dir(cache_dir: &Path) -> Result<PathBuf> {
130 if let Ok(override_path) = std::env::var(REGISTRY_DIR_ENV) {
131 let path = PathBuf::from(override_path);
132 if path.is_dir() {
133 return Ok(path);
134 }
135 }
136
137 let dest = cache_dir.join("default");
138 registry::fetch::clone_or_pull(DEFAULT_REGISTRY_URL, &dest).await?;
139 Ok(dest)
140}
141
142pub async fn resolve_registry_dir(
147 service_ref: &ServiceRef,
148 config: &Config,
149 cache_dir: &Path,
150) -> Result<PathBuf> {
151 match service_ref {
152 ServiceRef::Path { dir, .. } => Ok(dir.clone()),
154 ServiceRef::Default(_) => resolve_default_registry_dir(cache_dir).await,
155 ServiceRef::Custom { registry, .. } => {
156 let entry = config
157 .registries
158 .iter()
159 .find(|r| r.name == *registry)
160 .ok_or_else(|| Error::RegistryNotFound(registry.clone()))?;
161
162 let dest = cache_dir.join("registries").join(registry);
163 registry::fetch::clone_or_pull(&entry.url, &dest).await?;
164 Ok(dest)
165 }
166 }
167}
168
169pub async fn resolve_service(
174 service_ref: &ServiceRef,
175 config: &Config,
176 cache_dir: &Path,
177) -> Result<registry::RegistryService> {
178 let repo_dir = resolve_registry_dir(service_ref, config, cache_dir).await?;
179 registry::find_service(&repo_dir, service_ref.service_name())
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn parse_default_service() {
188 let r = ServiceRef::parse("forgejo").expect("should parse");
189 assert_eq!(r, ServiceRef::Default("forgejo".to_string()));
190 assert_eq!(r.service_name(), "forgejo");
191 assert_eq!(r.registry_name(), "default");
192 }
193
194 #[test]
195 fn path_detection_is_syntactic_only() {
196 for p in [".", "..", "./app", "../app", "/abs/app", "~/app"] {
198 assert!(is_path_like(p), "{p} should be treated as a path");
199 }
200 for name in ["forgejo", "acme/forgejo", "caddy", "my-app", "a/b"] {
204 assert!(!is_path_like(name), "{name} must stay a registry ref");
205 }
206 }
207
208 #[test]
209 fn parse_custom_service() {
210 let r = ServiceRef::parse("acme/forgejo").expect("should parse");
211 assert_eq!(
212 r,
213 ServiceRef::Custom {
214 registry: "acme".to_string(),
215 service: "forgejo".to_string(),
216 }
217 );
218 assert_eq!(r.service_name(), "forgejo");
219 assert_eq!(r.registry_name(), "acme");
220 }
221
222 #[test]
223 fn parse_empty_fails() {
224 let err = ServiceRef::parse("").expect_err("empty input should fail");
225 let msg = err.to_string();
226 assert!(
227 msg.contains("empty"),
228 "expected 'empty' in error message, got: {msg}"
229 );
230 }
231
232 #[test]
233 fn parse_empty_parts_fails() {
234 let err = ServiceRef::parse("/forgejo").expect_err("leading slash should fail");
235 let msg = err.to_string();
236 assert!(
237 msg.contains("empty"),
238 "expected 'empty' in error for '/forgejo', got: {msg}"
239 );
240
241 let err = ServiceRef::parse("acme/").expect_err("trailing slash should fail");
242 let msg = err.to_string();
243 assert!(
244 msg.contains("empty"),
245 "expected 'empty' in error for 'acme/', got: {msg}"
246 );
247 }
248
249 #[test]
250 fn parse_too_many_slashes_fails() {
251 let err = ServiceRef::parse("acme/sub/forgejo").expect_err("too many slashes should fail");
252 let msg = err.to_string();
253 assert!(
254 msg.contains("invalid"),
255 "expected 'invalid' in error message, got: {msg}"
256 );
257 }
258
259 #[test]
260 fn env_override_returns_path_directly() {
261 let tmp = tempfile::TempDir::new().expect("tempdir");
266 let cache = tempfile::TempDir::new().expect("cache tempdir");
267 unsafe { std::env::set_var(REGISTRY_DIR_ENV, tmp.path()) };
270
271 let rt = tokio::runtime::Runtime::new().expect("runtime");
272 let resolved = rt
273 .block_on(resolve_default_registry_dir(cache.path()))
274 .expect("resolve");
275 assert_eq!(resolved, tmp.path());
276
277 unsafe { std::env::remove_var(REGISTRY_DIR_ENV) };
278 }
279}