1use anyhow::{Context, Result};
44use serde::{Deserialize, Serialize};
45use std::path::PathBuf;
46
47#[derive(Debug, Clone, Serialize, Deserialize, Default)]
49pub struct Git2DBConfig {
50 pub repository: RepositoryConfig,
52 pub network: NetworkConfig,
54 pub performance: PerformanceConfig,
56 pub signature: GitSignature,
58 #[serde(default)]
60 pub worktree: WorktreeConfig,
61 #[cfg(feature = "gittorrent-transport")]
63 #[serde(default)]
64 pub gittorrent: hyprstream_p2p::service::GitTorrentConfig,
65 #[cfg(feature = "xet-storage")]
67 #[serde(default)]
68 pub xet: XetConfig,
69}
70
71impl Git2DBConfig {
72 pub fn builder() -> Result<config::ConfigBuilder<config::builder::DefaultState>> {
130 Ok(config::Config::builder()
131 .set_default("repository.prefer_shallow", true)?
133 .set_default("repository.shallow_depth", 1)?
134 .set_default("repository.auto_init", true)?
135 .set_default("repository.auto_init_submodules", true)?
136 .set_default("network.timeout_secs", 30u64)?
137 .set_default("network.max_retries", 3)?
138 .set_default("network.retry_base_delay_ms", 500u64)?
139 .set_default("network.retry_max_delay_secs", 10u64)?
140 .set_default("network.user_agent", format!("git2db/{}", crate::VERSION))?
141 .set_default("network.use_credential_helper", false)?
142 .set_default("performance.max_repo_cache", 100)?
143 .set_default("performance.repo_cache_ttl_secs", 300u64)?
144 .set_default("performance.auto_cleanup", true)?
145 .set_default("performance.cleanup_interval_secs", 60u64)?
146 .set_default("performance.max_concurrent_ops", 10)?
147 .set_default("worktree.driver", "vfs")?
148 .set_default("worktree.log_driver", true)?
149 .set_default("signature.name", "git2db")?
150 .set_default("signature.email", "git2db@local")?
151 .add_source(
153 config::File::from(Self::default_config_path().unwrap_or_default()).required(false),
154 )
155 .add_source(
157 config::Environment::with_prefix("GIT2DB")
158 .separator("__")
159 .try_parsing(true)
160 .ignore_empty(true),
161 ))
162 }
163
164 pub fn load() -> Result<Self> {
176 let config = Self::builder()?
177 .build()
178 .context("Failed to build configuration")?;
179
180 let deserialized: Self = config
181 .try_deserialize()
182 .context("Failed to deserialize configuration. This might be due to:\n - Invalid config file format\n - Invalid environment variable values\n - Type mismatches in config")?;
183
184 tracing::info!(
186 "Loaded git2db config: token present = {}, use_cred_helper = {}, worktree.driver = {}",
187 deserialized.network.access_token.is_some(),
188 deserialized.network.use_credential_helper,
189 deserialized.worktree.driver
190 );
191
192 Ok(deserialized)
193 }
194
195 fn default_config_path() -> Option<PathBuf> {
197 #[cfg(target_os = "linux")]
198 {
199 if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
200 return Some(PathBuf::from(xdg_config).join("git2db").join("config.toml"));
201 }
202 }
203
204 if let Ok(home) = std::env::var("HOME") {
205 return Some(
206 PathBuf::from(home)
207 .join(".config")
208 .join("git2db")
209 .join("config.toml"),
210 );
211 }
212
213 None
214 }
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct RepositoryConfig {
220 pub prefer_shallow: bool,
222 pub shallow_depth: Option<u32>,
224 pub auto_init: bool,
226 pub auto_init_submodules: bool,
234}
235
236impl Default for RepositoryConfig {
237 fn default() -> Self {
238 Self {
239 prefer_shallow: true,
240 shallow_depth: Some(1),
241 auto_init: true,
242 auto_init_submodules: true,
243 }
244 }
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct NetworkConfig {
256 #[serde(default = "default_network_timeout_secs")]
258 pub timeout_secs: u64,
259 #[serde(default = "default_max_retries")]
261 pub max_retries: usize,
262 #[serde(default = "default_retry_base_delay_ms")]
264 pub retry_base_delay_ms: u64,
265 #[serde(default = "default_retry_max_delay_secs")]
267 pub retry_max_delay_secs: u64,
268 pub proxy_url: Option<String>,
270 #[serde(default = "default_user_agent")]
272 pub user_agent: String,
273 #[serde(default = "default_use_credential_helper")]
276 pub use_credential_helper: bool,
277 pub access_token: Option<String>,
280 #[serde(default)]
287 pub access_token_host: Option<String>,
288}
289
290fn default_use_credential_helper() -> bool {
291 false
297}
298
299fn default_network_timeout_secs() -> u64 {
300 30
301}
302
303fn default_max_retries() -> usize {
304 3
305}
306
307fn default_retry_base_delay_ms() -> u64 {
308 500
309}
310
311fn default_retry_max_delay_secs() -> u64 {
312 10
313}
314
315fn default_user_agent() -> String {
316 format!("git2db/{}", crate::VERSION)
317}
318
319fn default_max_repo_cache() -> usize {
320 100
321}
322
323fn default_repo_cache_ttl_secs() -> u64 {
324 300
325}
326
327fn default_auto_cleanup() -> bool {
328 true
329}
330
331fn default_cleanup_interval_secs() -> u64 {
332 60
333}
334
335fn default_max_concurrent_ops() -> usize {
336 10
337}
338
339impl Default for NetworkConfig {
340 fn default() -> Self {
341 Self {
342 timeout_secs: default_network_timeout_secs(),
343 max_retries: default_max_retries(),
344 retry_base_delay_ms: default_retry_base_delay_ms(),
345 retry_max_delay_secs: default_retry_max_delay_secs(),
346 proxy_url: None,
347 user_agent: default_user_agent(),
348 use_credential_helper: default_use_credential_helper(),
349 access_token: None,
350 access_token_host: None,
351 }
352 }
353}
354
355#[derive(Debug, Clone, Serialize, Deserialize)]
363pub struct PerformanceConfig {
364 #[serde(default = "default_max_repo_cache")]
366 pub max_repo_cache: usize,
367 #[serde(default = "default_repo_cache_ttl_secs")]
369 pub repo_cache_ttl_secs: u64,
370 #[serde(default = "default_auto_cleanup")]
372 pub auto_cleanup: bool,
373 #[serde(default = "default_cleanup_interval_secs")]
375 pub cleanup_interval_secs: u64,
376 #[serde(default = "default_max_concurrent_ops")]
378 pub max_concurrent_ops: usize,
379}
380
381impl Default for PerformanceConfig {
382 fn default() -> Self {
383 Self {
384 max_repo_cache: default_max_repo_cache(),
385 repo_cache_ttl_secs: default_repo_cache_ttl_secs(),
386 auto_cleanup: default_auto_cleanup(),
387 cleanup_interval_secs: default_cleanup_interval_secs(),
388 max_concurrent_ops: default_max_concurrent_ops(),
389 }
390 }
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct GitSignature {
396 pub name: String,
398 pub email: String,
400}
401
402impl Default for GitSignature {
403 fn default() -> Self {
404 Self {
405 name: "git2db".to_owned(),
406 email: "git2db@local".to_owned(),
407 }
408 }
409}
410
411impl GitSignature {
412 pub fn new<N: Into<String>, E: Into<String>>(name: N, email: E) -> Self {
414 Self {
415 name: name.into(),
416 email: email.into(),
417 }
418 }
419
420 pub fn to_git2_signature(&self) -> Result<git2::Signature<'static>, git2::Error> {
422 git2::Signature::now(&self.name, &self.email)
423 }
424}
425
426#[cfg(test)]
427mod tests {
428 use super::*;
429
430 #[test]
431 fn test_default_config() {
432 let config = Git2DBConfig::default();
433 assert!(config.repository.prefer_shallow);
434 assert_eq!(config.repository.shallow_depth, Some(1));
435 assert_eq!(config.network.timeout_secs, 30);
436 assert_eq!(config.performance.max_repo_cache, 100);
437 }
438
439 #[test]
440 fn test_git_signature() -> Result<(), git2::Error> {
441 let sig = GitSignature::new("Test User", "test@example.com");
442 assert_eq!(sig.name, "Test User");
443 assert_eq!(sig.email, "test@example.com");
444
445 let git2_sig = sig.to_git2_signature()?;
446 assert_eq!(git2_sig.name(), Some("Test User"));
447 assert_eq!(git2_sig.email(), Some("test@example.com"));
448 Ok(())
449 }
450
451 #[test]
452 fn test_repository_config_defaults() {
453 let config = RepositoryConfig::default();
454 assert!(config.prefer_shallow);
455 assert_eq!(config.shallow_depth, Some(1));
456 assert!(config.auto_init);
457 }
458
459 #[test]
460 fn test_network_config_defaults() {
461 let config = NetworkConfig::default();
462 assert_eq!(config.timeout_secs, 30);
463 assert_eq!(config.max_retries, 3);
464 assert_eq!(config.retry_base_delay_ms, 500);
465 assert_eq!(config.retry_max_delay_secs, 10);
466 assert!(config.proxy_url.is_none());
467 assert!(config.user_agent.contains("git2db"));
468 }
469
470 #[test]
471 fn test_performance_config_defaults() {
472 let config = PerformanceConfig::default();
473 assert_eq!(config.max_repo_cache, 100);
474 assert_eq!(config.repo_cache_ttl_secs, 300);
475 assert!(config.auto_cleanup);
476 assert_eq!(config.cleanup_interval_secs, 60);
477 assert_eq!(config.max_concurrent_ops, 10);
478 }
479
480 #[test]
481 fn test_git_signature_defaults() {
482 let sig = GitSignature::default();
483 assert_eq!(sig.name, "git2db");
484 assert_eq!(sig.email, "git2db@local");
485 }
486
487 #[test]
488 fn test_config_serialization() -> Result<(), serde_json::Error> {
489 let config = Git2DBConfig::default();
490
491 let json = serde_json::to_string(&config)?;
493 assert!(json.contains("\"prefer_shallow\":true"));
494 assert!(json.contains("\"max_repo_cache\":100"));
495
496 let deserialized: Git2DBConfig = serde_json::from_str(&json)?;
498 assert_eq!(
499 config.repository.prefer_shallow,
500 deserialized.repository.prefer_shallow
501 );
502 assert_eq!(
503 config.performance.max_repo_cache,
504 deserialized.performance.max_repo_cache
505 );
506 Ok(())
507 }
508
509 #[test]
510 fn test_git_signature_with_special_characters() -> Result<(), git2::Error> {
511 let sig = GitSignature::new("Test User with Ünicöde", "test+tag@example.com");
512 assert_eq!(sig.name, "Test User with Ünicöde");
513 assert_eq!(sig.email, "test+tag@example.com");
514
515 let git2_sig = sig.to_git2_signature()?;
517 assert_eq!(git2_sig.name(), Some("Test User with Ünicöde"));
518 assert_eq!(git2_sig.email(), Some("test+tag@example.com"));
519 Ok(())
520 }
521
522 #[test]
523 fn test_config_builder_returns_config_builder() {
524 let builder = Git2DBConfig::builder();
526 assert!(builder.is_ok());
527 }
528
529 #[test]
530 fn test_config_components_independently() {
531 let repo_config = RepositoryConfig {
533 prefer_shallow: false,
534 shallow_depth: Some(10),
535 auto_init: false,
536 auto_init_submodules: false,
537 };
538 assert!(!repo_config.prefer_shallow);
539 assert_eq!(repo_config.shallow_depth, Some(10));
540
541 let network_config = NetworkConfig {
542 timeout_secs: 120,
543 max_retries: 5,
544 retry_base_delay_ms: 1000,
545 retry_max_delay_secs: 30,
546 proxy_url: Some("http://proxy.example.com:8080".to_owned()),
547 user_agent: "test-agent".to_owned(),
548 use_credential_helper: true,
549 access_token: Some("test-token".to_owned()),
550 access_token_host: None,
551 };
552 assert_eq!(network_config.timeout_secs, 120);
553 assert_eq!(network_config.max_retries, 5);
554
555 let perf_config = PerformanceConfig {
556 max_repo_cache: 500,
557 repo_cache_ttl_secs: 600,
558 auto_cleanup: false,
559 cleanup_interval_secs: 120,
560 max_concurrent_ops: 50,
561 };
562 assert_eq!(perf_config.max_repo_cache, 500);
563 assert!(!perf_config.auto_cleanup);
564 }
565
566 #[test]
567 fn test_full_config_construction() {
568 let config = Git2DBConfig {
570 repository: RepositoryConfig {
571 prefer_shallow: false,
572 shallow_depth: None,
573 auto_init: false,
574 auto_init_submodules: false,
575 },
576 network: NetworkConfig::default(),
577 performance: PerformanceConfig::default(),
578 signature: GitSignature::new("Test", "test@example.com"),
579 worktree: WorktreeConfig::default(),
580 #[cfg(feature = "gittorrent-transport")]
581 gittorrent: hyprstream_p2p::service::GitTorrentConfig::default(),
582 #[cfg(feature = "xet-storage")]
583 xet: git_xet_filter::XetConfig::default(),
584 };
585
586 assert!(!config.repository.prefer_shallow);
587 assert_eq!(config.signature.name, "Test");
588 }
589
590 #[test]
591 fn test_git_signature_creation_variants() {
592 let sig1 = GitSignature::new("User1".to_owned(), "user1@example.com".to_owned());
594 assert_eq!(sig1.name, "User1");
595
596 let sig2 = GitSignature::new("User2", "user2@example.com");
598 assert_eq!(sig2.name, "User2");
599
600 let name = "User3".to_owned();
602 let email = "user3@example.com".to_owned();
603 let sig3 = GitSignature::new(&name, &email);
604 assert_eq!(sig3.name, "User3");
605 }
606}
607
608#[derive(Debug, Clone, Serialize, Deserialize)]
632pub struct WorktreeConfig {
633 #[serde(default = "default_driver")]
642 pub driver: String,
643}
644
645fn default_driver() -> String {
646 "vfs".to_owned()
647}
648
649impl Default for WorktreeConfig {
650 fn default() -> Self {
651 Self {
652 driver: "vfs".to_owned(),
653 }
654 }
655}
656
657#[cfg(feature = "xet-storage")]
662pub use git_xet_filter::XetConfig;