-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloader.rs
More file actions
539 lines (470 loc) · 16.8 KB
/
loader.rs
File metadata and controls
539 lines (470 loc) · 16.8 KB
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Configuration loading utilities.
//!
//! Supports multiple configuration formats:
//! - TOML (`.toml`) - Primary format
//! - JSON with comments (`.json`, `.jsonc`) - OpenCode-compatible format
use std::path::{Path, PathBuf};
use tracing::debug;
use super::project_config::{
find_project_config, load_project_config, load_project_config_async, merge_configs,
};
use super::types::ConfigToml;
/// Configuration file name (TOML).
pub const CONFIG_FILE: &str = "config.toml";
/// Configuration file name (JSON).
pub const CONFIG_FILE_JSON: &str = "config.json";
/// Configuration file name (JSONC).
pub const CONFIG_FILE_JSONC: &str = "config.jsonc";
/// Environment variable for custom config file path.
pub const CORTEX_CONFIG_ENV: &str = "CORTEX_CONFIG";
/// Environment variable for custom config directory.
pub const CORTEX_CONFIG_DIR_ENV: &str = "CORTEX_CONFIG_DIR";
/// Find the Cortex home directory.
///
/// Checks in order:
/// 1. `CORTEX_CONFIG_DIR` environment variable
/// 2. `CORTEX_HOME` environment variable
/// 3. Default `~/.cortex` directory
pub fn find_cortex_home() -> std::io::Result<PathBuf> {
// Check CORTEX_CONFIG_DIR environment variable first (new)
if let Ok(val) = std::env::var(CORTEX_CONFIG_DIR_ENV)
&& !val.is_empty()
{
let path = PathBuf::from(&val);
debug!(path = %path.display(), "Using CORTEX_CONFIG_DIR");
return Ok(path);
}
// Check CORTEX_HOME environment variable
if let Ok(val) = std::env::var("CORTEX_HOME")
&& !val.is_empty()
{
let path = PathBuf::from(&val);
debug!(path = %path.display(), "Using CORTEX_HOME");
return Ok(path);
}
// Default to ~/.cortex
let mut home = dirs::home_dir().ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::NotFound, "Home directory not found")
})?;
home.push(".cortex");
Ok(home)
}
/// Get the config file path, checking cortex_CONFIG env var first.
///
/// Returns the path to the config file to load. If `cortex_CONFIG` is set,
/// returns that path directly. Otherwise, returns `{cortex_home}/config.toml`.
pub fn get_config_path(cortex_home: &Path) -> PathBuf {
// Check cortex_CONFIG environment variable
if let Ok(val) = std::env::var(CORTEX_CONFIG_ENV)
&& !val.is_empty()
{
let path = PathBuf::from(&val);
debug!(path = %path.display(), "Using cortex_CONFIG");
return path;
}
cortex_home.join(CONFIG_FILE)
}
/// Load global configuration from disk.
pub async fn load_config(cortex_home: &Path) -> std::io::Result<ConfigToml> {
let config_path = get_config_path(cortex_home);
load_config_from_path(&config_path).await
}
/// Load configuration from a specific path.
///
/// Supports both TOML and JSONC formats based on file extension.
async fn load_config_from_path(config_path: &Path) -> std::io::Result<ConfigToml> {
if !config_path.exists() {
debug!(path = %config_path.display(), "Config file not found, using defaults");
return Ok(ConfigToml::default());
}
debug!(path = %config_path.display(), "Loading config file");
let content = tokio::fs::read_to_string(config_path).await?;
let format = ConfigFormat::from_path(config_path);
parse_config_content(&content, format).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Failed to parse {}: {e}", config_path.display()),
)
})
}
/// Load configuration synchronously.
pub fn load_config_sync(cortex_home: &Path) -> std::io::Result<ConfigToml> {
let config_path = get_config_path(cortex_home);
load_config_from_path_sync(&config_path)
}
/// Load configuration from a specific path synchronously.
///
/// Supports both TOML and JSONC formats based on file extension.
fn load_config_from_path_sync(config_path: &Path) -> std::io::Result<ConfigToml> {
if !config_path.exists() {
debug!(path = %config_path.display(), "Config file not found, using defaults");
return Ok(ConfigToml::default());
}
debug!(path = %config_path.display(), "Loading config file");
let content = std::fs::read_to_string(config_path)?;
let format = ConfigFormat::from_path(config_path);
parse_config_content(&content, format).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Failed to parse {}: {e}", config_path.display()),
)
})
}
/// Load merged configuration (global + project).
///
/// This is the main entry point for loading configuration with project-level
/// overrides. It:
/// 1. Loads the global config from `~/.cortex/config.toml`
/// 2. Discovers and loads project config (`.cortex/config.toml` or `Cortex.toml`)
/// 3. Merges them with project taking precedence over global
///
/// # Arguments
/// * `cortex_home` - The global Cortex home directory
/// * `cwd` - Current working directory for project config discovery
///
/// # Returns
/// * `Ok((ConfigToml, Option<PathBuf>))` - Merged config and optional project config path
pub async fn load_merged_config(
cortex_home: &Path,
cwd: &Path,
) -> std::io::Result<(ConfigToml, Option<PathBuf>)> {
// Load global config
let global_config = load_config(cortex_home).await?;
// Try to find and load project config
let project_config_path = find_project_config(cwd);
let project_config = if let Some(ref path) = project_config_path {
match load_project_config_async(path).await {
Ok(config) => Some(config),
Err(e) => {
debug!(path = %path.display(), error = %e, "Failed to load project config");
None
}
}
} else {
None
};
// Merge configs
let merged = merge_configs(global_config, project_config);
Ok((merged, project_config_path))
}
/// Load merged configuration synchronously.
pub fn load_merged_config_sync(
cortex_home: &Path,
cwd: &Path,
) -> std::io::Result<(ConfigToml, Option<PathBuf>)> {
// Load global config
let global_config = load_config_sync(cortex_home)?;
// Try to find and load project config
let project_config_path = find_project_config(cwd);
let project_config = if let Some(ref path) = project_config_path {
match load_project_config(path) {
Ok(config) => Some(config),
Err(e) => {
debug!(path = %path.display(), error = %e, "Failed to load project config");
None
}
}
} else {
None
};
// Merge configs
let merged = merge_configs(global_config, project_config);
Ok((merged, project_config_path))
}
/// Ensure Cortex home directory exists.
pub fn ensure_cortex_home(cortex_home: &Path) -> std::io::Result<()> {
if !cortex_home.exists() {
std::fs::create_dir_all(cortex_home)?;
}
Ok(())
}
/// Get the sessions directory.
pub fn sessions_dir(cortex_home: &Path) -> PathBuf {
cortex_home.join("sessions")
}
/// Get the log directory.
pub fn log_dir(cortex_home: &Path) -> PathBuf {
cortex_home.join("log")
}
/// Detected configuration format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigFormat {
/// TOML format (.toml)
Toml,
/// JSON with comments (.json, .jsonc)
JsonC,
}
impl ConfigFormat {
/// Detect format from file extension.
pub fn from_path(path: &Path) -> Self {
match path.extension().and_then(|e| e.to_str()) {
Some("json") | Some("jsonc") => Self::JsonC,
_ => Self::Toml, // Default to TOML
}
}
}
/// Strip C-style and C++ style comments from JSON content.
///
/// Handles:
/// - Single-line comments: `// comment`
/// - Multi-line comments: `/* comment */`
/// - Preserves comments inside strings
pub fn strip_json_comments(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
let mut in_string = false;
let mut escape_next = false;
while let Some(c) = chars.next() {
if escape_next {
result.push(c);
escape_next = false;
continue;
}
if in_string {
result.push(c);
if c == '\\' {
escape_next = true;
} else if c == '"' {
in_string = false;
}
continue;
}
match c {
'"' => {
in_string = true;
result.push(c);
}
'/' => {
match chars.peek() {
Some('/') => {
// Single-line comment - skip until newline
chars.next();
while let Some(&next) = chars.peek() {
if next == '\n' {
break;
}
chars.next();
}
}
Some('*') => {
// Multi-line comment - skip until */
chars.next();
let mut found_star = false;
for next in chars.by_ref() {
if found_star && next == '/' {
break;
}
found_star = next == '*';
}
}
_ => {
result.push(c);
}
}
}
_ => {
result.push(c);
}
}
}
result
}
/// Parse configuration content based on format.
pub fn parse_config_content(content: &str, format: ConfigFormat) -> std::io::Result<ConfigToml> {
match format {
ConfigFormat::Toml => toml::from_str(content).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Failed to parse TOML config: {e}"),
)
}),
ConfigFormat::JsonC => {
let stripped = strip_json_comments(content);
serde_json::from_str(&stripped).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Failed to parse JSON config: {e}"),
)
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[tokio::test]
async fn test_load_missing_config() {
let temp_dir = TempDir::new().unwrap();
let config = load_config(temp_dir.path()).await.unwrap();
assert!(config.model.is_none());
}
#[tokio::test]
async fn test_load_valid_config() {
let temp_dir = TempDir::new().unwrap();
let config_content = r#"
model = "gpt-4o"
model_provider = "openai"
approval_policy = "on-request"
"#;
tokio::fs::write(temp_dir.path().join(CONFIG_FILE), config_content)
.await
.unwrap();
let config = load_config(temp_dir.path()).await.unwrap();
assert_eq!(config.model, Some("gpt-4o".to_string()));
}
#[tokio::test]
async fn test_load_merged_config_global_only() {
let temp_dir = TempDir::new().unwrap();
let global_home = temp_dir.path().join("global");
std::fs::create_dir_all(&global_home).unwrap();
let project_dir = temp_dir.path().join("project");
std::fs::create_dir_all(&project_dir).unwrap();
// Write global config
let global_config = r#"
model = "global-model"
model_provider = "global-provider"
"#;
std::fs::write(global_home.join(CONFIG_FILE), global_config).unwrap();
let (config, project_path) = load_merged_config(&global_home, &project_dir)
.await
.unwrap();
assert_eq!(config.model, Some("global-model".to_string()));
assert_eq!(config.model_provider, Some("global-provider".to_string()));
assert!(project_path.is_none());
}
#[tokio::test]
async fn test_load_merged_config_with_project() {
let temp_dir = TempDir::new().unwrap();
let global_home = temp_dir.path().join("global");
std::fs::create_dir_all(&global_home).unwrap();
let project_dir = temp_dir.path().join("project");
let cortex_dir = project_dir.join(".cortex");
std::fs::create_dir_all(&cortex_dir).unwrap();
// Write global config
let global_config = r#"
model = "global-model"
model_provider = "global-provider"
"#;
std::fs::write(global_home.join(CONFIG_FILE), global_config).unwrap();
// Write project config
let project_config = r#"
model = "project-model"
"#;
std::fs::write(cortex_dir.join(CONFIG_FILE), project_config).unwrap();
let (config, project_path) = load_merged_config(&global_home, &project_dir)
.await
.unwrap();
// Project model should override global
assert_eq!(config.model, Some("project-model".to_string()));
// Global provider should be preserved
assert_eq!(config.model_provider, Some("global-provider".to_string()));
assert!(project_path.is_some());
}
#[test]
fn test_load_merged_config_sync() {
let temp_dir = TempDir::new().unwrap();
let global_home = temp_dir.path().join("global");
std::fs::create_dir_all(&global_home).unwrap();
let project_dir = temp_dir.path().join("project");
std::fs::create_dir_all(&project_dir).unwrap();
// Write global config
let global_config = r#"
model = "sync-model"
"#;
std::fs::write(global_home.join(CONFIG_FILE), global_config).unwrap();
let (config, _) = load_merged_config_sync(&global_home, &project_dir).unwrap();
assert_eq!(config.model, Some("sync-model".to_string()));
}
#[test]
fn test_get_config_path_default() {
// Clear any env vars that might interfere
// SAFETY: This is test code running in a single-threaded test context.
// No other threads are concurrently accessing this environment variable.
unsafe {
std::env::remove_var(CORTEX_CONFIG_ENV);
}
let cortex_home = PathBuf::from("/test/Cortex");
let path = get_config_path(&cortex_home);
assert_eq!(path, cortex_home.join(CONFIG_FILE));
}
#[test]
fn test_strip_json_comments_single_line() {
let input = r#"{
// This is a comment
"model": "gpt-4o"
}"#;
let stripped = strip_json_comments(input);
assert!(!stripped.contains("//"));
assert!(stripped.contains("\"model\""));
}
#[test]
fn test_strip_json_comments_multi_line() {
let input = r#"{
/* This is a
multi-line comment */
"model": "gpt-4o"
}"#;
let stripped = strip_json_comments(input);
assert!(!stripped.contains("/*"));
assert!(!stripped.contains("*/"));
assert!(stripped.contains("\"model\""));
}
#[test]
fn test_strip_json_comments_preserves_strings() {
let input = r#"{
"url": "https://example.com/path",
"comment": "This // is not a comment"
}"#;
let stripped = strip_json_comments(input);
assert!(stripped.contains("https://example.com/path"));
assert!(stripped.contains("This // is not a comment"));
}
#[test]
fn test_config_format_detection() {
assert_eq!(
ConfigFormat::from_path(Path::new("config.toml")),
ConfigFormat::Toml
);
assert_eq!(
ConfigFormat::from_path(Path::new("config.json")),
ConfigFormat::JsonC
);
assert_eq!(
ConfigFormat::from_path(Path::new("config.jsonc")),
ConfigFormat::JsonC
);
assert_eq!(
ConfigFormat::from_path(Path::new("config")),
ConfigFormat::Toml
);
}
#[test]
fn test_parse_json_config() {
let json_content = r#"{
// OpenCode-style config with comments
"model": "claude-3-opus",
"model_provider": "anthropic"
}"#;
let config = parse_config_content(json_content, ConfigFormat::JsonC).unwrap();
assert_eq!(config.model, Some("claude-3-opus".to_string()));
assert_eq!(config.model_provider, Some("anthropic".to_string()));
}
#[tokio::test]
async fn test_load_json_config() {
let temp_dir = TempDir::new().unwrap();
let config_content = r#"{
// This is a JSONC config file
"model": "gpt-4o",
"model_provider": "openai"
}"#;
tokio::fs::write(temp_dir.path().join("config.json"), config_content)
.await
.unwrap();
let config = load_config_from_path(&temp_dir.path().join("config.json"))
.await
.unwrap();
assert_eq!(config.model, Some("gpt-4o".to_string()));
assert_eq!(config.model_provider, Some("openai".to_string()));
}
}