Show file colours for symlink targets

This requires the dir field to store a reference to the path that
created it, so that path can be used to join onto the filename so it can
be properly statted.
This commit is contained in:
Ben S 2014-06-21 19:39:27 +01:00
parent eff87440fa
commit 8839cf4ca5
2 changed files with 38 additions and 13 deletions

4
dir.rs
View File

@ -8,13 +8,15 @@ use file::File;
// differently if a certain other file exists.
pub struct Dir<'a> {
contents: Vec<Path>,
pub contents: Vec<Path>,
pub path: Path,
}
impl<'a> Dir<'a> {
pub fn readdir(path: Path) -> IoResult<Dir<'a>> {
fs::readdir(&path).map(|paths| Dir {
contents: paths,
path: path.clone(),
})
}

33
file.rs
View File

@ -110,11 +110,11 @@ impl<'a> File<'a> {
let displayed_name = self.file_colour().paint(self.name);
if self.stat.kind == io::TypeSymlink {
match fs::readlink(self.path) {
Ok(path) => format!("{} {} {}", displayed_name, Fixed(244).paint("=>"), path.display()),
Err(e) => {
println!("{}", e);
displayed_name
},
Ok(path) => {
let target_path = if path.is_absolute() { path } else { self.dir.path.join(path) };
format!("{} {}", displayed_name, self.target_file_name_and_arrow(target_path))
}
Err(_) => displayed_name,
}
}
else {
@ -122,6 +122,29 @@ impl<'a> File<'a> {
}
}
fn target_file_name_and_arrow(&self, target_path: Path) -> String {
let filename = target_path.as_str().unwrap();
let link_target = fs::stat(&target_path).map(|stat| File {
path: &target_path,
dir: self.dir,
stat: stat,
name: filename,
ext: File::ext(filename),
parts: vec![], // not needed
});
// Statting a path usually fails because the file at the other
// end doesn't exist. Show this by highlighting the target
// file in red instead of displaying an error, because the
// error would be shown out of context and it's almost always
// that reason anyway.
match link_target {
Ok(file) => format!("{} {}", Fixed(244).paint("=>"), file.file_colour().paint(filename)),
Err(_) => format!("{} {}", Red.paint("=>"), Red.underline().paint(filename)),
}
}
fn file_size(&self, use_iec_prefixes: bool) -> String {
// Don't report file sizes for directories. I've never looked
// at one of those numbers and gained any information from it.