dir.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use std::io;
  2. use std::fs;
  3. use std::path::{Path, PathBuf};
  4. use std::slice::Iter as SliceIter;
  5. use feature::Git;
  6. use file::{File, fields};
  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, or if there's an IO error that occurs
  22. /// while scanning.
  23. pub fn readdir(path: &Path, git: bool) -> io::Result<Dir> {
  24. let reader = try!(fs::read_dir(path));
  25. let contents = try!(reader.map(|e| e.map(|e| e.path())).collect());
  26. Ok(Dir {
  27. contents: contents,
  28. path: path.to_path_buf(),
  29. git: if git { Git::scan(path).ok() } else { None },
  30. })
  31. }
  32. /// Produce an iterator of IO results of trying to read all the files in
  33. /// this directory.
  34. pub fn files<'dir>(&'dir self) -> Files<'dir> {
  35. Files {
  36. inner: self.contents.iter(),
  37. dir: &self,
  38. }
  39. }
  40. /// Whether this directory contains a file with the given path.
  41. pub fn contains(&self, path: &Path) -> bool {
  42. self.contents.iter().any(|ref p| p.as_path() == path)
  43. }
  44. /// Append a path onto the path specified by this directory.
  45. pub fn join(&self, child: &Path) -> PathBuf {
  46. self.path.join(child)
  47. }
  48. /// Return whether there's a Git repository on or above this directory.
  49. pub fn has_git_repo(&self) -> bool {
  50. self.git.is_some()
  51. }
  52. /// Get a string describing the Git status of the given file.
  53. pub fn git_status(&self, path: &Path, prefix_lookup: bool) -> fields::Git {
  54. match (&self.git, prefix_lookup) {
  55. (&Some(ref git), false) => git.status(path),
  56. (&Some(ref git), true) => git.dir_status(path),
  57. (&None, _) => fields::Git::empty()
  58. }
  59. }
  60. }
  61. pub struct Files<'dir> {
  62. inner: SliceIter<'dir, PathBuf>,
  63. dir: &'dir Dir,
  64. }
  65. impl<'dir> Iterator for Files<'dir> {
  66. type Item = Result<File<'dir>, (PathBuf, io::Error)>;
  67. fn next(&mut self) -> Option<Self::Item> {
  68. self.inner.next().map(|path| File::from_path(path, Some(self.dir)).map_err(|t| (path.clone(), t)))
  69. }
  70. }