fix most clippy warnings

This commit is contained in:
Thibaut Brandscheid 2018-06-19 14:58:03 +02:00
parent a3b2f2b3f4
commit 755876e9b6
21 changed files with 79 additions and 94 deletions

View File

@ -19,7 +19,7 @@ fn main() {
match e.kind() { match e.kind() {
ErrorKind::BrokenPipe => exit(exits::SUCCESS), ErrorKind::BrokenPipe => exit(exits::SUCCESS),
_ => { _ => {
writeln!(stderr(), "{}", e).unwrap(); eprintln!("{}", e);
exit(exits::RUNTIME_ERROR); exit(exits::RUNTIME_ERROR);
}, },
}; };
@ -39,7 +39,7 @@ fn main() {
}, },
Err(ref e) => { Err(ref e) => {
writeln!(stdout(), "{}", e).unwrap(); println!("{}", e);
exit(exits::SUCCESS); exit(exits::SUCCESS);
}, },
}; };

View File

@ -83,7 +83,7 @@ impl Vars for LiveVars {
/// listed before theyre actually listed, if the options demand it. /// listed before theyre actually listed, if the options demand it.
fn git_options(options: &Options, args: &[&OsStr]) -> Option<GitCache> { fn git_options(options: &Options, args: &[&OsStr]) -> Option<GitCache> {
if options.should_scan_for_git() { if options.should_scan_for_git() {
Some(args.iter().map(|os| PathBuf::from(os)).collect()) Some(args.iter().map(PathBuf::from).collect())
} }
else { else {
None None
@ -166,7 +166,7 @@ impl<'args, 'w, W: Write + 'w> Exa<'args, 'w, W> {
first = false; first = false;
} }
else { else {
write!(self.writer, "\n")?; writeln!(self.writer)?;
} }
if !is_only_dir { if !is_only_dir {

View File

@ -52,7 +52,7 @@ impl Dir {
dir: self, dir: self,
dotfiles: dots.shows_dotfiles(), dotfiles: dots.shows_dotfiles(),
dots: dots.dots(), dots: dots.dots(),
ignore: ignore, ignore,
} }
} }
@ -103,7 +103,7 @@ impl<'dir, 'ig> Files<'dir, 'ig> {
loop { loop {
if let Some(path) = self.inner.next() { if let Some(path) = self.inner.next() {
let filename = File::filename(path); let filename = File::filename(path);
if !self.dotfiles && filename.starts_with(".") { continue } if !self.dotfiles && filename.starts_with('.') { continue }
if let Some(i) = self.ignore { if let Some(i) = self.ignore {
if i.is_ignored(path) { continue } if i.is_ignored(path) { continue }
@ -180,8 +180,8 @@ impl Default for DotFilter {
impl DotFilter { impl DotFilter {
/// Whether this filter should show dotfiles in a listing. /// Whether this filter should show dotfiles in a listing.
fn shows_dotfiles(&self) -> bool { fn shows_dotfiles(self) -> bool {
match *self { match self {
DotFilter::JustFiles => false, DotFilter::JustFiles => false,
DotFilter::Dotfiles => true, DotFilter::Dotfiles => true,
DotFilter::DotfilesAndDots => true, DotFilter::DotfilesAndDots => true,
@ -189,8 +189,8 @@ impl DotFilter {
} }
/// Whether this filter should add dot directories to a listing. /// Whether this filter should add dot directories to a listing.
fn dots(&self) -> Dots { fn dots(self) -> Dots {
match *self { match self {
DotFilter::JustFiles => Dots::FilesNext, DotFilter::JustFiles => Dots::FilesNext,
DotFilter::Dotfiles => Dots::FilesNext, DotFilter::Dotfiles => Dots::FilesNext,
DotFilter::DotfilesAndDots => Dots::DotNext, DotFilter::DotfilesAndDots => Dots::DotNext,

View File

@ -134,7 +134,7 @@ impl GitRepo {
debug!("Querying Git repo {:?} for the first time", &self.workdir); debug!("Querying Git repo {:?} for the first time", &self.workdir);
let repo = replace(&mut *contents, Processing).inner_repo(); let repo = replace(&mut *contents, Processing).inner_repo();
let statuses = repo_to_statuses(repo, &self.workdir); let statuses = repo_to_statuses(&repo, &self.workdir);
let result = statuses.status(index, prefix_lookup); let result = statuses.status(index, prefix_lookup);
let _processing = replace(&mut *contents, After { statuses }); let _processing = replace(&mut *contents, After { statuses });
result result
@ -194,7 +194,7 @@ impl GitContents {
/// mapping of files to their Git status. /// mapping of files to their Git status.
/// We will have already used the working directory at this point, so it gets /// We will have already used the working directory at this point, so it gets
/// passed in rather than deriving it from the `Repository` again. /// passed in rather than deriving it from the `Repository` again.
fn repo_to_statuses(repo: git2::Repository, workdir: &Path) -> Git { fn repo_to_statuses(repo: &git2::Repository, workdir: &Path) -> Git {
let mut statuses = Vec::new(); let mut statuses = Vec::new();
info!("Getting Git statuses for repo with workdir {:?}", workdir); info!("Getting Git statuses for repo with workdir {:?}", workdir);

View File

@ -72,7 +72,7 @@ fn file_lines_to_patterns<'a, I>(iter: I) -> IgnorePatterns
where I: Iterator<Item=&'a str> where I: Iterator<Item=&'a str>
{ {
let iter = iter.filter(|el| !el.is_empty()); let iter = iter.filter(|el| !el.is_empty());
let iter = iter.filter(|el| !el.starts_with("#")); let iter = iter.filter(|el| !el.starts_with('#'));
// TODO: Figure out if this should trim whitespace or not // TODO: Figure out if this should trim whitespace or not

View File

@ -203,7 +203,7 @@ mod lister {
impl Lister { impl Lister {
pub fn new(follow_symlinks: FollowSymlinks) -> Lister { pub fn new(follow_symlinks: FollowSymlinks) -> Lister {
Lister { follow_symlinks: follow_symlinks } Lister { follow_symlinks }
} }
pub fn translate_attribute_name(&self, input: &[u8]) -> String { pub fn translate_attribute_name(&self, input: &[u8]) -> String {

View File

@ -95,13 +95,7 @@ impl<'dir> File<'dir> {
/// against a pre-compiled list of extensions which are known to only exist /// against a pre-compiled list of extensions which are known to only exist
/// within ASCII, so its alright. /// within ASCII, so its alright.
fn ext(path: &Path) -> Option<String> { fn ext(path: &Path) -> Option<String> {
#[allow(unused)] let name = path.file_name().map(|f| f.to_string_lossy().to_string())?;
use std::ascii::AsciiExt;
let name = match path.file_name() {
Some(f) => f.to_string_lossy().to_string(),
None => return None,
};
name.rfind('.').map(|p| name[p+1..].to_ascii_lowercase()) name.rfind('.').map(|p| name[p+1..].to_ascii_lowercase())
} }
@ -209,7 +203,7 @@ impl<'dir> File<'dir> {
Ok(metadata) => { Ok(metadata) => {
let ext = File::ext(&path); let ext = File::ext(&path);
let name = File::filename(&path); let name = File::filename(&path);
FileTarget::Ok(File { parent_dir: None, path, ext, metadata, name }) FileTarget::Ok(Box::new(File { parent_dir: None, path, ext, metadata, name }))
} }
Err(e) => { Err(e) => {
error!("Error following link {:?}: {:#?}", &path, e); error!("Error following link {:?}: {:#?}", &path, e);
@ -229,7 +223,7 @@ impl<'dir> File<'dir> {
let count = self.metadata.nlink(); let count = self.metadata.nlink();
f::Links { f::Links {
count: count, count,
multiple: self.is_file() && count > 1, multiple: self.is_file() && count > 1,
} }
} }
@ -394,7 +388,7 @@ impl<'a> AsRef<File<'a>> for File<'a> {
pub enum FileTarget<'dir> { pub enum FileTarget<'dir> {
/// The symlink pointed at a file that exists. /// The symlink pointed at a file that exists.
Ok(File<'dir>), Ok(Box<File<'dir>>),
/// The symlink pointed at a file that does not exist. Holds the path /// The symlink pointed at a file that does not exist. Holds the path
/// where the file would be, if it existed. /// where the file would be, if it existed.

View File

@ -227,10 +227,10 @@ impl SortField {
/// into groups between letters and numbers, and then sorts those blocks /// into groups between letters and numbers, and then sorts those blocks
/// together, so `file10` will sort after `file9`, instead of before it /// together, so `file10` will sort after `file9`, instead of before it
/// because of the `1`. /// because of the `1`.
pub fn compare_files(&self, a: &File, b: &File) -> Ordering { pub fn compare_files(self, a: &File, b: &File) -> Ordering {
use self::SortCase::{ABCabc, AaBbCc}; use self::SortCase::{ABCabc, AaBbCc};
match *self { match self {
SortField::Unsorted => Ordering::Equal, SortField::Unsorted => Ordering::Equal,
SortField::Name(ABCabc) => natord::compare(&a.name, &b.name), SortField::Name(ABCabc) => natord::compare(&a.name, &b.name),
@ -270,7 +270,7 @@ impl SortField {
} }
fn strip_dot(n: &str) -> &str { fn strip_dot(n: &str) -> &str {
if n.starts_with(".") { if n.starts_with('.') {
&n[1..] &n[1..]
} else { } else {
n n

View File

@ -96,7 +96,7 @@ impl fmt::Display for HelpString {
/// Format this help options into an actual string of help /// Format this help options into an actual string of help
/// text to be displayed to the user. /// text to be displayed to the user.
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "Usage:\n exa [options] [files...]\n")?; writeln!(f, "Usage:\n exa [options] [files...]")?;
if !self.only_long { if !self.only_long {
write!(f, "{}", OPTIONS)?; write!(f, "{}", OPTIONS)?;

View File

@ -117,20 +117,14 @@ impl Misfire {
/// went wrong. /// went wrong.
pub fn suggestion(&self) -> Option<&'static str> { pub fn suggestion(&self) -> Option<&'static str> {
// ls -lt and ls -ltr are common combinations // ls -lt and ls -ltr are common combinations
if let Misfire::BadArgument(ref time, ref r) = *self { match *self {
if *time == &flags::TIME && r == "r" { Misfire::BadArgument(ref time, ref r) if *time == &flags::TIME && r == "r" =>
return Some("To sort oldest files last, try \"--sort oldest\", or just \"-sold\""); Some("To sort oldest files last, try \"--sort oldest\", or just \"-sold\""),
Misfire::InvalidOptions(ParseError::NeedsValue { ref flag, .. }) if *flag == Flag::Short(b't') =>
Some("To sort newest files last, try \"--sort newest\", or just \"-snew\""),
_ => None
} }
} }
if let Misfire::InvalidOptions(ParseError::NeedsValue { ref flag, values: _ }) = *self {
if *flag == Flag::Short(b't') {
return Some("To sort newest files last, try \"--sort newest\", or just \"-snew\"");
}
}
None
}
} }

View File

@ -452,7 +452,7 @@ fn split_on_equals(input: &OsStr) -> Option<(&OsStr, &OsStr)> {
let (before, after) = input.as_bytes().split_at(index); let (before, after) = input.as_bytes().split_at(index);
// The after string contains the = that we need to remove. // The after string contains the = that we need to remove.
if before.len() >= 1 && after.len() >= 2 { if !before.is_empty() && after.len() >= 2 {
return Some((OsStr::from_bytes(before), return Some((OsStr::from_bytes(before),
OsStr::from_bytes(&after[1..]))) OsStr::from_bytes(&after[1..])))
} }

View File

@ -72,12 +72,10 @@ impl Mode {
Ok(Mode::Grid(grid)) Ok(Mode::Grid(grid))
} }
} }
else {
// If the terminal width couldnt be matched for some reason, such // If the terminal width couldnt be matched for some reason, such
// as the programs stdout being connected to a file, then // as the programs stdout being connected to a file, then
// fallback to the lines view. // fallback to the lines view.
else if matches.has(&flags::TREE)? {
if matches.has(&flags::TREE)? {
let details = details::Options { let details = details::Options {
table: None, table: None,
header: false, header: false,
@ -89,7 +87,6 @@ impl Mode {
else { else {
Ok(Mode::Lines) Ok(Mode::Lines)
} }
}
}; };
if matches.has(&flags::LONG)? { if matches.has(&flags::LONG)? {
@ -256,14 +253,14 @@ impl TimeFormat {
let word = match matches.get(&flags::TIME_STYLE)? { let word = match matches.get(&flags::TIME_STYLE)? {
Some(w) => w, Some(w) => w,
None => return Ok(TimeFormat::DefaultFormat(DefaultFormat::new())), None => return Ok(TimeFormat::DefaultFormat(DefaultFormat::default())),
}; };
if word == "default" { if word == "default" {
Ok(TimeFormat::DefaultFormat(DefaultFormat::new())) Ok(TimeFormat::DefaultFormat(DefaultFormat::default()))
} }
else if word == "iso" { else if word == "iso" {
Ok(TimeFormat::ISOFormat(ISOFormat::new())) Ok(TimeFormat::ISOFormat(ISOFormat::default()))
} }
else if word == "long-iso" { else if word == "long-iso" {
Ok(TimeFormat::LongISO) Ok(TimeFormat::LongISO)

View File

@ -44,7 +44,7 @@ impl TextCell {
TextCell { TextCell {
contents: vec![ style.paint(text) ].into(), contents: vec![ style.paint(text) ].into(),
width: width, width,
} }
} }
@ -56,7 +56,7 @@ impl TextCell {
TextCell { TextCell {
contents: vec![ style.paint(text) ].into(), contents: vec![ style.paint(text) ].into(),
width: width, width,
} }
} }

View File

@ -184,7 +184,7 @@ impl<'a> Render<'a> {
/// Adds files to the table, possibly recursively. This is easily /// Adds files to the table, possibly recursively. This is easily
/// parallelisable, and uses a pool of threads. /// parallelisable, and uses a pool of threads.
fn add_files_to_table<'dir, 'ig>(&self, pool: &mut Pool, table: &mut Option<Table<'a>>, rows: &mut Vec<Row>, src: &Vec<File<'dir>>, ignore: Option<&'ig IgnoreCache>, depth: TreeDepth) { fn add_files_to_table<'dir, 'ig>(&self, pool: &mut Pool, table: &mut Option<Table<'a>>, rows: &mut Vec<Row>, src: &[File<'dir>], ignore: Option<&'ig IgnoreCache>, depth: TreeDepth) {
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use fs::feature::xattr; use fs::feature::xattr;
@ -294,7 +294,7 @@ impl<'a> Render<'a> {
if !files.is_empty() { if !files.is_empty() {
for xattr in egg.xattrs { for xattr in egg.xattrs {
rows.push(self.render_xattr(xattr, TreeParams::new(depth.deeper(), false))); rows.push(self.render_xattr(&xattr, TreeParams::new(depth.deeper(), false)));
} }
for (error, path) in errors { for (error, path) in errors {
@ -308,7 +308,7 @@ impl<'a> Render<'a> {
let count = egg.xattrs.len(); let count = egg.xattrs.len();
for (index, xattr) in egg.xattrs.into_iter().enumerate() { for (index, xattr) in egg.xattrs.into_iter().enumerate() {
rows.push(self.render_xattr(xattr, TreeParams::new(depth.deeper(), errors.is_empty() && index == count - 1))); rows.push(self.render_xattr(&xattr, TreeParams::new(depth.deeper(), errors.is_empty() && index == count - 1)));
} }
let count = errors.len(); let count = errors.len();
@ -340,7 +340,7 @@ impl<'a> Render<'a> {
Row { cells: None, name, tree } Row { cells: None, name, tree }
} }
fn render_xattr(&self, xattr: Attribute, tree: TreeParams) -> Row { fn render_xattr(&self, xattr: &Attribute, tree: TreeParams) -> Row {
let name = TextCell::paint(self.colours.perms.attribute, format!("{} (len {})", xattr.name, xattr.size)); let name = TextCell::paint(self.colours.perms.attribute, format!("{} (len {})", xattr.name, xattr.size));
Row { cells: None, name, tree } Row { cells: None, name, tree }
} }
@ -353,7 +353,7 @@ impl<'a> Render<'a> {
TableIter { TableIter {
tree_trunk: TreeTrunk::default(), tree_trunk: TreeTrunk::default(),
total_width: table.widths().total(), total_width: table.widths().total(),
table: table, table,
inner: rows.into_iter(), inner: rows.into_iter(),
tree_style: self.colours.punctuation, tree_style: self.colours.punctuation,
} }

View File

@ -37,7 +37,7 @@ impl<'a> Render<'a> {
grid.reserve(self.files.len()); grid.reserve(self.files.len());
for file in self.files.iter() { for file in &self.files {
let filename = self.style.for_file(file, self.colours).paint(); let filename = self.style.for_file(file, self.colours).paint();
let width = filename.width(); let width = filename.width();
@ -54,7 +54,7 @@ impl<'a> Render<'a> {
// File names too long for a grid - drop down to just listing them! // File names too long for a grid - drop down to just listing them!
// This isnt *quite* the same as the lines view, which also // This isnt *quite* the same as the lines view, which also
// displays full link paths. // displays full link paths.
for file in self.files.iter() { for file in &self.files {
let name_cell = self.style.for_file(file, self.colours).paint(); let name_cell = self.style.for_file(file, self.colours).paint();
writeln!(w, "{}", name_cell.strings())?; writeln!(w, "{}", name_cell.strings())?;
} }

View File

@ -87,7 +87,7 @@ impl<'a> Render<'a> {
/// *n* files into each columns table, not all of them. /// *n* files into each columns table, not all of them.
pub fn details(&self) -> DetailsRender<'a> { pub fn details(&self) -> DetailsRender<'a> {
DetailsRender { DetailsRender {
dir: self.dir.clone(), dir: self.dir,
files: Vec::new(), files: Vec::new(),
colours: self.colours, colours: self.colours,
style: self.style, style: self.style,
@ -170,7 +170,7 @@ impl<'a> Render<'a> {
None None
} }
fn make_table<'t>(&'a self, options: &'a TableOptions, mut git: Option<&'a GitCache>, drender: &DetailsRender) -> (Table<'a>, Vec<DetailsRow>) { fn make_table(&'a self, options: &'a TableOptions, mut git: Option<&'a GitCache>, drender: &DetailsRender) -> (Table<'a>, Vec<DetailsRow>) {
match (git, self.dir) { match (git, self.dir) {
(Some(g), Some(d)) => if !g.has_anything_for(&d.path) { git = None }, (Some(g), Some(d)) => if !g.has_anything_for(&d.path) { git = None },
(Some(g), None) => if !self.files.iter().any(|f| g.has_anything_for(&f.path)) { git = None }, (Some(g), None) => if !self.files.iter().any(|f| g.has_anything_for(&f.path)) { git = None },
@ -226,7 +226,7 @@ impl<'a> Render<'a> {
else { grid::Direction::TopToBottom }; else { grid::Direction::TopToBottom };
let mut grid = grid::Grid::new(grid::GridOptions { let mut grid = grid::Grid::new(grid::GridOptions {
direction: direction, direction,
filling: grid::Filling::Spaces(4), filling: grid::Filling::Spaces(4),
}); });

View File

@ -41,7 +41,7 @@ impl f::Size {
let width = DisplayWidth::from(number.len() + symbol.len()); let width = DisplayWidth::from(number.len() + symbol.len());
TextCell { TextCell {
width: width, width,
contents: vec![ contents: vec![
colours.size(size).paint(number), colours.size(size).paint(number),
colours.unit().paint(symbol), colours.unit().paint(symbol),

View File

@ -189,8 +189,8 @@ pub enum TimeType {
impl TimeType { impl TimeType {
/// Returns the text to use for a columns heading in the columns output. /// Returns the text to use for a columns heading in the columns output.
pub fn header(&self) -> &'static str { pub fn header(self) -> &'static str {
match *self { match self {
TimeType::Accessed => "Date Accessed", TimeType::Accessed => "Date Accessed",
TimeType::Modified => "Date Modified", TimeType::Modified => "Date Modified",
TimeType::Created => "Date Created", TimeType::Created => "Date Created",
@ -324,7 +324,7 @@ impl<'a, 'f> Table<'a> {
f::PermissionsPlus { f::PermissionsPlus {
file_type: file.type_char(), file_type: file.type_char(),
permissions: file.permissions(), permissions: file.permissions(),
xattrs: xattrs, xattrs,
} }
} }
@ -379,7 +379,7 @@ pub struct TableWidths(Vec<usize>);
impl Deref for TableWidths { impl Deref for TableWidths {
type Target = [usize]; type Target = [usize];
fn deref<'a>(&'a self) -> &'a Self::Target { fn deref(&self) -> &Self::Target {
&self.0 &self.0
} }
} }

View File

@ -88,8 +88,8 @@ pub struct DefaultFormat {
pub date_and_year: DateFormat<'static>, pub date_and_year: DateFormat<'static>,
} }
impl DefaultFormat { impl Default for DefaultFormat {
pub fn new() -> DefaultFormat { fn default() -> DefaultFormat {
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
let locale = locale::Time::load_user_locale() let locale = locale::Time::load_user_locale()
@ -120,7 +120,9 @@ impl DefaultFormat {
DefaultFormat { current_year, locale, date_and_time, date_and_year } DefaultFormat { current_year, locale, date_and_time, date_and_year }
} }
}
impl DefaultFormat {
fn is_recent(&self, date: LocalDateTime) -> bool { fn is_recent(&self, date: LocalDateTime) -> bool {
date.year() == self.current_year date.year() == self.current_year
} }
@ -199,12 +201,14 @@ pub struct ISOFormat {
pub current_year: i64, pub current_year: i64,
} }
impl ISOFormat { impl Default for ISOFormat {
pub fn new() -> Self { fn default() -> ISOFormat {
let current_year = LocalDateTime::now().year(); let current_year = LocalDateTime::now().year();
ISOFormat { current_year } ISOFormat { current_year }
} }
}
impl ISOFormat {
fn is_recent(&self, date: LocalDateTime) -> bool { fn is_recent(&self, date: LocalDateTime) -> bool {
date.year() == self.current_year date.year() == self.current_year
} }

View File

@ -111,7 +111,7 @@ impl Colours {
pub fn colourful(scale: bool) -> Colours { pub fn colourful(scale: bool) -> Colours {
Colours { Colours {
colourful: true, colourful: true,
scale: scale, scale,
filekinds: FileKinds { filekinds: FileKinds {
normal: Style::default(), normal: Style::default(),

View File

@ -8,8 +8,8 @@ pub struct LSColors<'var>(pub &'var str);
impl<'var> LSColors<'var> { impl<'var> LSColors<'var> {
pub fn each_pair<C>(&mut self, mut callback: C) where C: FnMut(Pair<'var>) -> () { pub fn each_pair<C>(&mut self, mut callback: C) where C: FnMut(Pair<'var>) -> () {
for next in self.0.split(":") { for next in self.0.split(':') {
let bits = next.split("=") let bits = next.split('=')
.take(3) .take(3)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -28,25 +28,21 @@ pub struct Pair<'var> {
use std::iter::Peekable; use std::iter::Peekable;
fn parse_into_high_colour<'a, I>(iter: &mut Peekable<I>) -> Option<Colour> fn parse_into_high_colour<'a, I>(iter: &mut Peekable<I>) -> Option<Colour>
where I: Iterator<Item=&'a str> { where I: Iterator<Item=&'a str> {
match iter.peek() { if let Some(&"5") = iter.peek() {
Some(&"5") => { let _ = iter.next();
let _5 = iter.next();
if let Some(byte) = iter.next() { if let Some(byte) = iter.next() {
if let Ok(num) = byte.parse() { if let Ok(num) = byte.parse() {
return Some(Fixed(num)); return Some(Fixed(num));
} }
} }
} }
_ => {},
}
None None
} }
impl<'var> Pair<'var> { impl<'var> Pair<'var> {
pub fn to_style(&self) -> Style { pub fn to_style(&self) -> Style {
let mut style = Style::default(); let mut style = Style::default();
let mut iter = self.value.split(";").peekable(); let mut iter = self.value.split(';').peekable();
while let Some(num) = iter.next() { while let Some(num) = iter.next() {
match num { match num {