command-vault 0.3.0

An advanced command history manager with tagging and search capabilities
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
use anyhow::Result;
use chrono::{TimeZone, Utc};
use command_vault::{
    cli::{args::Commands, commands::handle_command},
    db::{Command, models::Parameter},
};
use tempfile::tempdir;
use std::env;

mod test_utils;
use test_utils::create_test_db;

// Set up test environment
#[ctor::ctor]
fn setup() {
    std::env::set_var("COMMAND_VAULT_TEST", "1");
}

#[test]
fn test_ls_empty() -> Result<()> {
    let (db, _db_dir) = create_test_db()?;
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 0);
    Ok(())
}

#[test]
fn test_handle_command_list() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let command = Command {
        id: None,
        command: "test command".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: Vec::new(),
    };
    db.add_command(&command)?;
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].command, "test command");
    Ok(())
}

#[test]
fn test_ls_with_limit() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    for i in 0..5 {
        let command = Command {
            id: None,
            command: format!("command {}", i),
            timestamp: Utc::now(),
            directory: "/test".to_string(),
            tags: vec![],
            parameters: Vec::new(),
        };
        db.add_command(&command)?;
    }
    let commands = db.list_commands(3, false)?;
    assert_eq!(commands.len(), 3);
    Ok(())
}

#[test]
fn test_ls_ordering() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let timestamps = vec![
        Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap(),
        Utc.with_ymd_and_hms(2022, 1, 2, 0, 0, 0).unwrap(),
        Utc.with_ymd_and_hms(2022, 1, 3, 0, 0, 0).unwrap(),
    ];
    
    for (i, timestamp) in timestamps.iter().enumerate() {
        let command = Command {
            id: None,
            command: format!("command {}", i),
            timestamp: *timestamp,
            directory: "/test".to_string(),
            tags: vec![],
            parameters: Vec::new(),
        };
        db.add_command(&command)?;
    }
    
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 3);
    assert_eq!(commands[0].command, "command 2");
    assert_eq!(commands[1].command, "command 1");
    assert_eq!(commands[2].command, "command 0");
    Ok(())
}

#[test]
fn test_delete_command() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let command = Command {
        id: None,
        command: "test command".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: Vec::new(),
    };
    let id = db.add_command(&command)?;
    db.delete_command(id)?;
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 0);
    Ok(())
}

#[test]
fn test_search_commands() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let command = Command {
        id: None,
        command: "test command".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: Vec::new(),
    };
    db.add_command(&command)?;
    let commands = db.search_commands("test", 10)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].command, "test command");
    Ok(())
}

#[test]
fn test_add_command_with_tags() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let temp_dir = tempdir()?;
    std::fs::create_dir_all(temp_dir.path())?;

    // Change to the test directory
    let original_dir = env::current_dir()?;
    let test_dir = temp_dir.path().canonicalize()?;
    env::set_current_dir(&test_dir)?;
    
    let command = vec!["test".to_string(), "command".to_string()];
    let add_command = Commands::Add { 
        command: command.clone(), 
        tags: vec!["tag1".to_string(), "tag2".to_string()] 
    };
    
    handle_command(add_command, &mut db, false)?;
    
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].command, "test command");
    assert_eq!(commands[0].tags, vec!["tag1", "tag2"]);
    
    // Restore the original directory
    env::set_current_dir(original_dir)?;
    
    Ok(())
}

#[test]
fn test_command_with_output() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Test command that would produce output
    let command = vec!["echo".to_string(), "\"Hello, World!\"".to_string()];
    let add_command = Commands::Add { 
        command: command.clone(), 
        tags: vec![] 
    };
    
    handle_command(add_command, &mut db, false)?;
    
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].command, "echo \"Hello, World!\"");
    
    Ok(())
}

#[test]
fn test_command_with_stderr() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Test command that would produce stderr
    let command = vec!["ls".to_string(), "nonexistent_directory".to_string()];
    let add_command = Commands::Add { 
        command: command.clone(), 
        tags: vec![] 
    };
    
    handle_command(add_command, &mut db, false)?;
    
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].command, "ls nonexistent_directory");
    
    Ok(())
}

#[test]
fn test_git_log_format_command() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let temp_dir = tempdir()?;
    std::fs::create_dir_all(temp_dir.path())?;

    // Change to the test directory
    let original_dir = env::current_dir()?;
    let test_dir = temp_dir.path().canonicalize()?;
    env::set_current_dir(&test_dir)?;
    
    // Add the git log command with format string
    let format_str = "%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset";
    let command = vec![
        "git".to_string(),
        "log".to_string(),
        "--graph".to_string(),
        format!("--pretty=format:{}", format_str),
        "--abbrev-commit".to_string(),
    ];
    
    let add_command = Commands::Add { 
        command: command.clone(), 
        tags: vec![] 
    };
    
    handle_command(add_command, &mut db, false)?;
    
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(
        commands[0].command, 
        format!("git log --graph \"--pretty=format:{}\" --abbrev-commit", format_str)
    );
    
    // Restore the original directory
    env::set_current_dir(original_dir)?;
    
    Ok(())
}

#[test]
fn test_parameter_parsing() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Test basic parameter
    let command = Command {
        id: None,
        command: "echo @message".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: vec![Parameter::with_description(
            "message".to_string(),
            Some("User_name".to_string())
        )],
    };
    let id = db.add_command(&command)?;
    let saved = db.get_command(id)?.unwrap();
    assert_eq!(saved.parameters.len(), 1);
    assert_eq!(saved.parameters[0].name, "message");
    assert_eq!(saved.parameters[0].description, Some("User_name".to_string()));
    
    // Test parameter with description
    let command = Command {
        id: None,
        command: "echo @message:User_name".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: vec![Parameter::with_description(
            "message".to_string(),
            Some("User_name".to_string())
        )],
    };
    let id = db.add_command(&command)?;
    let saved = db.get_command(id)?.unwrap();
    assert_eq!(saved.parameters.len(), 1);
    assert_eq!(saved.parameters[0].name, "message");
    assert_eq!(saved.parameters[0].description, Some("User_name".to_string()));
    
    Ok(())
}

#[test]
fn test_exec_command_with_parameters() -> Result<()> {
    // Ensure we're in test mode
    std::env::set_var("COMMAND_VAULT_TEST", "1");
    
    let (mut db, _db_dir) = create_test_db()?;
    let temp_dir = tempdir()?;
    let test_dir = temp_dir.path().canonicalize()?;
    
    // Add a command with parameters
    let command = Command {
        id: None,
        command: "echo @message".to_string(),
        timestamp: Utc::now(),
        directory: test_dir.to_string_lossy().to_string(),
        tags: vec![],
        parameters: vec![Parameter::with_description(
            "message".to_string(),
            Some("test message".to_string())
        )],
    };
    let id = db.add_command(&command)?;
    
    // Execute command with default parameter
    let exec_command = Commands::Exec { command_id: id, debug: false };
    handle_command(exec_command, &mut db, false)?;
    
    // Verify command was saved correctly
    let saved = db.get_command(id)?.unwrap();
    assert_eq!(saved.parameters.len(), 1);
    assert_eq!(saved.parameters[0].name, "message");
    assert_eq!(saved.parameters[0].description, Some("test message".to_string()));
    
    Ok(())
}

#[test]
fn test_exec_command_not_found() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Try to execute a non-existent command
    let exec_command = Commands::Exec { command_id: 999, debug: false };
    let result = handle_command(exec_command, &mut db, false);
    
    // Verify that we get an error
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Command not found"));
    
    Ok(())
}

#[test]
fn test_parameter_validation() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Test invalid parameter name (starts with number)
    let command = Command {
        id: None,
        command: "echo @1name".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: vec![],
    };
    let id = db.add_command(&command)?;
    let saved = db.get_command(id)?.unwrap();
    assert_eq!(saved.parameters.len(), 0); // Invalid parameter should be ignored
    
    // Test invalid parameter name (special characters)
    let command = Command {
        id: None,
        command: "echo @name!".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: vec![],
    };
    let id = db.add_command(&command)?;
    let saved = db.get_command(id)?.unwrap();
    assert_eq!(saved.parameters.len(), 0); // Invalid parameter should be ignored
    
    Ok(())
}

#[test]
fn test_command_with_spaces_in_parameters() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let command = Command {
        id: None,
        command: "echo @message".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec!["test".to_string()],
        parameters: vec![Parameter::with_description(
            "message".to_string(),
            Some("A test message".to_string())
        )],
    };
    
    db.add_command(&command)?;
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].command, "echo @message");
    assert_eq!(commands[0].parameters[0].name, "message");
    assert_eq!(commands[0].parameters[0].description, Some("A test message".to_string()));
    Ok(())
}

#[test]
fn test_command_with_multiple_tags() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let command = Command {
        id: None,
        command: "test command".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec!["tag1".to_string(), "tag2".to_string(), "tag3".to_string()],
        parameters: Vec::new(),
    };
    
    db.add_command(&command)?;
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].tags.len(), 3);
    assert!(commands[0].tags.contains(&"tag1".to_string()));
    assert!(commands[0].tags.contains(&"tag2".to_string()));
    assert!(commands[0].tags.contains(&"tag3".to_string()));
    Ok(())
}

#[test]
fn test_command_with_special_chars() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let command = Command {
        id: None,
        command: "grep -r \"@pattern\" @directory".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec!["search".to_string()],
        parameters: vec![
            Parameter::with_description(
                "pattern".to_string(),
                Some("Search pattern".to_string())
            ),
            Parameter::with_description(
                "directory".to_string(),
                Some("Directory to search in".to_string())
            ),
        ],
    };
    
    db.add_command(&command)?;
    let commands = db.list_commands(1, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].parameters.len(), 2);
    assert_eq!(commands[0].parameters[0].name, "pattern");
    assert_eq!(commands[0].parameters[0].description, Some("Search pattern".to_string()));
    assert_eq!(commands[0].parameters[1].name, "directory");
    assert_eq!(commands[0].parameters[1].description, Some("Directory to search in".to_string()));
    Ok(())
}

#[test]
fn test_handle_command_debug() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    let temp_dir = tempdir()?;
    let test_dir = temp_dir.path().canonicalize()?;
    std::env::set_current_dir(&test_dir)?;
    
    // First add a simple command that works in any shell
    let add_command = Commands::Add {
        command: vec!["echo".to_string(), "test".to_string()],
        tags: vec![],
    };
    handle_command(add_command, &mut db, true)?;

    // Then get the id of the added command
    let commands = db.list_commands(1, false)?;
    let id = commands[0].id.unwrap();

    // Execute the command in debug mode
    let exec_command = Commands::Exec { command_id: id, debug: true };
    handle_command(exec_command, &mut db, true)?;

    Ok(())
}

#[test]
fn test_handle_command_delete() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Add a test command
    let command = Command {
        id: None,
        command: "test command".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec![],
        parameters: Vec::new(),
    };
    let id = db.add_command(&command)?;
    
    // Verify command exists
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 1);
    
    // Delete the command
    handle_command(Commands::Delete { command_id: id }, &mut db, false)?;
    
    // Verify command was deleted
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 0);
    Ok(())
}

#[test]
fn test_handle_command_delete_nonexistent() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Try to delete a command that doesn't exist
    let result = handle_command(Commands::Delete { command_id: 999 }, &mut db, false);
    
    // Verify we get an error
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Command with ID 999 not found"));
    Ok(())
}

#[test]
fn test_handle_command_delete_with_tags() -> Result<()> {
    let (mut db, _db_dir) = create_test_db()?;
    
    // Add a test command with tags
    let command = Command {
        id: None,
        command: "test command".to_string(),
        timestamp: Utc::now(),
        directory: "/test".to_string(),
        tags: vec!["test".to_string(), "example".to_string()],
        parameters: Vec::new(),
    };
    let id = db.add_command(&command)?;
    
    // Verify command exists with tags
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].tags.len(), 2);
    
    // Delete the command
    handle_command(Commands::Delete { command_id: id }, &mut db, false)?;
    
    // Verify command and its tags were deleted
    let commands = db.list_commands(10, false)?;
    assert_eq!(commands.len(), 0);
    
    // Verify tags were removed
    let tags = db.list_tags()?;
    assert_eq!(tags.len(), 0);
    Ok(())
}