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
//! Local file system backend.
//!
//! This sub-module provides types for accessing the local file system as a backend.
//!
//! # Example
//!
//! ```
//! use ruplicity::backend::Backend;
//! use ruplicity::backend::local::LocalBackend;
//! use std::io::Read;
//! use std::path::Path;
//!
//! let backend = LocalBackend::new("tests/backend");
//! for file in backend.file_names().unwrap() {
//! // print the current path
//! let path: &Path = file.as_ref();
//! println!("file: {}", path.to_str().unwrap());
//! // print file contents
//! let mut file = backend.open_file(path).unwrap();
//! let mut contents = Vec::new();
//! file.read_to_end(&mut contents).unwrap();
//! println!("contents: {}", String::from_utf8(contents).unwrap());
//! }
//! ```
use super::Backend;
use std::fs::{self, File};
use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
/// Backend for some directory in the local file system.
#[derive(Debug)]
pub struct LocalBackend {
base_path: PathBuf,
}
/// Iterator over a set of file names.
pub struct FileNameIterator(fs::ReadDir);
impl LocalBackend {
/// Creates a new local backend for the given directory.
pub fn new<P: AsRef<Path>>(path: P) -> Self {
LocalBackend { base_path: path.as_ref().to_path_buf() }
}
}
impl Backend for LocalBackend {
type FileName = OsString;
type FileNameIter = FileNameIterator;
type FileStream = File;
fn file_names(&self) -> io::Result<Self::FileNameIter> {
let dir = try!(fs::read_dir(self.base_path.as_path()));
Ok(FileNameIterator(dir))
}
fn open_file(&self, name: &Path) -> io::Result<File> {
let mut path = self.base_path.clone();
path.push(name);
File::open(path)
}
}
impl Iterator for FileNameIterator {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
for entry in &mut self.0 {
if let Ok(entry) = entry {
return Some(entry.file_name());
}
}
None
}
}