rfgrep 0.3.0

Advanced recursive file grep utility with comprehensive file type classification - search, list, and analyze 153+ file formats with intelligent filtering and safety policies
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
# Rfgrep Library Documentation

## Overview
The rfgrep library provides a comprehensive, modular search system with advanced features including streaming search, plugin architecture, TUI interface, and multiple search algorithms.

## Core Library Structure

### Public API Exports
```rust
// Main types and functions
pub use crate::error::Result;
pub use clap::Parser;
pub use cli::{Cli, Commands, SearchMode};
pub use list::FileInfo;
pub use processor::{is_binary, search_file};
pub use search_algorithms::{
    BoyerMoore, RegexSearch, SearchAlgorithm, SearchAlgorithmFactory, 
    SearchMatch, SimdSearch, SimpleSearch,
};
pub use std::path::PathBuf;
pub use walker::walk_dir;
```

## New Module Implementations

### 1. `app_simple` - Simplified Application Architecture

#### Purpose
Provides a streamlined application structure that orchestrates all rfgrep functionality.

#### Key Components

##### `RfgrepApp` Struct
```rust
pub struct RfgrepApp {
    plugin_manager: Arc<EnhancedPluginManager>,
}
```

**Features:**
- Centralized application management
- Plugin system integration
- Async runtime management
- Command routing and delegation

**Methods:**
- `new()` - Initialize application with plugin system
- `run(cli: Cli)` - Main application entry point
- `handle_search()` - Process search commands with streaming pipeline
- `handle_plugin_command()` - Delegate plugin management commands
- `handle_tui_command()` - Launch interactive TUI interface

#### Usage Example
```rust
use rfgrep::app_simple::RfgrepApp;
use rfgrep::cli::Cli;

let app = RfgrepApp::new()?;
let cli = Cli::parse();
app.run(cli).await?;
```

### 2. `streaming_search` - High-Performance Streaming Search

#### Purpose
Provides efficient, memory-conscious search capabilities for large files and datasets.

#### Key Components

##### `StreamingConfig` Struct
```rust
pub struct StreamingConfig {
    pub algorithm: SearchAlgorithm,
    pub context_lines: usize,
    pub case_sensitive: bool,
    pub invert_match: bool,
    pub max_matches: Option<usize>,
    pub timeout_per_file: Option<u64>,
    pub chunk_size: usize,      // Default: 8KB
    pub buffer_size: usize,     // Default: 64KB
}
```

##### `StreamingSearchPipeline` Struct
```rust
pub struct StreamingSearchPipeline {
    config: StreamingConfig,
}
```

**Features:**
- Chunk-based file processing
- Parallel file search with configurable workers
- Memory-efficient streaming
- Binary file detection and skipping
- Context line management
- Performance estimation and algorithm suggestion

**Methods:**
- `new(config)` - Create pipeline with configuration
- `search_file(path, pattern)` - Search single file
- `search_files_parallel(files, pattern, workers)` - Parallel multi-file search
- `process_file_streaming()` - Low-level streaming processor
- `estimate_performance()` - Performance prediction
- `suggest_algorithm()` - Algorithm recommendation

#### Usage Example
```rust
use rfgrep::streaming_search::{StreamingConfig, StreamingSearchPipeline};
use rfgrep::search_algorithms::SearchAlgorithm;

let config = StreamingConfig {
    algorithm: SearchAlgorithm::BoyerMoore,
    context_lines: 3,
    case_sensitive: true,
    chunk_size: 16384,
    buffer_size: 131072,
    ..Default::default()
};

let pipeline = StreamingSearchPipeline::new(config);
let matches = pipeline.search_file(&path, "pattern").await?;
```

### 3. `plugin_system` - Enhanced Plugin Architecture

#### Purpose
Provides a flexible, extensible plugin system for custom search implementations.

#### Key Components

##### `EnhancedSearchPlugin` Trait
```rust
pub trait EnhancedSearchPlugin: Send + Sync {
    fn name(&self) -> &str;
    fn version(&self) -> &str;
    fn description(&self) -> &str;
    fn can_handle(&self, file: &Path) -> bool;
    fn priority(&self) -> u32;
    fn search(&self, file: &Path, pattern: &str) -> RfgrepResult<Vec<SearchMatch>>;
    fn supported_extensions(&self) -> Vec<String>;
    fn get_config_options(&self) -> HashMap<String, PluginConfigOption>;
    fn update_config(&mut self, config: HashMap<String, serde_json::Value>) -> RfgrepResult<()>;
    fn supports_streaming(&self) -> bool;
    fn preferred_algorithm(&self) -> Option<SearchAlgorithm>;
}
```

##### `EnhancedPluginManager` Struct
```rust
pub struct EnhancedPluginManager {
    plugins: Arc<RwLock<HashMap<String, Box<dyn EnhancedSearchPlugin>>>>,
    plugin_configs: Arc<RwLock<HashMap<String, PluginConfig>>>,
    streaming_pipeline: Option<StreamingSearchPipeline>,
}
```

**Features:**
- Dynamic plugin loading and management
- Configuration management per plugin
- Priority-based plugin selection
- Streaming search integration
- Plugin statistics and monitoring
- Extensible configuration system

**Built-in Plugins:**
- `EnhancedTextSearchPlugin` - Advanced text file search
- `EnhancedBinarySearchPlugin` - Binary file search with metadata

##### `PluginRegistry` Struct
```rust
pub struct PluginRegistry {
    manager: Arc<EnhancedPluginManager>,
}
```

**Methods:**
- `load_plugins()` - Discover and load available plugins
- `register_plugin()` - Manually register plugins
- `unregister_plugin()` - Remove plugins
- `list_plugins()` - Get plugin information
- `get_plugin_stats()` - Retrieve usage statistics

#### Usage Example
```rust
use rfgrep::plugin_system::{EnhancedPluginManager, PluginRegistry};

let manager = Arc::new(EnhancedPluginManager::new());
let registry = PluginRegistry::new(manager.clone());
registry.load_plugins().await?;

let matches = manager.search_file(&path, "pattern").await?;
```

### 4. `plugin_cli` - Plugin Management CLI

#### Purpose
Provides command-line interface for plugin management and configuration.

#### Key Components

##### `PluginCli` Struct
```rust
pub struct PluginCli {
    manager: Arc<EnhancedPluginManager>,
}
```

**Commands:**
- `list` - List all available plugins
- `stats` - Show plugin usage statistics
- `info <name>` - Display detailed plugin information
- `enable <name>` - Enable a plugin
- `disable <name>` - Disable a plugin
- `priority <name> <priority>` - Set plugin priority
- `config <name>` - Show plugin configuration
- `test <name>` - Test plugin functionality

#### Usage Example
```rust
use rfgrep::plugin_cli::PluginCli;

let plugin_cli = PluginCli::new(manager);
plugin_cli.handle_command(PluginCommands::List).await?;
```

### 5. `tui` - Modern Terminal User Interface

#### Purpose
Provides an interactive, modern TUI using ratatui for enhanced user experience.

#### Key Components

##### `TuiState` Struct
```rust
pub struct TuiState {
    pub pattern: String,
    pub matches: Vec<SearchMatch>,
    pub current_file_index: usize,
    pub current_match_index: usize,
    pub files: Vec<String>,
    pub search_mode: SearchMode,
    pub algorithm: SearchAlgorithm,
    pub case_sensitive: bool,
    pub context_lines: usize,
    pub show_help: bool,
    pub status_message: String,
    pub search_in_progress: bool,
    pub scroll_offset: usize,
}
```

##### `TuiApp` Struct
```rust
pub struct TuiApp {
    pub state: TuiState,
    plugin_manager: Arc<EnhancedPluginManager>,
    streaming_pipeline: Option<StreamingSearchPipeline>,
    terminal: Terminal<CrosstermBackend<Stdout>>,
    should_quit: bool,
}
```

**Features:**
- Real-time search with live updates
- Interactive file and match navigation
- Configurable search parameters
- Plugin integration
- Keyboard shortcuts and help system
- Responsive layout with multiple panels
- Status messages and progress indicators

**UI Components:**
- Header with search pattern and status
- File list with match counts
- Match details with context
- Help panel with keyboard shortcuts
- Status bar with current settings

**Key Bindings:**
- `q` - Quit application
- `h` - Toggle help
- `j/k` - Navigate matches
- `n/N` - Next/previous match
- `c` - Toggle case sensitivity
- `m` - Cycle search modes
- `a` - Cycle algorithms
- `Enter` - Open current file

#### Usage Example
```rust
use rfgrep::tui::{TuiApp, init_terminal, restore_terminal};

let mut terminal = init_terminal()?;
let mut app = TuiApp::new()?;
app.run(&mut terminal).await?;
restore_terminal(&mut terminal)?;
```

## Configuration and Utilities

### `AppConfig` Struct
```rust
pub struct AppConfig {
    pub chunk_size: Option<u32>,
    pub rfgrep_exe: PathBuf,
    pub results_dir: PathBuf,
}
```

**Methods:**
- `from_cli(cli: &Cli)` - Create from CLI arguments
- `load_config()` - Load from configuration file

### Utility Functions
```rust
pub fn run_external_command(command: &str, args: &[&str], env: Option<&str>) -> std::io::Result<()>
pub fn run_benchmarks(config: &AppConfig, test_dir: &Path) -> Result<()>
pub fn run_benchmarks_cli(cli: &Cli) -> Result<()>
```

## Integration Examples

### Complete Application Setup
```rust
use rfgrep::app_simple::RfgrepApp;
use rfgrep::cli::Cli;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = RfgrepApp::new()?;
    let cli = Cli::parse();
    app.run(cli).await?;
    Ok(())
}
```

### Custom Plugin Implementation
```rust
use rfgrep::plugin_system::EnhancedSearchPlugin;
use rfgrep::processor::SearchMatch;

struct CustomSearchPlugin {
    config: HashMap<String, serde_json::Value>,
}

impl EnhancedSearchPlugin for CustomSearchPlugin {
    fn name(&self) -> &str { "custom" }
    fn version(&self) -> &str { "1.0.0" }
    fn description(&self) -> &str { "Custom search plugin" }
    fn can_handle(&self, file: &Path) -> bool {
        file.extension().map_or(false, |ext| ext == "custom")
    }
    fn search(&self, file: &Path, pattern: &str) -> RfgrepResult<Vec<SearchMatch>> {
        // Custom search implementation
        Ok(vec![])
    }
    // ... implement other required methods
}
```

### Streaming Search with Custom Configuration
```rust
use rfgrep::streaming_search::{StreamingConfig, StreamingSearchPipeline};
use rfgrep::search_algorithms::SearchAlgorithm;

let config = StreamingConfig {
    algorithm: SearchAlgorithm::Simd,
    context_lines: 5,
    case_sensitive: false,
    max_matches: Some(1000),
    chunk_size: 32768,
    buffer_size: 262144,
    ..Default::default()
};

let pipeline = StreamingSearchPipeline::new(config);
let files = vec![Path::new("file1.txt"), Path::new("file2.txt")];
let file_refs: Vec<&Path> = files.iter().map(|p| p.as_path()).collect();
let matches = pipeline.search_files_parallel(&file_refs, "pattern", 4).await?;
```

## Performance Characteristics

### Streaming Search
- **Memory Usage**: O(chunk_size) per file
- **Throughput**: ~100-500 MB/s depending on algorithm
- **Scalability**: Handles files of any size
- **Parallelism**: Configurable worker threads

### Plugin System
- **Loading**: Lazy loading with caching
- **Performance**: Minimal overhead (~1-5% for plugin selection)
- **Extensibility**: Hot-swappable plugins
- **Configuration**: Runtime configurable

### TUI Interface
- **Responsiveness**: 60 FPS rendering
- **Memory**: O(matches) for display state
- **Latency**: <16ms for user interactions
- **Scalability**: Handles 10,000+ matches efficiently

## Error Handling

All modules use the centralized `RfgrepResult<T>` type for consistent error handling:

```rust
pub type Result<T> = std::result::Result<T, RfgrepError>;

pub enum RfgrepError {
    Io(std::io::Error),
    Regex(regex::Error),
    Other(String),
    // ... other error types
}
```

## Thread Safety

All public APIs are designed for concurrent use:
- `Send + Sync` bounds on all public traits
- `Arc<RwLock<T>>` for shared mutable state
- Async/await support throughout
- Thread-safe plugin loading and management

## Future Extensibility

The library is designed for easy extension:
- Plugin system supports custom search algorithms
- Streaming pipeline can be extended with new processors
- TUI can be customized with additional widgets
- Configuration system supports arbitrary key-value pairs
- CLI can be extended with new commands and options