exa/file.rs

232 lines
9.5 KiB
Rust
Raw Normal View History

2014-06-21 17:17:24 +00:00
use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan, Fixed};
use std::io::{fs, IoResult};
use std::io;
2014-06-22 07:09:16 +00:00
use column::{Column, Permissions, FileName, FileSize, User, Group, HardLinks, Inode, Blocks};
2014-05-26 19:24:51 +00:00
use format::{format_metric_bytes, format_IEC_bytes};
use unix::Unix;
2014-06-01 10:54:31 +00:00
use sort::SortPart;
use dir::Dir;
2014-06-17 21:17:22 +00:00
use filetype::HasType;
2014-05-26 19:24:51 +00:00
// Instead of working with Rust's Paths, we have our own File object
// that holds the Path and various cached information. Each file is
// definitely going to have its filename used at least once, its stat
// information queried at least once, and its file extension extracted
// at least once, so we may as well carry around that information with
// the actual path.
pub struct File<'a> {
2014-06-21 09:11:50 +00:00
pub name: &'a str,
pub dir: &'a Dir<'a>,
pub ext: Option<&'a str>,
pub path: &'a Path,
pub stat: io::FileStat,
2014-06-01 15:30:18 +00:00
pub parts: Vec<SortPart>,
}
impl<'a> File<'a> {
pub fn from_path(path: &'a Path, parent: &'a Dir) -> IoResult<File<'a>> {
2014-05-26 19:24:51 +00:00
// Getting the string from a filename fails whenever it's not
// UTF-8 representable - just assume it is for now.
let filename: &str = path.filename_str().unwrap();
2014-05-26 19:24:51 +00:00
// Use lstat here instead of file.stat(), as it doesn't follow
// symbolic links. Otherwise, the stat() call will fail if it
// encounters a link that's target is non-existent.
fs::lstat(path).map(|stat| File {
2014-06-01 10:54:31 +00:00
path: path,
dir: parent,
2014-06-01 10:54:31 +00:00
stat: stat,
name: filename,
ext: File::ext(filename),
parts: SortPart::split_into_parts(filename),
})
}
fn ext(name: &'a str) -> Option<&'a str> {
2014-05-26 19:24:51 +00:00
// The extension is the series of characters after a dot at
// the end of a filename. This deliberately also counts
// dotfiles - the ".git" folder has the extension "git".
let re = regex!(r"\.([^.]+)$");
re.captures(name).map(|caps| caps.at(1))
2014-05-24 01:32:57 +00:00
}
pub fn is_dotfile(&self) -> bool {
self.name.starts_with(".")
}
pub fn is_tmpfile(&self) -> bool {
self.name.ends_with("~") || (self.name.starts_with("#") && self.name.ends_with("#"))
}
// Highlight the compiled versions of files. Some of them, like .o,
// get special highlighting when they're alone because there's no
// point in existing without their source. Others can be perfectly
// content without their source files, such as how .js is valid
// without a .coffee.
pub fn get_source_files(&self) -> Vec<Path> {
match self.ext {
Some("class") => vec![self.path.with_extension("java")], // Java
Some("elc") => vec![self.path.with_extension("el")], // Emacs Lisp
Some("hi") => vec![self.path.with_extension("hs")], // Haskell
Some("o") => vec![self.path.with_extension("c"), self.path.with_extension("cpp")], // C, C++
Some("pyc") => vec![self.path.with_extension("py")], // Python
Some("js") => vec![self.path.with_extension("coffee"), self.path.with_extension("ts")], // CoffeeScript, TypeScript
Some("css") => vec![self.path.with_extension("sass"), self.path.with_extension("less")], // SASS, Less
Some("aux") => vec![self.path.with_extension("tex")], // TeX: auxiliary file
Some("bbl") => vec![self.path.with_extension("tex")], // BibTeX bibliography file
Some("blg") => vec![self.path.with_extension("tex")], // BibTeX log file
Some("lof") => vec![self.path.with_extension("tex")], // list of figures
Some("log") => vec![self.path.with_extension("tex")], // TeX log file
Some("lot") => vec![self.path.with_extension("tex")], // list of tables
Some("toc") => vec![self.path.with_extension("tex")], // table of contents
_ => vec![],
}
}
pub fn display(&self, column: &Column, unix: &mut Unix) -> String {
match *column {
2014-05-26 19:24:51 +00:00
Permissions => self.permissions_string(),
2014-06-21 09:11:50 +00:00
FileName => self.file_name(),
2014-05-26 19:24:51 +00:00
FileSize(use_iec) => self.file_size(use_iec),
// A file with multiple links is interesting, but
// directories and suchlike can have multiple links all
// the time.
HardLinks => {
let style = if self.stat.kind == io::TypeFile && self.stat.unstable.nlink > 1 { Red.on(Yellow) } else { Red.normal() };
style.paint(self.stat.unstable.nlink.to_str().as_slice())
},
2014-06-22 06:44:00 +00:00
Inode => Purple.paint(self.stat.unstable.inode.to_str().as_slice()),
2014-06-22 07:09:16 +00:00
Blocks => {
if self.stat.kind == io::TypeFile || self.stat.kind == io::TypeSymlink {
Cyan.paint(self.stat.unstable.blocks.to_str().as_slice())
}
else {
Fixed(244).paint("-")
}
},
2014-05-26 19:24:51 +00:00
// Display the ID if the user/group doesn't exist, which
// usually means it was deleted but its files weren't.
User => {
let uid = self.stat.unstable.uid as u32;
unix.load_user(uid);
let style = if unix.uid == uid { Yellow.bold() } else { Plain };
let string = unix.get_user_name(uid).unwrap_or(uid.to_str());
style.paint(string.as_slice())
},
Group => {
let gid = self.stat.unstable.gid as u32;
unix.load_group(gid);
let name = unix.get_group_name(gid).unwrap_or(gid.to_str());
let style = if unix.is_group_member(gid) { Yellow.normal() } else { Plain };
style.paint(name.as_slice())
2014-05-27 18:05:15 +00:00
},
}
}
2014-06-21 09:11:50 +00:00
fn file_name(&self) -> String {
let displayed_name = self.file_colour().paint(self.name);
if self.stat.kind == io::TypeSymlink {
match fs::readlink(self.path) {
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,
2014-06-21 09:11:50 +00:00
}
}
else {
displayed_name
}
}
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)),
}
}
2014-05-26 19:24:51 +00:00
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.
if self.stat.kind == io::TypeDirectory {
2014-06-22 07:09:16 +00:00
Fixed(244).paint("-")
} else {
let (size, suffix) = if use_iec_prefixes {
2014-05-26 19:24:51 +00:00
format_IEC_bytes(self.stat.size)
} else {
2014-05-26 19:24:51 +00:00
format_metric_bytes(self.stat.size)
};
return format!("{}{}", Green.bold().paint(size.as_slice()), Green.paint(suffix.as_slice()));
}
}
2014-05-26 10:08:33 +00:00
fn type_char(&self) -> String {
return match self.stat.kind {
io::TypeFile => ".".to_string(),
2014-05-26 19:24:51 +00:00
io::TypeDirectory => Blue.paint("d"),
io::TypeNamedPipe => Yellow.paint("|"),
io::TypeBlockSpecial => Purple.paint("s"),
2014-05-26 19:24:51 +00:00
io::TypeSymlink => Cyan.paint("l"),
io::TypeUnknown => "?".to_string(),
}
}
fn file_colour(&self) -> Style {
2014-06-17 21:17:22 +00:00
self.get_type().style()
}
2014-05-26 19:24:51 +00:00
fn permissions_string(&self) -> String {
let bits = self.stat.perm;
return format!("{}{}{}{}{}{}{}{}{}{}",
self.type_char(),
2014-05-26 19:24:51 +00:00
// The first three are bold because they're the ones used
// most often.
File::permission_bit(bits, io::UserRead, "r", Yellow.bold()),
File::permission_bit(bits, io::UserWrite, "w", Red.bold()),
File::permission_bit(bits, io::UserExecute, "x", Green.bold().underline()),
File::permission_bit(bits, io::GroupRead, "r", Yellow.normal()),
File::permission_bit(bits, io::GroupWrite, "w", Red.normal()),
File::permission_bit(bits, io::GroupExecute, "x", Green.normal()),
File::permission_bit(bits, io::OtherRead, "r", Yellow.normal()),
File::permission_bit(bits, io::OtherWrite, "w", Red.normal()),
File::permission_bit(bits, io::OtherExecute, "x", Green.normal()),
);
}
2014-05-26 19:24:51 +00:00
fn permission_bit(bits: io::FilePermission, bit: io::FilePermission, character: &'static str, style: Style) -> String {
if bits.contains(bit) {
2014-05-26 19:24:51 +00:00
style.paint(character.as_slice())
} else {
Black.bold().paint("-".as_slice())
}
}
}