dir.rs 2.4 KB

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