oxirs 0.2.4

Command-line interface for OxiRS - import, export, migration, and benchmarking tools
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
473
474
475
476
//! Configuration management with profiles and environment detection
//!
//! Provides a hierarchical configuration system with profiles, environment
//! variables, and automatic configuration discovery.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use toml;

use crate::cli::error::{CliError, CliResult};

/// Configuration manager with profile support
pub struct ConfigManager {
    /// Base configuration directory
    config_dir: PathBuf,
    /// Current profile
    active_profile: String,
    /// Loaded configurations by profile
    configs: HashMap<String, OxirsConfig>,
}

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct OxirsConfig {
    /// General settings
    #[serde(default)]
    pub general: GeneralConfig,

    /// Server settings
    #[serde(default)]
    pub server: ServerConfig,

    /// Dataset configurations
    #[serde(default)]
    pub datasets: HashMap<String, DatasetConfig>,

    /// Tool-specific settings
    #[serde(default)]
    pub tools: ToolsConfig,

    /// Environment-specific overrides
    #[serde(default)]
    pub env: HashMap<String, toml::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    /// Default RDF format
    #[serde(default = "default_format")]
    pub default_format: String,

    /// Default output directory
    #[serde(default)]
    pub output_dir: Option<PathBuf>,

    /// Enable progress bars
    #[serde(default = "default_true")]
    pub show_progress: bool,

    /// Enable colored output
    #[serde(default = "default_true")]
    pub colored_output: bool,

    /// Default timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout: u64,

    /// Log level
    #[serde(default = "default_log_level")]
    pub log_level: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// Default host
    #[serde(default = "default_host")]
    pub host: String,

    /// Default port
    #[serde(default = "default_port")]
    pub port: u16,

    /// Enable admin interface
    #[serde(default)]
    pub admin_enabled: bool,

    /// CORS settings
    #[serde(default)]
    pub cors: CorsConfig,

    /// Authentication settings
    #[serde(default)]
    pub auth: AuthConfig,

    /// Enable GraphQL endpoint
    #[serde(default)]
    pub enable_graphql: bool,

    /// GraphQL endpoint path
    #[serde(default = "default_graphql_path")]
    pub graphql_path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CorsConfig {
    pub enabled: bool,
    pub allowed_origins: Vec<String>,
    pub allowed_methods: Vec<String>,
    pub allowed_headers: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AuthConfig {
    pub enabled: bool,
    pub method: Option<String>, // basic, jwt, oauth
    pub config: HashMap<String, toml::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetConfig {
    /// Dataset type (tdb2, memory, remote)
    pub dataset_type: String,

    /// Location (path or URL)
    pub location: String,

    /// Read-only mode
    #[serde(default)]
    pub read_only: bool,

    /// Dataset-specific options
    #[serde(default)]
    pub options: HashMap<String, toml::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolsConfig {
    /// RDF I/O settings
    #[serde(default)]
    pub riot: RiotConfig,

    /// Query settings
    #[serde(default)]
    pub query: QueryConfig,

    /// TDB settings
    #[serde(default)]
    pub tdb: TdbConfig,

    /// Validation settings
    #[serde(default)]
    pub validation: ValidationConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RiotConfig {
    pub strict_mode: bool,
    pub base_uri: Option<String>,
    pub pretty_print: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct QueryConfig {
    pub timeout: Option<u64>,
    pub optimize: bool,
    pub explain: bool,
    pub result_limit: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TdbConfig {
    pub cache_size: Option<usize>,
    pub file_mode: Option<String>,
    pub sync_mode: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ValidationConfig {
    pub abort_on_error: bool,
    pub max_errors: Option<usize>,
    pub report_format: Option<String>,
}

impl ConfigManager {
    /// Create a new configuration manager
    pub fn new() -> CliResult<Self> {
        let config_dir = Self::get_config_dir()?;

        Ok(Self {
            config_dir,
            active_profile: "default".to_string(),
            configs: HashMap::new(),
        })
    }

    /// Get the configuration directory
    fn get_config_dir() -> CliResult<PathBuf> {
        // Check environment variable first
        if let Ok(dir) = std::env::var("OXIRS_CONFIG_DIR") {
            return Ok(PathBuf::from(dir));
        }

        // Use platform-specific config directory
        dirs::config_dir()
            .map(|p| p.join("oxirs"))
            .ok_or_else(|| CliError::config_error("Cannot determine config directory"))
    }

    /// Load configuration for a profile
    pub fn load_profile(&mut self, profile: &str) -> CliResult<&OxirsConfig> {
        if self.configs.contains_key(profile) {
            return Ok(&self.configs[profile]);
        }

        let config = self.load_config_cascade(profile)?;
        self.configs.insert(profile.to_string(), config);
        self.active_profile = profile.to_string();

        Ok(&self.configs[profile])
    }

    /// Load configuration with cascade (defaults -> profile -> env -> cli)
    fn load_config_cascade(&self, profile: &str) -> CliResult<OxirsConfig> {
        // Start with defaults
        let mut config = OxirsConfig::default();

        // Load global config if exists
        let global_path = self.config_dir.join("config.toml");
        if global_path.exists() {
            let global_config = self.load_config_file(&global_path)?;
            config = self.merge_configs(config, global_config);
        }

        // Load profile-specific config if exists
        if profile != "default" {
            let profile_path = self.config_dir.join(format!("config.{profile}.toml"));
            if profile_path.exists() {
                let profile_config = self.load_config_file(&profile_path)?;
                config = self.merge_configs(config, profile_config);
            }
        }

        // Apply environment variable overrides
        config = self.apply_env_overrides(config)?;

        Ok(config)
    }

    /// Load a configuration file
    fn load_config_file(&self, path: &Path) -> CliResult<OxirsConfig> {
        let content = fs::read_to_string(path)
            .map_err(|e| CliError::config_error(format!("Cannot read config file: {e}")))?;

        toml::from_str(&content)
            .map_err(|e| CliError::config_error(format!("Invalid TOML in config file: {e}")))
    }

    /// Merge two configurations (right overwrites left)
    fn merge_configs(&self, mut base: OxirsConfig, overlay: OxirsConfig) -> OxirsConfig {
        // Merge general settings
        if overlay.general.default_format != default_format() {
            base.general.default_format = overlay.general.default_format;
        }
        if overlay.general.output_dir.is_some() {
            base.general.output_dir = overlay.general.output_dir;
        }

        // Merge server settings
        if overlay.server.host != default_host() {
            base.server.host = overlay.server.host;
        }
        if overlay.server.port != default_port() {
            base.server.port = overlay.server.port;
        }

        // Merge datasets
        base.datasets.extend(overlay.datasets);

        // Deep merge tools config
        base.tools = overlay.tools;

        base
    }

    /// Apply environment variable overrides
    fn apply_env_overrides(&self, mut config: OxirsConfig) -> CliResult<OxirsConfig> {
        // OXIRS_DEFAULT_FORMAT
        if let Ok(format) = std::env::var("OXIRS_DEFAULT_FORMAT") {
            config.general.default_format = format;
        }

        // OXIRS_OUTPUT_DIR
        if let Ok(dir) = std::env::var("OXIRS_OUTPUT_DIR") {
            config.general.output_dir = Some(PathBuf::from(dir));
        }

        // OXIRS_NO_COLOR
        if std::env::var("OXIRS_NO_COLOR").is_ok() || std::env::var("NO_COLOR").is_ok() {
            config.general.colored_output = false;
        }

        // OXIRS_SERVER_HOST
        if let Ok(host) = std::env::var("OXIRS_SERVER_HOST") {
            config.server.host = host;
        }

        // OXIRS_SERVER_PORT
        if let Ok(port_str) = std::env::var("OXIRS_SERVER_PORT") {
            if let Ok(port) = port_str.parse::<u16>() {
                config.server.port = port;
            }
        }

        Ok(config)
    }

    /// Get active configuration
    pub fn get_config(&self) -> CliResult<&OxirsConfig> {
        self.configs
            .get(&self.active_profile)
            .ok_or_else(|| CliError::config_error("No configuration loaded"))
    }

    /// Save configuration to file
    pub fn save_config(&self, config: &OxirsConfig, profile: Option<&str>) -> CliResult<()> {
        let profile = profile.unwrap_or(&self.active_profile);

        // Ensure config directory exists
        fs::create_dir_all(&self.config_dir)
            .map_err(|e| CliError::config_error(format!("Cannot create config directory: {e}")))?;

        let path = if profile == "default" {
            self.config_dir.join("config.toml")
        } else {
            self.config_dir.join(format!("config.{profile}.toml"))
        };

        let content = toml::to_string_pretty(config)
            .map_err(|e| CliError::config_error(format!("Cannot serialize config: {e}")))?;

        fs::write(&path, content)
            .map_err(|e| CliError::config_error(format!("Cannot write config file: {e}")))?;

        Ok(())
    }

    /// List available profiles
    pub fn list_profiles(&self) -> CliResult<Vec<String>> {
        let mut profiles = vec!["default".to_string()];

        if self.config_dir.exists() {
            for entry in fs::read_dir(&self.config_dir)? {
                let entry = entry?;
                let path = entry.path();

                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                    if name.starts_with("config.") && name.ends_with(".toml") {
                        let profile = name
                            .strip_prefix("config.")
                            .and_then(|n| n.strip_suffix(".toml"))
                            .unwrap_or("");

                        if !profile.is_empty() {
                            profiles.push(profile.to_string());
                        }
                    }
                }
            }
        }

        profiles.sort();
        profiles.dedup();
        Ok(profiles)
    }

    /// Generate a default configuration file
    pub fn generate_default_config(&self) -> CliResult<()> {
        let config = OxirsConfig::default();
        self.save_config(&config, Some("default"))
    }
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            default_format: default_format(),
            output_dir: None,
            show_progress: default_true(),
            colored_output: default_true(),
            timeout: default_timeout(),
            log_level: default_log_level(),
        }
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            admin_enabled: false,
            cors: CorsConfig::default(),
            auth: AuthConfig::default(),
            enable_graphql: false,
            graphql_path: default_graphql_path(),
        }
    }
}

// Default value functions for serde
fn default_format() -> String {
    "turtle".to_string()
}
fn default_true() -> bool {
    true
}
fn default_timeout() -> u64 {
    30
}
fn default_log_level() -> String {
    "info".to_string()
}
fn default_host() -> String {
    "localhost".to_string()
}
fn default_port() -> u16 {
    3030
}
fn default_graphql_path() -> String {
    "/graphql".to_string()
}

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

    #[test]
    fn test_default_config() {
        let config = OxirsConfig::default();
        assert_eq!(config.general.default_format, "turtle");
        assert_eq!(config.server.host, "localhost");
        assert_eq!(config.server.port, 3030);
    }

    #[test]
    fn test_config_serialization() {
        let config = OxirsConfig::default();
        let toml_str = toml::to_string(&config).unwrap();
        assert!(toml_str.contains("[general]"));
        assert!(toml_str.contains("[server]"));
    }

    #[test]
    fn test_env_override() {
        // Use a lock to ensure single-threaded access to environment variables
        use std::sync::Mutex;
        static ENV_LOCK: Mutex<()> = Mutex::new(());
        let _guard = ENV_LOCK.lock().expect("lock should not be poisoned");

        // Set test environment variables - safe because we have exclusive access via mutex
        std::env::set_var("OXIRS_DEFAULT_FORMAT", "ntriples");
        std::env::set_var("OXIRS_SERVER_PORT", "8080");

        let manager = ConfigManager::new().unwrap();
        let config = manager.apply_env_overrides(OxirsConfig::default()).unwrap();

        assert_eq!(config.general.default_format, "ntriples");
        assert_eq!(config.server.port, 8080);

        // Clean up - safe because we still have exclusive access via mutex
        std::env::remove_var("OXIRS_DEFAULT_FORMAT");
        std::env::remove_var("OXIRS_SERVER_PORT");
    }
}