codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use crate::error::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub git: GitConfig,
    #[serde(default)]
    pub templates: HashMap<String, TemplateConfig>,
    #[serde(default)]
    pub validation: ValidationConfig,
    #[serde(default)]
    pub hooks: HooksConfig,
    #[serde(default)]
    pub auto: AutoConfig,
}

/// Operation template for predefined branch/commit conventions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateConfig {
    /// Prefix for branch names using this template (overrides git.branch_prefix)
    #[serde(default)]
    pub branch_prefix: Option<String>,
    /// Format string for auto-generated commit messages
    /// Use {description} as placeholder for operation description
    #[serde(default = "default_commit_format")]
    pub commit_message_format: String,
}

fn default_commit_format() -> String {
    "Save changes to {description}".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitConfig {
    /// Prefix for auto-generated branch names
    pub branch_prefix: String,
    /// Default base branch
    pub base_branch: String,
    /// Auto-push branches to remote
    pub auto_push: bool,
    /// Default remote name
    pub remote_name: String,
    /// Maximum file size in bytes for staging (0 = no limit). Prevents
    /// accidental commits of large files (e.g., binaries, logs).
    #[serde(default)]
    pub max_file_size: u64,
}

/// Pre-commit validation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationConfig {
    /// Validation mode: "off", "optional", or "required"
    #[serde(default = "default_validation_mode")]
    pub mode: String,
    /// Command to run for validation (e.g., "cargo test", "npm test")
    #[serde(default)]
    pub command: Option<String>,
}

fn default_validation_mode() -> String {
    "off".to_string()
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            mode: default_validation_mode(),
            command: None,
        }
    }
}

impl ValidationConfig {
    /// Returns true if validation should run by default
    pub fn is_required(&self) -> bool {
        self.mode == "required"
    }

    /// Returns true if validation is completely disabled
    pub fn is_off(&self) -> bool {
        self.mode == "off"
    }
}

/// Multi-stage hook configuration. Each stage can have multiple commands.
/// Stages: pre_save, post_save, pre_finish, post_finish.
/// Commands run in order. If any command fails, the stage aborts (for pre_* stages,
/// the operation is blocked; for post_* stages, the error is reported but the
/// operation already completed).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HooksConfig {
    #[serde(default)]
    pub pre_save: Vec<String>,
    #[serde(default)]
    pub post_save: Vec<String>,
    #[serde(default)]
    pub pre_finish: Vec<String>,
    #[serde(default)]
    pub post_finish: Vec<String>,
}

impl HooksConfig {
    /// Get hooks for a given stage name
    pub fn get(&self, stage: &str) -> &[String] {
        match stage {
            "pre_save" => &self.pre_save,
            "post_save" => &self.post_save,
            "pre_finish" => &self.pre_finish,
            "post_finish" => &self.post_finish,
            _ => &[],
        }
    }

    /// Returns true if any hooks are configured
    pub fn has_hooks(&self) -> bool {
        !self.pre_save.is_empty()
            || !self.post_save.is_empty()
            || !self.pre_finish.is_empty()
            || !self.post_finish.is_empty()
    }
}

impl Default for TemplateConfig {
    fn default() -> Self {
        Self {
            branch_prefix: None,
            commit_message_format: default_commit_format(),
        }
    }
}

/// Auto-commit policy configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AutoConfig {
    /// Auto-save uncommitted changes before switching branches.
    /// When false (default), `switch` snapshots the working tree instead.
    #[serde(default)]
    pub save_on_switch: bool,
}

impl Default for Config {
    fn default() -> Self {
        let mut templates = HashMap::new();
        templates.insert("refactor".to_string(), TemplateConfig {
            branch_prefix: Some("refactor".to_string()),
            commit_message_format: "Refactor: {description}".to_string(),
        });
        templates.insert("bugfix".to_string(), TemplateConfig {
            branch_prefix: Some("fix".to_string()),
            commit_message_format: "Fix: {description}".to_string(),
        });
        templates.insert("feature".to_string(), TemplateConfig {
            branch_prefix: Some("feat".to_string()),
            commit_message_format: "Feat: {description}".to_string(),
        });

        Self {
            git: GitConfig {
                branch_prefix: "codetree".to_string(),
                base_branch: "main".to_string(),
                auto_push: false,
                remote_name: "origin".to_string(),
                max_file_size: 0,
            },
            templates,
            validation: ValidationConfig::default(),
            hooks: HooksConfig::default(),
            auto: AutoConfig::default(),
        }
    }
}

impl Config {
    /// Get configuration path from optional input
    pub fn get_config_path(config_path: Option<&Path>) -> Result<PathBuf> {
        match config_path {
            Some(path) => Ok(path.to_path_buf()),
            None => Self::default_config_path(),
        }
    }

    /// Load configuration from file or create default
    pub async fn load(config_path: &Path) -> Result<Self> {
        let config_file = config_path.to_path_buf();

        if config_file.exists() {
            let content = fs::read_to_string(&config_file)
                .await
                .with_context(|| format!("Failed to read config file: {:?}", config_file))?;

            let config: Config = toml::from_str(&content)
                .with_context(|| format!("Failed to parse config file: {:?}", config_file))?;

            Ok(config)
        } else {
            // Create default config
            let config = Self::default();
            config.save(&config_file).await?;
            Ok(config)
        }
    }

    /// Save configuration to file
    pub async fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).await
                .with_context(|| format!("Failed to create config directory: {:?}", parent))?;
        }

        let content = toml::to_string_pretty(self)
            .context("Failed to serialize configuration")?;

        crate::atomic::write_atomic(path, content.as_bytes())
            .with_context(|| format!("Failed to write config file: {:?}", path))?;

        Ok(())
    }

    /// Get default configuration file path
    pub fn default_config_path() -> Result<PathBuf> {
        let current_dir = std::env::current_dir()
            .context("Failed to get current directory")?;

        // First try .codetree.toml in current directory
        let local_config = current_dir.join(".codetree.toml");
        if local_config.exists() {
            return Ok(local_config);
        }

        // Then try global config directory
        if let Ok(home) = std::env::var("HOME") {
            let global_config = PathBuf::from(home)
                .join(".config")
                .join("codetree")
                .join("config.toml");
            return Ok(global_config);
        }

        // Fallback to local config
        Ok(local_config)
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<()> {
        if self.git.branch_prefix.is_empty() {
            bail!("branch_prefix cannot be empty");
        }
        if self.git.base_branch.is_empty() {
            bail!("base_branch cannot be empty");
        }
        Ok(())
    }

    /// Get template by name, returns None if not found
    pub fn get_template(&self, name: &str) -> Option<&TemplateConfig> {
        self.templates.get(name)
    }

    /// Get codetree data directory
    pub fn get_data_dir() -> Result<PathBuf> {
        let current_dir = std::env::current_dir()
            .context("Failed to get current directory")?;

        Ok(current_dir.join(".codetree"))
    }

    /// Check if codetree is initialized in current directory
    pub async fn is_initialized() -> Result<bool> {
        let data_dir = Self::get_data_dir()?;
        Ok(data_dir.exists())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_config_default_values() {
        let config = Config::default();

        assert_eq!(config.git.branch_prefix, "codetree");
        assert_eq!(config.git.base_branch, "main");
    }

    #[tokio::test]
    async fn test_config_save_and_load() -> Result<()> {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.toml");

        // Create and save config
        let mut config = Config::default();
        config.git.branch_prefix = "agent".to_string();
        config.git.base_branch = "main".to_string();
        config.save(&config_path).await?;

        // Load and verify
        let loaded_config = Config::load(&config_path).await?;
        assert_eq!(loaded_config.git.branch_prefix, "agent");
        assert_eq!(loaded_config.git.base_branch, "main");

        Ok(())
    }

    #[tokio::test]
    async fn test_config_load_nonexistent_creates_default() -> Result<()> {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("nonexistent_config.toml");

        let config = Config::load(&config_path).await?;
        assert_eq!(config.git.branch_prefix, "codetree");
        assert!(config_path.exists()); // Should create the file

        Ok(())
    }

    #[tokio::test]
    async fn test_config_validation() {
        let mut config = Config::default();

        // Test valid config
        assert!(config.validate().is_ok());

        // Test invalid empty branch prefix
        config.git.branch_prefix = "".to_string();
        assert!(config.validate().is_err());

        // Test invalid empty base branch
        config.git.branch_prefix = "codetree".to_string();
        config.git.base_branch = "".to_string();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_get_config_path() {
        let custom_path = Path::new("/custom/config.toml");
        let result = Config::get_config_path(Some(custom_path)).unwrap();
        assert_eq!(result, custom_path);

        let default_result = Config::get_config_path(None);
        assert!(default_result.is_ok());
    }

    #[test]
    fn test_get_data_dir() {
        let data_dir = Config::get_data_dir().unwrap();
        assert!(data_dir.ends_with(".codetree"));
    }

    #[tokio::test]
    async fn test_is_initialized() {
        // Test when not initialized (in current project dir, .codetree should not exist in temp)
        let _temp_dir = TempDir::new().unwrap();
        // is_initialized checks current working directory, which we can't easily change
        // Just verify the function doesn't panic
        let result = Config::is_initialized().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_config_default_fields() {
        let config = Config::default();
        assert!(!config.git.auto_push);
        assert_eq!(config.git.remote_name, "origin");
    }

    #[tokio::test]
    async fn test_config_validation_edge_cases() {
        let mut config = Config::default();

        // Both invalid
        config.git.branch_prefix = "".to_string();
        config.git.base_branch = "".to_string();
        assert!(config.validate().is_err());

        // One valid, one invalid
        config.git.branch_prefix = "codetree".to_string();
        config.git.base_branch = "".to_string();
        assert!(config.validate().is_err());

        config.git.branch_prefix = "".to_string();
        config.git.base_branch = "main".to_string();
        assert!(config.validate().is_err());
    }

    #[tokio::test]
    async fn test_config_save_overwrites_existing() -> Result<()> {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("overwrite_config.toml");

        let mut config = Config::default();
        config.git.branch_prefix = "first".to_string();
        config.save(&config_path).await?;

        let mut config2 = Config::default();
        config2.git.branch_prefix = "second".to_string();
        config2.save(&config_path).await?;

        let loaded = Config::load(&config_path).await?;
        assert_eq!(loaded.git.branch_prefix, "second");

        Ok(())
    }

    #[tokio::test]
    async fn test_config_default_templates() {
        let config = Config::default();

        assert!(config.get_template("refactor").is_some());
        assert!(config.get_template("bugfix").is_some());
        assert!(config.get_template("feature").is_some());
        assert!(config.get_template("unknown").is_none());

        let refactor = config.get_template("refactor").unwrap();
        assert_eq!(refactor.branch_prefix.as_deref(), Some("refactor"));
        assert_eq!(refactor.commit_message_format, "Refactor: {description}");

        let bugfix = config.get_template("bugfix").unwrap();
        assert_eq!(bugfix.branch_prefix.as_deref(), Some("fix"));
        assert_eq!(bugfix.commit_message_format, "Fix: {description}");
    }

    #[tokio::test]
    async fn test_config_template_save_and_load() -> Result<()> {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("template_config.toml");

        let mut config = Config::default();
        config.templates.insert("custom".to_string(), TemplateConfig {
            branch_prefix: Some("custom".to_string()),
            commit_message_format: "Custom: {description}".to_string(),
        });
        config.save(&config_path).await?;

        let loaded = Config::load(&config_path).await?;
        let custom = loaded.get_template("custom").unwrap();
        assert_eq!(custom.branch_prefix.as_deref(), Some("custom"));
        assert_eq!(custom.commit_message_format, "Custom: {description}");

        Ok(())
    }

    #[tokio::test]
    async fn test_validation_config_default() {
        let config = Config::default();
        assert!(config.validation.is_off());
        assert!(!config.validation.is_required());
        assert!(config.validation.command.is_none());
    }

    #[tokio::test]
    async fn test_validation_config_save_and_load() -> Result<()> {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("validation_config.toml");

        let mut config = Config::default();
        config.validation.mode = "required".to_string();
        config.validation.command = Some("cargo test".to_string());
        config.save(&config_path).await?;

        let loaded = Config::load(&config_path).await?;
        assert!(loaded.validation.is_required());
        assert_eq!(loaded.validation.command.as_deref(), Some("cargo test"));

        Ok(())
    }
}