dir.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use feature::Git;
  2. use file::File;
  3. use file;
  4. use std::io;
  5. use std::fs;
  6. use std::path::{Path, PathBuf};
  7. /// A **Dir** provides a cached list of the file paths in a directory that's
  8. /// being listed.
  9. ///
  10. /// This object gets passed to the Files themselves, in order for them to
  11. /// check the existence of surrounding files, then highlight themselves
  12. /// accordingly. (See `File#get_source_files`)
  13. pub struct Dir {
  14. contents: Vec<PathBuf>,
  15. path: PathBuf,
  16. git: Option<Git>,
  17. }
  18. impl Dir {
  19. /// Create a new Dir object filled with all the files in the directory
  20. /// pointed to by the given path. Fails if the directory can't be read, or
  21. /// isn't actually a directory.
  22. pub fn readdir(path: &Path) -> io::Result<Dir> {
  23. fs::read_dir(path).map(|dir_obj| Dir {
  24. contents: dir_obj.map(|entry| entry.unwrap().path()).collect(),
  25. path: path.to_path_buf(),
  26. git: Git::scan(path).ok(),
  27. })
  28. }
  29. /// Produce a vector of File objects from an initialised directory,
  30. /// printing out an error if any of the Files fail to be created.
  31. ///
  32. /// Passing in `recurse` means that any directories will be scanned for
  33. /// their contents, as well.
  34. pub fn files(&self, recurse: bool) -> Vec<File> {
  35. let mut files = vec![];
  36. for path in self.contents.iter() {
  37. match File::from_path(path, Some(self), recurse) {
  38. Ok(file) => files.push(file),
  39. Err(e) => println!("{}: {}", path.display(), e),
  40. }
  41. }
  42. files
  43. }
  44. /// Whether this directory contains a file with the given path.
  45. pub fn contains(&self, path: &Path) -> bool {
  46. self.contents.iter().any(|ref p| p.as_path() == path)
  47. }
  48. /// Append a path onto the path specified by this directory.
  49. pub fn join(&self, child: &Path) -> PathBuf {
  50. self.path.join(child)
  51. }
  52. /// Return whether there's a Git repository on or above this directory.
  53. pub fn has_git_repo(&self) -> bool {
  54. self.git.is_some()
  55. }
  56. /// Get a string describing the Git status of the given file.
  57. pub fn git_status(&self, path: &Path, prefix_lookup: bool) -> file::Git {
  58. match (&self.git, prefix_lookup) {
  59. (&Some(ref git), false) => git.status(path),
  60. (&Some(ref git), true) => git.dir_status(path),
  61. (&None, _) => file::Git::empty()
  62. }
  63. }
  64. }