sqry-cli 6.0.22

CLI for sqry - semantic code search
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! Alias management for saved queries.
//!
//! The `AliasManager` provides a high-level API for creating, retrieving,
//! updating, and deleting saved query aliases.

use std::sync::Arc;

use chrono::Utc;

use crate::persistence::index::UserMetadataIndex;
use crate::persistence::types::{
    AliasExportFile, AliasWithScope, ImportConflictStrategy, ImportResult, SavedAlias,
    StorageScope, UserMetadata,
};
use crate::persistence::validation::{AliasNameError, validate_alias_name};

/// Error type for alias operations.
#[derive(Debug)]
pub enum AliasError {
    /// Alias name validation failed.
    InvalidName(AliasNameError),
    /// Alias not found.
    NotFound { name: String },
    /// Alias already exists.
    AlreadyExists { name: String, scope: StorageScope },
    /// Storage operation failed.
    Storage(anyhow::Error),
}

impl std::fmt::Display for AliasError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidName(e) => write!(f, "invalid alias name: {e}"),
            Self::NotFound { name } => write!(f, "alias '{name}' not found"),
            Self::AlreadyExists { name, scope } => {
                write!(f, "alias '{name}' already exists in {scope} storage")
            }
            Self::Storage(e) => write!(f, "storage error: {e}"),
        }
    }
}

impl std::error::Error for AliasError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidName(e) => Some(e),
            Self::Storage(e) => e.source(),
            _ => None,
        }
    }
}

impl From<AliasNameError> for AliasError {
    fn from(e: AliasNameError) -> Self {
        Self::InvalidName(e)
    }
}

impl From<anyhow::Error> for AliasError {
    fn from(e: anyhow::Error) -> Self {
        Self::Storage(e)
    }
}

/// Manager for saved query aliases.
///
/// Provides CRUD operations for aliases stored in the user metadata index.
/// Local aliases take precedence over global aliases when resolving by name.
#[derive(Debug, Clone)]
pub struct AliasManager {
    index: Arc<UserMetadataIndex>,
}

impl AliasManager {
    /// Create a new alias manager.
    #[must_use]
    pub fn new(index: Arc<UserMetadataIndex>) -> Self {
        Self { index }
    }

    /// Save a new alias.
    ///
    /// # Arguments
    ///
    /// * `name` - The alias name (validated against naming rules)
    /// * `command` - The command to execute (e.g., "query", "search")
    /// * `args` - Command arguments
    /// * `description` - Optional description
    /// * `scope` - Where to store the alias (Global or Local)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The name is invalid
    /// - An alias with the same name already exists in the target scope
    /// - The storage operation fails
    pub fn save(
        &self,
        name: &str,
        command: &str,
        args: &[String],
        description: Option<&str>,
        scope: StorageScope,
    ) -> Result<(), AliasError> {
        // Validate name
        validate_alias_name(name)?;

        // Check if alias already exists in target scope
        self.index
            .update(scope, |metadata| {
                if metadata.aliases.contains_key(name) {
                    anyhow::bail!("alias '{name}' already exists");
                }

                let alias = SavedAlias {
                    command: command.to_string(),
                    args: args.to_vec(),
                    created: Utc::now(),
                    description: description.map(String::from),
                };

                metadata.aliases.insert(name.to_string(), alias);
                Ok(())
            })
            .map_err(|e| {
                if e.to_string().contains("already exists") {
                    AliasError::AlreadyExists {
                        name: name.to_string(),
                        scope,
                    }
                } else {
                    AliasError::Storage(e)
                }
            })
    }

    /// Get an alias by name.
    ///
    /// Searches local storage first (if available), then global storage.
    /// Returns the alias and the scope it was found in.
    ///
    /// # Errors
    ///
    /// Returns an error if the alias is not found or storage fails.
    pub fn get(&self, name: &str) -> Result<AliasWithScope, AliasError> {
        // Check local first (if project root is set)
        if self.index.has_project_root() {
            let local = self.index.load(StorageScope::Local)?;
            if let Some(alias) = local.aliases.get(name) {
                return Ok(AliasWithScope {
                    name: name.to_string(),
                    alias: alias.clone(),
                    scope: StorageScope::Local,
                });
            }
        }

        // Check global
        let global = self.index.load(StorageScope::Global)?;
        if let Some(alias) = global.aliases.get(name) {
            return Ok(AliasWithScope {
                name: name.to_string(),
                alias: alias.clone(),
                scope: StorageScope::Global,
            });
        }

        Err(AliasError::NotFound {
            name: name.to_string(),
        })
    }

    /// Get an alias from a specific scope.
    ///
    /// # Errors
    ///
    /// Returns an error if the alias is not found or storage fails.
    pub fn get_from_scope(
        &self,
        name: &str,
        scope: StorageScope,
    ) -> Result<SavedAlias, AliasError> {
        let metadata = self.index.load(scope)?;
        metadata
            .aliases
            .get(name)
            .cloned()
            .ok_or_else(|| AliasError::NotFound {
                name: name.to_string(),
            })
    }

    /// List all aliases.
    ///
    /// Returns aliases from both local and global storage.
    /// If an alias exists in both scopes, only the local version is returned
    /// (local takes precedence).
    ///
    /// # Errors
    ///
    /// Returns an error if storage fails.
    pub fn list(&self) -> Result<Vec<AliasWithScope>, AliasError> {
        let mut result = Vec::new();
        let mut seen_names = std::collections::HashSet::new();

        // Load local aliases first (they take precedence)
        if self.index.has_project_root() {
            let local = self.index.load(StorageScope::Local)?;
            for (name, alias) in local.aliases {
                seen_names.insert(name.clone());
                result.push(AliasWithScope {
                    name,
                    alias,
                    scope: StorageScope::Local,
                });
            }
        }

        // Load global aliases (skip those already in local)
        let global = self.index.load(StorageScope::Global)?;
        for (name, alias) in global.aliases {
            if !seen_names.contains(&name) {
                result.push(AliasWithScope {
                    name,
                    alias,
                    scope: StorageScope::Global,
                });
            }
        }

        // Sort by name for consistent output
        result.sort_by(|a, b| a.name.cmp(&b.name));

        Ok(result)
    }

    /// List aliases from a specific scope only.
    ///
    /// # Errors
    ///
    /// Returns an error if storage fails.
    pub fn list_scope(&self, scope: StorageScope) -> Result<Vec<AliasWithScope>, AliasError> {
        let metadata = self.index.load(scope)?;
        let mut result: Vec<AliasWithScope> = metadata
            .aliases
            .into_iter()
            .map(|(name, alias)| AliasWithScope { name, alias, scope })
            .collect();

        result.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(result)
    }

    /// Delete an alias.
    ///
    /// If no scope is specified, deletes from both scopes.
    /// If a scope is specified, only deletes from that scope.
    ///
    /// # Errors
    ///
    /// Returns an error if the alias is not found or storage fails.
    pub fn delete(&self, name: &str, scope: Option<StorageScope>) -> Result<(), AliasError> {
        let mut deleted = false;

        if let Some(s) = scope {
            // Delete from specific scope
            self.delete_in_scope(s, name, &mut deleted)?;
        } else {
            // Delete from both scopes
            if self.index.has_project_root() {
                self.delete_in_scope(StorageScope::Local, name, &mut deleted)?;
            }

            self.delete_in_scope(StorageScope::Global, name, &mut deleted)?;
        }

        if deleted {
            Ok(())
        } else {
            Err(AliasError::NotFound {
                name: name.to_string(),
            })
        }
    }

    fn delete_in_scope(
        &self,
        scope: StorageScope,
        name: &str,
        deleted: &mut bool,
    ) -> Result<(), AliasError> {
        self.index.update(scope, |metadata| {
            if metadata.aliases.remove(name).is_some() {
                *deleted = true;
            }
            Ok(())
        })?;
        Ok(())
    }

    /// Rename an alias.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The old alias doesn't exist
    /// - The new name is invalid
    /// - An alias with the new name already exists
    /// - Storage fails
    pub fn rename(
        &self,
        old_name: &str,
        new_name: &str,
        scope: Option<StorageScope>,
    ) -> Result<StorageScope, AliasError> {
        // Validate new name
        validate_alias_name(new_name)?;

        let found_scope = self.resolve_alias_scope(old_name, scope)?;

        self.perform_rename(found_scope, old_name, new_name)?;

        Ok(found_scope)
    }

    fn resolve_alias_scope(
        &self,
        old_name: &str,
        scope: Option<StorageScope>,
    ) -> Result<StorageScope, AliasError> {
        if let Some(s) = scope {
            let metadata = self.index.load(s)?;
            if metadata.aliases.contains_key(old_name) {
                return Ok(s);
            }

            return Err(AliasError::NotFound {
                name: old_name.to_string(),
            });
        }

        let mut found = None;
        if self.index.has_project_root() {
            let local = self.index.load(StorageScope::Local)?;
            if local.aliases.contains_key(old_name) {
                found = Some(StorageScope::Local);
            }
        }
        if found.is_none() {
            let global = self.index.load(StorageScope::Global)?;
            if global.aliases.contains_key(old_name) {
                found = Some(StorageScope::Global);
            }
        }

        found.ok_or_else(|| AliasError::NotFound {
            name: old_name.to_string(),
        })
    }

    fn perform_rename(
        &self,
        found_scope: StorageScope,
        old_name: &str,
        new_name: &str,
    ) -> Result<(), AliasError> {
        self.index
            .update(found_scope, |metadata| {
                // Check new name doesn't already exist
                if metadata.aliases.contains_key(new_name) {
                    anyhow::bail!("alias '{new_name}' already exists");
                }

                // Remove old and insert new
                if let Some(alias) = metadata.aliases.remove(old_name) {
                    metadata.aliases.insert(new_name.to_string(), alias);
                }
                Ok(())
            })
            .map_err(|e| {
                if e.to_string().contains("already exists") {
                    AliasError::AlreadyExists {
                        name: new_name.to_string(),
                        scope: found_scope,
                    }
                } else {
                    AliasError::Storage(e)
                }
            })?;

        Ok(())
    }

    fn ensure_no_conflicts(
        &self,
        export: &AliasExportFile,
        scope: StorageScope,
    ) -> Result<(), AliasError> {
        let existing = self.index.load(scope)?;
        for name in export.aliases.keys() {
            if existing.aliases.contains_key(name) {
                return Err(AliasError::AlreadyExists {
                    name: name.clone(),
                    scope,
                });
            }
        }
        Ok(())
    }

    fn apply_import_entry(
        metadata: &mut UserMetadata,
        name: &str,
        alias: &SavedAlias,
        strategy: ImportConflictStrategy,
        result: &mut ImportResult,
    ) {
        if metadata.aliases.contains_key(name) {
            match strategy {
                ImportConflictStrategy::Skip => {
                    result.skipped += 1;
                    result.skipped_names.push(name.to_string());
                }
                ImportConflictStrategy::Overwrite => {
                    metadata.aliases.insert(name.to_string(), alias.clone());
                    result.overwritten += 1;
                }
                ImportConflictStrategy::Fail => {
                    // Should not reach here due to first pass check
                    unreachable!();
                }
            }
        } else {
            metadata.aliases.insert(name.to_string(), alias.clone());
            result.imported += 1;
        }
    }

    /// Check if an alias exists.
    ///
    /// Checks both local and global storage.
    #[must_use]
    pub fn exists(&self, name: &str) -> bool {
        self.get(name).is_ok()
    }

    /// Get the count of aliases in each scope.
    ///
    /// # Errors
    ///
    /// Returns an error if storage fails.
    pub fn count(&self) -> Result<(usize, usize), AliasError> {
        let local_count = if self.index.has_project_root() {
            self.index.load(StorageScope::Local)?.aliases.len()
        } else {
            0
        };
        let global_count = self.index.load(StorageScope::Global)?.aliases.len();
        Ok((local_count, global_count))
    }

    /// Import aliases from an export file.
    ///
    /// # Errors
    ///
    /// Returns an error if storage fails or conflict strategy is Fail and conflicts exist.
    pub fn import(
        &self,
        export: &AliasExportFile,
        scope: StorageScope,
        strategy: ImportConflictStrategy,
    ) -> Result<ImportResult, AliasError> {
        let mut result = ImportResult {
            imported: 0,
            skipped: 0,
            failed: 0,
            overwritten: 0,
            skipped_names: Vec::new(),
        };

        // First pass: check for conflicts if strategy is Fail
        if strategy == ImportConflictStrategy::Fail {
            self.ensure_no_conflicts(export, scope)?;
        }

        // Import each alias
        self.index.update(scope, |metadata| {
            for (name, alias) in &export.aliases {
                Self::apply_import_entry(metadata, name, alias, strategy, &mut result);
            }
            Ok(())
        })?;

        Ok(result)
    }
}

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

    fn setup() -> (TempDir, Arc<UserMetadataIndex>) {
        let dir = TempDir::new().unwrap();
        let config = PersistenceConfig {
            global_dir_override: Some(dir.path().join("global")),
            ..Default::default()
        };
        let index = Arc::new(UserMetadataIndex::open(Some(dir.path()), config).unwrap());
        (dir, index)
    }

    #[test]
    fn test_save_and_get_alias() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save(
                "test-query",
                "search",
                &[
                    "main".to_string(),
                    "--kind".to_string(),
                    "function".to_string(),
                ],
                Some("Find main functions"),
                StorageScope::Global,
            )
            .unwrap();

        let alias = manager.get("test-query").unwrap();
        assert_eq!(alias.name, "test-query");
        assert_eq!(alias.alias.command, "search");
        assert_eq!(alias.alias.args, vec!["main", "--kind", "function"]);
        assert_eq!(
            alias.alias.description,
            Some("Find main functions".to_string())
        );
        assert_eq!(alias.scope, StorageScope::Global);
    }

    #[test]
    fn test_local_takes_precedence() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        // Save to global
        manager
            .save(
                "shared",
                "search",
                &["global".to_string()],
                None,
                StorageScope::Global,
            )
            .unwrap();

        // Save same name to local
        manager
            .save(
                "shared",
                "query",
                &["local".to_string()],
                None,
                StorageScope::Local,
            )
            .unwrap();

        // Get should return local version
        let alias = manager.get("shared").unwrap();
        assert_eq!(alias.alias.command, "query");
        assert_eq!(alias.alias.args, vec!["local"]);
        assert_eq!(alias.scope, StorageScope::Local);
    }

    #[test]
    fn test_list_aliases() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save("alpha", "search", &[], None, StorageScope::Global)
            .unwrap();
        manager
            .save("beta", "query", &[], None, StorageScope::Local)
            .unwrap();
        manager
            .save("gamma", "search", &[], None, StorageScope::Global)
            .unwrap();

        let list = manager.list().unwrap();
        assert_eq!(list.len(), 3);
        assert_eq!(list[0].name, "alpha");
        assert_eq!(list[1].name, "beta");
        assert_eq!(list[2].name, "gamma");
    }

    #[test]
    fn test_delete_alias() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save("to-delete", "search", &[], None, StorageScope::Global)
            .unwrap();

        assert!(manager.exists("to-delete"));

        manager.delete("to-delete", None).unwrap();

        assert!(!manager.exists("to-delete"));
    }

    #[test]
    fn test_delete_from_specific_scope() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        // Save to both scopes
        manager
            .save(
                "shared",
                "search",
                &["global".to_string()],
                None,
                StorageScope::Global,
            )
            .unwrap();
        manager
            .save(
                "shared",
                "query",
                &["local".to_string()],
                None,
                StorageScope::Local,
            )
            .unwrap();

        // Delete only from local
        manager.delete("shared", Some(StorageScope::Local)).unwrap();

        // Should still exist in global
        let alias = manager.get("shared").unwrap();
        assert_eq!(alias.scope, StorageScope::Global);
        assert_eq!(alias.alias.args, vec!["global"]);
    }

    #[test]
    fn test_rename_alias() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save(
                "old-name",
                "search",
                &["test".to_string()],
                None,
                StorageScope::Global,
            )
            .unwrap();

        let scope = manager.rename("old-name", "new-name", None).unwrap();
        assert_eq!(scope, StorageScope::Global);

        assert!(!manager.exists("old-name"));
        assert!(manager.exists("new-name"));

        let alias = manager.get("new-name").unwrap();
        assert_eq!(alias.alias.args, vec!["test"]);
    }

    #[test]
    fn test_rename_to_existing_fails() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save("first", "search", &[], None, StorageScope::Global)
            .unwrap();
        manager
            .save("second", "query", &[], None, StorageScope::Global)
            .unwrap();

        let result = manager.rename("first", "second", None);
        assert!(matches!(result, Err(AliasError::AlreadyExists { .. })));
    }

    #[test]
    fn test_save_invalid_name_fails() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        let result = manager.save("123invalid", "search", &[], None, StorageScope::Global);
        assert!(matches!(result, Err(AliasError::InvalidName(_))));
    }

    #[test]
    fn test_get_nonexistent_fails() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        let result = manager.get("nonexistent");
        assert!(matches!(result, Err(AliasError::NotFound { .. })));
    }

    #[test]
    fn test_duplicate_save_fails() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save("unique", "search", &[], None, StorageScope::Global)
            .unwrap();

        let result = manager.save("unique", "query", &[], None, StorageScope::Global);
        assert!(matches!(result, Err(AliasError::AlreadyExists { .. })));
    }

    #[test]
    fn test_count() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        assert_eq!(manager.count().unwrap(), (0, 0));

        manager
            .save("global1", "search", &[], None, StorageScope::Global)
            .unwrap();
        manager
            .save("global2", "search", &[], None, StorageScope::Global)
            .unwrap();
        manager
            .save("local1", "search", &[], None, StorageScope::Local)
            .unwrap();

        assert_eq!(manager.count().unwrap(), (1, 2));
    }

    #[test]
    fn test_list_scope() {
        let (_dir, index) = setup();
        let manager = AliasManager::new(index);

        manager
            .save("global1", "search", &[], None, StorageScope::Global)
            .unwrap();
        manager
            .save("local1", "query", &[], None, StorageScope::Local)
            .unwrap();

        let global_list = manager.list_scope(StorageScope::Global).unwrap();
        assert_eq!(global_list.len(), 1);
        assert_eq!(global_list[0].name, "global1");

        let local_list = manager.list_scope(StorageScope::Local).unwrap();
        assert_eq!(local_list.len(), 1);
        assert_eq!(local_list[0].name, "local1");
    }

    #[test]
    fn test_error_display() {
        let err = AliasError::NotFound {
            name: "test".to_string(),
        };
        assert_eq!(err.to_string(), "alias 'test' not found");

        let err = AliasError::AlreadyExists {
            name: "test".to_string(),
            scope: StorageScope::Global,
        };
        assert_eq!(
            err.to_string(),
            "alias 'test' already exists in global storage"
        );
    }
}