Skip to main content

git2db/
config.rs

1//! Configuration for git2db operations
2//!
3//! This module uses the `config` crate directly for maximum flexibility.
4//! Configuration sources are loaded in priority order:
5//! 1. Programmatic overrides (`.set_override()`)
6//! 2. Environment variables (`GIT2DB__*`)
7//! 3. Config file (`~/.config/git2db/config.toml`)
8//! 4. Default values
9//!
10//! # Basic Usage
11//!
12//! ```rust,ignore
13//! use git2db::config::Git2DBConfig;
14//!
15//! // Simple case - use defaults
16//! let config = Git2DBConfig::load()?;
17//! ```
18//!
19//! # Programmatic Overrides
20//!
21//! ```rust,ignore
22//! use git2db::config::Git2DBConfig;
23//!
24//! let config: Git2DBConfig = Git2DBConfig::builder()?
25//!     .set_override("network.timeout_secs", 60)?
26//!     .set_override("performance.max_repo_cache", 200)?
27//!     .build()?
28//!     .try_deserialize()?;
29//! ```
30//!
31//! # Custom Config Files
32//!
33//! ```rust,ignore
34//! use git2db::config::Git2DBConfig;
35//! use config::File;
36//!
37//! let config: Git2DBConfig = Git2DBConfig::builder()?
38//!     .add_source(File::with_name("/custom/config"))?
39//!     .build()?
40//!     .try_deserialize()?;
41//! ```
42
43use anyhow::{Context, Result};
44use serde::{Deserialize, Serialize};
45use std::path::PathBuf;
46
47/// Main configuration for git2db operations
48#[derive(Debug, Clone, Serialize, Deserialize, Default)]
49pub struct Git2DBConfig {
50    /// Repository management configuration
51    pub repository: RepositoryConfig,
52    /// Network and authentication configuration
53    pub network: NetworkConfig,
54    /// Performance and caching configuration
55    pub performance: PerformanceConfig,
56    /// Default signature for commits
57    pub signature: GitSignature,
58    /// Worktree strategy configuration
59    #[serde(default)]
60    pub worktree: WorktreeConfig,
61    /// GitTorrent P2P transport configuration (optional, requires gittorrent-transport feature)
62    #[cfg(feature = "gittorrent-transport")]
63    #[serde(default)]
64    pub gittorrent: hyprstream_p2p::service::GitTorrentConfig,
65    /// XET large file storage configuration (optional, requires xet-storage feature)
66    #[cfg(feature = "xet-storage")]
67    #[serde(default)]
68    pub xet: XetConfig,
69}
70
71impl Git2DBConfig {
72    /// Create a configuration builder with git2db defaults
73    ///
74    /// Returns the native `config::ConfigBuilder` for maximum flexibility.
75    /// This follows the same pattern as gittorrent for consistency.
76    ///
77    /// **Default Priority Order (highest to lowest):**
78    /// 1. Programmatic overrides (`.set_override()`)
79    /// 2. Environment variables (`GIT2DB__*`)
80    /// 3. Config file (`~/.config/git2db/config.toml`)
81    /// 4. Default values
82    ///
83    /// # Basic Usage
84    ///
85    /// ```rust,ignore
86    /// use git2db::config::Git2DBConfig;
87    ///
88    /// // Simple case - use defaults
89    /// let config: Git2DBConfig = Git2DBConfig::builder()?
90    ///     .build()?
91    ///     .try_deserialize()?;
92    /// ```
93    ///
94    /// # Programmatic Overrides
95    ///
96    /// ```rust,ignore
97    /// use git2db::config::Git2DBConfig;
98    ///
99    /// let config: Git2DBConfig = Git2DBConfig::builder()?
100    ///     .set_override("network.timeout_secs", 60)?
101    ///     .set_override("performance.max_repo_cache", 200)?
102    ///     .build()?
103    ///     .try_deserialize()?;
104    /// ```
105    ///
106    /// # Custom Config Sources
107    ///
108    /// ```rust,ignore
109    /// use git2db::config::Git2DBConfig;
110    /// use config::File;
111    ///
112    /// let config: Git2DBConfig = Git2DBConfig::builder()?
113    ///     .add_source(File::with_name("/custom/config"))  // Highest priority
114    ///     .build()?
115    ///     .try_deserialize()?;
116    /// ```
117    ///
118    /// # Supported Environment Variables
119    ///
120    /// - `GIT2DB_REPOSITORY__PREFER_SHALLOW`: Enable shallow clones (bool)
121    /// - `GIT2DB_REPOSITORY__AUTO_INIT_SUBMODULES`: Auto-init submodules on open (bool)
122    /// - `GIT2DB_NETWORK__TIMEOUT_SECS`: Network timeout in seconds (u64)
123    /// - `GIT2DB_PERFORMANCE__MAX_REPO_CACHE`: Max cached repos (usize)
124    /// - `GIT2DB_SIGNATURE__NAME`: Git commit author name
125    /// - `GIT2DB_SIGNATURE__EMAIL`: Git commit author email
126    /// - `GIT2DB_WORKTREE__DRIVER`: Storage driver selection (overlay2, vfs, reflink)
127    /// - `GIT2DB_WORKTREE__LOG_DRIVER`: Log driver selection decisions (bool)
128    /// - `GIT2DB_GITTORRENT__P2P_PORT`: GitTorrent P2P port (requires feature)
129    pub fn builder() -> Result<config::ConfigBuilder<config::builder::DefaultState>> {
130        Ok(config::Config::builder()
131            // Set defaults (lowest priority)
132            .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 config file (optional, medium priority)
152            .add_source(
153                config::File::from(Self::default_config_path().unwrap_or_default()).required(false),
154            )
155            // Add environment variables (high priority)
156            .add_source(
157                config::Environment::with_prefix("GIT2DB")
158                    .separator("__")
159                    .try_parsing(true)
160                    .ignore_empty(true),
161            ))
162    }
163
164    /// Convenience method to load configuration with defaults
165    ///
166    /// This is equivalent to `Git2DBConfig::builder()?.build()?.try_deserialize()?`
167    ///
168    /// # Example
169    ///
170    /// ```rust,ignore
171    /// use git2db::config::Git2DBConfig;
172    ///
173    /// let config = Git2DBConfig::load()?;
174    /// ```
175    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        // Debug log
185        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    /// Get the default config file path (~/.config/git2db/config.toml)
196    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/// Repository-specific configuration
218#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct RepositoryConfig {
220    /// Enable shallow clones by default
221    pub prefer_shallow: bool,
222    /// Default clone depth for shallow clones
223    pub shallow_depth: Option<u32>,
224    /// Automatically create initial commit for new registries
225    pub auto_init: bool,
226    /// Automatically initialize and update submodules when opening registry
227    ///
228    /// When true (default), opening a registry will call `git submodule init`
229    /// and `git submodule update` to ensure all tracked repositories are
230    /// available. This is equivalent to `git clone --recurse-submodules`.
231    ///
232    /// Set to false if you want manual control over submodule initialization.
233    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/// Network and authentication configuration
248///
249/// Field naming convention: All timeout/duration fields use unit suffixes:
250/// - `*_secs` = seconds (u64)
251/// - `*_ms` = milliseconds (u64)
252///
253/// This ensures clear time unit specification in configuration files and environment variables.
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct NetworkConfig {
256    /// Network timeout for operations (in seconds)
257    #[serde(default = "default_network_timeout_secs")]
258    pub timeout_secs: u64,
259    /// Maximum retry attempts for network operations
260    #[serde(default = "default_max_retries")]
261    pub max_retries: usize,
262    /// Base delay for exponential backoff (in milliseconds)
263    #[serde(default = "default_retry_base_delay_ms")]
264    pub retry_base_delay_ms: u64,
265    /// Maximum delay between retries (in seconds)
266    #[serde(default = "default_retry_max_delay_secs")]
267    pub retry_max_delay_secs: u64,
268    /// Proxy configuration
269    pub proxy_url: Option<String>,
270    /// User agent for HTTP requests
271    #[serde(default = "default_user_agent")]
272    pub user_agent: String,
273    /// Enable git credential helper (default credentials)
274    /// This allows using system git credentials, SSH agents, etc.
275    #[serde(default = "default_use_credential_helper")]
276    pub use_credential_helper: bool,
277    /// Personal access token (e.g., for GitHub, GitLab, Hugging Face)
278    /// Can also be set via GIT2DB_NETWORK__ACCESS_TOKEN env var
279    pub access_token: Option<String>,
280    /// The exact origin host (e.g. `"github.com"`) that `access_token` is
281    /// bound to. When set, the default clone path attaches the token scoped to
282    /// this host — it is only offered to a remote whose URL host matches. When
283    /// unset, the token is **not** attached to the default clone path at all
284    /// (fail-closed against exfiltration to a caller-selected remote). See
285    /// issue #1429.
286    #[serde(default)]
287    pub access_token_host: Option<String>,
288}
289
290fn default_use_credential_helper() -> bool {
291    // Default off: ambient credential discovery (git credential helper,
292    // ~/.gitconfig, SSH agent) is an explicit opt-in. The secure default for
293    // git2db clones is strict certificates + ExplicitOnly auth, so an
294    // untrusted/forge-facing fetch cannot pick up operator credentials. See
295    // issue #1429.
296    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/// Performance and caching configuration
356///
357/// Field naming convention: All timeout/duration fields use unit suffixes:
358/// - `*_secs` = seconds (u64)
359/// - Cache sizes use `*_cache` suffix (usize)
360///
361/// This ensures clear time unit and size specification in configuration files and environment variables.
362#[derive(Debug, Clone, Serialize, Deserialize)]
363pub struct PerformanceConfig {
364    /// Maximum number of cached repository handles
365    #[serde(default = "default_max_repo_cache")]
366    pub max_repo_cache: usize,
367    /// Repository cache TTL (in seconds)
368    #[serde(default = "default_repo_cache_ttl_secs")]
369    pub repo_cache_ttl_secs: u64,
370    /// Enable automatic cache cleanup
371    #[serde(default = "default_auto_cleanup")]
372    pub auto_cleanup: bool,
373    /// Cleanup interval (in seconds)
374    #[serde(default = "default_cleanup_interval_secs")]
375    pub cleanup_interval_secs: u64,
376    /// Maximum concurrent git operations
377    #[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/// Git signature configuration
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct GitSignature {
396    /// Name for git commits
397    pub name: String,
398    /// Email for git commits
399    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    /// Create a new signature
413    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    /// Create a git2::Signature from this configuration
421    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        // Test JSON serialization
492        let json = serde_json::to_string(&config)?;
493        assert!(json.contains("\"prefer_shallow\":true"));
494        assert!(json.contains("\"max_repo_cache\":100"));
495
496        // Test deserialization
497        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        // Should be able to create git2 signature
516        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        // Test that builder() returns a ConfigBuilder
525        let builder = Git2DBConfig::builder();
526        assert!(builder.is_ok());
527    }
528
529    #[test]
530    fn test_config_components_independently() {
531        // Test each config component can be created with custom values
532        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        // Test building a complete config manually
569        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        // Test with owned strings
593        let sig1 = GitSignature::new("User1".to_owned(), "user1@example.com".to_owned());
594        assert_eq!(sig1.name, "User1");
595
596        // Test with &str
597        let sig2 = GitSignature::new("User2", "user2@example.com");
598        assert_eq!(sig2.name, "User2");
599
600        // Test with String references
601        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/// Worktree storage driver configuration
609///
610/// Configuration now requires explicit driver specification.
611/// Auto-detection and fallback behavior have been removed for simplicity.
612///
613/// # Configuration Sources
614///
615/// Use environment variables (highest priority):
616/// - `GIT2DB__WORKTREE__DRIVER=overlay2`
617/// - `GIT2DB__WORKTREE__LOG_DRIVER=true`
618///
619/// Or config file:
620/// ```toml
621/// [worktree]
622/// driver = "overlay2"  # or "vfs", "reflink"
623/// ```
624///
625/// # Example
626///
627/// ```toml
628/// [worktree]
629/// driver = "overlay2"  # or "vfs", "reflink"
630/// ```
631#[derive(Debug, Clone, Serialize, Deserialize)]
632pub struct WorktreeConfig {
633    /// Storage driver selection
634    ///
635    /// Options:
636    /// - "overlay2": Linux overlayfs (~80% space savings)
637    /// - "vfs": Plain directories (always works, no optimization)
638    /// - "reflink": Cross-platform copy-on-write support
639    ///
640    /// Default: "vfs" (safe fallback)
641    #[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/// XET large file storage configuration
658///
659/// Re-exported from git-xet-filter for convenience.
660/// The xet-filter crate can be used standalone.
661#[cfg(feature = "xet-storage")]
662pub use git_xet_filter::XetConfig;