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
//! # OpenGrep Library
//!
//! Advanced AST-aware code search with AI-powered insights. OpenGrep understands
//! code structure and provides intelligent search capabilities beyond simple pattern matching.
//!
//! ## Overview
//!
//! OpenGrep is a powerful code search tool that combines traditional pattern matching
//! with Abstract Syntax Tree (AST) analysis and optional AI integration. It supports
//! over 15 programming languages and provides various output formats for integration
//! into development workflows.
//!
//! ## Key Features
//!
//! - **AST-Aware Search**: Uses tree-sitter to understand code structure and context
//! - **Multi-Language Support**: Supports 20+ programming languages out of the box
//! - **AI Integration**: Optional OpenAI integration for intelligent code insights
//! - **High Performance**: Parallel search with efficient file traversal and caching
//! - **Flexible Output**: Multiple output formats (Text, JSON, HTML, XML, CSV)
//! - **Interactive Mode**: Built-in interactive search interface with fuzzy matching
//! - **Configuration**: Extensive configuration options via files and environment variables
//!
//! ## Supported Languages
//!
//! - **System Languages**: Rust, C, C++, Go
//! - **Web Languages**: JavaScript, TypeScript, CSS, HTML
//! - **Enterprise Languages**: Java, C#, Python
//! - **Scripting Languages**: Ruby, Bash, Shell
//! - **Data Languages**: JSON, TOML, YAML, XML
//!
//! ## Quick Start
//!
//! ### Basic Search
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! // Create default configuration
//! let config = Config::default();
//! let engine = SearchEngine::new(config);
//!
//! // Search for TODO comments in source directory
//! let results = engine.search("TODO", &[PathBuf::from("src")]).await?;
//!
//! // Process results
//! for result in results {
//! println!("Found {} matches in {}",
//! result.matches.len(),
//! result.path.display());
//!
//! for match_item in &result.matches {
//! println!(" Line {}: {}",
//! match_item.line_number,
//! match_item.line_text.trim());
//! }
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### AST-Aware Search
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let mut config = Config::default();
//! config.output.show_ast_context = true;
//! config.output.max_ast_depth = 3;
//!
//! let engine = SearchEngine::new(config);
//!
//! // Search for function implementations with AST context
//! let results = engine.search("fn.*impl", &[PathBuf::from("src")]).await?;
//!
//! for result in results {
//! for match_item in &result.matches {
//! if let Some(ast_context) = &match_item.ast_context {
//! println!("Found in {}: {}",
//! ast_context.summary,
//! match_item.line_text.trim());
//! }
//! }
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### Custom Configuration
//!
//! ```rust
//! use opengrep::{Config, SearchConfig, OutputConfig, AIConfig};
//!
//! let mut config = Config::default();
//!
//! // Configure search behavior
//! config.search.ignore_case = true;
//! config.search.regex = true;
//! config.search.context = 3;
//! config.search.threads = 8;
//! config.search.max_file_size = 10 * 1024 * 1024; // 10MB
//!
//! // Configure output formatting
//! config.output.show_line_numbers = true;
//! config.output.show_ast_context = true;
//! config.output.color = true;
//! config.output.before_context = 2;
//! config.output.after_context = 2;
//!
//! // Configure AI features (optional)
//! #[cfg(feature = "ai")]
//! {
//! config.ai.model = "gpt-4o-mini".to_string();
//! config.ai.enable_insights = true;
//! config.ai.max_tokens = 2000;
//! }
//! ```
//!
//! ### Parallel Processing
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let mut config = Config::default();
//! config.search.threads = num_cpus::get(); // Use all available cores
//!
//! let engine = SearchEngine::new(config);
//!
//! // Search multiple directories in parallel
//! let paths = vec![
//! PathBuf::from("src"),
//! PathBuf::from("tests"),
//! PathBuf::from("examples"),
//! ];
//!
//! let results = engine.search("FIXME|TODO|XXX", &paths).await?;
//!
//! println!("Found {} files with issues",
//! results.iter().filter(|r| !r.matches.is_empty()).count());
//!
//! Ok(())
//! }
//! ```
//!
//! ## Output Formats
//!
//! OpenGrep supports multiple output formats for integration with different tools:
//!
//! ### JSON Output
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine, output::OutputFormatter};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let config = Config::default();
//! let engine = SearchEngine::new(config);
//! let results = engine.search("pattern", &[PathBuf::from(".")]).await?;
//!
//! // Output as JSON
//! let json_output = serde_json::to_string_pretty(&results)?;
//! println!("{}", json_output);
//!
//! Ok(())
//! }
//! ```
//!
//! ## Error Handling
//!
//! OpenGrep uses the `anyhow` crate for error handling, providing rich error context:
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() {
//! let config = Config::default();
//! let engine = SearchEngine::new(config);
//!
//! match engine.search("pattern", &[PathBuf::from("nonexistent")]).await {
//! Ok(results) => {
//! println!("Found {} results", results.len());
//! }
//! Err(e) => {
//! eprintln!("Search failed: {}", e);
//! // Error context includes file paths, parsing errors, etc.
//! for cause in e.chain().skip(1) {
//! eprintln!(" Caused by: {}", cause);
//! }
//! }
//! }
//! }
//! ```
//!
//! ## Performance Optimization
//!
//! For large codebases, consider these performance optimizations:
//!
//! ```rust
//! use opengrep::{Config, SearchConfig};
//!
//! let mut config = Config::default();
//!
//! // Increase thread count for I/O bound operations
//! config.search.threads = num_cpus::get() * 2;
//!
//! // Set reasonable file size limits
//! config.search.max_file_size = 5 * 1024 * 1024; // 5MB limit
//!
//! // Use ignore patterns to skip irrelevant files
//! config.search.ignore_patterns = vec![
//! "*.log".to_string(),
//! "target/**".to_string(),
//! "node_modules/**".to_string(),
//! ];
//!
//! // Enable memory-efficient streaming for large files
//! config.search.streaming = true;
//! ```
//!
//! ## AI Integration
//!
//! When the `ai` feature is enabled, OpenGrep can provide intelligent code insights:
//!
//! ```rust,no_run
//! #[cfg(feature = "ai")]
//! use opengrep::{Config, SearchEngine, ai::AIAnalyzer};
//!
//! #[cfg(feature = "ai")]
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let mut config = Config::default();
//! config.ai.enable_insights = true;
//! config.ai.model = "gpt-4o-mini".to_string();
//!
//! let engine = SearchEngine::new(config);
//! let results = engine.search("unsafe", &[std::path::PathBuf::from("src")]).await?;
//!
//! // AI analysis provides context about unsafe code usage
//! for result in results {
//! for match_item in &result.matches {
//! if let Some(ai_insight) = &match_item.ai_insight {
//! println!("AI Analysis: {}", ai_insight.summary);
//! println!("Suggestion: {}", ai_insight.suggestion);
//! }
//! }
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ## Integration Examples
//!
//! ### CI/CD Pipeline Integration
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let config = Config::default();
//! let engine = SearchEngine::new(config);
//!
//! // Check for common issues in CI
//! let issues = vec![
//! ("TODO", "Unfinished work"),
//! ("FIXME", "Known bugs"),
//! ("XXX", "Problematic areas"),
//! ("println!", "Debug statements"),
//! ];
//!
//! let mut total_issues = 0;
//!
//! for (pattern, description) in issues {
//! let results = engine.search(pattern, &[PathBuf::from("src")]).await?;
//! let count: usize = results.iter().map(|r| r.matches.len()).sum();
//!
//! if count > 0 {
//! println!("Warning: Found {} instances of {}", count, description);
//! total_issues += count;
//! }
//! }
//!
//! if total_issues > 0 {
//! std::process::exit(1); // Fail CI if issues found
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### Code Review Integration
//!
//! ```rust,no_run
//! use opengrep::{Config, SearchEngine, output::json::JsonFormatter};
//! use std::path::PathBuf;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let mut config = Config::default();
//! config.output.show_ast_context = true;
//!
//! let engine = SearchEngine::new(config);
//!
//! // Find potential security issues
//! let security_patterns = vec![
//! "unsafe",
//! "transmute",
//! "eval\\(",
//! "exec\\(",
//! "system\\(",
//! ];
//!
//! for pattern in security_patterns {
//! let results = engine.search(pattern, &[PathBuf::from(".")]).await?;
//!
//! if !results.is_empty() {
//! // Generate detailed JSON report for code review tools
//! let json_report = serde_json::to_string_pretty(&results)?;
//! std::fs::write(format!("security-report-{}.json", pattern), json_report)?;
//! }
//! }
//!
//! Ok(())
//! }
//! ```
use Result;
/// Library version
pub const VERSION: &str = env!;
// Re-export main types
pub use Config;
pub use ;
/// Initialize logging based on verbosity level
///
/// # Arguments
///
/// * `verbose` - Verbosity level (0-4)
/// - 0: ERROR only
/// - 1: WARN and above
/// - 2: INFO and above
/// - 3: DEBUG and above
/// - 4+: TRACE and above
///
/// # Example
///
/// ```rust
/// use opengrep::init_logging;
///
/// // Initialize with INFO level logging
/// init_logging(2).expect("Failed to initialize logging");
/// ```
/// Re-export commonly used types for convenience