fix: Address longstanding linter errors

This commit is contained in:
Matan Kushner 2019-07-31 19:48:51 -04:00
parent 616b50b4e3
commit f40f73dc8e
13 changed files with 66 additions and 75 deletions

View File

@ -9,5 +9,5 @@ jobs:
steps: steps:
- template: install-rust.yml - template: install-rust.yml
- script: cargo clippy -- -D warnings -D clippy::all -D clippy::nursery -D clippy::pedantic - script: cargo clippy -- -D clippy::all
displayName: Run clippy displayName: Run clippy

View File

@ -21,30 +21,27 @@ pub trait Config {
impl Config for Table { impl Config for Table {
/// Initialize the Config struct /// Initialize the Config struct
fn initialize() -> Table { fn initialize() -> Table {
if let Some(file_data) = Table::config_from_file() { if let Some(file_data) = Self::config_from_file() {
return file_data; return file_data;
} }
Table::new() Self::new()
} }
/// Create a config from a starship configuration file /// Create a config from a starship configuration file
fn config_from_file() -> Option<Table> { fn config_from_file() -> Option<Table> {
let file_path = match env::var("STARSHIP_CONFIG") { let file_path = if let Ok(path) = env::var("STARSHIP_CONFIG") {
Ok(path) => { // Use $STARSHIP_CONFIG as the config path if available
// Use $STARSHIP_CONFIG as the config path if available log::debug!("STARSHIP_CONFIG is set: \n{}", &path);
log::debug!("STARSHIP_CONFIG is set: \n{}", &path); path
path } else {
} // Default to using ~/.config/starhip.toml
Err(_) => { log::debug!("STARSHIP_CONFIG is not set");
// Default to using ~/.config/starhip.toml let config_path = home_dir()?.join(".config/starship.toml");
log::debug!("STARSHIP_CONFIG is not set"); let config_path_str = config_path.to_str()?.to_owned();
let config_path = home_dir()?.join(".config/starship.toml");
let config_path_str = config_path.to_str()?.to_owned();
log::debug!("Using default config path: {}", config_path_str); log::debug!("Using default config path: {}", config_path_str);
config_path_str config_path_str
}
}; };
let toml_content = match utils::read_file(&file_path) { let toml_content = match utils::read_file(&file_path) {
@ -65,10 +62,7 @@ impl Config for Table {
/// Get the subset of the table for a module by its name /// Get the subset of the table for a module by its name
fn get_module_config(&self, module_name: &str) -> Option<&toml::value::Table> { fn get_module_config(&self, module_name: &str) -> Option<&toml::value::Table> {
let module_config = self let module_config = self.get(module_name).and_then(toml::Value::as_table);
.get(module_name)
.map(toml::Value::as_table)
.unwrap_or(None);
if module_config.is_some() { if module_config.is_some() {
log::debug!( log::debug!(
@ -149,7 +143,7 @@ impl Config for Table {
} }
} }
#[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View File

@ -70,10 +70,10 @@ impl<'a> Context<'a> {
let repository = Repository::discover(&current_dir).ok(); let repository = Repository::discover(&current_dir).ok();
let repo_root = repository let repo_root = repository
.as_ref() .as_ref()
.and_then(|repo| repo.workdir().map(|repo| repo.to_path_buf())); .and_then(|repo| repo.workdir().map(std::path::Path::to_path_buf));
let branch_name = repository let branch_name = repository
.as_ref() .as_ref()
.and_then(|repo| get_current_branch(&repo)); .and_then(|repo| get_current_branch(repo));
Context { Context {
config, config,
@ -102,9 +102,7 @@ impl<'a> Context<'a> {
let config = self.config.get_module_config(name); let config = self.config.get_module_config(name);
// If the segment has "disabled" set to "true", don't show it // If the segment has "disabled" set to "true", don't show it
let disabled = config let disabled = config.and_then(|table| table.get_as_bool("disabled"));
.map(|table| table.get_as_bool("disabled"))
.unwrap_or(None);
if disabled == Some(true) { if disabled == Some(true) {
return None; return None;
@ -135,17 +133,17 @@ pub struct ScanDir<'a> {
} }
impl<'a> ScanDir<'a> { impl<'a> ScanDir<'a> {
pub fn set_files(mut self, files: &'a [&'a str]) -> Self { pub const fn set_files(mut self, files: &'a [&'a str]) -> Self {
self.files = files; self.files = files;
self self
} }
pub fn set_extensions(mut self, extensions: &'a [&'a str]) -> Self { pub const fn set_extensions(mut self, extensions: &'a [&'a str]) -> Self {
self.extensions = extensions; self.extensions = extensions;
self self
} }
pub fn set_folders(mut self, folders: &'a [&'a str]) -> Self { pub const fn set_folders(mut self, folders: &'a [&'a str]) -> Self {
self.folders = folders; self.folders = folders;
self self
} }
@ -155,9 +153,9 @@ impl<'a> ScanDir<'a> {
pub fn scan(&mut self) -> bool { pub fn scan(&mut self) -> bool {
self.dir_files.iter().any(|path| { self.dir_files.iter().any(|path| {
if path.is_dir() { if path.is_dir() {
return path_has_name(&path, &self.folders); path_has_name(path, self.folders)
} else { } else {
return path_has_name(&path, &self.files) || has_extension(&path, &self.extensions); path_has_name(path, self.files) || has_extension(path, self.extensions)
} }
}) })
} }
@ -199,7 +197,7 @@ fn get_current_branch(repository: &Repository) -> Option<String> {
let head = repository.head().ok()?; let head = repository.head().ok()?;
let shorthand = head.shorthand(); let shorthand = head.shorthand();
shorthand.map(|branch| branch.to_string()) shorthand.map(std::string::ToString::to_string)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -54,8 +54,7 @@ pub fn init(shell_name: &str) {
} }
}; };
if setup_script.is_some() { if let Some(script) = setup_script {
let script = setup_script.unwrap();
print!("{}", script); print!("{}", script);
} }
} }

View File

@ -17,13 +17,13 @@ pub struct Module<'a> {
style: Style, style: Style,
/// The prefix used to separate the current module from the previous one. /// The prefix used to separate the current module from the previous one.
prefix: ModuleAffix, prefix: Affix,
/// The collection of segments that compose this module. /// The collection of segments that compose this module.
segments: Vec<Segment>, segments: Vec<Segment>,
/// The suffix used to separate the current module from the next one. /// The suffix used to separate the current module from the next one.
suffix: ModuleAffix, suffix: Affix,
} }
impl<'a> Module<'a> { impl<'a> Module<'a> {
@ -33,9 +33,9 @@ impl<'a> Module<'a> {
config, config,
name: name.to_string(), name: name.to_string(),
style: Style::default(), style: Style::default(),
prefix: ModuleAffix::default_prefix(name.to_string()), prefix: Affix::default_prefix(name),
segments: Vec::new(), segments: Vec::new(),
suffix: ModuleAffix::default_suffix(name.to_string()), suffix: Affix::default_suffix(name),
} }
} }
@ -56,12 +56,12 @@ impl<'a> Module<'a> {
} }
/// Get the module's prefix /// Get the module's prefix
pub fn get_prefix(&mut self) -> &mut ModuleAffix { pub fn get_prefix(&mut self) -> &mut Affix {
&mut self.prefix &mut self.prefix
} }
/// Get the module's suffix /// Get the module's suffix
pub fn get_suffix(&mut self) -> &mut ModuleAffix { pub fn get_suffix(&mut self) -> &mut Affix {
&mut self.suffix &mut self.suffix
} }
@ -82,7 +82,7 @@ impl<'a> Module<'a> {
let mut ansi_strings = self let mut ansi_strings = self
.segments .segments
.iter() .iter()
.map(|s| s.ansi_string()) .map(Segment::ansi_string)
.collect::<Vec<ANSIString>>(); .collect::<Vec<ANSIString>>();
ansi_strings.insert(0, self.prefix.ansi_string()); ansi_strings.insert(0, self.prefix.ansi_string());
@ -119,7 +119,7 @@ impl<'a> fmt::Display for Module<'a> {
} }
/// Module affixes are to be used for the prefix or suffix of a module. /// Module affixes are to be used for the prefix or suffix of a module.
pub struct ModuleAffix { pub struct Affix {
/// The affix's name, to be used in configuration and logging. /// The affix's name, to be used in configuration and logging.
name: String, name: String,
@ -130,17 +130,17 @@ pub struct ModuleAffix {
value: String, value: String,
} }
impl ModuleAffix { impl Affix {
pub fn default_prefix(name: String) -> ModuleAffix { pub fn default_prefix(name: &str) -> Self {
ModuleAffix { Self {
name: format!("{}_prefix", name), name: format!("{}_prefix", name),
style: Style::default(), style: Style::default(),
value: "via ".to_string(), value: "via ".to_string(),
} }
} }
pub fn default_suffix(name: String) -> ModuleAffix { pub fn default_suffix(name: &str) -> Self {
ModuleAffix { Self {
name: format!("{}_suffix", name), name: format!("{}_suffix", name),
style: Style::default(), style: Style::default(),
value: " ".to_string(), value: " ".to_string(),
@ -150,7 +150,7 @@ impl ModuleAffix {
/// Sets the style of the module. /// Sets the style of the module.
/// ///
/// Accepts either `Color` or `Style`. /// Accepts either `Color` or `Style`.
pub fn set_style<T>(&mut self, style: T) -> &mut ModuleAffix pub fn set_style<T>(&mut self, style: T) -> &mut Self
where where
T: Into<Style>, T: Into<Style>,
{ {
@ -159,7 +159,7 @@ impl ModuleAffix {
} }
/// Sets the value of the module. /// Sets the value of the module.
pub fn set_value<T>(&mut self, value: T) -> &mut ModuleAffix pub fn set_value<T>(&mut self, value: T) -> &mut Self
where where
T: Into<String>, T: Into<String>,
{ {
@ -173,7 +173,7 @@ impl ModuleAffix {
} }
} }
impl fmt::Display for ModuleAffix { impl fmt::Display for Affix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.ansi_string()) write!(f, "{}", self.ansi_string())
} }

View File

@ -33,12 +33,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
// Contract the path to the git repo root // Contract the path to the git repo root
let repo_folder_name = repo_root.file_name().unwrap().to_str().unwrap(); let repo_folder_name = repo_root.file_name().unwrap().to_str().unwrap();
dir_string = contract_path(&current_dir, repo_root, repo_folder_name); dir_string = contract_path(current_dir, repo_root, repo_folder_name);
} else { } else {
// Contract the path to the home directory // Contract the path to the home directory
let home_dir = dirs::home_dir().unwrap(); let home_dir = dirs::home_dir().unwrap();
dir_string = contract_path(&current_dir, &home_dir, HOME_SYMBOL); dir_string = contract_path(current_dir, &home_dir, HOME_SYMBOL);
} }
// Truncate the dir string to the maximum number of path components // Truncate the dir string to the maximum number of path components
@ -89,8 +89,8 @@ fn replace_c_dir(path: String) -> String {
/// ///
/// On non-Windows OS, does nothing /// On non-Windows OS, does nothing
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
fn replace_c_dir(path: String) -> String { const fn replace_c_dir(path: String) -> String {
return path; path
} }
/// Truncate a path to only have a set number of path components /// Truncate a path to only have a set number of path components

View File

@ -6,9 +6,9 @@ use super::{Context, Module};
/// ///
/// Will display the branch name if the current directory is a git repo /// Will display the branch name if the current directory is a git repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let branch_name = context.branch_name.as_ref()?;
const GIT_BRANCH_CHAR: &str = ""; const GIT_BRANCH_CHAR: &str = "";
let branch_name = context.branch_name.as_ref()?;
let segment_color = Color::Purple.bold(); let segment_color = Color::Purple.bold();
let mut module = context.new_module("git_branch")?; let mut module = context.new_module("git_branch")?;

View File

@ -40,11 +40,11 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
module.get_suffix().set_value("] ").set_style(module_style); module.get_suffix().set_value("] ").set_style(module_style);
module.set_style(module_style); module.set_style(module_style);
let ahead_behind = get_ahead_behind(&repository, &branch_name); let ahead_behind = get_ahead_behind(&repository, branch_name);
if ahead_behind != Ok((0, 0)) { if ahead_behind == Ok((0, 0)) {
log::debug!("Repo ahead/behind: {:?}", ahead_behind);
} else {
log::trace!("No ahead/behind found"); log::trace!("No ahead/behind found");
} else {
log::debug!("Repo ahead/behind: {:?}", ahead_behind);
} }
let stash_object = repository.revparse_single("refs/stash"); let stash_object = repository.revparse_single("refs/stash");

View File

@ -33,7 +33,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("go")?; let mut module = context.new_module("go")?;
module.set_style(module_color); module.set_style(module_color);
let formatted_version = format_go_version(go_version)?; let formatted_version = format_go_version(&go_version)?;
module.new_segment("symbol", GO_CHAR); module.new_segment("symbol", GO_CHAR);
module.new_segment("version", &formatted_version); module.new_segment("version", &formatted_version);
@ -51,7 +51,7 @@ fn get_go_version() -> Option<String> {
.and_then(|output| String::from_utf8(output.stdout).ok()) .and_then(|output| String::from_utf8(output.stdout).ok())
} }
fn format_go_version(go_stdout: String) -> Option<String> { fn format_go_version(go_stdout: &str) -> Option<String> {
let version = go_stdout let version = go_stdout
// split into ["", "1.12.4 linux/amd64"] // split into ["", "1.12.4 linux/amd64"]
.splitn(2, "go version go") .splitn(2, "go version go")
@ -74,7 +74,7 @@ mod tests {
#[test] #[test]
fn test_format_go_version() { fn test_format_go_version() {
let input = String::from("go version go1.12 darwin/amd64"); let input = "go version go1.12 darwin/amd64";
assert_eq!(format_go_version(input), Some("v1.12".to_string())); assert_eq!(format_go_version(input), Some("v1.12".to_string()));
} }
} }

View File

@ -28,7 +28,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
} }
fn extract_cargo_version(file_contents: &str) -> Option<String> { fn extract_cargo_version(file_contents: &str) -> Option<String> {
let cargo_toml: toml::Value = toml::from_str(&file_contents).ok()?; let cargo_toml: toml::Value = toml::from_str(file_contents).ok()?;
let raw_version = cargo_toml.get("package")?.get("version")?.as_str()?; let raw_version = cargo_toml.get("package")?.get("version")?.as_str()?;
let formatted_version = format_version(raw_version); let formatted_version = format_version(raw_version);
@ -36,7 +36,7 @@ fn extract_cargo_version(file_contents: &str) -> Option<String> {
} }
fn extract_package_version(file_contents: &str) -> Option<String> { fn extract_package_version(file_contents: &str) -> Option<String> {
let package_json: json::Value = json::from_str(&file_contents).ok()?; let package_json: json::Value = json::from_str(file_contents).ok()?;
let raw_version = package_json.get("version")?.as_str()?; let raw_version = package_json.get("version")?.as_str()?;
if raw_version == "null" { if raw_version == "null" {
return None; return None;

View File

@ -29,7 +29,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("python")?; let mut module = context.new_module("python")?;
module.set_style(module_color); module.set_style(module_color);
let formatted_version = format_python_version(python_version); let formatted_version = format_python_version(&python_version);
module.new_segment("symbol", PYTHON_CHAR); module.new_segment("symbol", PYTHON_CHAR);
module.new_segment("version", &formatted_version); module.new_segment("version", &formatted_version);
@ -57,7 +57,7 @@ fn get_python_version() -> Option<String> {
} }
} }
fn format_python_version(python_stdout: String) -> String { fn format_python_version(python_stdout: &str) -> String {
format!("v{}", python_stdout.trim_start_matches("Python ").trim()) format!("v{}", python_stdout.trim_start_matches("Python ").trim())
} }
@ -67,7 +67,7 @@ mod tests {
#[test] #[test]
fn test_format_python_version() { fn test_format_python_version() {
let input = String::from("Python 3.7.2"); let input = "Python 3.7.2";
assert_eq!(format_python_version(input), "v3.7.2"); assert_eq!(format_python_version(input), "v3.7.2");
} }
} }

View File

@ -7,9 +7,9 @@ use super::{Context, Module};
/// Creates a module with the current user's username /// Creates a module with the current user's username
/// ///
/// Will display the usename if any of the following criteria are met: /// Will display the usename if any of the following criteria are met:
/// - The current user isn't the same as the one that is logged in ($LOGNAME != $USER) /// - The current user isn't the same as the one that is logged in (`$LOGNAME` != `$USER`)
/// - The current user is root (UID = 0) /// - The current user is root (UID = 0)
/// - The user is currently connected as an SSH session ($SSH_CONNECTION) /// - The user is currently connected as an SSH session (`$SSH_CONNECTION`)
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let user = env::var("USER").ok(); let user = env::var("USER").ok();
let logname = env::var("LOGNAME").ok(); let logname = env::var("LOGNAME").ok();

View File

@ -17,8 +17,8 @@ pub struct Segment {
impl Segment { impl Segment {
/// Creates a new segment with default fields. /// Creates a new segment with default fields.
pub fn new(name: &str) -> Segment { pub fn new(name: &str) -> Self {
Segment { Self {
name: name.to_string(), name: name.to_string(),
style: None, style: None,
value: "".to_string(), value: "".to_string(),
@ -28,7 +28,7 @@ impl Segment {
/// Sets the style of the segment. /// Sets the style of the segment.
/// ///
/// Accepts either `Color` or `Style`. /// Accepts either `Color` or `Style`.
pub fn set_style<T>(&mut self, style: T) -> &mut Segment pub fn set_style<T>(&mut self, style: T) -> &mut Self
where where
T: Into<Style>, T: Into<Style>,
{ {
@ -37,7 +37,7 @@ impl Segment {
} }
/// Sets the value of the segment. /// Sets the value of the segment.
pub fn set_value<T>(&mut self, value: T) -> &mut Segment pub fn set_value<T>(&mut self, value: T) -> &mut Self
where where
T: Into<String>, T: Into<String>,
{ {