ix-config 0.1.0

Hierarchical configuration loading for Ixchel
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
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;

/// Get the Ixchel home directory (`~/.ixchel` or `$IXCHEL_HOME`).
///
/// This is the root directory for all Ixchel global config/state/data.
///
/// # Environment Override
/// Set `IXCHEL_HOME` to override the default location.
#[must_use]
pub fn ixchel_home() -> PathBuf {
    if let Ok(home) = std::env::var("IXCHEL_HOME") {
        return PathBuf::from(home);
    }
    if let Ok(home) = std::env::var("HELIX_HOME") {
        return PathBuf::from(home);
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".ixchel")
}

/// Get the config directory (`~/.ixchel/config`).
///
/// Contains user-editable TOML configuration files.
#[must_use]
pub fn ixchel_config_dir() -> PathBuf {
    ixchel_home().join("config")
}

/// Get the data directory (`~/.ixchel/data`).
///
/// Contains caches and databases (auto-generated, safe to delete).
#[must_use]
pub fn ixchel_data_dir() -> PathBuf {
    ixchel_home().join("data")
}

/// Get the state directory (`~/.ixchel/state`).
///
/// Contains runtime metadata (agents, locks, ephemeral caches).
#[must_use]
pub fn ixchel_state_dir() -> PathBuf {
    ixchel_home().join("state")
}

/// Get the log directory (`~/.ixchel/log`).
///
/// Contains operation logs for debugging.
#[must_use]
pub fn ixchel_log_dir() -> PathBuf {
    ixchel_home().join("log")
}

/// Shared configuration used by multiple Ixchel tools.
///
/// Loaded from `~/.ixchel/config/config.toml` and `.ixchel/config.toml`.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct IxchelConfig {
    #[serde(default)]
    pub github: GitHubConfig,
    #[serde(default)]
    pub embedding: EmbeddingConfig,
    #[serde(default)]
    pub storage: StorageConfig,
}

pub type SharedConfig = IxchelConfig;

/// GitHub-related configuration.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct GitHubConfig {
    /// GitHub personal access token. Can also be set via `GITHUB_TOKEN` or `GH_TOKEN`.
    pub token: Option<String>,
}

/// Embedding model configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EmbeddingConfig {
    /// Provider implementation to use (e.g. "fastembed").
    #[serde(default = "default_embedding_provider")]
    pub provider: String,
    /// The embedding model to use.
    #[serde(default = "default_embedding_model")]
    pub model: String,
    /// Batch size for embedding operations.
    #[serde(default = "default_batch_size")]
    pub batch_size: usize,
    /// Optional dimension override for providers that don't advertise dims.
    #[serde(default)]
    pub dimension: Option<usize>,
}

impl Default for EmbeddingConfig {
    fn default() -> Self {
        Self {
            provider: default_embedding_provider(),
            model: default_embedding_model(),
            batch_size: default_batch_size(),
            dimension: None,
        }
    }
}

fn default_embedding_provider() -> String {
    "fastembed".to_string()
}

fn default_embedding_model() -> String {
    "BAAI/bge-small-en-v1.5".to_string()
}

const fn default_batch_size() -> usize {
    32
}

/// Storage configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StorageConfig {
    /// Storage backend to use (e.g. "helixdb", "surrealdb").
    #[serde(default = "default_storage_backend")]
    pub backend: String,

    /// Path relative to `.ixchel/` for rebuildable storage.
    #[serde(default = "default_storage_path")]
    pub path: String,

    /// Storage engine for backends that support multiple engines.
    ///
    /// For `SurrealDB`: "rocksdb" (default) or "surrealkv".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub engine: Option<String>,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            backend: default_storage_backend(),
            path: default_storage_path(),
            engine: None,
        }
    }
}

fn default_storage_backend() -> String {
    "surrealdb".to_string()
}

fn default_storage_path() -> String {
    "data/ixchel".to_string()
}

impl IxchelConfig {
    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
        let raw = toml::to_string_pretty(self).map_err(|source| ConfigError::SerializeError {
            path: path.to_path_buf(),
            source,
        })?;
        std::fs::write(path, raw).map_err(|source| ConfigError::WriteError {
            path: path.to_path_buf(),
            source,
        })?;
        Ok(())
    }
}

/// Load the shared configuration from global and project config files.
///
/// # Errors
/// Returns an error if config files exist but cannot be read or parsed.
pub fn load_shared_config() -> Result<SharedConfig, ConfigError> {
    ConfigLoader::new("").load()
}

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("Failed to read config file {}: {source}", path.display())]
    ReadError {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to parse config file {}: {source}", path.display())]
    ParseError {
        path: PathBuf,
        #[source]
        source: toml::de::Error,
    },

    #[error("Failed to write config file {}: {source}", path.display())]
    WriteError {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to serialize config file {}: {source}", path.display())]
    SerializeError {
        path: PathBuf,
        #[source]
        source: toml::ser::Error,
    },
}

pub fn load_config<T: DeserializeOwned + Default>(tool_name: &str) -> Result<T, ConfigError> {
    ConfigLoader::new(tool_name).load()
}

pub struct ConfigLoader {
    tool_name: String,
    env_prefix: Option<String>,
    project_dir: Option<PathBuf>,
    global_dir: Option<PathBuf>,
}

impl ConfigLoader {
    pub fn new(tool_name: impl Into<String>) -> Self {
        Self {
            tool_name: tool_name.into(),
            env_prefix: None,
            project_dir: None,
            global_dir: None,
        }
    }

    #[must_use]
    pub fn with_env_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.env_prefix = Some(prefix.into());
        self
    }

    #[must_use]
    pub fn with_project_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.project_dir = Some(path.into());
        self
    }

    #[must_use]
    pub fn with_global_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.global_dir = Some(path.into());
        self
    }

    pub fn load<T: DeserializeOwned + Default>(self) -> Result<T, ConfigError> {
        let mut merged = toml::Table::new();

        let global_dir = self.global_dir.unwrap_or_else(ixchel_config_dir);

        let project_dir = self.project_dir.or_else(find_project_config_dir);
        if let Some(dir) = project_dir {
            if let Some(table) = load_toml_file(&dir.join("config.toml"))? {
                merge_tables(&mut merged, table);
            }

            if !self.tool_name.is_empty() {
                let tool_config = dir.join(format!("{}.toml", self.tool_name));
                if let Some(table) = load_toml_file(&tool_config)? {
                    merge_tables(&mut merged, table);
                }
            }
        }

        if let Some(table) = load_toml_file(&global_dir.join("config.toml"))? {
            merge_tables(&mut merged, table);
        }

        if !self.tool_name.is_empty() {
            let tool_config = global_dir.join(format!("{}.toml", self.tool_name));
            if let Some(table) = load_toml_file(&tool_config)? {
                merge_tables(&mut merged, table);
            }
        }

        if merged.is_empty() {
            return Ok(T::default());
        }

        let value = toml::Value::Table(merged);
        value.try_into().map_err(|e| ConfigError::ParseError {
            path: PathBuf::from("<merged>"),
            source: e,
        })
    }
}

fn load_toml_file(path: &Path) -> Result<Option<toml::Table>, ConfigError> {
    if !path.exists() {
        return Ok(None);
    }

    let content = std::fs::read_to_string(path).map_err(|e| ConfigError::ReadError {
        path: path.to_path_buf(),
        source: e,
    })?;

    let table: toml::Table = toml::from_str(&content).map_err(|e| ConfigError::ParseError {
        path: path.to_path_buf(),
        source: e,
    })?;

    Ok(Some(table))
}

fn merge_tables(base: &mut toml::Table, overlay: toml::Table) {
    for (key, value) in overlay {
        match (base.get_mut(&key), value) {
            (Some(toml::Value::Table(base_table)), toml::Value::Table(overlay_table)) => {
                merge_tables(base_table, overlay_table);
            }
            (_, value) => {
                base.insert(key, value);
            }
        }
    }
}

/// Get the global config directory (`~/.ixchel/config`).
///
/// This is a convenience alias for [`ixchel_config_dir`].
#[must_use]
#[deprecated(since = "0.2.0", note = "use ixchel_config_dir() instead")]
pub fn global_config_dir() -> Option<PathBuf> {
    Some(ixchel_config_dir())
}

/// Find the project config directory (`.ixchel/`) by walking to git root.
///
/// Returns `None` if no `.ixchel/` directory exists at the repository root.
#[must_use]
pub fn find_project_config_dir() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    let root = find_git_root(&cwd)?;
    let ixchel_dir = root.join(".ixchel");
    ixchel_dir.exists().then_some(ixchel_dir)
}

#[deprecated(since = "0.2.0", note = "use find_project_config_dir() instead")]
pub fn project_config_dir() -> Option<PathBuf> {
    find_project_config_dir()
}

#[must_use]
fn find_git_root(start: &Path) -> Option<PathBuf> {
    let mut current = Some(start);
    while let Some(dir) = current {
        if dir.join(".git").exists() {
            return Some(dir.to_path_buf());
        }
        current = dir.parent();
    }
    None
}

/// Detect GitHub token from multiple sources.
///
/// Detection order (highest priority first):
/// 1. `GITHUB_TOKEN` environment variable
/// 2. `GH_TOKEN` environment variable
/// 3. `github.token` in config files
/// 4. `gh auth token` command output
#[must_use]
pub fn detect_github_token() -> Option<String> {
    if let Ok(token) = std::env::var("GITHUB_TOKEN") {
        return Some(token);
    }

    if let Ok(token) = std::env::var("GH_TOKEN") {
        return Some(token);
    }

    if let Ok(config) = load_shared_config()
        && let Some(token) = config.github.token
    {
        return Some(token);
    }

    std::process::Command::new("gh")
        .args(["auth", "token"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;

    #[derive(Debug, Default, Deserialize, PartialEq)]
    struct TestConfig {
        #[serde(default)]
        value: i32,
        #[serde(default)]
        nested: NestedConfig,
    }

    #[derive(Debug, Default, Deserialize, PartialEq)]
    struct NestedConfig {
        #[serde(default)]
        inner: String,
    }

    #[test]
    fn test_merge_tables_simple() {
        let mut base: toml::Table = toml::toml! {
            value = 1
            other = "kept"
        };

        let overlay: toml::Table = toml::toml! {
            value = 2
        };

        merge_tables(&mut base, overlay);

        assert_eq!(base.get("value").unwrap().as_integer(), Some(2));
        assert_eq!(base.get("other").unwrap().as_str(), Some("kept"));
    }

    #[test]
    fn test_merge_tables_nested() {
        let mut base: toml::Table = toml::toml! {
            [nested]
            inner = "base"
            other = "kept"
        };

        let overlay: toml::Table = toml::toml! {
            [nested]
            inner = "overlay"
        };

        merge_tables(&mut base, overlay);

        let nested = base.get("nested").unwrap().as_table().unwrap();
        assert_eq!(nested.get("inner").unwrap().as_str(), Some("overlay"));
        assert_eq!(nested.get("other").unwrap().as_str(), Some("kept"));
    }

    #[test]
    fn test_load_missing_returns_default() {
        let config: TestConfig = ConfigLoader::new("nonexistent")
            .with_global_dir("/nonexistent/path")
            .with_project_dir("/nonexistent/path")
            .load()
            .unwrap();

        assert_eq!(config, TestConfig::default());
    }
}