vectordb-cli 1.6.0

A CLI tool for semantic code search.
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
// src/cli/repo_commands.rs
pub mod list; // Make public for testing
pub mod r#use; // Make public for testing
pub mod clear;
pub mod query;
pub mod sync;
pub mod use_branch;
pub mod add;
pub mod remove;
pub mod helpers; // Make public
pub mod config; // Add new config module

use anyhow::Result;
use clap::{Args, Subcommand};
use std::{path::PathBuf, sync::Arc};

use crate::cli::commands::CliArgs;
use crate::config::AppConfig;
use crate::vectordb::qdrant_client_trait::QdrantClientTrait;
use std::fmt::Debug;

const COLLECTION_NAME_PREFIX: &str = "repo_";
pub(crate) const FIELD_BRANCH: &str = "branch";
pub(crate) const FIELD_COMMIT_HASH: &str = "commit_hash";

#[derive(Args, Debug)]
#[derive(Clone)]
pub struct RepoArgs {
    #[command(subcommand)]
    pub command: RepoCommand,
}

#[derive(Subcommand, Debug)]
#[derive(Clone)]
pub enum RepoCommand {
    /// Add a new repository to manage.
    Add(add::AddRepoArgs),
    /// List managed repositories.
    List,
    /// Set the active repository for commands.
    Use(r#use::UseRepoArgs),
    /// Remove a managed repository (config and index).
    Remove(remove::RemoveRepoArgs),
    /// Clear the index for a repository.
    Clear(clear::ClearRepoArgs),
    /// Checkout a branch and set it as active for the current repository.
    UseBranch(use_branch::UseBranchArgs),
    /// Query the index for a specific repository.
    Query(query::RepoQueryArgs),
    /// Fetch updates and sync the index for the current/specified repository.
    Sync(sync::SyncRepoArgs),
    /// Show statistics about the vector database collection for a repository.
    Stats(super::stats::StatsArgs),
    /// Configure repository settings.
    Config(config::ConfigArgs),
}

pub async fn handle_repo_command<C>(
    args: RepoArgs,
    cli_args: &CliArgs,
    config: &mut AppConfig,
    client: Arc<C>,
    override_path: Option<&PathBuf>,
) -> Result<()>
where
    C: QdrantClientTrait + Send + Sync + 'static,
{
    match args.command {
        RepoCommand::Add(add_args) => add::handle_repo_add(add_args, config, Arc::clone(&client), override_path).await?,
        RepoCommand::List => list::list_repositories(config)?,
        RepoCommand::Use(use_args) => r#use::use_repository(use_args, config, override_path)?,
        RepoCommand::Remove(remove_args) => remove::handle_repo_remove(remove_args, config, Arc::clone(&client), override_path).await?,
        RepoCommand::Clear(clear_args) => clear::handle_repo_clear(clear_args, config, client, override_path).await?,
        RepoCommand::UseBranch(branch_args) => use_branch::handle_use_branch(branch_args, config, override_path).await?,
        RepoCommand::Query(query_args) => query::handle_repo_query(query_args, config, Arc::clone(&client), cli_args).await?,
        RepoCommand::Sync(sync_args) => sync::handle_repo_sync(sync_args, cli_args, config, Arc::clone(&client), override_path).await?,
        RepoCommand::Stats(stats_args) => super::stats::handle_stats(stats_args, config.clone(), Arc::clone(&client)).await?,
        RepoCommand::Config(config_args) => config::handle_config(config_args, config, override_path)?,
    }
    Ok(())
}

// Helper function for tests - allows access to the list_repositories function
#[cfg(test)]
pub fn handle_repo_command_test(config: &AppConfig) -> Result<()> {
    list::list_repositories(config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{AppConfig, RepositoryConfig, load_config, save_config};
    use crate::cli::commands::Commands;
    use crate::cli::repo_commands::{RepoArgs, RepoCommand};
    use crate::cli::repo_commands::remove::RemoveRepoArgs;
    use qdrant_client::{Qdrant};
    use std::sync::Arc;
    use tokio::runtime::Runtime;
    use std::collections::HashMap;
    use std::path::{PathBuf};
    use std::fs;
    use tempfile::{tempdir};
    use crate::vectordb::qdrant_client_trait::MockQdrantClientTrait;
    use mockall::predicate::eq;

    // Helper function to create a default AppConfig for tests
    fn create_test_config_data() -> AppConfig {
        AppConfig {
            repositories: vec![
                RepositoryConfig { name: "repo1".to_string(), url: "url1".to_string(), local_path: PathBuf::from("/tmp/vectordb_test_repo1"), default_branch: "main".to_string(), tracked_branches: vec!["main".to_string()], active_branch: Some("main".to_string()), remote_name: Some("origin".to_string()), ssh_key_path: None, ssh_key_passphrase: None, last_synced_commits: HashMap::new(), indexed_languages: None },
                RepositoryConfig { name: "repo2".to_string(), url: "url2".to_string(), local_path: PathBuf::from("/tmp/vectordb_test_repo2"), default_branch: "dev".to_string(), tracked_branches: vec!["dev".to_string()], active_branch: Some("dev".to_string()), remote_name: Some("origin".to_string()), ssh_key_path: None, ssh_key_passphrase: None, last_synced_commits: HashMap::new(), indexed_languages: None },
            ],
            active_repository: None,
            qdrant_url: "http://localhost:6334".to_string(),
            onnx_model_path: None,
            onnx_tokenizer_path: None,
            server_api_key_path: None,
            repositories_base_path: None,
        }
    }

    // Helper function to create dummy CliArgs
     fn create_dummy_cli_args(repo_command: RepoCommand) -> CliArgs {
        // Add default dummy paths for ONNX, tests needing real paths should override
        let dummy_model_path = Some(PathBuf::from("/tmp/dummy_model.onnx"));
        let dummy_tokenizer_dir = Some(PathBuf::from("/tmp/dummy_tokenizer/"));

        CliArgs {
             command: Commands::Repo(RepoArgs { command: repo_command }),
             // Convert PathBuf to String
             onnx_model_path_arg: dummy_model_path.map(|p| p.to_string_lossy().into_owned()),
             onnx_tokenizer_dir_arg: dummy_tokenizer_dir.map(|p| p.to_string_lossy().into_owned()),
         }
      }

    // --- Updated Tests --- 
    // Note: repo clear tests might still need Qdrant connection or mocking
    // They don't save config, so isolation isn't strictly needed for that
    #[test]
    fn test_handle_repo_clear_specific_repo() {
        let rt = Runtime::new().unwrap();
        rt.block_on(async {
            let test_repo_name = "my-test-repo-clear-specific".to_string();
            let collection_name = helpers::get_collection_name(&test_repo_name);

            // Configure Mock Client
            let mut mock_client = MockQdrantClientTrait::new();
            mock_client.expect_collection_exists()
                .with(eq(collection_name.clone()))
                .times(1)
                .returning(|_| Ok(true)); // Collection exists
            
            mock_client.expect_delete_points_blocking()
                .times(1)
                .returning(|_, _| Ok(())); // Successfully deleted points
            
            let client = Arc::new(mock_client);

            // Setup config
            let mut config = create_test_config_data(); 
            config.repositories.push(RepositoryConfig {
                 name: test_repo_name.clone(), 
                 url: "url_clear".to_string(), 
                 local_path: PathBuf::from("/tmp/clear_spec"), 
                 default_branch: "main".to_string(), 
                 tracked_branches: vec![], 
                 active_branch: None, 
                 remote_name: None, 
                 ssh_key_path: None, 
                 ssh_key_passphrase: None, 
                 last_synced_commits: HashMap::from([("main".to_string(), "dummy_commit".to_string())]), // Add some dummy sync state
                 indexed_languages: Some(vec!["rust".to_string()])
            });
            config.active_repository = Some("other_repo".to_string()); // Ensure it clears the specified one
            
            let args = clear::ClearRepoArgs { name: Some(test_repo_name.to_string()), yes: true };
            let dummy_cli_args = create_dummy_cli_args(RepoCommand::Clear(args.clone()));

            // Execute with Mock Client
            let result = handle_repo_command(RepoArgs{ command: RepoCommand::Clear(args)}, &dummy_cli_args, &mut config, client, None).await;
            
            // Assertions
            assert!(result.is_ok(), "handle_repo_command failed: {:?}", result.err());
            let updated_repo = config.repositories.iter().find(|r| r.name == test_repo_name).expect("Test repo config not found after clear");
            assert!(updated_repo.last_synced_commits.is_empty(), "Sync status was not cleared");
            assert!(updated_repo.indexed_languages.is_none(), "Indexed languages were not cleared");
        });
    }
    #[test]
    fn test_handle_repo_clear_active_repo() {
         let rt = Runtime::new().unwrap();
         rt.block_on(async {
             let active_repo_name = "my-test-repo-clear-active".to_string();
             let collection_name = helpers::get_collection_name(&active_repo_name);

            // Configure Mock Client
            let mut mock_client = MockQdrantClientTrait::new();
            mock_client.expect_collection_exists()
                .with(eq(collection_name.clone()))
                .times(1)
                .returning(|_| Ok(true)); // Collection exists
            
            mock_client.expect_delete_points_blocking()
                .times(1)
                .returning(|_, _| Ok(())); // Successfully deleted points
            
            let client = Arc::new(mock_client);

             // Setup config
             let mut config = create_test_config_data(); 
             config.repositories.push(RepositoryConfig {
                 name: active_repo_name.clone(), 
                 url: "url_clear_active".to_string(), 
                 local_path: PathBuf::from("/tmp/clear_active"), 
                 default_branch: "main".to_string(), 
                 tracked_branches: vec![], 
                 active_branch: Some("main".to_string()), 
                 remote_name: None, 
                 ssh_key_path: None, 
                 ssh_key_passphrase: None,
                 last_synced_commits: HashMap::from([("main".to_string(), "dummy_commit_active".to_string())]), // Add dummy sync state
                 indexed_languages: Some(vec!["python".to_string()])
             });
             config.active_repository = Some(active_repo_name.to_string());

             let args = clear::ClearRepoArgs { name: None, yes: true }; // Clear active
             let dummy_cli_args = create_dummy_cli_args(RepoCommand::Clear(args.clone()));

             // Execute with Mock Client
             let result = handle_repo_command(RepoArgs{ command: RepoCommand::Clear(args)}, &dummy_cli_args, &mut config, client, None).await;
             
             // Assertions
             assert!(result.is_ok(), "handle_repo_command failed: {:?}", result.err());
             let updated_repo = config.repositories.iter().find(|r| r.name == active_repo_name).expect("Active repo config not found after clear");
             assert!(updated_repo.last_synced_commits.is_empty(), "Sync status was not cleared for active repo");
             assert!(updated_repo.indexed_languages.is_none(), "Indexed languages were not cleared for active repo");
         });
    }
    #[test]
    fn test_handle_repo_clear_no_active_or_specified_fails() {
        let rt = Runtime::new().unwrap();
        rt.block_on(async {
            let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap());
            // Use create_test_config_data directly
            let mut config = create_test_config_data();
            config.repositories.clear();
            config.active_repository = None;

            let args = clear::ClearRepoArgs { name: None, yes: true }; 
            let dummy_cli_args = create_dummy_cli_args(RepoCommand::Clear(args.clone()));

            let result = handle_repo_command(RepoArgs{ command: RepoCommand::Clear(args)}, &dummy_cli_args, &mut config, client, None).await;
            assert!(result.is_err());
            assert!(result.unwrap_err().to_string().contains("No active repository set"));
        });
    }

     #[test]
     fn test_handle_repo_use_existing() {
         let temp_dir = tempdir().unwrap(); // Use tempdir
         let temp_path = temp_dir.path().join("test_config.toml"); // Define path within tempdir

         let mut config = create_test_config_data();
         config.active_repository = Some("repo1".to_string());
         save_config(&config, Some(&temp_path)).unwrap(); // Save initial state to temp path

         let use_args = r#use::UseRepoArgs { name: "repo2".to_string() };
         let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap()); 
         let dummy_cli_args = create_dummy_cli_args(RepoCommand::Use(use_args.clone()));

         // Pass Some(&temp_path) as override_path
         let result = tokio::runtime::Runtime::new().unwrap().block_on(async {
              handle_repo_command(RepoArgs{ command: RepoCommand::Use(use_args)}, &dummy_cli_args, &mut config, client, Some(&temp_path)).await
         });
         assert!(result.is_ok());
         
         // Verify by loading from the temporary file
         let saved_config = load_config(Some(&temp_path)).unwrap();
         assert_eq!(saved_config.active_repository, Some("repo2".to_string()));

         // Keep temp_dir alive until end of test scope automatically
     }

     #[test]
     fn test_handle_repo_use_nonexistent() {
        let temp_dir = tempdir().unwrap(); // Use tempdir
        let temp_path = temp_dir.path().join("test_config.toml"); // Define path within tempdir

        let mut config = create_test_config_data();
        save_config(&config, Some(&temp_path)).unwrap();
        let initial_config_state = config.clone(); // Save for comparison
        
        let use_args = r#use::UseRepoArgs { name: "repo3".to_string() }; 
        let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap()); 
        let dummy_cli_args = create_dummy_cli_args(RepoCommand::Use(use_args.clone()));

        let result = tokio::runtime::Runtime::new().unwrap().block_on(async {
              handle_repo_command(RepoArgs{ command: RepoCommand::Use(use_args)}, &dummy_cli_args, &mut config, client, Some(&temp_path)).await
         });
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Repository 'repo3' not found"));

        // Verify config file was NOT changed because the command errored before saving
        let saved_config = load_config(Some(&temp_path)).unwrap();
        assert_eq!(saved_config.repositories, initial_config_state.repositories);
        assert_eq!(saved_config.active_repository, initial_config_state.active_repository);

        // Keep temp_dir alive until end of test scope automatically
     }

     #[test]
     fn test_handle_repo_remove_config_only_non_active() {
        let rt = Runtime::new().unwrap();
         rt.block_on(async {
             let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap());
             let temp_dir = tempdir().unwrap(); // Use tempdir
             let temp_path = temp_dir.path().join("test_config.toml"); // Define path within tempdir

             let mut config = create_test_config_data();
             config.active_repository = Some("repo1".to_string());
             save_config(&config, Some(&temp_path)).unwrap();
             let initial_repo_count = config.repositories.len();
             
             let remove_args = RemoveRepoArgs { name: "repo2".to_string(), yes: true }; 
             let dummy_cli_args = create_dummy_cli_args(RepoCommand::Remove(remove_args.clone()));
             let _ = fs::remove_dir_all("/tmp/vectordb_test_repo2"); // Keep dummy dir removal

             let result = handle_repo_command(RepoArgs{ command: RepoCommand::Remove(remove_args)}, &dummy_cli_args, &mut config, client.clone(), Some(&temp_path)).await;
             assert!(result.is_ok());
             
             // Verify by loading from the temporary file
             let saved_config = load_config(Some(&temp_path)).unwrap();
             assert_eq!(saved_config.repositories.len(), initial_repo_count - 1);
             assert!(!saved_config.repositories.iter().any(|r| r.name == "repo2"));
             assert_eq!(saved_config.active_repository, Some("repo1".to_string()));

             // Keep temp_dir alive until end of test scope automatically
         });
     }

      #[test]
      fn test_handle_repo_remove_config_only_active() {
         let rt = Runtime::new().unwrap();
          rt.block_on(async {
              let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap());
              let temp_dir = tempdir().unwrap(); // Use tempdir
              let temp_path = temp_dir.path().join("test_config.toml"); // Define path within tempdir

              let mut config = create_test_config_data();
              config.active_repository = Some("repo2".to_string());
              config.repositories.push(RepositoryConfig { name: "repo3".to_string(), url: "url3".to_string(), local_path: PathBuf::from("/tmp/vectordb_test_repo3"), default_branch: "main".to_string(), tracked_branches: vec!["main".to_string()], active_branch: Some("main".to_string()), remote_name: Some("origin".to_string()), ssh_key_path: None, ssh_key_passphrase: None, last_synced_commits: HashMap::new(), indexed_languages: None });
              save_config(&config, Some(&temp_path)).unwrap();
              let initial_repo_count = config.repositories.len();

              let remove_args = RemoveRepoArgs { name: "repo2".to_string(), yes: true };
              let dummy_cli_args = create_dummy_cli_args(RepoCommand::Remove(remove_args.clone()));
              let _ = fs::remove_dir_all("/tmp/vectordb_test_repo2");

              let result = handle_repo_command(RepoArgs{ command: RepoCommand::Remove(remove_args)}, &dummy_cli_args, &mut config, client.clone(), Some(&temp_path)).await;
              assert!(result.is_ok());
              
              // Verify by loading from the temporary file
              let saved_config = load_config(Some(&temp_path)).unwrap();
              assert_eq!(saved_config.repositories.len(), initial_repo_count - 1);
              assert!(!saved_config.repositories.iter().any(|r| r.name == "repo2"));
              assert_eq!(saved_config.active_repository, Some("repo1".to_string())); // Should switch to repo1

              // Keep temp_dir alive until end of test scope automatically
          });
      }

       #[test]
       fn test_handle_repo_remove_nonexistent() {
          let rt = Runtime::new().unwrap();
           rt.block_on(async {
               let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap());
               let temp_dir = tempdir().unwrap(); // Use tempdir
               let temp_path = temp_dir.path().join("test_config.toml"); // Define path within tempdir

               let mut config = create_test_config_data();
               save_config(&config, Some(&temp_path)).unwrap();
               let initial_config_state = config.clone();
               let initial_repo_count = config.repositories.len();

               let remove_args = RemoveRepoArgs { name: "repo3".to_string(), yes: true }; 
               let dummy_cli_args = create_dummy_cli_args(RepoCommand::Remove(remove_args.clone()));

               let result = handle_repo_command(RepoArgs{ command: RepoCommand::Remove(remove_args)}, &dummy_cli_args, &mut config, client.clone(), Some(&temp_path)).await;
               assert!(result.is_err());
               assert!(result.unwrap_err().to_string().contains("Repository 'repo3' not found"));

               // Verify config file was NOT changed
               let saved_config = load_config(Some(&temp_path)).unwrap();
               assert_eq!(saved_config.repositories, initial_config_state.repositories);
               assert_eq!(saved_config.repositories.len(), initial_repo_count);

               // Keep temp_dir alive until end of test scope automatically
           });
       }

    // Keep repo list test as is, it doesn't save config
    #[test]
    fn test_handle_repo_list() {
        // Setup config
        let mut config = create_test_config_data();
        config.active_repository = Some("repo1".to_string());

        // Call list_repositories directly or via handle_repo_command
        // Since list doesn't modify/save, override_path isn't strictly needed, but let's pass None for consistency
        let list_args = RepoArgs { command: RepoCommand::List };
        let dummy_cli_args = create_dummy_cli_args(RepoCommand::List);
        let client = Arc::new(Qdrant::from_url("http://localhost:6334").build().unwrap()); // Dummy client needed for handle_repo_command signature

        let result = tokio::runtime::Runtime::new().unwrap().block_on(async {
             handle_repo_command(list_args, &dummy_cli_args, &mut config, client, None).await // Pass None
        });

        // List command prints to stdout, so we'd typically capture stdout to assert output
        // For now, just assert it runs without error
        assert!(result.is_ok());
    }

    // TODO: Add tests for sync_repository, especially for the extension filter.
    // #[tokio::test]
    // async fn test_sync_with_extension_filter() { ... }

    // #[tokio::test]
    // async fn test_sync_without_extension_filter() { ... }

    // #[tokio::test]
    // async fn test_sync_with_invalid_extension_filter() { ... }
}