kerf 0.1.2

Simple tokio-based trace event collector
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
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::{Result, anyhow};
use tracing::Level;

/// Output format options for trace events
#[derive(Debug, Clone, PartialEq)]
pub enum OutputFormat {
    /// Just message and module: "[cactui::tui] Frame rendered"
    Minimal,
    /// Level, module, message: "DEBUG [cactui::tui] Frame rendered"
    Standard,
    /// Full timestamp, level, module, file:line, message
    Full,
    /// Custom format string (future extension)
    Custom(String),
}

impl Default for OutputFormat {
    fn default() -> Self {
        OutputFormat::Standard
    }
}

impl FromStr for OutputFormat {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "minimal" => Ok(OutputFormat::Minimal),
            "standard" => Ok(OutputFormat::Standard),
            "full" => Ok(OutputFormat::Full),
            custom => Ok(OutputFormat::Custom(custom.to_string())),
        }
    }
}

/// Configuration parsed from environment variables
#[derive(Debug, Clone)]
pub struct EnvConfig {
    /// Global exclusion patterns applied to all tabs
    pub global_excludes: Vec<String>,
    /// Tab definitions: (name, level, pattern)
    pub tabs: Vec<(String, String, String)>,
    /// Output directory for log files
    pub output_dir: Option<PathBuf>,
    /// Output format for trace events
    pub output_format: OutputFormat,
    /// Stream routing: stream_name -> file_path
    pub streams: HashMap<String, PathBuf>,
    /// Per-stream configurations: stream_name -> (level, patterns)
    pub stream_configs: HashMap<String, (String, Vec<String>)>,
    /// TUI-specific configuration
    pub tui_config: Option<TuiConfig>,
}

/// TUI-specific debugging configuration
#[derive(Debug, Clone)]
pub struct TuiConfig {
    pub enabled: bool,
    pub modules: Vec<String>,
    pub level: String,
    pub output: Option<PathBuf>,
}

impl Default for EnvConfig {
    fn default() -> Self {
        Self {
            global_excludes: Vec::new(),
            tabs: Vec::new(),
            output_dir: None,
            output_format: OutputFormat::default(),
            streams: HashMap::new(),
            stream_configs: HashMap::new(),
            tui_config: None,
        }
    }
}

impl EnvConfig {
    /// Parse configuration from environment variables
    pub fn from_env() -> Result<Self> {
        let mut config = Self::default();

        // Parse global exclusions
        if let Ok(excludes) = std::env::var("KERF_GLOBAL_EXCLUDE") {
            config.global_excludes = parse_comma_separated(&excludes);
        }

        // Parse tab definitions: "errors:error:*,api:info:api_*,tui:debug:cactui::*"
        if let Ok(tabs) = std::env::var("KERF_TABS") {
            config.tabs = parse_tab_definitions(&tabs)?;
        }

        // Parse output directory
        if let Ok(dir) = std::env::var("KERF_OUTPUT_DIR") {
            config.output_dir = Some(PathBuf::from(dir));
        }

        // Parse output format
        if let Ok(format) = std::env::var("KERF_OUTPUT_FORMAT") {
            config.output_format = OutputFormat::from_str(&format)?;
        }

        // Parse stream routing: "console:/tmp/console.log,errors:/tmp/errors.log"
        if let Ok(streams) = std::env::var("KERF_STREAMS") {
            config.streams = parse_stream_routing(&streams)?;
        }

        // Parse per-stream configurations
        for (stream_name, _) in &config.streams {
            let env_var = format!("KERF_STREAM_{}", stream_name);
            if let Ok(stream_config) = std::env::var(&env_var) {
                let (level, patterns) = parse_stream_config(&stream_config)?;
                config.stream_configs.insert(stream_name.clone(), (level, patterns));
            }
        }

        // Parse TUI-specific configuration
        config.tui_config = parse_tui_config()?;

        Ok(config)
    }

    /// Check if any environment variables are set
    pub fn has_env_config() -> bool {
        std::env::var("KERF_GLOBAL_EXCLUDE").is_ok()
            || std::env::var("KERF_TABS").is_ok()
            || std::env::var("KERF_OUTPUT_DIR").is_ok()
            || std::env::var("KERF_OUTPUT_FORMAT").is_ok()
            || std::env::var("KERF_STREAMS").is_ok()
            || std::env::var("TUI_KERF_ENABLE").is_ok()
    }
}

/// Parse comma-separated values
fn parse_comma_separated(input: &str) -> Vec<String> {
    input
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Parse tab definitions: "errors:error:*,api:info:api_*"
fn parse_tab_definitions(input: &str) -> Result<Vec<(String, String, String)>> {
    let mut tabs = Vec::new();
    
    for tab_def in input.split(',') {
        let parts: Vec<&str> = tab_def.trim().split(':').collect();
        if parts.len() != 3 {
            return Err(anyhow!(
                "Invalid tab definition '{}'. Expected format: 'name:level:pattern'",
                tab_def
            ));
        }
        
        let name = parts[0].trim().to_string();
        let level = parts[1].trim().to_string();
        let pattern = parts[2].trim().to_string();
        
        // Validate level
        validate_level(&level)?;
        
        tabs.push((name, level, pattern));
    }
    
    Ok(tabs)
}

/// Parse stream routing: "console:/tmp/console.log,errors:/tmp/errors.log"
fn parse_stream_routing(input: &str) -> Result<HashMap<String, PathBuf>> {
    let mut streams = HashMap::new();
    
    for stream_def in input.split(',') {
        let parts: Vec<&str> = stream_def.trim().split(':').collect();
        if parts.len() != 2 {
            return Err(anyhow!(
                "Invalid stream definition '{}'. Expected format: 'name:path'",
                stream_def
            ));
        }
        
        let name = parts[0].trim().to_string();
        let path = PathBuf::from(parts[1].trim());
        
        streams.insert(name, path);
    }
    
    Ok(streams)
}

/// Parse stream configuration: "info:*,-hyper::*,-tokio::*"
fn parse_stream_config(input: &str) -> Result<(String, Vec<String>)> {
    let parts: Vec<&str> = input.splitn(2, ':').collect();
    if parts.len() != 2 {
        return Err(anyhow!(
            "Invalid stream config '{}'. Expected format: 'level:patterns'",
            input
        ));
    }
    
    let level = parts[0].trim().to_string();
    validate_level(&level)?;
    
    let patterns = parse_comma_separated(parts[1]);
    
    Ok((level, patterns))
}

/// Parse TUI-specific configuration
fn parse_tui_config() -> Result<Option<TuiConfig>> {
    if std::env::var("TUI_KERF_ENABLE").is_err() {
        return Ok(None);
    }
    
    let mut config = TuiConfig {
        enabled: true,
        modules: Vec::new(),
        level: "debug".to_string(),
        output: None,
    };
    
    // Parse modules
    if let Ok(modules) = std::env::var("TUI_KERF_MODULES") {
        config.modules = parse_comma_separated(&modules);
    } else {
        // Default TUI modules
        config.modules = vec!["cactui::*".to_string(), "codeng_tui::*".to_string()];
    }
    
    // Parse level
    if let Ok(level) = std::env::var("TUI_KERF_LEVEL") {
        validate_level(&level)?;
        config.level = level;
    }
    
    // Parse output path
    if let Ok(output) = std::env::var("TUI_KERF_OUTPUT") {
        config.output = Some(PathBuf::from(output));
    }
    
    Ok(Some(config))
}

/// Validate that a level string is valid
fn validate_level(level: &str) -> Result<()> {
    match level.to_lowercase().as_str() {
        "trace" | "debug" | "info" | "warn" | "error" => Ok(()),
        _ => Err(anyhow!("Invalid log level '{}'. Must be one of: trace, debug, info, warn, error", level)),
    }
}

/// Convert string level to tracing::Level
pub fn parse_level(level: &str) -> Result<Level> {
    match level.to_lowercase().as_str() {
        "trace" => Ok(Level::TRACE),
        "debug" => Ok(Level::DEBUG),
        "info" => Ok(Level::INFO),
        "warn" => Ok(Level::WARN),
        "error" => Ok(Level::ERROR),
        _ => Err(anyhow!("Invalid log level '{}'", level)),
    }
}

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

    #[test]
    fn test_parse_comma_separated() {
        assert_eq!(
            parse_comma_separated("a,b,c"),
            vec!["a", "b", "c"]
        );
        assert_eq!(
            parse_comma_separated("  a  ,  b  ,  c  "),
            vec!["a", "b", "c"]
        );
        assert_eq!(
            parse_comma_separated(""),
            Vec::<String>::new()
        );
    }

    #[test]
    fn test_parse_tab_definitions() {
        let result = parse_tab_definitions("errors:error:*,api:info:api_*").unwrap();
        assert_eq!(result, vec![
            ("errors".to_string(), "error".to_string(), "*".to_string()),
            ("api".to_string(), "info".to_string(), "api_*".to_string()),
        ]);
    }

    #[test]
    fn test_parse_tab_definitions_invalid() {
        assert!(parse_tab_definitions("invalid").is_err());
        assert!(parse_tab_definitions("name:invalid_level:pattern").is_err());
    }

    #[test]
    fn test_parse_stream_routing() {
        let result = parse_stream_routing("console:/tmp/console.log,errors:/tmp/errors.log").unwrap();
        let mut expected = HashMap::new();
        expected.insert("console".to_string(), PathBuf::from("/tmp/console.log"));
        expected.insert("errors".to_string(), PathBuf::from("/tmp/errors.log"));
        assert_eq!(result, expected);
    }

    #[test]
    fn test_parse_stream_config() {
        let (level, patterns) = parse_stream_config("info:*,-hyper::*").unwrap();
        assert_eq!(level, "info");
        assert_eq!(patterns, vec!["*", "-hyper::*"]);
    }

    #[test]
    fn test_output_format_from_str() {
        assert_eq!(OutputFormat::from_str("minimal").unwrap(), OutputFormat::Minimal);
        assert_eq!(OutputFormat::from_str("standard").unwrap(), OutputFormat::Standard);
        assert_eq!(OutputFormat::from_str("full").unwrap(), OutputFormat::Full);
        assert_eq!(OutputFormat::from_str("custom").unwrap(), OutputFormat::Custom("custom".to_string()));
    }

    #[test]
    fn test_validate_level() {
        assert!(validate_level("trace").is_ok());
        assert!(validate_level("debug").is_ok());
        assert!(validate_level("info").is_ok());
        assert!(validate_level("warn").is_ok());
        assert!(validate_level("error").is_ok());
        assert!(validate_level("invalid").is_err());
    }

    #[test]
    fn test_parse_level() {
        assert_eq!(parse_level("trace").unwrap(), Level::TRACE);
        assert_eq!(parse_level("debug").unwrap(), Level::DEBUG);
        assert_eq!(parse_level("info").unwrap(), Level::INFO);
        assert_eq!(parse_level("warn").unwrap(), Level::WARN);
        assert_eq!(parse_level("error").unwrap(), Level::ERROR);
        assert!(parse_level("invalid").is_err());
    }

    #[test]
    fn test_env_config_from_env() {
        // Clean up first
        unsafe {
            env::remove_var("KERF_GLOBAL_EXCLUDE");
            env::remove_var("KERF_TABS");
            env::remove_var("KERF_OUTPUT_FORMAT");
            env::remove_var("TUI_KERF_ENABLE");
            env::remove_var("TUI_KERF_MODULES");
            env::remove_var("TUI_KERF_LEVEL");
        }

        // Set up test environment variables
        unsafe {
            env::set_var("KERF_GLOBAL_EXCLUDE", "hyper::*,tokio::*");
            env::set_var("KERF_TABS", "errors:error:*,api:info:api_*");
            env::set_var("KERF_OUTPUT_FORMAT", "minimal");
            env::set_var("TUI_KERF_ENABLE", "1");
            env::set_var("TUI_KERF_MODULES", "cactui::*");
            env::set_var("TUI_KERF_LEVEL", "debug");
        }

        let config = EnvConfig::from_env().unwrap();

        assert_eq!(config.global_excludes, vec!["hyper::*", "tokio::*"]);
        assert_eq!(config.tabs.len(), 2);
        assert_eq!(config.output_format, OutputFormat::Minimal);
        assert!(config.tui_config.is_some());

        let tui_config = config.tui_config.unwrap();
        assert!(tui_config.enabled);
        assert_eq!(tui_config.modules, vec!["cactui::*"]);
        assert_eq!(tui_config.level, "debug");

        // Clean up
        unsafe {
            env::remove_var("KERF_GLOBAL_EXCLUDE");
            env::remove_var("KERF_TABS");
            env::remove_var("KERF_OUTPUT_FORMAT");
            env::remove_var("TUI_KERF_ENABLE");
            env::remove_var("TUI_KERF_MODULES");
            env::remove_var("TUI_KERF_LEVEL");
        }
    }

    #[test]
    fn test_has_env_config() {
        // Clean up first to ensure clean state
        unsafe {
            env::remove_var("KERF_GLOBAL_EXCLUDE");
            env::remove_var("KERF_TABS");
            env::remove_var("KERF_OUTPUT_DIR");
            env::remove_var("KERF_OUTPUT_FORMAT");
            env::remove_var("KERF_STREAMS");
            env::remove_var("TUI_KERF_ENABLE");
        }

        // Initially no config
        assert!(!EnvConfig::has_env_config());

        // Set one variable
        unsafe {
            env::set_var("KERF_GLOBAL_EXCLUDE", "test");
        }
        assert!(EnvConfig::has_env_config());

        // Clean up
        unsafe {
            env::remove_var("KERF_GLOBAL_EXCLUDE");
        }
        assert!(!EnvConfig::has_env_config());
    }
}