1use std::{
9 path::{Path, PathBuf},
10 process::Command,
11};
12
13use crate::engine::{
14 Error, ErrorCode, LoggerTrait,
15 config::{
16 BaseConfig, RulesConfig,
17 env::get_env_registry_params,
18 resolver::{load_rules_config, load_standard_config},
19 },
20 models::runtime::resolution::{AvailableConfig, resolve_available_config},
21};
22
23#[derive(Debug, Clone)]
29pub struct RegistrySpec {
30 pub url: String,
31 pub r#ref: String,
32 pub section: Option<String>,
33}
34
35#[derive(Debug, Clone)]
37pub struct RegistryLoadResult {
38 pub config: AvailableConfig,
39 pub resolved_commit: String,
40}
41
42pub fn resolve_registry_spec(
50 cli_url: Option<&str>,
51 cli_ref: Option<&str>,
52 cli_section: Option<&str>,
53 base_config: Option<&BaseConfig>,
54) -> Option<RegistrySpec> {
55 let env_params = get_env_registry_params();
57
58 let url = cli_url
59 .map(str::to_owned)
60 .or_else(|| env_params.url.clone())
61 .or_else(|| resolve_url_from_config(base_config))?;
62
63 let resolved_ref = cli_ref
65 .map(str::to_owned)
66 .or_else(|| env_params.r#ref.clone())
67 .or_else(|| resolve_ref_from_config(base_config, &url))
68 .unwrap_or_else(|| "HEAD".to_string());
69
70 let section = cli_section
72 .map(str::to_owned)
73 .or_else(|| env_params.section.clone())
74 .or_else(|| resolve_section_from_top_level(base_config))
75 .or_else(|| resolve_section_from_named_registry(base_config, &url));
76
77 Some(RegistrySpec {
78 url,
79 r#ref: resolved_ref,
80 section,
81 })
82}
83
84fn resolve_url_from_config(config: Option<&BaseConfig>) -> Option<String> {
85 let config = config?;
86 let use_name = config.registry_use()?;
87 let registries = config.registries_map();
88 registries.get(&use_name).and_then(|r| r.url.clone())
89}
90
91fn resolve_ref_from_config(config: Option<&BaseConfig>, url: &str) -> Option<String> {
92 let config = config?;
93 let use_name = config.registry_use()?;
94 let registries = config.registries_map();
95 registries
97 .iter()
98 .find(|(name, r)| *name == &use_name || r.url.as_deref() == Some(url))
99 .and_then(|(_, r)| r.r#ref.clone())
100}
101
102fn resolve_section_from_top_level(config: Option<&BaseConfig>) -> Option<String> {
103 config?.registry.as_ref().and_then(|r| r.section.clone())
104}
105
106fn resolve_section_from_named_registry(config: Option<&BaseConfig>, url: &str) -> Option<String> {
107 let config = config?;
108 let use_name = config.registry_use()?;
109 let registries = config.registries_map();
110
111 registries
112 .iter()
113 .find(|(name, r)| *name == &use_name || r.url.as_deref() == Some(url))
114 .and_then(|(_, r)| {
115 r.section
117 .clone()
118 .or_else(|| r.sections.as_ref().and_then(|s| s.first().cloned()))
120 })
121}
122
123pub fn load_registry(
140 spec: &RegistrySpec,
141 cache_dir: &Path,
142 state_file: &Path,
143 use_cache: bool,
144 logger: &dyn LoggerTrait,
145) -> Result<RegistryLoadResult, Error> {
146 logger.debug(&format!(
147 "[registry] loading: url={}, ref={}, section={}, local={}",
148 spec.url,
149 spec.r#ref,
150 spec.section.as_deref().unwrap_or("(root)"),
151 is_local_path(&spec.url),
152 ));
153 if is_local_path(&spec.url) {
154 load_local_registry(spec, logger)
155 } else {
156 evict_stale_cache(spec, state_file, logger);
158 load_git_registry(spec, cache_dir, use_cache, logger)
159 }
160}
161
162fn is_local_path(url: &str) -> bool {
163 url.starts_with('/')
164 || url.starts_with("./")
165 || url.starts_with("../")
166 || url == "."
167 || url == ".."
168 || Path::new(url).exists()
169}
170
171fn evict_stale_cache(spec: &RegistrySpec, state_file: &Path, logger: &dyn LoggerTrait) {
181 use crate::engine::models::state::AppState;
182
183 let state = match AppState::load(state_file) {
184 Ok(s) => s,
185 Err(_) => return,
186 };
187
188 let prev = match state.registry {
189 Some(r) => r,
190 None => return,
191 };
192
193 if prev.url != spec.url || prev.r#ref == spec.r#ref {
195 return;
196 }
197
198 logger.debug(&format!(
199 "[registry] ref changed ({} → {}) — evicting old cache",
200 prev.r#ref, spec.r#ref,
201 ));
202
203 let old_cache = PathBuf::from(&prev.cache_path);
204 if old_cache.exists() {
205 match std::fs::remove_dir_all(&old_cache) {
206 Ok(_) => logger.debug(&format!("[registry] evicted old cache: {:?}", old_cache)),
207 Err(e) => logger.warn(&format!(
208 "[registry] failed to evict old cache {:?}: {e}",
209 old_cache
210 )),
211 }
212 }
213}
214
215fn load_local_registry(
220 spec: &RegistrySpec,
221 logger: &dyn LoggerTrait,
222) -> Result<RegistryLoadResult, Error> {
223 let base = PathBuf::from(&spec.url);
224 let dir = match &spec.section {
225 Some(section) => base.join(section),
226 None => base,
227 };
228
229 logger.debug(&format!("[registry] local path resolved to: {:?}", dir));
230
231 if !dir.exists() {
232 logger.warn(&format!("[registry] local path does not exist: {:?}", dir));
233 return Err(ErrorCode::RegistrySectionMissing
234 .error()
235 .with_context("path", dir.display().to_string()));
236 }
237
238 let config = read_registry_dir(&dir, logger)?;
239
240 Ok(RegistryLoadResult {
241 config,
242 resolved_commit: "local".to_string(),
244 })
245}
246
247fn load_git_registry(
252 spec: &RegistrySpec,
253 cache_dir: &Path,
254 use_cache: bool,
255 logger: &dyn LoggerTrait,
256) -> Result<RegistryLoadResult, Error> {
257 let registry_id = registry_cache_id(&spec.url, &spec.r#ref);
258 let registry_path = cache_dir.join("registries").join(®istry_id);
259
260 if !use_cache && registry_path.exists() {
262 logger.debug("[registry] cache disabled — removing cached copy");
263 let _ = std::fs::remove_dir_all(®istry_path);
264 }
265
266 logger.debug(&format!(
267 "[registry] cache path: {:?}, exists={}",
268 registry_path,
269 registry_path.exists()
270 ));
271
272 if registry_path.exists() {
273 if is_version_tag(&spec.r#ref) {
275 logger.debug(&format!(
276 "[registry] cache hit, version tag {} — skipping sync",
277 spec.r#ref
278 ));
279 } else {
280 logger.debug(&format!(
281 "[registry] cache hit, ref={} — checking for remote changes",
282 spec.r#ref
283 ));
284 if let Err(e) = maybe_sync_registry(®istry_path, spec, logger) {
286 logger.warn(&format!(
287 "[registry] sync failed, using cached copy of {}: {e}",
288 spec.url
289 ));
290 }
291 }
292 } else {
293 logger.debug("[registry] no cache — cloning repository");
295 clone_registry(®istry_path, spec)?;
296 if !is_version_tag(&spec.r#ref) {
297 logger.debug(&format!("[registry] checking out ref: {}", spec.r#ref));
298 checkout_registry(®istry_path, spec)?;
299 }
300 }
301
302 let dir = match &spec.section {
303 Some(section) => registry_path.join(section),
304 None => registry_path.clone(),
305 };
306
307 logger.debug(&format!(
308 "[registry] reading config from dir: {:?}, exists={}",
309 dir,
310 dir.exists()
311 ));
312
313 if !dir.exists() {
314 logger.warn(&format!(
315 "[registry] section directory not found: {:?}",
316 dir
317 ));
318 return Err(ErrorCode::RegistrySectionMissing
319 .error()
320 .with_context("section", spec.section.as_deref().unwrap_or("(root)"))
321 .with_context("path", dir.display().to_string()));
322 }
323
324 let config = read_registry_dir(&dir, logger)?;
325 let resolved_commit = get_resolved_commit(®istry_path)?;
326 logger.trace(&format!("[registry] resolved commit: {}", resolved_commit));
327
328 Ok(RegistryLoadResult {
329 config,
330 resolved_commit,
331 })
332}
333
334fn registry_cache_id(url: &str, git_ref: &str) -> String {
335 use std::collections::hash_map::DefaultHasher;
336 use std::hash::{Hash, Hasher};
337 let mut h = DefaultHasher::new();
338 format!("{url}#{git_ref}").hash(&mut h);
339 format!("{:x}", h.finish())
340}
341
342pub fn registry_cache_path(url: &str, git_ref: &str, cache_dir: &Path) -> PathBuf {
345 let id = registry_cache_id(url, git_ref);
346 cache_dir.join("registries").join(id)
347}
348
349fn run_git(args: &[&str], cwd: &Path) -> Result<(), Error> {
350 let output = Command::new("git")
351 .current_dir(cwd)
352 .args(args)
353 .output()
354 .map_err(|e| {
355 ErrorCode::GitCommandFailed
356 .error()
357 .with_context("command", format!("git {}", args.join(" ")))
358 .with_context("error", e.to_string())
359 })?;
360
361 if !output.status.success() {
362 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
363 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
364 return Err(ErrorCode::RegistrySyncFailed
365 .error()
366 .with_context("command", format!("git {}", args.join(" ")))
367 .with_context("stderr", stderr)
368 .with_context("stdout", stdout));
369 }
370 Ok(())
371}
372
373fn clone_registry(dest: &Path, spec: &RegistrySpec) -> Result<(), Error> {
374 if let Some(parent) = dest.parent() {
375 std::fs::create_dir_all(parent).map_err(|e| {
376 ErrorCode::RegistrySyncFailed
377 .error()
378 .with_context("action", "create cache directory")
379 .with_context("path", parent.display().to_string())
380 .with_context("error", e.to_string())
381 })?;
382 }
383
384 let dest_str = dest.to_str().ok_or_else(|| {
385 ErrorCode::RegistrySyncFailed
386 .error()
387 .with_context("action", "clone registry")
388 .with_context("error", "cache path contains non-UTF8 characters")
389 .with_context("path", dest.display().to_string())
390 })?;
391
392 run_git(
393 &if is_version_tag(&spec.r#ref) {
396 vec![
397 "clone",
398 "--depth",
399 "1",
400 "--branch",
401 &spec.r#ref,
402 &spec.url,
403 dest_str,
404 ]
405 } else {
406 vec![
407 "clone",
408 "--depth",
409 "1",
410 "--no-single-branch",
411 &spec.url,
412 dest_str,
413 ]
414 },
415 dest.parent().unwrap_or(Path::new(".")),
416 )
417 .map_err(|e| {
418 e.with_context("url", spec.url.clone())
419 .with_context("action", "clone registry")
420 })
421}
422
423fn maybe_sync_registry(
429 dest: &Path,
430 spec: &RegistrySpec,
431 logger: &dyn LoggerTrait,
432) -> Result<(), Error> {
433 if has_remote_changes(dest)? {
434 logger.info("[registry] remote has changes — fetching");
435 fetch_registry(dest, spec)?;
436 logger.info(&format!("[registry] checking out ref: {}", spec.r#ref));
437 checkout_registry(dest, spec)?;
438 } else {
439 logger.info("[registry] no remote changes — using cache");
440 }
441 Ok(())
442}
443
444fn is_version_tag(r#ref: &str) -> bool {
448 r#ref.starts_with('v')
450 && r#ref.len() > 1
451 && r#ref[1..].chars().next().map_or(false, char::is_numeric)
452}
453
454fn has_remote_changes(repo_path: &Path) -> Result<bool, Error> {
459 let _ = run_git(&["fetch", "--depth", "1", "origin"], repo_path);
461
462 let local_head = get_resolved_commit(repo_path)?;
464
465 let output = Command::new("git")
467 .current_dir(repo_path)
468 .args(["rev-parse", "origin/HEAD"])
469 .output();
470
471 match output {
472 Ok(o) if o.status.success() => {
473 let remote_head = String::from_utf8_lossy(&o.stdout).trim().to_string();
474 Ok(local_head != remote_head)
476 }
477 _ => {
478 Ok(false)
480 }
481 }
482}
483
484fn fetch_registry(dest: &Path, spec: &RegistrySpec) -> Result<(), Error> {
485 run_git(&["fetch", "--depth", "1", "origin"], dest).map_err(|e| {
486 e.with_context("url", spec.url.clone())
487 .with_context("action", "fetch registry updates")
488 })
489}
490
491fn checkout_registry(dest: &Path, spec: &RegistrySpec) -> Result<(), Error> {
492 run_git(&["checkout", &spec.r#ref], dest).map_err(|e| {
493 e.with_context("ref", spec.r#ref.clone())
494 .with_context("action", "checkout registry ref")
495 })
496}
497
498fn get_resolved_commit(repo_path: &Path) -> Result<String, Error> {
499 let output = Command::new("git")
500 .current_dir(repo_path)
501 .args(["rev-parse", "HEAD"])
502 .output()
503 .map_err(|e| {
504 ErrorCode::GitCommandFailed
505 .error()
506 .with_context("command", "git rev-parse HEAD")
507 .with_context("error", e.to_string())
508 })?;
509
510 if !output.status.success() {
511 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
512 return Err(ErrorCode::RegistrySyncFailed
513 .error()
514 .with_context("command", "git rev-parse HEAD")
515 .with_context("stderr", stderr));
516 }
517
518 Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
519}
520
521fn read_registry_dir(dir: &Path, logger: &dyn LoggerTrait) -> Result<AvailableConfig, Error> {
526 let config_path = dir.join("config.toml");
527 let rules_path = dir.join("rules.toml");
528
529 logger.debug(&format!(
530 "[registry] config.toml: {:?}, exists={}",
531 config_path,
532 config_path.exists()
533 ));
534 logger.debug(&format!(
535 "[registry] rules.toml: {:?}, exists={}",
536 rules_path,
537 rules_path.exists()
538 ));
539
540 if !config_path.exists() {
542 logger.warn(&format!(
543 "[registry] config.toml missing at {:?}",
544 config_path
545 ));
546 return Err(ErrorCode::RegistryInvalid
547 .error()
548 .with_context("missing_file", config_path.display().to_string()));
549 }
550
551 let base: Option<BaseConfig> = load_standard_config(&config_path).map(|sc| {
552 use crate::engine::config::resolver::extract_config_from_standard_config;
553 extract_config_from_standard_config(&sc)
554 });
555
556 match &base {
557 Some(b) => logger.trace(&format!(
558 "[registry] config.toml parsed ok: commit.types={:?}",
559 b.commit
560 .as_ref()
561 .and_then(|c| c.types.as_ref())
562 .map(|t| t.keys().cloned().collect::<Vec<_>>()),
563 )),
564 None => {
565 logger.warn("[registry] config.toml exists but failed to parse — base config is None")
566 }
567 }
568
569 let rules: Option<RulesConfig> = rules_path
571 .exists()
572 .then(|| load_rules_config(&rules_path))
573 .flatten();
574
575 match &rules {
576 Some(_) => logger.debug("[registry] rules.toml parsed ok"),
577 None if rules_path.exists() => {
578 logger.warn("[registry] rules.toml exists but failed to parse")
579 }
580 None => logger.debug("[registry] rules.toml not present (optional)"),
581 }
582
583 Ok(resolve_available_config(base, rules))
584}