turboprop 0.1.2

Fast semantic code search and indexing tool
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
//! Search command implementation for the TurboProp CLI.
//!
//! This module provides the complete search command functionality including
//! query processing, result filtering, output formatting, and error handling.

use anyhow::{Context, Result};
use std::path::Path;
use tracing::{debug, info, warn};

use crate::filters::SearchFilter;
use crate::model_validation::{validate_instruction_compatibility, validate_model_selection};
use crate::output::{OutputFormat, ResultFormatter};
use crate::search_with_config;

/// Threshold for warning about large result limits that may impact performance
const LARGE_RESULT_LIMIT_WARNING_THRESHOLD: usize = 1000;

/// Configuration for the search command
#[derive(Debug, Clone)]
pub struct SearchCommandConfig {
    /// The search query string
    pub query: String,
    /// Repository path to search in
    pub repo_path: String,
    /// Maximum number of results to return
    pub limit: usize,
    /// Minimum similarity threshold (0.0 to 1.0)
    pub threshold: Option<f32>,
    /// Output format (json or text)
    pub output_format: OutputFormat,
    /// Optional file extension filter
    pub filetype: Option<String>,
    /// Optional glob pattern filter
    pub glob_pattern: Option<String>,
}

impl SearchCommandConfig {
    /// Create a new search command configuration
    pub fn new(
        query: String,
        repo_path: String,
        limit: usize,
        threshold: Option<f32>,
        output_format: OutputFormat,
        filetype: Option<String>,
        glob_pattern: Option<String>,
    ) -> Self {
        Self {
            query,
            repo_path,
            limit,
            threshold,
            output_format,
            filetype,
            glob_pattern,
        }
    }

    /// Validate the search command configuration
    pub fn validate(&self) -> Result<()> {
        // Validate query
        crate::query::validate_query(&self.query)
            .with_context(|| format!("Search query validation failed: '{}'", self.query))?;

        // Validate repository path
        let repo_path = Path::new(&self.repo_path);
        if !repo_path.exists() {
            return Err(anyhow::anyhow!("Repository path does not exist"))
                .with_context(|| format!("Invalid repository path: {}", self.repo_path));
        }

        // Validate threshold range
        if let Some(threshold) = self.threshold {
            if !(0.0..=1.0).contains(&threshold) {
                return Err(anyhow::anyhow!("Threshold out of valid range")).with_context(|| {
                    format!("Threshold must be between 0.0 and 1.0, got: {}", threshold)
                });
            }
        }

        // Validate limit
        if self.limit == 0 {
            return Err(anyhow::anyhow!("Invalid limit value"))
                .with_context(|| format!("Limit must be greater than 0, got: {}", self.limit));
        }

        if self.limit > LARGE_RESULT_LIMIT_WARNING_THRESHOLD {
            warn!(
                "Large result limit specified ({}), this may impact performance",
                self.limit
            );
        }

        // Validate file extension if provided
        if let Some(ref filetype) = self.filetype {
            crate::filters::normalize_file_extension(filetype)
                .with_context(|| format!("File extension validation failed for '{}'", filetype))?;
        }

        // Validate glob pattern if provided
        if let Some(ref glob_pattern) = self.glob_pattern {
            crate::filters::validate_glob_pattern(glob_pattern).with_context(|| {
                format!("Glob pattern validation failed for '{}'", glob_pattern)
            })?;
        }

        Ok(())
    }
}

/// Execute the search command with comprehensive error handling and logging
pub async fn execute_search_command(
    config: SearchCommandConfig,
    turboprop_config: &crate::config::TurboPropConfig,
) -> Result<()> {
    info!("Starting search command execution");
    debug!("Search config: {:?}", config);

    // Validate configuration
    config
        .validate()
        .context("Search configuration validation failed")?;

    // Validate the specified embedding model
    let model_info = validate_model_selection(&turboprop_config.embedding.model_name)
        .await
        .with_context(|| {
            format!(
                "Model validation failed for '{}'",
                turboprop_config.embedding.model_name
            )
        })?;

    // Validate instruction compatibility if instruction is provided
    validate_instruction_compatibility(
        &model_info,
        turboprop_config.current_instruction.as_deref(),
    )
    .with_context(|| "Instruction validation failed")?;

    // Log search parameters
    info!("Searching for: '{}'", config.query);
    info!("Repository: {}", config.repo_path);
    info!("Output format: {}", config.output_format);
    info!("Result limit: {}", config.limit);

    if let Some(threshold) = config.threshold {
        info!("Similarity threshold: {:.1}%", threshold * 100.0);
    }

    if let Some(ref glob_pattern) = config.glob_pattern {
        info!("Glob pattern filter: {}", glob_pattern);
    }

    // Create search filter with configuration
    let search_filter = SearchFilter::from_cli_args_with_config(
        config.filetype.clone(),
        config.glob_pattern.clone(),
        turboprop_config,
    );

    if search_filter.has_active_filters() {
        let filter_descriptions = search_filter.describe_filters();
        info!("Active filters: {}", filter_descriptions.join(", "));
    }

    // Perform the search
    info!("Executing search query...");
    let repo_path = Path::new(&config.repo_path);

    let results = search_with_config(
        &config.query,
        repo_path,
        Some(config.limit),
        config.threshold,
    )
    .await
    .context("Search execution failed")?;

    debug!("Raw search returned {} results", results.len());

    // Apply filters to results
    let filtered_results = search_filter
        .apply_filters(results)
        .context("Failed to apply result filters")?;

    info!("Found {} results after filtering", filtered_results.len());

    // Format and output results
    let formatter = ResultFormatter::new(config.output_format, turboprop_config.search.clone());

    if filtered_results.is_empty() {
        formatter
            .print_no_results(&config.query, config.threshold)
            .with_context(|| {
                format!(
                    "Failed to format no-results output for query '{}'",
                    config.query
                )
            })?;
    } else {
        formatter
            .print_results(&filtered_results, &config.query)
            .with_context(|| {
                format!(
                    "Failed to format {} search results for query '{}'",
                    filtered_results.len(),
                    config.query
                )
            })?;
    }

    info!("Search command completed successfully");
    Ok(())
}

/// CLI arguments for the search command
#[derive(Debug, Clone)]
pub struct SearchCliArgs {
    pub query: String,
    pub repo: std::path::PathBuf,
    pub limit: usize,
    pub threshold: Option<f32>,
    pub output: String,
    pub filetype: Option<String>,
    pub filter: Option<String>,
}

impl SearchCliArgs {
    /// Create a new SearchCliArgs instance
    pub fn new(
        query: String,
        repo: std::path::PathBuf,
        limit: usize,
        threshold: Option<f32>,
        output: String,
        filetype: Option<String>,
        filter: Option<String>,
    ) -> Self {
        Self {
            query,
            repo,
            limit,
            threshold,
            output,
            filetype,
            filter,
        }
    }
}

/// Execute search command from CLI arguments
pub async fn execute_search_command_cli(
    args: SearchCliArgs,
    turboprop_config: &crate::config::TurboPropConfig,
) -> Result<()> {
    // Parse output format
    let output_format: OutputFormat = args
        .output
        .parse()
        .map_err(|e| anyhow::anyhow!("{}", e))
        .with_context(|| format!("Invalid output format: '{}'", args.output))?;

    // Create configuration
    let config = SearchCommandConfig::new(
        args.query,
        args.repo.to_string_lossy().to_string(),
        args.limit,
        args.threshold,
        output_format,
        args.filetype,
        args.filter,
    );

    // Execute the command
    execute_search_command(config, turboprop_config).await
}

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

    #[test]
    fn test_search_command_config_validation() {
        // Valid configuration
        let config = SearchCommandConfig::new(
            "test query".to_string(),
            ".".to_string(),
            10,
            Some(0.5),
            OutputFormat::Json,
            Some("rs".to_string()),
            Some("*.rs".to_string()),
        );
        assert!(config.validate().is_ok());

        // Empty query should fail
        let config = SearchCommandConfig::new(
            "".to_string(),
            ".".to_string(),
            10,
            None,
            OutputFormat::Json,
            None,
            None,
        );
        assert!(config.validate().is_err());

        // Invalid threshold should fail
        let config = SearchCommandConfig::new(
            "test".to_string(),
            ".".to_string(),
            10,
            Some(1.5),
            OutputFormat::Json,
            None,
            None,
        );
        assert!(config.validate().is_err());

        // Zero limit should fail
        let config = SearchCommandConfig::new(
            "test".to_string(),
            ".".to_string(),
            0,
            None,
            OutputFormat::Json,
            None,
            None,
        );
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_search_command_config_nonexistent_path() {
        let config = SearchCommandConfig::new(
            "test query".to_string(),
            "/nonexistent/path".to_string(),
            10,
            None,
            OutputFormat::Json,
            None,
            None,
        );
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_search_command_config_invalid_filetype() {
        let config = SearchCommandConfig::new(
            "test query".to_string(),
            ".".to_string(),
            10,
            None,
            OutputFormat::Json,
            Some("".to_string()), // Empty filetype should be invalid
            None,
        );
        assert!(config.validate().is_err());
    }

    #[tokio::test]
    async fn test_search_command_with_temp_directory() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_string_lossy().to_string();

        let config = SearchCommandConfig::new(
            "test query".to_string(),
            temp_path,
            10,
            None,
            OutputFormat::Json,
            None,
            None,
        );

        // This will fail because there's no index, but configuration should be valid
        assert!(config.validate().is_ok());

        // The actual search execution will fail due to missing index, which is expected
        let turboprop_config = crate::config::TurboPropConfig::default();
        let result = execute_search_command(config, &turboprop_config).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_search_command_config_with_valid_glob_pattern() {
        // Valid glob patterns should pass validation
        let valid_patterns = vec!["*.rs", "src/*.js", "**/*.py", "test_*.txt"];

        for pattern in valid_patterns {
            let config = SearchCommandConfig::new(
                "test query".to_string(),
                ".".to_string(),
                10,
                None,
                OutputFormat::Json,
                None,
                Some(pattern.to_string()),
            );
            assert!(
                config.validate().is_ok(),
                "Pattern '{}' should be valid",
                pattern
            );
        }
    }

    #[test]
    fn test_search_command_config_with_invalid_glob_pattern() {
        // Invalid glob patterns should fail validation
        let invalid_patterns = vec!["", "   ", "[invalid"];

        for pattern in invalid_patterns {
            let config = SearchCommandConfig::new(
                "test query".to_string(),
                ".".to_string(),
                10,
                None,
                OutputFormat::Json,
                None,
                Some(pattern.to_string()),
            );
            assert!(
                config.validate().is_err(),
                "Pattern '{}' should be invalid",
                pattern
            );
        }
    }

    #[test]
    fn test_search_command_config_with_no_glob_pattern() {
        // No glob pattern should be valid
        let config = SearchCommandConfig::new(
            "test query".to_string(),
            ".".to_string(),
            10,
            None,
            OutputFormat::Json,
            None,
            None,
        );
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_search_command_config_with_both_filetype_and_glob() {
        // Should be able to have both filetype and glob pattern
        let config = SearchCommandConfig::new(
            "test query".to_string(),
            ".".to_string(),
            10,
            None,
            OutputFormat::Json,
            Some("rs".to_string()),
            Some("src/*.rs".to_string()),
        );
        assert!(config.validate().is_ok());
    }
}