Skip to main content

ryra_core/registry/
resolve.rs

1use 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/// A reference to a service in a registry.
9///
10/// - `Default("forgejo")` — refers to a service in the project-managed
11///   default registry (cloned from [`DEFAULT_REGISTRY_URL`]).
12/// - `Custom { registry: "acme", service: "forgejo" }` — refers to a
13///   service in a user-added custom registry.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ServiceRef {
16    /// A service from the default registry. E.g., `forgejo`.
17    Default(String),
18    /// A service from a named custom registry. E.g., `acme/forgejo`.
19    Custom { registry: String, service: String },
20    /// A local project directory whose `service.toml` lives at its root
21    /// (`ryra add .` / `ryra add ./path`). `dir` is absolute; `name` is the
22    /// `[service].name` read from the file.
23    Path { dir: PathBuf, name: String },
24}
25
26/// Whether a CLI argument is a local project path rather than a registry
27/// reference. Purely *syntactic* — a path must carry an explicit marker (`.`,
28/// `..`, `./`, `../`, `/`, `~`), exactly like `./script` vs `script` in a shell.
29///
30/// Deliberately does NOT probe the filesystem: if a bare name like `forgejo`
31/// resolved to a local `./forgejo/` folder whenever one happened to exist, the
32/// meaning of `ryra add forgejo` would depend on your cwd, and a planted
33/// `forgejo/service.toml` (which can run arbitrary build/run commands) could
34/// hijack a trusted registry name. A bare word is always a registry ref.
35pub 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
44/// Build a [`ServiceRef::Path`] from a directory, reading its `service.toml`
45/// for the canonical service name. The path is absolutized so the install
46/// record survives a later `cd`.
47pub 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    /// Parse a service reference from a string.
58    ///
59    /// - `"forgejo"` → `Default("forgejo")`
60    /// - `"acme/forgejo"` → `Custom { registry: "acme", service: "forgejo" }`
61    /// - `""`, `"/forgejo"`, `"acme/"`, `"acme/sub/forgejo"` → error
62    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    /// Returns the service name part of this reference.
100    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    /// Returns the registry name for this reference.
109    ///
110    /// Returns `"default"` for default-registry services. For a local path
111    /// install it returns the project directory, which is what gets recorded in
112    /// metadata so `ryra upgrade` can re-read the same `service.toml`.
113    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
122/// Resolve the on-disk directory of the default registry.
123///
124/// If `RYRA_REGISTRY_DIR` is set to an existing directory, that path is
125/// returned as-is (no clone, no pull) — the escape hatch tests use to inject
126/// `/opt/ryra-test-registry` inside the VM without network access. Otherwise
127/// the registry is cloned (or pulled) from [`DEFAULT_REGISTRY_URL`] into
128/// `<cache_dir>/default/`.
129pub 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
142/// Resolve the registry directory for a service reference.
143///
144/// - For `Default`: see [`resolve_default_registry_dir`].
145/// - For `Custom`: looks up the registry name in `config.registries` and clones/pulls it.
146pub async fn resolve_registry_dir(
147    service_ref: &ServiceRef,
148    config: &Config,
149    cache_dir: &Path,
150) -> Result<PathBuf> {
151    match service_ref {
152        // A local project: the directory *is* the source, no clone/pull.
153        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
169/// Resolve a service from a registry, returning its definition and directory.
170///
171/// - For `Default`: finds the service in the default registry.
172/// - For `Custom`: finds the service in the named custom registry.
173pub 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        // Explicit markers → local path.
197        for p in [".", "..", "./app", "../app", "/abs/app", "~/app"] {
198            assert!(is_path_like(p), "{p} should be treated as a path");
199        }
200        // Bare names and registry refs are NEVER paths, regardless of what
201        // directories exist in the cwd. This is the security property: a planted
202        // `./forgejo/` folder can't hijack `ryra add forgejo`.
203        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        // SAFETY: this test sets a process-global env var; running multiple
262        // env-mutating tests in parallel within the same process can race.
263        // Cargo runs tests in threads, so we scope to a tempdir that
264        // exists for the duration of the call.
265        let tmp = tempfile::TempDir::new().expect("tempdir");
266        let cache = tempfile::TempDir::new().expect("cache tempdir");
267        // SAFETY: tests in this module are single-threaded by Cargo's
268        // default scheduler; setting env here doesn't escape the call.
269        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}