The Selfening

This commit uses Clippy to fix all the 'use_self' warnings. Using Self instead of the type name has been good Rust style for a while now, and it's become the style I'm used to seeing.
This commit is contained in:
Benjamin Sago 2020-10-10 13:55:26 +01:00
parent 74d9f1402b
commit 70a30ed683
26 changed files with 251 additions and 251 deletions

View File

@ -35,14 +35,14 @@ impl Dir {
/// The `read_dir` iterator doesnt actually yield the `.` and `..` /// The `read_dir` iterator doesnt actually yield the `.` and `..`
/// entries, so if the user wants to see them, well have to add them /// entries, so if the user wants to see them, well have to add them
/// ourselves after the files have been read. /// ourselves after the files have been read.
pub fn read_dir(path: PathBuf) -> IOResult<Dir> { pub fn read_dir(path: PathBuf) -> IOResult<Self> {
info!("Reading directory {:?}", &path); info!("Reading directory {:?}", &path);
let contents = fs::read_dir(&path)? let contents = fs::read_dir(&path)?
.map(|result| result.map(|entry| entry.path())) .map(|result| result.map(|entry| entry.path()))
.collect::<Result<_,_>>()?; .collect::<Result<_,_>>()?;
Ok(Dir { contents, path }) Ok(Self { contents, path })
} }
/// Produce an iterator of IO results of trying to read all the files in /// Produce an iterator of IO results of trying to read all the files in
@ -180,8 +180,8 @@ pub enum DotFilter {
} }
impl Default for DotFilter { impl Default for DotFilter {
fn default() -> DotFilter { fn default() -> Self {
DotFilter::JustFiles Self::JustFiles
} }
} }
@ -190,18 +190,18 @@ 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, Self::JustFiles => false,
DotFilter::Dotfiles => true, Self::Dotfiles => true,
DotFilter::DotfilesAndDots => true, Self::DotfilesAndDots => true,
} }
} }
/// Whether this filter should add dot directories to a listing. /// Whether this filter should add dot directories to a listing.
fn dots(self) -> DotsNext { fn dots(self) -> DotsNext {
match self { match self {
DotFilter::JustFiles => DotsNext::Files, Self::JustFiles => DotsNext::Files,
DotFilter::Dotfiles => DotsNext::Files, Self::Dotfiles => DotsNext::Files,
DotFilter::DotfilesAndDots => DotsNext::Dot, Self::DotfilesAndDots => DotsNext::Dot,
} }
} }
} }

View File

@ -41,7 +41,7 @@ impl DirAction {
/// Gets the recurse options, if this dir action has any. /// Gets the recurse options, if this dir action has any.
pub fn recurse_options(&self) -> Option<RecurseOptions> { pub fn recurse_options(&self) -> Option<RecurseOptions> {
match *self { match *self {
DirAction::Recurse(o) => Some(o), Self::Recurse(o) => Some(o),
_ => None, _ => None,
} }
} }
@ -49,8 +49,8 @@ impl DirAction {
/// Whether to treat directories as regular files or not. /// Whether to treat directories as regular files or not.
pub fn treat_dirs_as_files(&self) -> bool { pub fn treat_dirs_as_files(&self) -> bool {
match *self { match *self {
DirAction::AsFile => true, Self::AsFile => true,
DirAction::Recurse(o) => o.tree, Self::Recurse(o) => o.tree,
_ => false, _ => false,
} }
} }

View File

@ -38,7 +38,7 @@ use std::iter::FromIterator;
impl FromIterator<PathBuf> for GitCache { impl FromIterator<PathBuf> for GitCache {
fn from_iter<I: IntoIterator<Item=PathBuf>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item=PathBuf>>(iter: I) -> Self {
let iter = iter.into_iter(); let iter = iter.into_iter();
let mut git = GitCache { let mut git = Self {
repos: Vec::with_capacity(iter.size_hint().0), repos: Vec::with_capacity(iter.size_hint().0),
misses: Vec::new(), misses: Vec::new(),
}; };
@ -152,7 +152,7 @@ impl GitRepo {
/// Searches for a Git repository at any point above the given path. /// Searches for a Git repository at any point above the given path.
/// Returns the original buffer if none is found. /// Returns the original buffer if none is found.
fn discover(path: PathBuf) -> Result<GitRepo, PathBuf> { fn discover(path: PathBuf) -> Result<Self, PathBuf> {
info!("Searching for Git repository above {:?}", path); info!("Searching for Git repository above {:?}", path);
let repo = match git2::Repository::discover(&path) { let repo = match git2::Repository::discover(&path) {
Ok(r) => r, Ok(r) => r,
@ -165,7 +165,7 @@ impl GitRepo {
match repo.workdir().map(|wd| wd.to_path_buf()) { match repo.workdir().map(|wd| wd.to_path_buf()) {
Some(workdir) => { Some(workdir) => {
let contents = Mutex::new(GitContents::Before { repo }); let contents = Mutex::new(GitContents::Before { repo });
Ok(GitRepo { contents, workdir, original_path: path, extra_paths: Vec::new() }) Ok(Self { contents, workdir, original_path: path, extra_paths: Vec::new() })
}, },
None => { None => {
warn!("Repository has no workdir?"); warn!("Repository has no workdir?");
@ -181,7 +181,7 @@ impl GitContents {
/// (consuming the value) if it has. This is needed because the entire /// (consuming the value) if it has. This is needed because the entire
/// enum variant gets replaced when a repo is queried (see above). /// enum variant gets replaced when a repo is queried (see above).
fn inner_repo(self) -> git2::Repository { fn inner_repo(self) -> git2::Repository {
if let GitContents::Before { repo } = self { if let Self::Before { repo } = self {
repo repo
} }
else { else {

View File

@ -126,13 +126,13 @@ mod lister {
} }
impl Lister { impl Lister {
pub fn new(do_follow: FollowSymlinks) -> Lister { pub fn new(do_follow: FollowSymlinks) -> Self {
let c_flags: c_int = match do_follow { let c_flags: c_int = match do_follow {
FollowSymlinks::Yes => 0x0001, FollowSymlinks::Yes => 0x0001,
FollowSymlinks::No => 0x0000, FollowSymlinks::No => 0x0000,
}; };
Lister { c_flags } Self { c_flags }
} }
pub fn translate_attribute_name(&self, input: &[u8]) -> String { pub fn translate_attribute_name(&self, input: &[u8]) -> String {

View File

@ -50,7 +50,7 @@ pub enum Type {
impl Type { impl Type {
pub fn is_regular_file(&self) -> bool { pub fn is_regular_file(&self) -> bool {
matches!(*self, Type::File) matches!(*self, Self::File)
} }
} }
@ -220,7 +220,7 @@ use std::default::Default;
impl Default for Git { impl Default for Git {
/// Create a Git status for a file with nothing done to it. /// Create a Git status for a file with nothing done to it.
fn default() -> Git { fn default() -> Self {
Git { staged: GitStatus::NotModified, unstaged: GitStatus::NotModified } Self { staged: GitStatus::NotModified, unstaged: GitStatus::NotModified }
} }
} }

View File

@ -240,41 +240,41 @@ impl SortField {
use self::SortCase::{ABCabc, AaBbCc}; use self::SortCase::{ABCabc, AaBbCc};
match self { match self {
SortField::Unsorted => Ordering::Equal, Self::Unsorted => Ordering::Equal,
SortField::Name(ABCabc) => natord::compare(&a.name, &b.name), Self::Name(ABCabc) => natord::compare(&a.name, &b.name),
SortField::Name(AaBbCc) => natord::compare_ignore_case(&a.name, &b.name), Self::Name(AaBbCc) => natord::compare_ignore_case(&a.name, &b.name),
SortField::Size => a.metadata.len().cmp(&b.metadata.len()), Self::Size => a.metadata.len().cmp(&b.metadata.len()),
SortField::FileInode => a.metadata.ino().cmp(&b.metadata.ino()), Self::FileInode => a.metadata.ino().cmp(&b.metadata.ino()),
SortField::ModifiedDate => a.modified_time().cmp(&b.modified_time()), Self::ModifiedDate => a.modified_time().cmp(&b.modified_time()),
SortField::AccessedDate => a.accessed_time().cmp(&b.accessed_time()), Self::AccessedDate => a.accessed_time().cmp(&b.accessed_time()),
SortField::ChangedDate => a.changed_time().cmp(&b.changed_time()), Self::ChangedDate => a.changed_time().cmp(&b.changed_time()),
SortField::CreatedDate => a.created_time().cmp(&b.created_time()), Self::CreatedDate => a.created_time().cmp(&b.created_time()),
SortField::ModifiedAge => b.modified_time().cmp(&a.modified_time()), // flip b and a Self::ModifiedAge => b.modified_time().cmp(&a.modified_time()), // flip b and a
SortField::FileType => match a.type_char().cmp(&b.type_char()) { // todo: this recomputes Self::FileType => match a.type_char().cmp(&b.type_char()) { // todo: this recomputes
Ordering::Equal => natord::compare(&*a.name, &*b.name), Ordering::Equal => natord::compare(&*a.name, &*b.name),
order => order, order => order,
}, },
SortField::Extension(ABCabc) => match a.ext.cmp(&b.ext) { Self::Extension(ABCabc) => match a.ext.cmp(&b.ext) {
Ordering::Equal => natord::compare(&*a.name, &*b.name), Ordering::Equal => natord::compare(&*a.name, &*b.name),
order => order, order => order,
}, },
SortField::Extension(AaBbCc) => match a.ext.cmp(&b.ext) { Self::Extension(AaBbCc) => match a.ext.cmp(&b.ext) {
Ordering::Equal => natord::compare_ignore_case(&*a.name, &*b.name), Ordering::Equal => natord::compare_ignore_case(&*a.name, &*b.name),
order => order, order => order,
}, },
SortField::NameMixHidden(ABCabc) => natord::compare( Self::NameMixHidden(ABCabc) => natord::compare(
SortField::strip_dot(&a.name), Self::strip_dot(&a.name),
SortField::strip_dot(&b.name) Self::strip_dot(&b.name)
), ),
SortField::NameMixHidden(AaBbCc) => natord::compare_ignore_case( Self::NameMixHidden(AaBbCc) => natord::compare_ignore_case(
SortField::strip_dot(&a.name), Self::strip_dot(&a.name),
SortField::strip_dot(&b.name) Self::strip_dot(&b.name)
) )
} }
} }
@ -299,7 +299,7 @@ pub struct IgnorePatterns {
impl FromIterator<glob::Pattern> for IgnorePatterns { impl FromIterator<glob::Pattern> for IgnorePatterns {
fn from_iter<I: IntoIterator<Item = glob::Pattern>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = glob::Pattern>>(iter: I) -> Self {
IgnorePatterns { patterns: iter.into_iter().collect() } Self { patterns: iter.into_iter().collect() }
} }
} }
@ -328,12 +328,12 @@ impl IgnorePatterns {
} }
} }
(IgnorePatterns { patterns }, errors) (Self { patterns }, errors)
} }
/// Create a new empty set of patterns that matches nothing. /// Create a new empty set of patterns that matches nothing.
pub fn empty() -> IgnorePatterns { pub fn empty() -> Self {
IgnorePatterns { patterns: Vec::new() } Self { patterns: Vec::new() }
} }
/// Test whether the given file should be hidden from the results. /// Test whether the given file should be hidden from the results.

View File

@ -12,7 +12,7 @@ impl DirAction {
/// There are three possible actions, and they overlap somewhat: the /// There are three possible actions, and they overlap somewhat: the
/// `--tree` flag is another form of recursion, so those two are allowed /// `--tree` flag is another form of recursion, so those two are allowed
/// to both be present, but the `--list-dirs` flag is used separately. /// to both be present, but the `--list-dirs` flag is used separately.
pub fn deduce(matches: &MatchedFlags) -> Result<DirAction, Misfire> { pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let recurse = matches.has(&flags::RECURSE)?; let recurse = matches.has(&flags::RECURSE)?;
let as_file = matches.has(&flags::LIST_DIRS)?; let as_file = matches.has(&flags::LIST_DIRS)?;
let tree = matches.has(&flags::TREE)?; let tree = matches.has(&flags::TREE)?;
@ -31,16 +31,16 @@ impl DirAction {
} }
if tree { if tree {
Ok(DirAction::Recurse(RecurseOptions::deduce(matches, true)?)) Ok(Self::Recurse(RecurseOptions::deduce(matches, true)?))
} }
else if recurse { else if recurse {
Ok(DirAction::Recurse(RecurseOptions::deduce(matches, false)?)) Ok(Self::Recurse(RecurseOptions::deduce(matches, false)?))
} }
else if as_file { else if as_file {
Ok(DirAction::AsFile) Ok(Self::AsFile)
} }
else { else {
Ok(DirAction::List) Ok(Self::List)
} }
} }
} }
@ -52,7 +52,7 @@ impl RecurseOptions {
/// flags value, and whether the `--tree` flag was passed, which was /// flags value, and whether the `--tree` flag was passed, which was
/// determined earlier. The maximum level should be a number, and this /// determined earlier. The maximum level should be a number, and this
/// will fail with an `Err` if it isnt. /// will fail with an `Err` if it isnt.
pub fn deduce(matches: &MatchedFlags, tree: bool) -> Result<RecurseOptions, Misfire> { pub fn deduce(matches: &MatchedFlags, tree: bool) -> Result<Self, Misfire> {
let max_depth = if let Some(level) = matches.get(&flags::LEVEL)? { let max_depth = if let Some(level) = matches.get(&flags::LEVEL)? {
match level.to_string_lossy().parse() { match level.to_string_lossy().parse() {
Ok(l) => Some(l), Ok(l) => Some(l),
@ -63,7 +63,7 @@ impl RecurseOptions {
None None
}; };
Ok(RecurseOptions { tree, max_depth }) Ok(Self { tree, max_depth })
} }
} }

View File

@ -10,8 +10,8 @@ use crate::options::parser::MatchedFlags;
impl FileFilter { impl FileFilter {
/// Determines which of all the file filter options to use. /// Determines which of all the file filter options to use.
pub fn deduce(matches: &MatchedFlags) -> Result<FileFilter, Misfire> { pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
Ok(FileFilter { Ok(Self {
list_dirs_first: matches.has(&flags::DIRS_FIRST)?, list_dirs_first: matches.has(&flags::DIRS_FIRST)?,
reverse: matches.has(&flags::REVERSE)?, reverse: matches.has(&flags::REVERSE)?,
only_dirs: matches.has(&flags::ONLY_DIRS)?, only_dirs: matches.has(&flags::ONLY_DIRS)?,
@ -29,10 +29,10 @@ impl SortField {
/// This arguments value can be one of several flags, listed above. /// This arguments value can be one of several flags, listed above.
/// Returns the default sort field if none is given, or `Err` if the /// Returns the default sort field if none is given, or `Err` if the
/// value doesnt correspond to a sort field we know about. /// value doesnt correspond to a sort field we know about.
fn deduce(matches: &MatchedFlags) -> Result<SortField, Misfire> { fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let word = match matches.get(&flags::SORT)? { let word = match matches.get(&flags::SORT)? {
Some(w) => w, Some(w) => w,
None => return Ok(SortField::default()), None => return Ok(Self::default()),
}; };
// Get String because we cant match an OsStr // Get String because we cant match an OsStr
@ -42,28 +42,28 @@ impl SortField {
}; };
let field = match word { let field = match word {
"name" | "filename" => SortField::Name(SortCase::AaBbCc), "name" | "filename" => Self::Name(SortCase::AaBbCc),
"Name" | "Filename" => SortField::Name(SortCase::ABCabc), "Name" | "Filename" => Self::Name(SortCase::ABCabc),
".name" | ".filename" => SortField::NameMixHidden(SortCase::AaBbCc), ".name" | ".filename" => Self::NameMixHidden(SortCase::AaBbCc),
".Name" | ".Filename" => SortField::NameMixHidden(SortCase::ABCabc), ".Name" | ".Filename" => Self::NameMixHidden(SortCase::ABCabc),
"size" | "filesize" => SortField::Size, "size" | "filesize" => Self::Size,
"ext" | "extension" => SortField::Extension(SortCase::AaBbCc), "ext" | "extension" => Self::Extension(SortCase::AaBbCc),
"Ext" | "Extension" => SortField::Extension(SortCase::ABCabc), "Ext" | "Extension" => Self::Extension(SortCase::ABCabc),
// “new” sorts oldest at the top and newest at the bottom; “old” // “new” sorts oldest at the top and newest at the bottom; “old”
// sorts newest at the top and oldest at the bottom. I think this // sorts newest at the top and oldest at the bottom. I think this
// is the right way round to do this: “size” puts the smallest at // is the right way round to do this: “size” puts the smallest at
// the top and the largest at the bottom, doesnt it? // the top and the largest at the bottom, doesnt it?
"date" | "time" | "mod" | "modified" | "new" | "newest" => SortField::ModifiedDate, "date" | "time" | "mod" | "modified" | "new" | "newest" => Self::ModifiedDate,
// Similarly, “age” means that files with the least age (the // Similarly, “age” means that files with the least age (the
// newest files) get sorted at the top, and files with the most // newest files) get sorted at the top, and files with the most
// age (the oldest) at the bottom. // age (the oldest) at the bottom.
"age" | "old" | "oldest" => SortField::ModifiedAge, "age" | "old" | "oldest" => Self::ModifiedAge,
"ch" | "changed" => SortField::ChangedDate, "ch" | "changed" => Self::ChangedDate,
"acc" | "accessed" => SortField::AccessedDate, "acc" | "accessed" => Self::AccessedDate,
"cr" | "created" => SortField::CreatedDate, "cr" | "created" => Self::CreatedDate,
"inode" => SortField::FileInode, "inode" => Self::FileInode,
"type" => SortField::FileType, "type" => Self::FileType,
"none" => SortField::Unsorted, "none" => Self::Unsorted,
_ => return Err(Misfire::BadArgument(&flags::SORT, word.into())) _ => return Err(Misfire::BadArgument(&flags::SORT, word.into()))
}; };
@ -105,8 +105,8 @@ impl SortField {
// You can get the old behaviour back by sorting with `--sort=Name`. // You can get the old behaviour back by sorting with `--sort=Name`.
impl Default for SortField { impl Default for SortField {
fn default() -> SortField { fn default() -> Self {
SortField::Name(SortCase::AaBbCc) Self::Name(SortCase::AaBbCc)
} }
} }
@ -119,14 +119,14 @@ impl DotFilter {
/// It also checks for the `--tree` option in strict mode, because of a /// It also checks for the `--tree` option in strict mode, because of a
/// special case where `--tree --all --all` wont work: listing the /// special case where `--tree --all --all` wont work: listing the
/// parent directory in tree mode would loop onto itself! /// parent directory in tree mode would loop onto itself!
pub fn deduce(matches: &MatchedFlags) -> Result<DotFilter, Misfire> { pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let count = matches.count(&flags::ALL); let count = matches.count(&flags::ALL);
if count == 0 { if count == 0 {
Ok(DotFilter::JustFiles) Ok(Self::JustFiles)
} }
else if count == 1 { else if count == 1 {
Ok(DotFilter::Dotfiles) Ok(Self::Dotfiles)
} }
else if matches.count(&flags::TREE) > 0 { else if matches.count(&flags::TREE) > 0 {
Err(Misfire::TreeAllAll) Err(Misfire::TreeAllAll)
@ -135,7 +135,7 @@ impl DotFilter {
Err(Misfire::Conflict(&flags::ALL, &flags::ALL)) Err(Misfire::Conflict(&flags::ALL, &flags::ALL))
} }
else { else {
Ok(DotFilter::DotfilesAndDots) Ok(Self::DotfilesAndDots)
} }
} }
} }
@ -146,18 +146,18 @@ impl IgnorePatterns {
/// Determines the set of glob patterns to use based on the /// Determines the set of glob patterns to use based on the
/// `--ignore-glob` arguments value. This is a list of strings /// `--ignore-glob` arguments value. This is a list of strings
/// separated by pipe (`|`) characters, given in any order. /// separated by pipe (`|`) characters, given in any order.
pub fn deduce(matches: &MatchedFlags) -> Result<IgnorePatterns, Misfire> { pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
// If there are no inputs, we return a set of patterns that doesnt // If there are no inputs, we return a set of patterns that doesnt
// match anything, rather than, say, `None`. // match anything, rather than, say, `None`.
let inputs = match matches.get(&flags::IGNORE_GLOB)? { let inputs = match matches.get(&flags::IGNORE_GLOB)? {
None => return Ok(IgnorePatterns::empty()), None => return Ok(Self::empty()),
Some(is) => is, Some(is) => is,
}; };
// Awkwardly, though, a glob pattern can be invalid, and we need to // Awkwardly, though, a glob pattern can be invalid, and we need to
// deal with invalid patterns somehow. // deal with invalid patterns somehow.
let (patterns, mut errors) = IgnorePatterns::parse_from_iter(inputs.to_string_lossy().split('|')); let (patterns, mut errors) = Self::parse_from_iter(inputs.to_string_lossy().split('|'));
// It can actually return more than one glob error, // It can actually return more than one glob error,
// but we only use one. (TODO) // but we only use one. (TODO)
@ -171,8 +171,8 @@ impl IgnorePatterns {
impl GitIgnore { impl GitIgnore {
pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> { pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
Ok(if matches.has(&flags::GIT_IGNORE)? { GitIgnore::CheckAndIgnore } Ok(if matches.has(&flags::GIT_IGNORE)? { Self::CheckAndIgnore }
else { GitIgnore::Off }) else { Self::Off })
} }
} }

View File

@ -86,12 +86,12 @@ impl HelpString {
/// We dont do any strict-mode error checking here: its OK to give /// We dont do any strict-mode error checking here: its OK to give
/// the --help or --long flags more than once. Actually checking for /// the --help or --long flags more than once. Actually checking for
/// errors when the user wants help is kind of petty! /// errors when the user wants help is kind of petty!
pub fn deduce(matches: &MatchedFlags) -> Result<(), HelpString> { pub fn deduce(matches: &MatchedFlags) -> Result<(), Self> {
if matches.count(&flags::HELP) > 0 { if matches.count(&flags::HELP) > 0 {
let only_long = matches.count(&flags::LONG) > 0; let only_long = matches.count(&flags::LONG) > 0;
let git = cfg!(feature="git"); let git = cfg!(feature="git");
let xattrs = xattr::ENABLED; let xattrs = xattr::ENABLED;
Err(HelpString { only_long, git, xattrs }) Err(Self { only_long, git, xattrs })
} }
else { else {
Ok(()) // no help needs to be shown Ok(()) // no help needs to be shown

View File

@ -56,16 +56,16 @@ impl Misfire {
/// The OS return code this misfire should signify. /// The OS return code this misfire should signify.
pub fn is_error(&self) -> bool { pub fn is_error(&self) -> bool {
match *self { match *self {
Misfire::Help(_) => false, Self::Help(_) => false,
Misfire::Version(_) => false, Self::Version(_) => false,
_ => true, _ => true,
} }
} }
} }
impl From<glob::PatternError> for Misfire { impl From<glob::PatternError> for Misfire {
fn from(error: glob::PatternError) -> Misfire { fn from(error: glob::PatternError) -> Self {
Misfire::FailedGlobPattern(error.to_string()) Self::FailedGlobPattern(error.to_string())
} }
} }
@ -120,9 +120,9 @@ impl Misfire {
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
match *self { match *self {
Misfire::BadArgument(ref time, ref r) if *time == &flags::TIME && r == "r" => Self::BadArgument(ref time, ref r) if *time == &flags::TIME && r == "r" =>
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') => Self::InvalidOptions(ParseError::NeedsValue { ref flag, .. }) if *flag == Flag::Short(b't') =>
Some("To sort newest files last, try \"--sort newest\", or just \"-snew\""), Some("To sort newest files last, try \"--sort newest\", or just \"-snew\""),
_ => None _ => None
} }

View File

@ -119,7 +119,7 @@ impl Options {
/// struct and a list of free filenames, using the environment variables /// struct and a list of free filenames, using the environment variables
/// for extra options. /// for extra options.
#[allow(unused_results)] #[allow(unused_results)]
pub fn parse<'args, I, V>(args: I, vars: &V) -> Result<(Options, Vec<&'args OsStr>), Misfire> pub fn parse<'args, I, V>(args: I, vars: &V) -> Result<(Self, Vec<&'args OsStr>), Misfire>
where I: IntoIterator<Item=&'args OsString>, where I: IntoIterator<Item=&'args OsString>,
V: Vars { V: Vars {
use crate::options::parser::{Matches, Strictness}; use crate::options::parser::{Matches, Strictness};
@ -138,7 +138,7 @@ impl Options {
HelpString::deduce(&flags).map_err(Misfire::Help)?; HelpString::deduce(&flags).map_err(Misfire::Help)?;
VersionString::deduce(&flags).map_err(Misfire::Version)?; VersionString::deduce(&flags).map_err(Misfire::Version)?;
let options = Options::deduce(&flags, vars)?; let options = Self::deduce(&flags, vars)?;
Ok((options, frees)) Ok((options, frees))
} }
@ -159,12 +159,12 @@ impl Options {
/// Determines the complete set of options based on the given command-line /// Determines the complete set of options based on the given command-line
/// arguments, after theyve been parsed. /// arguments, after theyve been parsed.
fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<Options, Misfire> { fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<Self, Misfire> {
let dir_action = DirAction::deduce(matches)?; let dir_action = DirAction::deduce(matches)?;
let filter = FileFilter::deduce(matches)?; let filter = FileFilter::deduce(matches)?;
let view = View::deduce(matches, vars)?; let view = View::deduce(matches, vars)?;
Ok(Options { dir_action, view, filter }) Ok(Self { dir_action, view, filter })
} }
} }

View File

@ -61,8 +61,8 @@ pub enum Flag {
impl Flag { impl Flag {
pub fn matches(&self, arg: &Arg) -> bool { pub fn matches(&self, arg: &Arg) -> bool {
match *self { match *self {
Flag::Short(short) => arg.short == Some(short), Self::Short(short) => arg.short == Some(short),
Flag::Long(long) => arg.long == long, Self::Long(long) => arg.long == long,
} }
} }
} }
@ -70,8 +70,8 @@ impl Flag {
impl fmt::Display for Flag { impl fmt::Display for Flag {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self { match *self {
Flag::Short(short) => write!(f, "-{}", short as char), Self::Short(short) => write!(f, "-{}", short as char),
Flag::Long(long) => write!(f, "--{}", long), Self::Long(long) => write!(f, "--{}", long),
} }
} }
} }

View File

@ -28,8 +28,8 @@ enum TerminalColours {
} }
impl Default for TerminalColours { impl Default for TerminalColours {
fn default() -> TerminalColours { fn default() -> Self {
TerminalColours::Automatic Self::Automatic
} }
} }
@ -37,21 +37,21 @@ impl Default for TerminalColours {
impl TerminalColours { impl TerminalColours {
/// Determine which terminal colour conditions to use. /// Determine which terminal colour conditions to use.
fn deduce(matches: &MatchedFlags) -> Result<TerminalColours, Misfire> { fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let word = match matches.get_where(|f| f.matches(&flags::COLOR) || f.matches(&flags::COLOUR))? { let word = match matches.get_where(|f| f.matches(&flags::COLOR) || f.matches(&flags::COLOUR))? {
Some(w) => w, Some(w) => w,
None => return Ok(TerminalColours::default()), None => return Ok(Self::default()),
}; };
if word == "always" { if word == "always" {
Ok(TerminalColours::Always) Ok(Self::Always)
} }
else if word == "auto" || word == "automatic" { else if word == "auto" || word == "automatic" {
Ok(TerminalColours::Automatic) Ok(Self::Automatic)
} }
else if word == "never" { else if word == "never" {
Ok(TerminalColours::Never) Ok(Self::Never)
} }
else { else {
Err(Misfire::BadArgument(&flags::COLOR, word.into())) Err(Misfire::BadArgument(&flags::COLOR, word.into()))
@ -90,7 +90,7 @@ impl Styles {
// custom colours at all // custom colours at all
let tc = TerminalColours::deduce(matches)?; let tc = TerminalColours::deduce(matches)?;
if tc == Never || (tc == Automatic && widther().is_none()) { if tc == Never || (tc == Automatic && widther().is_none()) {
return Ok(Styles { return Ok(Self {
colours: Colours::plain(), colours: Colours::plain(),
style: FileStyle { classify, exts: Box::new(NoFileColours) }, style: FileStyle { classify, exts: Box::new(NoFileColours) },
}); });
@ -111,7 +111,7 @@ impl Styles {
}; };
let style = FileStyle { classify, exts }; let style = FileStyle { classify, exts };
Ok(Styles { colours, style }) Ok(Self { colours, style })
} }
} }
@ -197,11 +197,11 @@ impl ExtensionMappings {
impl Classify { impl Classify {
fn deduce(matches: &MatchedFlags) -> Result<Classify, Misfire> { fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let flagged = matches.has(&flags::CLASSIFY)?; let flagged = matches.has(&flags::CLASSIFY)?;
Ok(if flagged { Classify::AddFileIndicators } Ok(if flagged { Self::AddFileIndicators }
else { Classify::JustFilenames }) else { Self::JustFilenames })
} }
} }

View File

@ -19,9 +19,9 @@ impl VersionString {
/// deduce functions, returning Err if help needs to be shown. /// deduce functions, returning Err if help needs to be shown.
/// ///
/// Like --help, this doesnt bother checking for errors. /// Like --help, this doesnt bother checking for errors.
pub fn deduce(matches: &MatchedFlags) -> Result<(), VersionString> { pub fn deduce(matches: &MatchedFlags) -> Result<(), Self> {
if matches.count(&flags::VERSION) > 0 { if matches.count(&flags::VERSION) > 0 {
Err(VersionString) Err(Self)
} }
else { else {
Ok(()) // no version needs to be shown Ok(()) // no version needs to be shown

View File

@ -13,12 +13,12 @@ use crate::fs::feature::xattr;
impl View { impl View {
/// Determine which view to use and all of that views arguments. /// Determine which view to use and all of that views arguments.
pub fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<View, Misfire> { pub fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<Self, Misfire> {
use crate::options::style::Styles; use crate::options::style::Styles;
let mode = Mode::deduce(matches, vars)?; let mode = Mode::deduce(matches, vars)?;
let Styles { colours, style } = Styles::deduce(matches, vars, || *TERM_WIDTH)?; let Styles { colours, style } = Styles::deduce(matches, vars, || *TERM_WIDTH)?;
Ok(View { mode, colours, style }) Ok(Self { mode, colours, style })
} }
} }
@ -26,7 +26,7 @@ impl View {
impl Mode { impl Mode {
/// Determine the mode from the command-line arguments. /// Determine the mode from the command-line arguments.
pub fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<Mode, Misfire> { pub fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<Self, Misfire> {
use crate::options::misfire::Misfire::*; use crate::options::misfire::Misfire::*;
let long = || { let long = || {
@ -54,7 +54,7 @@ impl Mode {
} }
else { else {
let lines = lines::Options { icons: matches.has(&flags::ICONS)? }; let lines = lines::Options { icons: matches.has(&flags::ICONS)? };
Ok(Mode::Lines(lines)) Ok(Self::Lines(lines))
} }
} }
else if matches.has(&flags::TREE)? { else if matches.has(&flags::TREE)? {
@ -65,7 +65,7 @@ impl Mode {
icons: matches.has(&flags::ICONS)?, icons: matches.has(&flags::ICONS)?,
}; };
Ok(Mode::Details(details)) Ok(Self::Details(details))
} }
else { else {
let grid = grid::Options { let grid = grid::Options {
@ -74,7 +74,7 @@ impl Mode {
icons: matches.has(&flags::ICONS)?, icons: matches.has(&flags::ICONS)?,
}; };
Ok(Mode::Grid(grid)) Ok(Self::Grid(grid))
} }
} }
@ -89,14 +89,14 @@ impl Mode {
icons: matches.has(&flags::ICONS)?, icons: matches.has(&flags::ICONS)?,
}; };
Ok(Mode::Details(details)) Ok(Self::Details(details))
} }
else if matches.has(&flags::LONG)? { else if matches.has(&flags::LONG)? {
let details = long()?; let details = long()?;
Ok(Mode::Details(details)) Ok(Self::Details(details))
} else { } else {
let lines = lines::Options { icons: matches.has(&flags::ICONS)?, }; let lines = lines::Options { icons: matches.has(&flags::ICONS)?, };
Ok(Mode::Lines(lines)) Ok(Self::Lines(lines))
} }
}; };
@ -104,16 +104,16 @@ impl Mode {
let details = long()?; let details = long()?;
if matches.has(&flags::GRID)? { if matches.has(&flags::GRID)? {
let other_options_mode = other_options_scan()?; let other_options_mode = other_options_scan()?;
if let Mode::Grid(grid) = other_options_mode { if let Self::Grid(grid) = other_options_mode {
let row_threshold = RowThreshold::deduce(vars)?; let row_threshold = RowThreshold::deduce(vars)?;
return Ok(Mode::GridDetails(grid_details::Options { grid, details, row_threshold })); return Ok(Self::GridDetails(grid_details::Options { grid, details, row_threshold }));
} }
else { else {
return Ok(other_options_mode); return Ok(other_options_mode);
} }
} }
else { else {
return Ok(Mode::Details(details)); return Ok(Self::Details(details));
} }
} }
@ -161,28 +161,28 @@ impl TerminalWidth {
/// Determine a requested terminal width from the command-line arguments. /// Determine a requested terminal width from the command-line arguments.
/// ///
/// Returns an error if a requested width doesnt parse to an integer. /// Returns an error if a requested width doesnt parse to an integer.
fn deduce<V: Vars>(vars: &V) -> Result<TerminalWidth, Misfire> { fn deduce<V: Vars>(vars: &V) -> Result<Self, Misfire> {
use crate::options::vars; use crate::options::vars;
if let Some(columns) = vars.get(vars::COLUMNS).and_then(|s| s.into_string().ok()) { if let Some(columns) = vars.get(vars::COLUMNS).and_then(|s| s.into_string().ok()) {
match columns.parse() { match columns.parse() {
Ok(width) => Ok(TerminalWidth::Set(width)), Ok(width) => Ok(Self::Set(width)),
Err(e) => Err(Misfire::FailedParse(e)), Err(e) => Err(Misfire::FailedParse(e)),
} }
} }
else if let Some(width) = *TERM_WIDTH { else if let Some(width) = *TERM_WIDTH {
Ok(TerminalWidth::Terminal(width)) Ok(Self::Terminal(width))
} }
else { else {
Ok(TerminalWidth::Unset) Ok(Self::Unset)
} }
} }
fn width(&self) -> Option<usize> { fn width(&self) -> Option<usize> {
match *self { match *self {
TerminalWidth::Set(width) | Self::Set(width) |
TerminalWidth::Terminal(width) => Some(width), Self::Terminal(width) => Some(width),
TerminalWidth::Unset => None, Self::Unset => None,
} }
} }
} }
@ -192,17 +192,17 @@ impl RowThreshold {
/// Determine whether to use a row threshold based on the given /// Determine whether to use a row threshold based on the given
/// environment variables. /// environment variables.
fn deduce<V: Vars>(vars: &V) -> Result<RowThreshold, Misfire> { fn deduce<V: Vars>(vars: &V) -> Result<Self, Misfire> {
use crate::options::vars; use crate::options::vars;
if let Some(columns) = vars.get(vars::EXA_GRID_ROWS).and_then(|s| s.into_string().ok()) { if let Some(columns) = vars.get(vars::EXA_GRID_ROWS).and_then(|s| s.into_string().ok()) {
match columns.parse() { match columns.parse() {
Ok(rows) => Ok(RowThreshold::MinimumRows(rows)), Ok(rows) => Ok(Self::MinimumRows(rows)),
Err(e) => Err(Misfire::FailedParse(e)), Err(e) => Err(Misfire::FailedParse(e)),
} }
} }
else { else {
Ok(RowThreshold::AlwaysGrid) Ok(Self::AlwaysGrid)
} }
} }
} }
@ -214,7 +214,7 @@ impl TableOptions {
let time_format = TimeFormat::deduce(matches, vars)?; let time_format = TimeFormat::deduce(matches, vars)?;
let size_format = SizeFormat::deduce(matches)?; let size_format = SizeFormat::deduce(matches)?;
let columns = Columns::deduce(matches)?; let columns = Columns::deduce(matches)?;
Ok(TableOptions { env, time_format, size_format, columns }) Ok(Self { env, time_format, size_format, columns })
} }
} }
@ -234,7 +234,7 @@ impl Columns {
let filesize = !matches.has(&flags::NO_FILESIZE)?; let filesize = !matches.has(&flags::NO_FILESIZE)?;
let user = !matches.has(&flags::NO_USER)?; let user = !matches.has(&flags::NO_USER)?;
Ok(Columns { time_types, git, octal, blocks, group, inode, links, permissions, filesize, user }) Ok(Self { time_types, git, octal, blocks, group, inode, links, permissions, filesize, user })
} }
} }
@ -249,13 +249,13 @@ impl SizeFormat {
/// strings of digits in your head. Changing the format to anything else /// strings of digits in your head. Changing the format to anything else
/// involves the `--binary` or `--bytes` flags, and these conflict with /// involves the `--binary` or `--bytes` flags, and these conflict with
/// each other. /// each other.
fn deduce(matches: &MatchedFlags) -> Result<SizeFormat, Misfire> { fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let flag = matches.has_where(|f| f.matches(&flags::BINARY) || f.matches(&flags::BYTES))?; let flag = matches.has_where(|f| f.matches(&flags::BINARY) || f.matches(&flags::BYTES))?;
Ok(match flag { Ok(match flag {
Some(f) if f.matches(&flags::BINARY) => SizeFormat::BinaryBytes, Some(f) if f.matches(&flags::BINARY) => Self::BinaryBytes,
Some(f) if f.matches(&flags::BYTES) => SizeFormat::JustBytes, Some(f) if f.matches(&flags::BYTES) => Self::JustBytes,
_ => SizeFormat::DecimalBytes, _ => Self::DecimalBytes,
}) })
} }
} }
@ -264,7 +264,7 @@ impl SizeFormat {
impl TimeFormat { impl TimeFormat {
/// Determine how time should be formatted in timestamp columns. /// Determine how time should be formatted in timestamp columns.
fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<TimeFormat, Misfire> { fn deduce<V: Vars>(matches: &MatchedFlags, vars: &V) -> Result<Self, Misfire> {
pub use crate::output::time::{DefaultFormat, ISOFormat}; pub use crate::output::time::{DefaultFormat, ISOFormat};
let word = match matches.get(&flags::TIME_STYLE)? { let word = match matches.get(&flags::TIME_STYLE)? {
@ -273,22 +273,22 @@ impl TimeFormat {
use crate::options::vars; use crate::options::vars;
match vars.get(vars::TIME_STYLE) { match vars.get(vars::TIME_STYLE) {
Some(ref t) if !t.is_empty() => t.clone(), Some(ref t) if !t.is_empty() => t.clone(),
_ => return Ok(TimeFormat::DefaultFormat(DefaultFormat::load())) _ => return Ok(Self::DefaultFormat(DefaultFormat::load()))
} }
}, },
}; };
if &word == "default" { if &word == "default" {
Ok(TimeFormat::DefaultFormat(DefaultFormat::load())) Ok(Self::DefaultFormat(DefaultFormat::load()))
} }
else if &word == "iso" { else if &word == "iso" {
Ok(TimeFormat::ISOFormat(ISOFormat::load())) Ok(Self::ISOFormat(ISOFormat::load()))
} }
else if &word == "long-iso" { else if &word == "long-iso" {
Ok(TimeFormat::LongISO) Ok(Self::LongISO)
} }
else if &word == "full-iso" { else if &word == "full-iso" {
Ok(TimeFormat::FullISO) Ok(Self::FullISO)
} }
else { else {
Err(Misfire::BadArgument(&flags::TIME_STYLE, word)) Err(Misfire::BadArgument(&flags::TIME_STYLE, word))
@ -309,7 +309,7 @@ impl TimeTypes {
/// Its valid to show more than one column by passing in more than one /// Its valid to show more than one column by passing in more than one
/// option, but passing *no* options means that the user just wants to /// option, but passing *no* options means that the user just wants to
/// see the default set. /// see the default set.
fn deduce(matches: &MatchedFlags) -> Result<TimeTypes, Misfire> { fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
let possible_word = matches.get(&flags::TIME)?; let possible_word = matches.get(&flags::TIME)?;
let modified = matches.has(&flags::MODIFIED)?; let modified = matches.has(&flags::MODIFIED)?;
let changed = matches.has(&flags::CHANGED)?; let changed = matches.has(&flags::CHANGED)?;
@ -319,7 +319,7 @@ impl TimeTypes {
let no_time = matches.has(&flags::NO_TIME)?; let no_time = matches.has(&flags::NO_TIME)?;
let time_types = if no_time { let time_types = if no_time {
TimeTypes { modified: false, changed: false, accessed: false, created: false } Self { modified: false, changed: false, accessed: false, created: false }
} else if let Some(word) = possible_word { } else if let Some(word) = possible_word {
if modified { if modified {
return Err(Misfire::Useless(&flags::MODIFIED, true, &flags::TIME)); return Err(Misfire::Useless(&flags::MODIFIED, true, &flags::TIME));
@ -334,26 +334,26 @@ impl TimeTypes {
return Err(Misfire::Useless(&flags::CREATED, true, &flags::TIME)); return Err(Misfire::Useless(&flags::CREATED, true, &flags::TIME));
} }
else if word == "mod" || word == "modified" { else if word == "mod" || word == "modified" {
TimeTypes { modified: true, changed: false, accessed: false, created: false } Self { modified: true, changed: false, accessed: false, created: false }
} }
else if word == "ch" || word == "changed" { else if word == "ch" || word == "changed" {
TimeTypes { modified: false, changed: true, accessed: false, created: false } Self { modified: false, changed: true, accessed: false, created: false }
} }
else if word == "acc" || word == "accessed" { else if word == "acc" || word == "accessed" {
TimeTypes { modified: false, changed: false, accessed: true, created: false } Self { modified: false, changed: false, accessed: true, created: false }
} }
else if word == "cr" || word == "created" { else if word == "cr" || word == "created" {
TimeTypes { modified: false, changed: false, accessed: false, created: true } Self { modified: false, changed: false, accessed: false, created: true }
} }
else { else {
return Err(Misfire::BadArgument(&flags::TIME, word.into())); return Err(Misfire::BadArgument(&flags::TIME, word.into()));
} }
} }
else if modified || changed || accessed || created { else if modified || changed || accessed || created {
TimeTypes { modified, changed, accessed, created } Self { modified, changed, accessed, created }
} }
else { else {
TimeTypes::default() Self::default()
}; };
Ok(time_types) Ok(time_types)

View File

@ -42,7 +42,7 @@ impl TextCell {
pub fn paint(style: Style, text: String) -> Self { pub fn paint(style: Style, text: String) -> Self {
let width = DisplayWidth::from(&*text); let width = DisplayWidth::from(&*text);
TextCell { Self {
contents: vec![ style.paint(text) ].into(), contents: vec![ style.paint(text) ].into(),
width, width,
} }
@ -54,7 +54,7 @@ impl TextCell {
pub fn paint_str(style: Style, text: &'static str) -> Self { pub fn paint_str(style: Style, text: &'static str) -> Self {
let width = DisplayWidth::from(text); let width = DisplayWidth::from(text);
TextCell { Self {
contents: vec![ style.paint(text) ].into(), contents: vec![ style.paint(text) ].into(),
width, width,
} }
@ -67,7 +67,7 @@ impl TextCell {
/// This is used in place of empty table cells, as it is easier to read /// This is used in place of empty table cells, as it is easier to read
/// tabular data when there is *something* in each cell. /// tabular data when there is *something* in each cell.
pub fn blank(style: Style) -> Self { pub fn blank(style: Style) -> Self {
TextCell { Self {
contents: vec![ style.paint("-") ].into(), contents: vec![ style.paint("-") ].into(),
width: DisplayWidth::from(1), width: DisplayWidth::from(1),
} }
@ -92,7 +92,7 @@ impl TextCell {
} }
/// Adds all the contents of another `TextCell` to the end of this cell. /// Adds all the contents of another `TextCell` to the end of this cell.
pub fn append(&mut self, other: TextCell) { pub fn append(&mut self, other: Self) {
(*self.width) += *other.width; (*self.width) += *other.width;
self.contents.0.extend(other.contents.0); self.contents.0.extend(other.contents.0);
} }
@ -136,8 +136,8 @@ impl TextCell {
pub struct TextCellContents(Vec<ANSIString<'static>>); pub struct TextCellContents(Vec<ANSIString<'static>>);
impl From<Vec<ANSIString<'static>>> for TextCellContents { impl From<Vec<ANSIString<'static>>> for TextCellContents {
fn from(strings: Vec<ANSIString<'static>>) -> TextCellContents { fn from(strings: Vec<ANSIString<'static>>) -> Self {
TextCellContents(strings) Self(strings)
} }
} }
@ -197,14 +197,14 @@ impl TextCellContents {
pub struct DisplayWidth(usize); pub struct DisplayWidth(usize);
impl<'a> From<&'a str> for DisplayWidth { impl<'a> From<&'a str> for DisplayWidth {
fn from(input: &'a str) -> DisplayWidth { fn from(input: &'a str) -> Self {
DisplayWidth(UnicodeWidthStr::width(input)) Self(UnicodeWidthStr::width(input))
} }
} }
impl From<usize> for DisplayWidth { impl From<usize> for DisplayWidth {
fn from(width: usize) -> DisplayWidth { fn from(width: usize) -> Self {
DisplayWidth(width) Self(width)
} }
} }
@ -223,24 +223,24 @@ impl DerefMut for DisplayWidth {
} }
impl Add for DisplayWidth { impl Add for DisplayWidth {
type Output = DisplayWidth; type Output = Self;
fn add(self, rhs: DisplayWidth) -> Self::Output { fn add(self, rhs: Self) -> Self::Output {
DisplayWidth(self.0 + rhs.0) Self(self.0 + rhs.0)
} }
} }
impl Add<usize> for DisplayWidth { impl Add<usize> for DisplayWidth {
type Output = DisplayWidth; type Output = Self;
fn add(self, rhs: usize) -> Self::Output { fn add(self, rhs: usize) -> Self::Output {
DisplayWidth(self.0 + rhs) Self(self.0 + rhs)
} }
} }
impl Sum for DisplayWidth { impl Sum for DisplayWidth {
fn sum<I>(iter: I) -> Self where I: Iterator<Item=Self> { fn sum<I>(iter: I) -> Self where I: Iterator<Item=Self> {
iter.fold(DisplayWidth(0), Add::add) iter.fold(Self(0), Add::add)
} }
} }

View File

@ -65,8 +65,8 @@ pub enum Classify {
} }
impl Default for Classify { impl Default for Classify {
fn default() -> Classify { fn default() -> Self {
Classify::JustFilenames Self::JustFilenames
} }
} }

View File

@ -17,9 +17,9 @@ pub enum Icons {
impl Icons { impl Icons {
pub fn value(&self) -> char { pub fn value(&self) -> char {
match *self { match *self {
Icons::Audio => '\u{f001}', Self::Audio => '\u{f001}',
Icons::Image => '\u{f1c5}', Self::Image => '\u{f1c5}',
Icons::Video => '\u{f03d}', Self::Video => '\u{f03d}',
} }
} }
} }

View File

@ -7,8 +7,8 @@ use crate::fs::fields as f;
impl f::Blocks { impl f::Blocks {
pub fn render<C: Colours>(&self, colours: &C) -> TextCell { pub fn render<C: Colours>(&self, colours: &C) -> TextCell {
match *self { match *self {
f::Blocks::Some(ref blk) => TextCell::paint(colours.block_count(), blk.to_string()), Self::Some(ref blk) => TextCell::paint(colours.block_count(), blk.to_string()),
f::Blocks::None => TextCell::blank(colours.no_blocks()), Self::None => TextCell::blank(colours.no_blocks()),
} }
} }
} }

View File

@ -6,14 +6,14 @@ use crate::fs::fields as f;
impl f::Type { impl f::Type {
pub fn render<C: Colours>(&self, colours: &C) -> ANSIString<'static> { pub fn render<C: Colours>(&self, colours: &C) -> ANSIString<'static> {
match *self { match *self {
f::Type::File => colours.normal().paint("."), Self::File => colours.normal().paint("."),
f::Type::Directory => colours.directory().paint("d"), Self::Directory => colours.directory().paint("d"),
f::Type::Pipe => colours.pipe().paint("|"), Self::Pipe => colours.pipe().paint("|"),
f::Type::Link => colours.symlink().paint("l"), Self::Link => colours.symlink().paint("l"),
f::Type::BlockDevice => colours.block_device().paint("b"), Self::BlockDevice => colours.block_device().paint("b"),
f::Type::CharDevice => colours.char_device().paint("c"), Self::CharDevice => colours.char_device().paint("c"),
f::Type::Socket => colours.socket().paint("s"), Self::Socket => colours.socket().paint("s"),
f::Type::Special => colours.special().paint("?"), Self::Special => colours.special().paint("?"),
} }
} }
} }

View File

@ -20,14 +20,14 @@ impl f::Git {
impl f::GitStatus { impl f::GitStatus {
fn render(&self, colours: &dyn Colours) -> ANSIString<'static> { fn render(&self, colours: &dyn Colours) -> ANSIString<'static> {
match *self { match *self {
f::GitStatus::NotModified => colours.not_modified().paint("-"), Self::NotModified => colours.not_modified().paint("-"),
f::GitStatus::New => colours.new().paint("N"), Self::New => colours.new().paint("N"),
f::GitStatus::Modified => colours.modified().paint("M"), Self::Modified => colours.modified().paint("M"),
f::GitStatus::Deleted => colours.deleted().paint("D"), Self::Deleted => colours.deleted().paint("D"),
f::GitStatus::Renamed => colours.renamed().paint("R"), Self::Renamed => colours.renamed().paint("R"),
f::GitStatus::TypeChange => colours.type_change().paint("T"), Self::TypeChange => colours.type_change().paint("T"),
f::GitStatus::Ignored => colours.ignored().paint("I"), Self::Ignored => colours.ignored().paint("I"),
f::GitStatus::Conflicted => colours.conflicted().paint("U"), Self::Conflicted => colours.conflicted().paint("U"),
} }
} }
} }

View File

@ -12,9 +12,9 @@ impl f::Size {
use number_prefix::NumberPrefix; use number_prefix::NumberPrefix;
let size = match *self { let size = match *self {
f::Size::Some(s) => s, Self::Some(s) => s,
f::Size::None => return TextCell::blank(colours.no_size()), Self::None => return TextCell::blank(colours.no_size()),
f::Size::DeviceIDs(ref ids) => return ids.render(colours), Self::DeviceIDs(ref ids) => return ids.render(colours),
}; };
let result = match size_format { let result = match size_format {

View File

@ -144,12 +144,12 @@ impl Column {
/// Get the alignment this column should use. /// Get the alignment this column should use.
pub fn alignment(&self) -> Alignment { pub fn alignment(&self) -> Alignment {
match *self { match *self {
Column::FileSize Self::FileSize |
| Column::HardLinks Self::HardLinks |
| Column::Inode Self::Inode |
| Column::Blocks Self::Blocks |
| Column::GitStatus => Alignment::Right, Self::GitStatus => Alignment::Right,
_ => Alignment::Left, _ => Alignment::Left,
} }
} }
@ -157,16 +157,16 @@ impl Column {
/// to have a header row printed. /// to have a header row printed.
pub fn header(&self) -> &'static str { pub fn header(&self) -> &'static str {
match *self { match *self {
Column::Permissions => "Permissions", Self::Permissions => "Permissions",
Column::FileSize => "Size", Self::FileSize => "Size",
Column::Timestamp(t) => t.header(), Self::Timestamp(t) => t.header(),
Column::Blocks => "Blocks", Self::Blocks => "Blocks",
Column::User => "User", Self::User => "User",
Column::Group => "Group", Self::Group => "Group",
Column::HardLinks => "Links", Self::HardLinks => "Links",
Column::Inode => "inode", Self::Inode => "inode",
Column::GitStatus => "Git", Self::GitStatus => "Git",
Column::Octal => "Octal", Self::Octal => "Octal",
} }
} }
} }
@ -189,8 +189,8 @@ pub enum SizeFormat {
} }
impl Default for SizeFormat { impl Default for SizeFormat {
fn default() -> SizeFormat { fn default() -> Self {
SizeFormat::DecimalBytes Self::DecimalBytes
} }
} }
@ -217,10 +217,10 @@ 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::Modified => "Date Modified", Self::Modified => "Date Modified",
TimeType::Changed => "Date Changed", Self::Changed => "Date Changed",
TimeType::Accessed => "Date Accessed", Self::Accessed => "Date Accessed",
TimeType::Created => "Date Created", Self::Created => "Date Created",
} }
} }
} }
@ -243,8 +243,8 @@ impl Default for TimeTypes {
/// By default, display just the modified time. This is the most /// By default, display just the modified time. This is the most
/// common option, which is why it has this shorthand. /// common option, which is why it has this shorthand.
fn default() -> TimeTypes { fn default() -> Self {
TimeTypes { modified: true, changed: false, accessed: false, created: false } Self { modified: true, changed: false, accessed: false, created: false }
} }
} }
@ -287,7 +287,7 @@ impl Environment {
let users = Mutex::new(UsersCache::new()); let users = Mutex::new(UsersCache::new());
Environment { tz, numeric, users } Self { tz, numeric, users }
} }
} }
@ -425,8 +425,8 @@ impl Deref for TableWidths {
} }
impl TableWidths { impl TableWidths {
pub fn zero(count: usize) -> TableWidths { pub fn zero(count: usize) -> Self {
TableWidths(vec![ 0; count ]) Self(vec![ 0; count ])
} }
pub fn add_widths(&mut self, row: &Row) { pub fn add_widths(&mut self, row: &Row) {

View File

@ -52,19 +52,19 @@ pub enum TimeFormat {
impl TimeFormat { impl TimeFormat {
pub fn format_local(&self, time: SystemTime) -> String { pub fn format_local(&self, time: SystemTime) -> String {
match *self { match *self {
TimeFormat::DefaultFormat(ref fmt) => fmt.format_local(time), Self::DefaultFormat(ref fmt) => fmt.format_local(time),
TimeFormat::ISOFormat(ref iso) => iso.format_local(time), Self::ISOFormat(ref iso) => iso.format_local(time),
TimeFormat::LongISO => long_local(time), Self::LongISO => long_local(time),
TimeFormat::FullISO => full_local(time), Self::FullISO => full_local(time),
} }
} }
pub fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String { pub fn format_zoned(&self, time: SystemTime, zone: &TimeZone) -> String {
match *self { match *self {
TimeFormat::DefaultFormat(ref fmt) => fmt.format_zoned(time, zone), Self::DefaultFormat(ref fmt) => fmt.format_zoned(time, zone),
TimeFormat::ISOFormat(ref iso) => iso.format_zoned(time, zone), Self::ISOFormat(ref iso) => iso.format_zoned(time, zone),
TimeFormat::LongISO => long_zoned(time, zone), Self::LongISO => long_zoned(time, zone),
TimeFormat::FullISO => full_zoned(time, zone), Self::FullISO => full_zoned(time, zone),
} }
} }
} }
@ -88,7 +88,7 @@ pub struct DefaultFormat {
} }
impl DefaultFormat { impl DefaultFormat {
pub fn load() -> DefaultFormat { pub fn load() -> Self {
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
let locale = locale::Time::load_user_locale() let locale = locale::Time::load_user_locale()
@ -117,7 +117,7 @@ impl DefaultFormat {
_ => DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap() _ => DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
}; };
DefaultFormat { current_year, locale, date_and_time, date_and_year } Self { current_year, locale, date_and_time, date_and_year }
} }
} }
@ -150,7 +150,7 @@ impl DefaultFormat {
if self.is_recent(date) { if self.is_recent(date) {
format!("{:2} {} {:02}:{:02}", format!("{:2} {} {:02}:{:02}",
date.day(), DefaultFormat::month_to_abbrev(date.month()), date.day(), Self::month_to_abbrev(date.month()),
date.hour(), date.minute()) date.hour(), date.minute())
} }
else { else {
@ -164,7 +164,7 @@ impl DefaultFormat {
if self.is_recent(date) { if self.is_recent(date) {
format!("{:2} {} {:02}:{:02}", format!("{:2} {} {:02}:{:02}",
date.day(), DefaultFormat::month_to_abbrev(date.month()), date.day(), Self::month_to_abbrev(date.month()),
date.hour(), date.minute()) date.hour(), date.minute())
} }
else { else {
@ -250,9 +250,9 @@ pub struct ISOFormat {
} }
impl ISOFormat { impl ISOFormat {
pub fn load() -> ISOFormat { pub fn load() -> Self {
let current_year = LocalDateTime::now().year(); let current_year = LocalDateTime::now().year();
ISOFormat { current_year } Self { current_year }
} }
} }

View File

@ -61,10 +61,10 @@ impl TreePart {
/// (Warning: not actually ASCII) /// (Warning: not actually ASCII)
pub fn ascii_art(&self) -> &'static str { pub fn ascii_art(&self) -> &'static str {
match *self { match *self {
TreePart::Edge => "├──", Self::Edge => "├──",
TreePart::Line => "", Self::Line => "",
TreePart::Corner => "└──", Self::Corner => "└──",
TreePart::Blank => " ", Self::Blank => " ",
} }
} }
} }
@ -138,8 +138,8 @@ impl TreeTrunk {
} }
impl TreeParams { impl TreeParams {
pub fn new(depth: TreeDepth, last: bool) -> TreeParams { pub fn new(depth: TreeDepth, last: bool) -> Self {
TreeParams { depth, last } Self { depth, last }
} }
pub fn is_at_root(&self) -> bool { pub fn is_at_root(&self) -> bool {
@ -148,12 +148,12 @@ impl TreeParams {
} }
impl TreeDepth { impl TreeDepth {
pub fn root() -> TreeDepth { pub fn root() -> Self {
TreeDepth(0) Self(0)
} }
pub fn deeper(self) -> TreeDepth { pub fn deeper(self) -> Self {
TreeDepth(self.0 + 1) Self(self.0 + 1)
} }
/// Creates an iterator that, as well as yielding each value, yields a /// Creates an iterator that, as well as yielding each value, yields a

View File

@ -109,12 +109,12 @@ pub struct Git {
} }
impl Colours { impl Colours {
pub fn plain() -> Colours { pub fn plain() -> Self {
Colours::default() Self::default()
} }
pub fn colourful(scale: bool) -> Colours { pub fn colourful(scale: bool) -> Self {
Colours { Self {
colourful: true, colourful: true,
filekinds: FileKinds { filekinds: FileKinds {