batless 0.7.0

A fast, non-blocking code and text viewer inspired by bat
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
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
540
541
542
543
544
545
546
547
548
549
550
551
//! Configuration management for batless
//!
//! This module handles all configuration-related functionality including
//! default values, validation, and configuration parsing.

use crate::config_validation::validate_config;
use crate::error::{BatlessError, BatlessResult};
use serde::{Deserialize, Serialize};

use std::fs;
use std::path::{Path, PathBuf};

/// Configuration structure for batless operations
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BatlessConfig {
    /// Maximum number of lines to process
    #[serde(default = "default_max_lines")]
    pub max_lines: usize,
    /// Maximum number of bytes to process (optional)
    #[serde(default)]
    pub max_bytes: Option<usize>,
    /// Override language detection with specific language
    #[serde(default)]
    pub language: Option<String>,
    /// Whether to strip ANSI escape sequences
    #[serde(default)]
    pub strip_ansi: bool,
    /// Whether to use color output
    #[serde(default = "default_use_color")]
    pub use_color: bool,
    /// Schema version for JSON output compatibility
    #[serde(default = "default_schema_version")]
    pub schema_version: String,
    /// Enable debug mode with detailed processing information
    #[serde(default)]
    pub debug: bool,
    /// Show line numbers (cat -n compatibility)
    #[serde(default)]
    pub show_line_numbers: bool,
    /// Show line numbers for non-blank lines only (cat -b compatibility)
    #[serde(default)]
    pub show_line_numbers_nonblank: bool,
    /// Pretty print JSON output (non-streaming JSON mode)
    #[serde(default)]
    pub pretty_json: bool,
    /// Include 1-based line numbers in JSON output lines array
    #[serde(default)]
    pub json_line_numbers: bool,
    /// Strip comment-only lines from output
    #[serde(default)]
    pub strip_comments: bool,
    /// Strip blank lines from output
    #[serde(default)]
    pub strip_blank_lines: bool,
}

const fn default_max_lines() -> usize {
    10000
}

const fn default_use_color() -> bool {
    true
}

fn default_schema_version() -> String {
    "2.1".to_string()
}

impl Default for BatlessConfig {
    fn default() -> Self {
        Self {
            max_lines: 10000,
            max_bytes: None,
            language: None,
            strip_ansi: false,
            use_color: true,
            schema_version: default_schema_version(),
            debug: false,
            show_line_numbers: false,
            show_line_numbers_nonblank: false,
            pretty_json: false,
            json_line_numbers: false,
            strip_comments: false,
            strip_blank_lines: false,
        }
    }
}

impl BatlessConfig {
    /// Create a new configuration with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum lines
    pub const fn with_max_lines(mut self, max_lines: usize) -> Self {
        self.max_lines = max_lines;
        self
    }

    /// Set maximum bytes
    pub const fn with_max_bytes(mut self, max_bytes: Option<usize>) -> Self {
        self.max_bytes = max_bytes;
        self
    }

    /// Set language override
    pub fn with_language(mut self, language: Option<String>) -> Self {
        self.language = language;
        self
    }

    /// Set ANSI stripping
    pub const fn with_strip_ansi(mut self, strip_ansi: bool) -> Self {
        self.strip_ansi = strip_ansi;
        self
    }

    /// Set color usage
    pub const fn with_use_color(mut self, use_color: bool) -> Self {
        self.use_color = use_color;
        self
    }

    /// Set schema version
    pub fn with_schema_version(mut self, version: String) -> Self {
        self.schema_version = version;
        self
    }

    /// Enable debug mode
    pub const fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Enable line numbering (cat -n compatibility)
    pub const fn with_show_line_numbers(mut self, show_line_numbers: bool) -> Self {
        self.show_line_numbers = show_line_numbers;
        self
    }

    /// Enable line numbering for non-blank lines only (cat -b compatibility)
    pub const fn with_show_line_numbers_nonblank(
        mut self,
        show_line_numbers_nonblank: bool,
    ) -> Self {
        self.show_line_numbers_nonblank = show_line_numbers_nonblank;
        self
    }

    /// Enable pretty JSON output
    pub const fn with_pretty_json(mut self, pretty: bool) -> Self {
        self.pretty_json = pretty;
        self
    }

    /// Include 1-based line numbers in JSON output lines array
    pub const fn with_json_line_numbers(mut self, enabled: bool) -> Self {
        self.json_line_numbers = enabled;
        self
    }

    /// Strip comment-only lines from output
    pub const fn with_strip_comments(mut self, enabled: bool) -> Self {
        self.strip_comments = enabled;
        self
    }

    /// Strip blank lines from output
    pub const fn with_strip_blank_lines(mut self, enabled: bool) -> Self {
        self.strip_blank_lines = enabled;
        self
    }

    /// Validate the configuration
    ///
    /// Delegates to [`crate::config_validation::validate_config`] for the actual checks.
    pub fn validate(&self) -> BatlessResult<()> {
        validate_config(self)
    }

    /// Check if color output should be used based on configuration and environment
    pub const fn should_use_color(&self, is_terminal: bool) -> bool {
        self.use_color && is_terminal
    }

    /// Get the effective maximum lines (considering both line and byte limits)
    pub const fn effective_max_lines(&self) -> usize {
        self.max_lines
    }

    /// Check if byte limiting is enabled
    pub const fn has_byte_limit(&self) -> bool {
        self.max_bytes.is_some()
    }

    /// Get byte limit if set
    pub const fn get_byte_limit(&self) -> Option<usize> {
        self.max_bytes
    }

    /// Load configuration from a TOML file
    pub fn from_file<P: AsRef<Path>>(path: P) -> BatlessResult<Self> {
        let content = fs::read_to_string(path.as_ref()).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to read config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check that the file exists and has proper permissions".to_string()),
            )
        })?;

        let config: Self = toml::from_str(&content).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to parse config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check the TOML syntax - use 'batless --help' for valid options".to_string()),
            )
        })?;

        config.validate()?;
        Ok(config)
    }

    /// Load configuration from JSON file (.batlessrc format)
    pub fn from_json_file<P: AsRef<Path>>(path: P) -> BatlessResult<Self> {
        let content = fs::read_to_string(path.as_ref()).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to read config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check that the file exists and has proper permissions".to_string()),
            )
        })?;

        let config: Self = serde_json::from_str(&content).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to parse config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check the JSON syntax - use 'batless --help' for valid options".to_string()),
            )
        })?;

        config.validate()?;
        Ok(config)
    }

    /// Save configuration to a TOML file
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> BatlessResult<()> {
        let content = toml::to_string_pretty(self).map_err(|e| {
            BatlessError::config_error_with_help(
                format!("Failed to serialize config: {e}"),
                Some("This is likely a bug - please report it".to_string()),
            )
        })?;

        fs::write(path.as_ref(), content).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to write config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check that the directory exists and has write permissions".to_string()),
            )
        })
    }

    /// Find configuration files in standard locations
    /// Returns a list of config file paths in order of precedence (highest first)
    pub fn find_config_files() -> Vec<PathBuf> {
        let mut paths = Vec::new();

        // 1. Project-level config files (highest precedence)
        paths.push(PathBuf::from(".batlessrc"));
        paths.push(PathBuf::from("batless.toml"));

        // 2. User home directory config files
        if let Some(home_dir) = dirs::home_dir() {
            paths.push(home_dir.join(".batlessrc"));
            paths.push(home_dir.join(".config/batless/config.toml"));
            paths.push(home_dir.join(".config/batless.toml"));
        }

        // 3. System config directories (lowest precedence)
        if let Some(config_dir) = dirs::config_dir() {
            paths.push(config_dir.join("batless/config.toml"));
        }

        paths
    }

    /// Load configuration with precedence: CLI args > project config > user config > defaults
    pub fn load_with_precedence() -> BatlessResult<Self> {
        let mut config = Self::default();

        // Try to load from config files in reverse precedence order
        for config_path in Self::find_config_files().into_iter().rev() {
            if config_path.exists() {
                let file_config = if config_path.extension() == Some(std::ffi::OsStr::new("toml")) {
                    Self::from_file(&config_path)?
                } else {
                    Self::from_json_file(&config_path)?
                };
                config = config.merge_with(file_config);
            }
        }

        Ok(config)
    }

    /// Merge this configuration with another, taking non-default values from the other
    pub fn merge_with(mut self, other: Self) -> Self {
        let default = Self::default();

        // Only update if the other value is different from default
        if other.max_lines != default.max_lines {
            self.max_lines = other.max_lines;
        }
        if other.max_bytes != default.max_bytes {
            self.max_bytes = other.max_bytes;
        }
        if other.language != default.language {
            self.language = other.language;
        }
        if other.strip_ansi != default.strip_ansi {
            self.strip_ansi = other.strip_ansi;
        }
        if other.use_color != default.use_color {
            self.use_color = other.use_color;
        }
        if other.schema_version != default.schema_version {
            self.schema_version = other.schema_version;
        }
        if other.debug != default.debug {
            self.debug = other.debug;
        }
        if other.show_line_numbers != default.show_line_numbers {
            self.show_line_numbers = other.show_line_numbers;
        }
        if other.show_line_numbers_nonblank != default.show_line_numbers_nonblank {
            self.show_line_numbers_nonblank = other.show_line_numbers_nonblank;
        }
        if other.pretty_json != default.pretty_json {
            self.pretty_json = other.pretty_json;
        }
        if other.json_line_numbers != default.json_line_numbers {
            self.json_line_numbers = other.json_line_numbers;
        }
        if other.strip_comments != default.strip_comments {
            self.strip_comments = other.strip_comments;
        }
        if other.strip_blank_lines != default.strip_blank_lines {
            self.strip_blank_lines = other.strip_blank_lines;
        }

        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_default_config() {
        let config = BatlessConfig::default();
        assert_eq!(config.max_lines, 10000);
        assert_eq!(config.max_bytes, None);
        assert_eq!(config.language, None);
        assert!(!config.strip_ansi);
        assert!(config.use_color);
    }

    #[test]
    fn test_builder_pattern() {
        let config = BatlessConfig::new()
            .with_max_lines(5000)
            .with_max_bytes(Some(1024))
            .with_language(Some("rust".to_string()))
            .with_strip_ansi(true)
            .with_use_color(false);

        assert_eq!(config.max_lines, 5000);
        assert_eq!(config.max_bytes, Some(1024));
        assert_eq!(config.language, Some("rust".to_string()));
        assert!(config.strip_ansi);
        assert!(!config.use_color);
    }

    #[test]
    fn test_validate_delegates_to_config_validation() {
        assert!(BatlessConfig::default().validate().is_ok());
        assert!(BatlessConfig::default()
            .with_max_lines(0)
            .validate()
            .is_err());
    }

    #[test]
    fn test_should_use_color() {
        let config = BatlessConfig::default();
        assert!(config.should_use_color(true));
        assert!(!config.should_use_color(false));

        let config_no_color = config.with_use_color(false);
        assert!(!config_no_color.should_use_color(true));
        assert!(!config_no_color.should_use_color(false));
    }

    #[test]
    fn test_byte_limit_helpers() {
        let config = BatlessConfig::default();
        assert!(!config.has_byte_limit());
        assert_eq!(config.get_byte_limit(), None);

        let config_with_limit = config.with_max_bytes(Some(1024));
        assert!(config_with_limit.has_byte_limit());
        assert_eq!(config_with_limit.get_byte_limit(), Some(1024));
    }

    #[test]
    fn test_toml_serialization() {
        let config = BatlessConfig::default().with_max_lines(5000);

        let toml_str = toml::to_string_pretty(&config).unwrap();
        assert!(toml_str.contains("max_lines = 5000"));

        let deserialized: BatlessConfig = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized.max_lines, 5000);
    }

    #[test]
    fn test_json_serialization() {
        let config = BatlessConfig::default().with_max_lines(3000);

        let json_str = serde_json::to_string_pretty(&config).unwrap();
        let deserialized: BatlessConfig = serde_json::from_str(&json_str).unwrap();
        assert_eq!(deserialized.max_lines, 3000);
    }

    #[test]
    fn test_merge_with() {
        let base = BatlessConfig::default();
        let override_config = BatlessConfig::default()
            .with_max_lines(2000)
            .with_schema_version("9.9".to_string())
            .with_debug(true)
            .with_show_line_numbers(true)
            .with_show_line_numbers_nonblank(true)
            .with_pretty_json(true);

        let merged = base.merge_with(override_config);
        assert_eq!(merged.max_lines, 2000);
        assert_eq!(merged.schema_version, "9.9");
        assert!(merged.debug);
        assert!(merged.show_line_numbers);
        assert!(merged.show_line_numbers_nonblank);
        assert!(merged.pretty_json);
        // Other values should remain default
        assert!(!merged.strip_ansi);
        assert!(merged.use_color);
    }

    #[test]
    fn test_config_file_discovery() {
        let paths = BatlessConfig::find_config_files();
        assert!(!paths.is_empty());
        assert!(paths
            .iter()
            .any(|p| p.file_name() == Some(std::ffi::OsStr::new(".batlessrc"))));
        assert!(paths
            .iter()
            .any(|p| p.file_name() == Some(std::ffi::OsStr::new("batless.toml"))));
    }

    #[test]
    fn test_load_from_toml_file() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let toml_content = r"
max_lines = 15000
use_color = false
";

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(toml_content.as_bytes()).unwrap();

        let config = BatlessConfig::from_file(temp_file.path()).unwrap();
        assert_eq!(config.max_lines, 15000);
        assert!(!config.use_color);
    }

    #[test]
    fn test_load_from_json_file() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let json_content = r#"{
  "max_lines": 8000,
  "strip_ansi": true
}"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(json_content.as_bytes()).unwrap();

        let config = BatlessConfig::from_json_file(temp_file.path()).unwrap();
        assert_eq!(config.max_lines, 8000);
        assert!(config.strip_ansi);
    }

    #[test]
    fn test_invalid_toml_config() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let invalid_toml = r#"
max_lines = "not_a_number"
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(invalid_toml.as_bytes()).unwrap();

        let result = BatlessConfig::from_file(temp_file.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_save_to_file() {
        use tempfile::NamedTempFile;

        let config = BatlessConfig::default().with_max_lines(7000);

        let temp_file = NamedTempFile::new().unwrap();
        config.save_to_file(temp_file.path()).unwrap();

        let loaded_config = BatlessConfig::from_file(temp_file.path()).unwrap();
        assert_eq!(loaded_config.max_lines, 7000);
    }
}