whi 0.3.1

Magically simple PATH management
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
use std::path::PathBuf;

pub struct PathSearcher {
    dirs: Vec<PathBuf>,
}

/// Validate a PATH entry for suspicious or malicious content
fn validate_path_entry(path: &str) -> Result<(), String> {
    // Check for null bytes
    if path.contains('\0') {
        return Err("PATH entry contains null byte".to_string());
    }

    // Check for control characters (except tab which is valid)
    for ch in path.chars() {
        if ch.is_control() && ch != '\t' {
            return Err(format!("PATH entry contains control character: {:?}", ch));
        }
    }

    Ok(())
}

/// Warn about potentially dangerous PATH entries
fn warn_suspicious_path(path: &str) {
    // Warn about shell metacharacters that could be dangerous
    const DANGEROUS_CHARS: &[char] = &['$', '`', ';', '&', '|', '<', '>', '(', ')', '{', '}'];

    for &ch in DANGEROUS_CHARS {
        if path.contains(ch) {
            eprintln!(
                "Warning: PATH entry contains shell metacharacter '{}': {}",
                ch, path
            );
            return;
        }
    }

    // Warn about relative paths (but don't reject)
    if !path.starts_with('/') && !path.is_empty() && path != "." {
        eprintln!("Warning: Relative PATH entry detected: {}", path);
    }
}

impl PathSearcher {
    pub fn new(path_var: &str) -> Self {
        let mut has_empty = false;

        let dirs: Vec<PathBuf> = path_var
            .split(':')
            .filter_map(|s| {
                // Check for empty components
                if s.is_empty() {
                    has_empty = true;
                    return None; // Skip empty components instead of treating as "."
                }

                // Validate entry
                if let Err(e) = validate_path_entry(s) {
                    eprintln!("Warning: Skipping invalid PATH entry: {}", e);
                    return None;
                }

                // Warn about suspicious entries
                warn_suspicious_path(s);

                Some(PathBuf::from(s))
            })
            .collect();

        if has_empty {
            eprintln!("Warning: Empty PATH component(s) detected and skipped. Empty components can be a security risk.");
        }

        PathSearcher { dirs }
    }

    pub fn dirs(&self) -> &[PathBuf] {
        &self.dirs
    }

    pub fn move_entry(&self, from: usize, to: usize) -> Result<String, String> {
        let len = self.dirs.len();

        // Validate indices (1-based)
        if from == 0 || to == 0 {
            return Err(format!(
                "Invalid index: indices must be >= 1 (got from={}, to={})",
                from, to
            ));
        }
        if from > len {
            return Err(format!(
                "Index {} out of bounds (PATH has {} entries)",
                from, len
            ));
        }
        if to > len {
            return Err(format!(
                "Index {} out of bounds (PATH has {} entries)",
                to, len
            ));
        }

        // Convert to 0-based
        let from_idx = from - 1;
        let to_idx = to - 1;

        // Create new ordering
        let mut new_dirs = self.dirs.clone();
        let item = new_dirs.remove(from_idx);
        new_dirs.insert(to_idx, item);

        // Return new PATH string
        Ok(new_dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(":"))
    }

    pub fn swap_entries(&self, idx1: usize, idx2: usize) -> Result<String, String> {
        let len = self.dirs.len();

        // Validate indices (1-based)
        if idx1 == 0 || idx2 == 0 {
            return Err(format!(
                "Invalid index: indices must be >= 1 (got idx1={}, idx2={})",
                idx1, idx2
            ));
        }
        if idx1 > len {
            return Err(format!(
                "Index {} out of bounds (PATH has {} entries)",
                idx1, len
            ));
        }
        if idx2 > len {
            return Err(format!(
                "Index {} out of bounds (PATH has {} entries)",
                idx2, len
            ));
        }

        // Convert to 0-based
        let idx1_0 = idx1 - 1;
        let idx2_0 = idx2 - 1;

        // Create new ordering with swapped entries
        let mut new_dirs = self.dirs.clone();
        new_dirs.swap(idx1_0, idx2_0);

        // Return new PATH string
        Ok(new_dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(":"))
    }

    pub fn clean_duplicates(&self) -> (String, Vec<usize>) {
        let mut seen = std::collections::HashSet::new();
        let mut cleaned = Vec::new();
        let mut removed_indices = Vec::new();

        for (idx, dir) in self.dirs.iter().enumerate() {
            let dir_str = dir.display().to_string();
            if seen.insert(dir_str.clone()) {
                cleaned.push(dir_str);
            } else {
                // Duplicate found - track 1-based index
                removed_indices.push(idx + 1);
            }
        }

        (cleaned.join(":"), removed_indices)
    }

    pub fn delete_entry(&self, idx: usize) -> Result<String, String> {
        let len = self.dirs.len();

        // Validate index (1-based)
        if idx == 0 {
            return Err(format!("Invalid index: {} (must be >= 1)", idx));
        }
        if idx > len {
            return Err(format!(
                "Index {} out of bounds (PATH has {} entries)",
                idx, len
            ));
        }

        // Convert to 0-based
        let idx_0 = idx - 1;

        // Create new PATH without this entry
        let mut new_dirs = self.dirs.clone();
        new_dirs.remove(idx_0);

        // Return new PATH string
        Ok(new_dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(":"))
    }

    pub fn delete_entries(&self, indices: &[usize]) -> Result<String, String> {
        let len = self.dirs.len();

        // Validate all indices (1-based)
        for &idx in indices {
            if idx == 0 {
                return Err(format!("Invalid index: {} (indices must be >= 1)", idx));
            }
            if idx > len {
                return Err(format!(
                    "Index {} out of bounds (PATH has {} entries)",
                    idx, len
                ));
            }
        }

        // Sort indices in descending order to delete from highest to lowest
        // This avoids index shifting issues
        let mut sorted_indices: Vec<usize> = indices.to_vec();
        sorted_indices.sort_unstable_by(|a, b| b.cmp(a));

        // Remove duplicates
        sorted_indices.dedup();

        // Create new PATH without these entries
        let mut new_dirs = self.dirs.clone();
        for &idx in &sorted_indices {
            let idx_0 = idx - 1; // Convert to 0-based
            new_dirs.remove(idx_0);
        }

        // Return new PATH string
        Ok(new_dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(":"))
    }

    /// Add a new directory to PATH if not already present at the beginning
    /// Returns the new PATH string and the index where it was added (1-based)
    pub fn add_path(&self, path: &std::path::Path) -> Result<(String, usize), String> {
        match self.add_path_at_position(path, 1) {
            Ok(new_path) => Ok((new_path, 1)),
            Err(e) => Err(e),
        }
    }

    /// Add a new directory to PATH at a specific position if not already present
    /// Returns the new PATH string (1-based position)
    pub fn add_path_at_position(
        &self,
        path: &std::path::Path,
        position: usize,
    ) -> Result<String, String> {
        let path_buf = path.to_path_buf();

        // Check if already exists
        if let Some(_idx) = self.find_path_index(&path_buf) {
            // Already exists - just return current PATH
            return Ok(self.to_path_string());
        }

        // Validate position (1-based)
        if position == 0 {
            return Err("Position must be >= 1".to_string());
        }

        let mut new_dirs = self.dirs.clone();

        // Convert to 0-based index, but cap at the end of the list
        let insert_idx = (position - 1).min(new_dirs.len());

        new_dirs.insert(insert_idx, path_buf);

        let new_path = new_dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(":");

        Ok(new_path)
    }

    /// Find the index of an exact path match (1-based)
    pub fn find_path_index(&self, path: &std::path::Path) -> Option<usize> {
        use std::fs;

        // Try to canonicalize the search path if it exists
        let canonical_search = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());

        for (idx, dir) in self.dirs.iter().enumerate() {
            // Compare both as-is and canonicalized
            if dir == path || dir == &canonical_search {
                return Some(idx + 1); // Return 1-based index
            }

            // Also try canonicalizing the dir in PATH
            if let Ok(canonical_dir) = fs::canonicalize(dir) {
                if canonical_dir == canonical_search {
                    return Some(idx + 1);
                }
            }
        }

        None
    }

    /// Find all indices matching a fuzzy pattern
    pub fn find_fuzzy_indices(
        &self,
        pattern: &str,
        executable_name: Option<&str>,
    ) -> Vec<(usize, &PathBuf)> {
        use crate::path_resolver::FuzzyMatcher;

        let matcher = FuzzyMatcher::new(pattern);
        let mut matches = Vec::new();

        for (idx, dir) in self.dirs.iter().enumerate() {
            if matcher.matches(dir) {
                // If executable specified, check it exists
                if let Some(name) = executable_name {
                    let exec_path = dir.join(name);
                    if !exec_path.exists() {
                        continue;
                    }
                }

                matches.push((idx + 1, dir)); // 1-based index
            }
        }

        // Sort by match quality (shorter paths first)
        matches.sort_by_key(|(_, path)| path.as_os_str().len());

        matches
    }

    /// Delete a PATH entry by exact path match
    #[allow(dead_code)]
    pub fn delete_by_path(&self, path: &std::path::Path) -> Result<String, String> {
        if let Some(idx) = self.find_path_index(path) {
            self.delete_entry(idx)
        } else {
            Err(format!("Path not found in PATH: {}", path.display()))
        }
    }

    /// Check if an executable exists in a directory
    pub fn has_executable(&self, dir: &std::path::Path, name: &str) -> bool {
        use crate::executor::ExecutableCheck;

        let exec_path = dir.join(name);
        exec_path.exists() && ExecutableCheck::new(&exec_path).is_executable()
    }

    /// Convert current dirs to PATH string
    pub fn to_path_string(&self) -> String {
        self.dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(":")
    }
}

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

    #[test]
    fn test_move_entry_forward() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.move_entry(5, 2).unwrap();
        assert_eq!(result, "/a:/e:/b:/c:/d");
    }

    #[test]
    fn test_move_entry_backward() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.move_entry(2, 4).unwrap();
        assert_eq!(result, "/a:/c:/d:/b:/e");
    }

    #[test]
    fn test_move_entry_to_first() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.move_entry(4, 1).unwrap();
        assert_eq!(result, "/d:/a:/b:/c:/e");
    }

    #[test]
    fn test_move_entry_to_last() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.move_entry(2, 5).unwrap();
        assert_eq!(result, "/a:/c:/d:/e:/b");
    }

    #[test]
    fn test_move_entry_same_position() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.move_entry(3, 3).unwrap();
        assert_eq!(result, "/a:/b:/c:/d:/e");
    }

    #[test]
    fn test_move_entry_zero_index() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.move_entry(0, 2);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("must be >= 1"));
        assert!(err.contains("0"));
    }

    #[test]
    fn test_move_entry_out_of_bounds() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.move_entry(1, 5);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("out of bounds"));
    }

    #[test]
    fn test_swap_entries_basic() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.swap_entries(2, 4).unwrap();
        assert_eq!(result, "/a:/d:/c:/b:/e");
    }

    #[test]
    fn test_swap_entries_same_index() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.swap_entries(3, 3).unwrap();
        assert_eq!(result, "/a:/b:/c:/d:/e");
    }

    #[test]
    fn test_swap_entries_first_and_last() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.swap_entries(1, 5).unwrap();
        assert_eq!(result, "/e:/b:/c:/d:/a");
    }

    #[test]
    fn test_swap_entries_zero_index() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.swap_entries(0, 2);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("must be >= 1"));
        assert!(err.contains("0"));
    }

    #[test]
    fn test_swap_entries_out_of_bounds() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.swap_entries(2, 5);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("out of bounds"));
    }

    #[test]
    fn test_clean_no_duplicates() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let (result, removed) = searcher.clean_duplicates();
        assert_eq!(result, "/a:/b:/c:/d:/e");
        assert!(removed.is_empty());
    }

    #[test]
    fn test_clean_with_duplicates() {
        let searcher = PathSearcher::new("/a:/b:/c:/b:/d:/a");
        let (result, removed) = searcher.clean_duplicates();
        assert_eq!(result, "/a:/b:/c:/d");
        assert_eq!(removed, vec![4, 6]); // /b at idx 4, /a at idx 6
    }

    #[test]
    fn test_clean_all_same() {
        let searcher = PathSearcher::new("/a:/a:/a");
        let (result, removed) = searcher.clean_duplicates();
        assert_eq!(result, "/a");
        assert_eq!(removed, vec![2, 3]);
    }

    #[test]
    fn test_clean_consecutive_duplicates() {
        let searcher = PathSearcher::new("/a:/a:/b:/b:/c");
        let (result, removed) = searcher.clean_duplicates();
        assert_eq!(result, "/a:/b:/c");
        assert_eq!(removed, vec![2, 4]);
    }

    #[test]
    fn test_clean_empty() {
        let searcher = PathSearcher::new("");
        let (result, removed) = searcher.clean_duplicates();
        assert_eq!(result, "");
        assert!(removed.is_empty());
    }

    #[test]
    fn test_clean_matches_delete() {
        // Verify that clean and delete produce identical results
        let path = "/a:/b:/c:/b:/d:/a:/e:/c";
        let searcher = PathSearcher::new(path);

        // Get clean result and removed indices
        let (clean_result, removed) = searcher.clean_duplicates();

        // Apply delete with the same indices
        let delete_result = searcher.delete_entries(&removed).unwrap();

        // Results must be identical
        assert_eq!(clean_result, delete_result);
        assert_eq!(removed, vec![4, 6, 8]); // /b at 4, /a at 6, /c at 8
    }

    #[test]
    fn test_delete_first() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entry(1).unwrap();
        assert_eq!(result, "/b:/c:/d:/e");
    }

    #[test]
    fn test_delete_middle() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entry(3).unwrap();
        assert_eq!(result, "/a:/b:/d:/e");
    }

    #[test]
    fn test_delete_last() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entry(5).unwrap();
        assert_eq!(result, "/a:/b:/c:/d");
    }

    #[test]
    fn test_delete_only_entry() {
        let searcher = PathSearcher::new("/a");
        let result = searcher.delete_entry(1).unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_delete_zero_index() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.delete_entry(0);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("must be >= 1"));
        assert!(err.contains("0"));
    }

    #[test]
    fn test_delete_out_of_bounds() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.delete_entry(5);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("out of bounds"));
    }

    #[test]
    fn test_delete_entries_multiple() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entries(&[2, 4]).unwrap();
        assert_eq!(result, "/a:/c:/e");
    }

    #[test]
    fn test_delete_entries_unordered() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entries(&[5, 2, 3]).unwrap();
        assert_eq!(result, "/a:/d");
    }

    #[test]
    fn test_delete_entries_with_duplicates() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entries(&[2, 2, 4, 4]).unwrap();
        assert_eq!(result, "/a:/c:/e");
    }

    #[test]
    fn test_delete_entries_all() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.delete_entries(&[1, 2, 3]).unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_delete_entries_zero_index() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.delete_entries(&[1, 0, 3]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("must be >= 1"));
        assert!(err.contains("0"));
    }

    #[test]
    fn test_delete_entries_out_of_bounds() {
        let searcher = PathSearcher::new("/a:/b:/c");
        let result = searcher.delete_entries(&[1, 5, 2]);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("out of bounds"));
    }

    #[test]
    fn test_delete_entries_single() {
        let searcher = PathSearcher::new("/a:/b:/c:/d:/e");
        let result = searcher.delete_entries(&[3]).unwrap();
        assert_eq!(result, "/a:/b:/d:/e");
    }

    // Security tests

    #[test]
    fn test_path_validation_null_byte() {
        let result = validate_path_entry("hello\0world");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("null byte"));
    }

    #[test]
    fn test_path_validation_control_chars() {
        let result = validate_path_entry("hello\x01world");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("control character"));
    }

    #[test]
    fn test_path_validation_tab_allowed() {
        // Tab is a valid character in paths
        let result = validate_path_entry("hello\tworld");
        assert!(result.is_ok());
    }

    #[test]
    fn test_path_validation_newline_rejected() {
        let result = validate_path_entry("hello\nworld");
        assert!(result.is_err());
    }

    #[test]
    fn test_empty_path_components_skipped() {
        // Empty components should be skipped, not treated as "."
        let searcher = PathSearcher::new("/a::/b");
        let dirs = searcher.dirs();
        assert_eq!(dirs.len(), 2);
        assert_eq!(dirs[0].to_str().unwrap(), "/a");
        assert_eq!(dirs[1].to_str().unwrap(), "/b");
    }

    #[test]
    fn test_malicious_path_filtered() {
        // Path with null byte should be filtered out
        let searcher = PathSearcher::new("/good:/bad\0path:/alsogood");
        let dirs = searcher.dirs();
        // Only /good and /alsogood should remain
        assert_eq!(dirs.len(), 2);
        assert_eq!(dirs[0].to_str().unwrap(), "/good");
        assert_eq!(dirs[1].to_str().unwrap(), "/alsogood");
    }

    #[test]
    fn test_error_messages_include_values() {
        let searcher = PathSearcher::new("/a:/b:/c");

        // Test zero index error includes the value
        let err = searcher.move_entry(0, 2).unwrap_err();
        assert!(err.contains("0"));
        assert!(err.contains("must be >= 1"));

        // Test out of bounds error includes the value
        let err = searcher.move_entry(5, 2).unwrap_err();
        assert!(err.contains("5"));
        assert!(err.contains("out of bounds"));
        assert!(err.contains("3 entries"));
    }
}