sibling 2.0.3

The API for traversing sibling directories (find next/previous directory).
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
//! The library for traversing the sibling directories.
//! This library provides the interface for obtaining the next/previous sibling directories of a given directory by sorting with alphabetical order.
//!
//! It supports various strategies for selecting the next directory,
//! such as [first](NexterType::First), [last](NexterType::Last), [next](NexterType::Next),
//! [previous](NexterType::Previous), [random](NexterType::Random), and [keep](NexterType::Keep) current.
//!
//! ## Example
//!
//! ```rust
//! let dirs = sibling::Dirs::new("../testdata/basic")
//!     .expect("Failed to create Dirs");
//! let nexter = sibling::NexterFactory::build(sibling::NexterType::Next);
//! let next_dir = nexter.next(&dirs); // Get the next sibling directory
//! ```
use std::fmt::Display;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

use clap::ValueEnum;

/// The result type for sibling operations.
pub type Result<T> = std::result::Result<T, Error>;

/// The type of the nexter.
#[derive(Debug, Eq, PartialEq, Clone, ValueEnum)]
pub enum NexterType {
    /// The first sibling directory.
    First,
    /// The last sibling directory.
    Last,
    /// The previous sibling directory (step parameter specifies how many to go back).
    Previous,
    /// The next sibling directory (step parameter specifies how many to go forward).
    Next,
    /// A random sibling directory (step parameter is ignored).
    Random,
    /// Keep the current directory (step parameter is ignored).
    Keep,
}

/// The error type for sibling.
#[derive(Debug)]
pub enum Error {
    /// I/O error occurred while accessing the file system.
    Io(std::io::Error),
    /// The specified path was not found.
    NotFound(PathBuf),
    /// The path has no parent directory (e.g., root directory).
    NoParent(PathBuf),
    /// The specified path is not a directory.
    NotDir(PathBuf),
    /// The specified path is not a file.
    NotFile(PathBuf),
    /// A fatal error with a custom message.
    Fatal(String),
    /// Multiple errors occurred (array of errors).
    Array(Vec<Error>),
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Io(e) => write!(f, "I/O error: {e}"),
            Error::NotDir(path) => write!(f, "{}: Not a directory", path.display()),
            Error::NoParent(path) => write!(f, "{}: No parent directory", path.display()),
            Error::Array(array) => array
                .iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
                .fmt(f),
            Error::NotFile(path) => write!(f, "{}: Not a file", path.display()),
            Error::NotFound(path) => write!(f, "{}: Not found", path.display()),
            Error::Fatal(message) => write!(f, "Fatal error: {message}"),
        }
    }
}

/// Stores a list of sibling directories, the parent directory path, and the index of the current directory.
#[derive(Debug, Clone)]
pub struct Dirs {
    /// The list of sibling directories, sorted alphabetically.
    entries: Vec<PathBuf>,
    /// The parent directory that contains all the sibling directories.
    parent: PathBuf,
    /// The index of the current directory in the `dirs` vector.
    current: usize,
}

/// The struct represents a directory in the traversal target set.
#[derive(Debug, Clone)]
pub struct Dir<'a> {
    /// Reference to the parent `Dirs` instance.
    dirs: &'a Dirs,
    /// The index of this directory in the `Dirs.dirs` vector.
    index: usize,
    /// Flag indicating if this is the first or last directory in the sorted list.
    last_item: bool,
}

impl Dir<'_> {
    /// Create a new [`Dir`] instance.
    #[must_use]
    pub fn new(dirs: &Dirs, index: usize) -> Dir<'_> {
        log::trace!("Dir::new(index={index})");
        Dir {
            dirs,
            index,
            last_item: false,
        }
    }

    /// Create a new [`Dir`] instance with the last item flag.
    #[must_use]
    pub fn new_of_last_item(dirs: &Dirs, index: usize) -> Dir<'_> {
        log::trace!("Dir::new_of_last_item(index={index})");
        Dir {
            dirs,
            index,
            last_item: true,
        }
    }

    /// Get the path of the directory.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.dirs.entries[self.index]
    }

    /// Get the index of the directory.
    #[must_use]
    pub fn index(&self) -> usize {
        self.index
    }

    /// Check if this directory is the last item.
    #[must_use]
    pub fn is_last_item(&self) -> bool {
        self.last_item
    }
}

impl Dirs {
    /// Create a new [`Dirs`] instance from the given directory and its sibling directories.
    /// If the current directory is ".", it uses the current working directory.
    ///
    /// # Returns
    ///
    /// A [`Result`]<[`Dirs`]> instance.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::Io`] if an I/O error occurs.
    /// - Returns [`Error::NotDir`] if the given path is not a directory.
    /// - Returns [`Error::NotFound`] if the given path does not exist.
    pub fn new<P: AsRef<Path>>(current_dir: P) -> Result<Self> {
        let current_dir = current_dir.as_ref();
        log::debug!("Dirs::new(current_dir={})", current_dir.display());
        if current_dir == Path::new(".") {
            match std::env::current_dir() {
                Ok(dir) => build_dirs(dir.clone().parent(), dir),
                Err(e) => {
                    log::error!("Dirs::new: I/O error: {e}");
                    Err(Error::Io(e))
                }
            }
        } else if current_dir.exists() {
            if current_dir.is_dir() {
                let current = std::fs::canonicalize(current_dir).map_err(Error::Io)?;
                build_dirs(current.clone().parent(), current)
            } else {
                log::error!("Dirs::new: Not a directory: {}", current_dir.display());
                Err(Error::NotDir(current_dir.to_path_buf()))
            }
        } else {
            log::error!("Dirs::new: Not found: {}", current_dir.display());
            Err(Error::NotFound(current_dir.to_path_buf()))
        }
    }

    /// Create a new [`Dirs`] instance from the given file.
    /// The file should contain a list of directories, one per line.
    /// The first line can optionally specify the parent directory in the format `parent:/path/to`.
    ///
    /// # Returns
    /// A [`Result`]<[`Dirs`]> instance.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::Io`] if an I/O error occurs.
    /// - Returns [`Error::NotFile`] if the given path is not a file.
    /// - Returns [`Error::NotFound`] if the given path does not exist.
    pub fn new_from_file<S: AsRef<str>>(file: S) -> Result<Self> {
        log::debug!("Dirs::new_from_file(file={})", file.as_ref());
        let file = file.as_ref();
        if file == "-" {
            log::info!("Reading directories from stdin");
            return Ok(build_from_reader(Box::new(std::io::stdin().lock())));
        }
        let path = PathBuf::from(file);
        if !path.exists() {
            log::error!("Dirs::new_from_file: Not found: {}", path.display());
            Err(Error::NotFound(path))
        } else if path.is_dir() {
            log::error!("Dirs::new_from_file: Not a file: {}", path.display());
            Err(Error::NotFile(path))
        } else {
            build_from_list(&path)
        }
    }

    /// Get the parent directory path.
    #[must_use]
    pub fn parent(&self) -> &Path {
        self.parent.as_path()
    }

    /// Get the current directory as a [`Dir`] instance.
    #[must_use]
    pub fn current(&self) -> Dir<'_> {
        Dir::new(self, self.current)
    }

    /// Check if the directory list is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get the number of directories in the list.
    /// 
    /// ## Panics
    /// 
    /// This function will panic if the number of directories exceeds `i32::MAX`.
    #[must_use]
    pub fn len(&self) -> i32 {
        i32::try_from(self.entries.len()).unwrap()
    }

    /// Get the next directory using the given [`Nexter`].
    #[must_use]
    pub fn next(&self, nexter: &dyn Nexter) -> Option<Dir<'_>> {
        nexter.next_with(self, 1)
    }

    /// Get the next directory using the given [`Nexter`] and step.
    /// 
    /// ## Panics
    /// 
    /// This function will panic if the step exceeds `i32::MAX`.
    #[must_use]
    pub fn next_with(&self, nexter: &dyn Nexter, step: usize) -> Option<Dir<'_>> {
        nexter.next_with(self, i32::try_from(step).unwrap())
    }

    /// Get an iterator over the directories.
    pub fn directories(&self) -> impl Iterator<Item = &PathBuf> {
        self.entries.iter()
    }
}

/// Collect sibling directories under parent and compute the index of current.
fn build_dirs(parent: Option<&Path>, current: PathBuf) -> Result<Dirs> {
    log::trace!("build_dirs(parent={parent:?}, current={})", current.display());
    let Some(parent) =  parent else {
        log::error!("build_dirs: No parent for current={}", current.display());
        return Err(Error::NoParent(current));
    };
    let mut errs = vec![];
    let dirs = collect_dirs(parent, &mut errs);
    if errs.is_empty() {
        let current_index = find_current(&dirs, &current);
        let index = if current_index == -1 {
            log::warn!(
                "build_dirs: current directory not found in siblings: {}",
                current.display()
            );
            0
        } else {
            usize::try_from(current_index).unwrap()
        };
        log::info!("build_dirs: siblings={}, current_index={index}", dirs.len());
        Ok(Dirs {
            entries: dirs,
            parent: parent.to_path_buf(),
            current: index,
        })
    } else {
        Err(Error::Array(errs))
    }
}

/// Read child directories under parent, push IO errors to errs, and return a sorted list.
fn collect_dirs(parent: &Path, errs: &mut Vec<Error>) -> Vec<PathBuf> {
    log::trace!("collect_dirs(parent={})", parent.display());
    let mut dirs = vec![];
    if let Ok(entries) = parent.read_dir() {
        for entry in entries {
            match entry {
                Ok(entry) => {
                    let path = entry.path();
                    if path.is_dir() {
                        dirs.push(path);
                    }
                }
                Err(e) => {
                    log::error!("collect_dirs: I/O error: {e}");
                    errs.push(Error::Io(e));
                }
            }
        }
    }
    if log::log_enabled!(log::Level::Warn) && dirs.is_empty() {
        log::warn!("collect_dirs: no directories under {}", parent.display());
    }
    dirs.sort();
    dirs
}

/// Return the index of current in dirs, or 0 if not found.
fn find_current(dirs: &[PathBuf], current: &PathBuf) -> i32 {
    let idx = dirs
        .iter()
        .position(|dir| dir == current)
        .map_or(-1, |i| i32::try_from(i).unwrap());
    log::trace!("find_current: index={} for {}", idx, current.display());
    idx
}

/// Parse lines from a reader; parent: sets base, remaining lines are directory entries.
fn build_from_reader(reader: Box<dyn BufRead>) -> Dirs {
    let lines = reader
        .lines()
        .filter_map(|line| line.map(|n| n.trim().to_string()).ok())
        .collect::<Vec<String>>();
    let base = if let Some(base) = lines.iter().find(|l| l.starts_with("parent:")) {
        base.chars().skip(7).collect::<String>().trim().to_string()
    } else {
        ".".to_string()
    };
    let dirs = lines
        .iter()
        .filter(|l| !l.starts_with("parent:"))
        .map(PathBuf::from)
        .collect::<Vec<PathBuf>>();
    log::debug!("build_from_reader: base='{}', entries={}", base, dirs.len());
    let current = find_current_dir_index(&dirs);
    if current == 0 {
        log::warn!("build_from_reader: current directory not found in siblings");
    }
    Dirs {
        entries: dirs,
        parent: PathBuf::from(base),
        current,
    }
}

fn find_current_dir_index(dirs: &[PathBuf]) -> usize {
    log::trace!("find_current_dir_index(dirs.len={})", dirs.len());
    if let Ok(pwd) = std::env::current_dir() {
        let cwd = PathBuf::from(".");
        if let Some(pos) = dirs
            .iter()
            .position(|dir| dir == &cwd || pwd.ends_with(dir))
        {
            return pos;
        }
    }
    0
}

fn build_from_list(filename: &Path) -> Result<Dirs> {
    if let Ok(f) = std::fs::File::open(filename) {
        let reader = BufReader::new(f);
        Ok(build_from_reader(Box::new(reader)))
    } else {
        log::error!("build_from_list: I/O error: {}", filename.display());
        Err(Error::Io(std::io::Error::last_os_error()))
    }
}

/// The trait for nexter.
/// This trait defines the interface for obtaining the next directory.
pub trait Nexter {
    /// Find the next directory with the given step.
    /// If the nexter type is `first`, `last`, `keep`, or `random`, the step parameter is ignored.
    fn next_with<'a>(&self, dirs: &'a Dirs, step: i32) -> Option<Dir<'a>>;

    /// Find the next directory (calls `self.next_with(dirs, 1)`).
    fn next<'a>(&self, dirs: &'a Dirs) -> Option<Dir<'a>> {
        self.next_with(dirs, 1)
    }
}

/// Factory pattern for creating [`Nexter`] instances.
pub struct NexterFactory {}

impl NexterFactory {
    /// Build a [`Nexter`] instance based on the given [`NexterType`].
    #[must_use]
    pub fn build(nexter_type: &NexterType) -> Box<dyn Nexter> {
        log::trace!("NexterFactory::build(nexter_type={nexter_type:?})");
        match nexter_type {
            NexterType::First => Box::new(First {}),
            NexterType::Last => Box::new(Last {}),
            NexterType::Previous => Box::new(Previous {}),
            NexterType::Next => Box::new(Next {}),
            NexterType::Random => Box::new(Random {}),
            NexterType::Keep => Box::new(Keep {}),
        }
    }
}

struct First {}
struct Last {}
struct Previous {}
struct Next {}
struct Random {}
struct Keep {}

impl Nexter for First {
    fn next_with<'a>(&self, dirs: &'a Dirs, _step: i32) -> Option<Dir<'a>> {
        Some(Dir::new_of_last_item(dirs, 0))
    }
}

impl Nexter for Last {
    fn next_with<'a>(&self, dirs: &'a Dirs, _step: i32) -> Option<Dir<'a>> {
        let next = dirs.len() - 1;
        Some(Dir::new_of_last_item(dirs, usize::try_from(next).unwrap()))
    }
}

impl Nexter for Previous {
    fn next_with<'a>(&self, dirs: &'a Dirs, step: i32) -> Option<Dir<'a>> {
        next_impl(dirs, -step)
    }
}

impl Nexter for Next {
    fn next_with<'a>(&self, dirs: &'a Dirs, step: i32) -> Option<Dir<'a>> {
        next_impl(dirs, step)
    }
}

impl Nexter for Random {
    fn next_with<'a>(&self, dirs: &'a Dirs, _step: i32) -> Option<Dir<'a>> {
        use rand::Rng;
        let mut rng = rand::rng();
        let next = rng.random_range(0..dirs.len());
        log::trace!("Random::next_with -> index {next}");
        Some(Dir::new(dirs, usize::try_from(next).unwrap()))
    }
}

impl Nexter for Keep {
    fn next_with<'a>(&self, dirs: &'a Dirs, _step: i32) -> Option<Dir<'a>> {
        Some(dirs.current())
    }
}

fn next_impl(dirs: &Dirs, step: i32) -> Option<Dir<'_>> {
    let next = i32::try_from(dirs.current).unwrap() + step;
    let length = dirs.len();
    log::trace!(
        "next_impl(step={step}, current={}, next={next})",
        dirs.current
    );
    if next < 0 || next >= dirs.len() {
        log::warn!(
            "next_impl: out of range (next={next}, len={})",
            dirs.len()
        );
        None
    } else if next == 0 {
        Some(Dir::new_of_last_item(dirs, 0))
    } else if next == length - 1 {
        Some(Dir::new_of_last_item(dirs, usize::try_from(length - 1).unwrap()))
    } else {
        Some(Dir::new(dirs, usize::try_from(next).unwrap()))
    }
}

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

    #[test]
    fn test_dirs_new() {
        let dirs = Dirs::new(PathBuf::from("../testdata/basic/d"));
        assert!(dirs.is_ok());
        let dirs = dirs.unwrap();
        assert_eq!(dirs.len(), 26);
        assert_eq!(dirs.current, 3);
    }

    #[test]
    fn test_worried_dirs() {
        let dirs = Dirs::new(PathBuf::from("../testdata/worried/dir with spaces"));
        assert!(dirs.is_ok());
        let dirs = dirs.unwrap();
        assert_eq!(dirs.len(), 2);
        assert_eq!(dirs.current, 0);
    }

    #[test]
    fn test_dir_dot() {
        let dirs = Dirs::new(PathBuf::from(".."));
        assert!(dirs.is_ok());
        let dirs = dirs.unwrap();
        assert_eq!(
            dirs.current().path().file_name().map(|s| s.to_str()),
            Some("sibling".into())
        );
    }

    #[test]
    fn test_dirs() {
        let dirs = Dirs::new(PathBuf::from("../testdata/basic/d")).unwrap();
        let abspath = Path::new("../testdata/basic").canonicalize().unwrap();
        assert_eq!(dirs.parent(), &abspath);
        assert_eq!(dirs.current().index(), 3);
        assert!(!dirs.is_empty());
        assert_eq!(dirs.len(), 26);
    }

    #[test]
    fn test_dir_from_file() {
        let dirs = Dirs::new_from_file("../testdata/basic/dirlist.txt");
        assert!(dirs.is_ok());
        let dirs = dirs.unwrap();
        assert_eq!(dirs.len(), 4);
        assert_eq!(dirs.current, 1);
        assert_eq!(dirs.parent, PathBuf::from("testdata/basic"));
    }

    #[test]
    fn test_nexter_first() {
        let dirs = Dirs::new("../testdata/basic/c").unwrap();
        let nexter = NexterFactory::build(&NexterType::First);
        match nexter.next(&dirs) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/a")),
            None => panic!("unexpected None"),
        }
    }

    #[test]
    fn test_nexter_keep() {
        let dirs = Dirs::new("../testdata/basic/c").unwrap();
        let nexter = NexterFactory::build(&NexterType::Keep);
        match nexter.next(&dirs) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/c")),
            None => panic!("unexpected None"),
        }
    }

    #[test]
    fn test_nexter_last() {
        let dirs = Dirs::new("../testdata/basic/k").unwrap();
        let nexter = NexterFactory::build(&NexterType::Last);
        match nexter.next(&dirs) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/z")),
            None => panic!("unexpected None"),
        }
    }

    #[test]
    fn test_nexter_next() {
        let dirs = Dirs::new("../testdata/basic/c").unwrap();
        let nexter = NexterFactory::build(&NexterType::Next);
        match nexter.next(&dirs) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/d")),
            None => panic!("unexpected None"),
        }
        match nexter.next_with(&dirs, 2) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/e"), "{:?}", p.path()),
            None => panic!("unexpected None"),
        }
        match nexter.next_with(&dirs, 23) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/z"), "{:?}", p.path()),
            None => panic!("unexpected None"),
        }
        match nexter.next_with(&dirs, 24) {
            None => {}
            Some(p) => panic!("unexpected {:?}", p.path()),
        }
    }

    #[test]
    fn test_nexter_prev() {
        let dirs = Dirs::new("../testdata/basic/k").unwrap();
        let nexter = NexterFactory::build(&NexterType::Previous);
        match nexter.next(&dirs) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/j")),
            None => panic!("unexpected None"),
        }
        match nexter.next(&dirs) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/j")),
            None => panic!("unexpected None"),
        }
        match nexter.next_with(&dirs, 4) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/g")),
            None => panic!("unexpected None"),
        }
        match nexter.next_with(&dirs, 10) {
            Some(p) => assert!(p.path().ends_with("testdata/basic/a")),
            None => panic!("unexpected None"),
        }
        if let Some(p) = nexter.next_with(&dirs, 11) {
            panic!("unexpected {:?}", p.path())
        }
    }
}