From 0ae61c775891b4dde1535c9224d44bc8d12899e2 Mon Sep 17 00:00:00 2001 From: David Knaack Date: Mon, 23 May 2022 12:58:27 +0200 Subject: [PATCH] chore(clippy): fix new lints (#4002) --- .github/config-schema.json | 2 +- src/config.rs | 18 ++++++------ src/configs/aws.rs | 2 +- src/configs/starship_root.rs | 2 +- src/configure.rs | 5 ++-- src/context.rs | 6 ++-- src/formatter/string_formatter.rs | 4 +-- src/formatter/version.rs | 7 +++-- src/init/mod.rs | 2 +- src/module.rs | 8 ++---- src/modules/aws.rs | 2 +- src/modules/c.rs | 9 ++---- src/modules/cmake.rs | 2 +- src/modules/custom.rs | 16 +++++++---- src/modules/directory.rs | 2 +- src/modules/docker_context.rs | 8 +++--- src/modules/dotnet.rs | 4 +-- src/modules/env_var.rs | 10 +++---- src/modules/gcloud.rs | 3 +- src/modules/git_commit.rs | 3 +- src/modules/hostname.rs | 2 +- src/modules/localip.rs | 2 +- src/modules/nix_shell.rs | 4 +-- src/modules/pulumi.rs | 8 +++--- src/modules/rust.rs | 20 ++++++-------- src/modules/status.rs | 5 ++-- src/modules/time.rs | 23 ++++++---------- src/modules/utils/directory_win.rs | 4 +-- src/print.rs | 2 +- src/segment.rs | 44 +++++++++++++++--------------- src/test/mod.rs | 7 +++-- src/utils.rs | 2 +- 32 files changed, 114 insertions(+), 124 deletions(-) diff --git a/.github/config-schema.json b/.github/config-schema.json index f4aa97a4..25d7ad9f 100644 --- a/.github/config-schema.json +++ b/.github/config-schema.json @@ -1476,7 +1476,7 @@ "definitions": { "AwsConfig": { "title": "AWS", - "description": "The `aws` module shows the current AWS region and profile when credentials or a `credential_process` have been setup. This is based on `AWS_REGION`, `AWS_DEFAULT_REGION`, and `AWS_PROFILE` env var with `~/.aws/config` file. This module also shows an expiration timer when using temporary credentials.\n\nThe module will display a profile only if its credentials are present in `~/.aws/credentials` or a `credential_process` is defined in `~/.aws/config`. Alternatively, having any of the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, or `AWS_SESSION_TOKEN` env vars defined will also suffice.\n\nWhen using [aws-vault](https://github.com/99designs/aws-vault) the profile is read from the `AWS_VAULT` env var and the credentials expiration date is read from the `AWS_SESSION_EXPIRATION` env var.\n\nWhen using [awsu](https://github.com/kreuzwerker/awsu) the profile is read from the `AWSU_PROFILE` env var.\n\nWhen using [AWSume](https://awsu.me) the profile is read from the `AWSUME_PROFILE` env var and the credentials expiration date is read from the `AWSUME_EXPIRATION` env var.", + "description": "The `aws` module shows the current AWS region and profile when credentials or a `credential_process` have been setup. This is based on `AWS_REGION`, `AWS_DEFAULT_REGION`, and `AWS_PROFILE` env var with `~/.aws/config` file. This module also shows an expiration timer when using temporary credentials.\n\nThe module will display a profile only if its credentials are present in `~/.aws/credentials` or a `credential_process` is defined in `~/.aws/config`. Alternatively, having any of the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, or `AWS_SESSION_TOKEN` env vars defined will also suffice.\n\nWhen using [aws-vault](https://github.com/99designs/aws-vault) the profile is read from the `AWS_VAULT` env var and the credentials expiration date is read from the `AWS_SESSION_EXPIRATION` env var.\n\nWhen using [awsu](https://github.com/kreuzwerker/awsu) the profile is read from the `AWSU_PROFILE` env var.\n\nWhen using [`AWSume`](https://awsu.me) the profile is read from the `AWSUME_PROFILE` env var and the credentials expiration date is read from the `AWSUME_EXPIRATION` env var.", "type": "object", "properties": { "format": { diff --git a/src/config.rs b/src/config.rs index ba323dd9..b4a93d40 100644 --- a/src/config.rs +++ b/src/config.rs @@ -34,15 +34,15 @@ where } } - /// Helper function that will call ModuleConfig::from_config(config) if config is Some, - /// or ModuleConfig::default() if config is None. + /// Helper function that will call `ModuleConfig::from_config(config) if config is Some, + /// or `ModuleConfig::default()` if config is None. fn try_load(config: Option<&'a Value>) -> Self { config.map(Self::load).unwrap_or_default() } } impl<'a, T: Deserialize<'a> + Default> ModuleConfig<'a, ValueError> for T { - /// Create ValueDeserializer wrapper and use it to call Deserialize::deserialize on it. + /// Create `ValueDeserializer` wrapper and use it to call `Deserialize::deserialize` on it. fn from_config(config: &'a Value) -> Result { let deserializer = ValueDeserializer::new(config); T::deserialize(deserializer) @@ -72,8 +72,8 @@ where { let either = Either::, T>::deserialize(deserializer)?; match either { - Either::First(v) => Ok(VecOr(v)), - Either::Second(s) => Ok(VecOr(vec![s])), + Either::First(v) => Ok(Self(v)), + Either::Second(s) => Ok(Self(vec![s])), } } } @@ -244,7 +244,7 @@ impl StarshipConfig { pub fn get_custom_modules(&self) -> Option<&toml::value::Table> { self.get_config(&["custom"])?.as_table() } - /// Get the table of all the registered env_var modules, if any + /// Get the table of all the registered `env_var` modules, if any pub fn get_env_var_modules(&self) -> Option<&toml::value::Table> { self.get_config(&["env_var"])?.as_table() } @@ -268,7 +268,7 @@ where - 'bold' - 'italic' - 'inverted' - - '' (see the parse_color_string doc for valid color strings) + - '' (see the `parse_color_string` doc for valid color strings) */ pub fn parse_style_string(style_string: &str) -> Option { style_string @@ -506,8 +506,8 @@ mod tests { { let s = String::deserialize(deserializer)?; match s.to_ascii_lowercase().as_str() { - "on" => Ok(Switch::On), - _ => Ok(Switch::Off), + "on" => Ok(Self::On), + _ => Ok(Self::Off), } } } diff --git a/src/configs/aws.rs b/src/configs/aws.rs index 47330324..171fd76f 100644 --- a/src/configs/aws.rs +++ b/src/configs/aws.rs @@ -25,7 +25,7 @@ use std::collections::HashMap; /// When using [awsu](https://github.com/kreuzwerker/awsu) the profile /// is read from the `AWSU_PROFILE` env var. /// -/// When using [AWSume](https://awsu.me) the profile +/// When using [`AWSume`](https://awsu.me) the profile /// is read from the `AWSUME_PROFILE` env var and the credentials expiration /// date is read from the `AWSUME_EXPIRATION` env var. pub struct AwsConfig<'a> { diff --git a/src/configs/starship_root.rs b/src/configs/starship_root.rs index e386b76a..63506ef5 100644 --- a/src/configs/starship_root.rs +++ b/src/configs/starship_root.rs @@ -99,7 +99,7 @@ pub const PROMPT_ORDER: &[&str] = &[ // On changes please also update `Default` for the `FullConfig` struct in `mod.rs` impl<'a> Default for StarshipRootConfig { fn default() -> Self { - StarshipRootConfig { + Self { schema: "https://starship.rs/config-schema.json".to_string(), format: "$all".to_string(), right_format: "".to_string(), diff --git a/src/configure.rs b/src/configure.rs index e07a03f3..e6f3d790 100644 --- a/src/configure.rs +++ b/src/configure.rs @@ -61,8 +61,7 @@ fn handle_update_configuration(doc: &mut Document, name: &str, value: &str) -> R } let mut new_value = toml_edit::Value::from_str(value) - .map(toml_edit::Item::Value) - .unwrap_or_else(|_| toml_edit::value(value)); + .map_or_else(|_| toml_edit::value(value), toml_edit::Item::Value); if let Some(value) = current_item.as_value() { *new_value.as_value_mut().unwrap().decor_mut() = value.decor().clone(); @@ -147,7 +146,7 @@ fn extract_toml_paths(mut config: toml::Value, paths: &[String]) -> toml::Value for &segment in parents { source_cursor = if let Some(child) = source_cursor .get_mut(segment) - .and_then(|value| value.as_table_mut()) + .and_then(toml::Value::as_table_mut) { child } else { diff --git a/src/context.rs b/src/context.rs index c837d635..11dd57aa 100644 --- a/src/context.rs +++ b/src/context.rs @@ -337,7 +337,7 @@ impl<'a> Context<'a> { ) } - /// Attempt to execute several commands with exec_cmd, return the results of the first that works + /// Attempt to execute several commands with `exec_cmd`, return the results of the first that works pub fn exec_cmds_return_first(&self, commands: Vec>) -> Option { commands .iter() @@ -513,7 +513,7 @@ impl<'a> ScanDir<'a> { self } - /// based on the current PathBuf check to see + /// based on the current `PathBuf` check to see /// if any of this criteria match or exist and returning a boolean pub fn is_match(&self) -> bool { self.dir_contents.has_any_extension(self.extensions) @@ -628,7 +628,7 @@ pub struct Properties { impl Default for Properties { fn default() -> Self { - Properties { + Self { status_code: None, pipestatus: None, terminal_width: default_width(), diff --git a/src/formatter/string_formatter.rs b/src/formatter/string_formatter.rs index 730e22f0..ab895b59 100644 --- a/src/formatter/string_formatter.rs +++ b/src/formatter/string_formatter.rs @@ -62,7 +62,7 @@ pub struct StringFormatter<'a> { } impl<'a> StringFormatter<'a> { - /// Creates an instance of StringFormatter from a format string + /// Creates an instance of `StringFormatter` from a format string /// /// This method will throw an Error when the given format string fails to parse. pub fn new(format: &'a str) -> Result { @@ -88,7 +88,7 @@ impl<'a> StringFormatter<'a> { }) } - /// A StringFormatter that does no formatting, parse just returns the raw text + /// A `StringFormatter` that does no formatting, parse just returns the raw text pub fn raw(text: &'a str) -> Self { Self { format: vec![FormatElement::Text(text.into())], diff --git a/src/formatter/version.rs b/src/formatter/version.rs index b88821c1..400d3f06 100644 --- a/src/formatter/version.rs +++ b/src/formatter/version.rs @@ -1,5 +1,6 @@ use super::string_formatter::StringFormatterError; use super::StringFormatter; +use crate::segment; use once_cell::sync::Lazy; use std::ops::Deref; use versions::Versioning; @@ -9,9 +10,9 @@ pub struct VersionFormatter<'a> { } impl<'a> VersionFormatter<'a> { - /// Creates an instance of a VersionFormatter from a format string + /// Creates an instance of a `VersionFormatter` from a format string /// - /// Like the StringFormatter, this will throw an error when the string isn't + /// Like the `StringFormatter`, this will throw an error when the string isn't /// parseable. pub fn new(format: &'a str) -> Result { let formatter = StringFormatter::new(format)?; @@ -56,7 +57,7 @@ impl<'a> VersionFormatter<'a> { formatted.map(|segments| { segments .iter() - .map(|segment| segment.value()) + .map(segment::Segment::value) .collect::() }) } diff --git a/src/init/mod.rs b/src/init/mod.rs index 477f1c0d..be00940a 100644 --- a/src/init/mod.rs +++ b/src/init/mod.rs @@ -40,7 +40,7 @@ impl StarshipPath { self.str_path().map(|p| shell_words::quote(p).into_owned()) } - /// PowerShell specific path escaping + /// `PowerShell` specific path escaping fn sprint_pwsh(&self) -> io::Result { self.str_path() .map(|s| s.replace('\'', "''")) diff --git a/src/module.rs b/src/module.rs index 0f2d01a8..84eca7ad 100644 --- a/src/module.rs +++ b/src/module.rs @@ -1,4 +1,5 @@ use crate::context::Shell; +use crate::segment; use crate::segment::{FillSegment, Segment}; use crate::utils::wrap_colorseq_for_shell; use ansi_term::{ANSIString, ANSIStrings}; @@ -139,13 +140,10 @@ impl<'a> Module<'a> { /// Get values of the module's segments pub fn get_segments(&self) -> Vec<&str> { - self.segments - .iter() - .map(|segment| segment.value()) - .collect() + self.segments.iter().map(segment::Segment::value).collect() } - /// Returns a vector of colored ANSIString elements to be later used with + /// Returns a vector of colored `ANSIString` elements to be later used with /// `ANSIStrings()` to optimize ANSI codes pub fn ansi_strings(&self) -> Vec { self.ansi_strings_for_shell(Shell::Unknown, None) diff --git a/src/modules/aws.rs b/src/modules/aws.rs index 3abf5621..a6a3b4a2 100644 --- a/src/modules/aws.rs +++ b/src/modules/aws.rs @@ -89,7 +89,7 @@ fn get_aws_region_from_config( let config = get_config(context, aws_config)?; let section = get_profile_config(config, aws_profile)?; - section.get("region").map(|region| region.to_owned()) + section.get("region").map(std::borrow::ToOwned::to_owned) } fn get_aws_profile_and_region( diff --git a/src/modules/c.rs b/src/modules/c.rs index 49113bd1..960acdd2 100644 --- a/src/modules/c.rs +++ b/src/modules/c.rs @@ -65,12 +65,9 @@ pub fn module<'a>(context: &'a Context) -> Option> { // so again we always want the first semver-ish word. VersionFormatter::format_module_version( module.get_name(), - c_compiler_info.split_whitespace().find_map( - |word| match Version::parse(word) { - Ok(_v) => Some(word), - Err(_e) => None, - }, - )?, + c_compiler_info + .split_whitespace() + .find(|word| Version::parse(word).is_ok())?, config.version_format, ) .map(Cow::Owned) diff --git a/src/modules/cmake.rs b/src/modules/cmake.rs index 11ad27bd..60ae3de2 100644 --- a/src/modules/cmake.rs +++ b/src/modules/cmake.rs @@ -4,7 +4,7 @@ use crate::formatter::VersionFormatter; use crate::configs::cmake::CMakeConfig; use crate::formatter::StringFormatter; -/// Creates a module with the current CMake version +/// Creates a module with the current `CMake` version pub fn module<'a>(context: &'a Context) -> Option> { let mut module = context.new_module("cmake"); let config = CMakeConfig::try_load(module.config); diff --git a/src/modules/custom.rs b/src/modules/custom.rs index f8b36567..f9971958 100644 --- a/src/modules/custom.rs +++ b/src/modules/custom.rs @@ -92,7 +92,7 @@ pub fn module<'a>(name: &str, context: &'a Context) -> Option> { Some(module) } -/// Return the invoking shell, using `shell` and fallbacking in order to STARSHIP_SHELL and "sh"/"cmd" +/// Return the invoking shell, using `shell` and fallbacking in order to `STARSHIP_SHELL` and "sh"/"cmd" fn get_shell<'a, 'b>( shell_args: &'b [&'a str], context: &Context, @@ -235,7 +235,7 @@ fn exec_command(cmd: &str, context: &Context, config: &CustomConfig) -> Option bool { @@ -289,7 +289,10 @@ mod tests { fn render_cmd(cmd: &str) -> io::Result> { let dir = tempfile::tempdir()?; let cmd = cmd.to_owned(); - let shell = SHELL.iter().map(|s| s.to_owned()).collect::>(); + let shell = SHELL + .iter() + .map(std::borrow::ToOwned::to_owned) + .collect::>(); let out = ModuleRenderer::new("custom.test") .path(dir.path()) .config(toml::toml! { @@ -308,7 +311,10 @@ mod tests { fn render_when(cmd: &str) -> io::Result { let dir = tempfile::tempdir()?; let cmd = cmd.to_owned(); - let shell = SHELL.iter().map(|s| s.to_owned()).collect::>(); + let shell = SHELL + .iter() + .map(std::borrow::ToOwned::to_owned) + .collect::>(); let out = ModuleRenderer::new("custom.test") .path(dir.path()) .config(toml::toml! { @@ -593,7 +599,7 @@ mod tests { let actual = ModuleRenderer::new("custom.test") .path(dir.path()) .config(toml::toml! { - command_timeout = 100000 + command_timeout = 100_000 [custom.test] format = "test" when = when diff --git a/src/modules/directory.rs b/src/modules/directory.rs index 53e9e73e..873dfde9 100644 --- a/src/modules/directory.rs +++ b/src/modules/directory.rs @@ -22,7 +22,7 @@ use crate::formatter::StringFormatter; /// /// **Contraction** /// - Paths beginning with the home directory or with a git repo right inside -/// the home directory will be contracted to `~`, or the set HOME_SYMBOL +/// the home directory will be contracted to `~`, or the set `HOME_SYMBOL` /// - Paths containing a git repo will contract to begin at the repo root /// /// **Substitution** diff --git a/src/modules/docker_context.rs b/src/modules/docker_context.rs index 1237565f..c1a4dc69 100644 --- a/src/modules/docker_context.rs +++ b/src/modules/docker_context.rs @@ -9,15 +9,15 @@ use crate::utils; /// Creates a module with the currently active Docker context /// /// Will display the Docker context if the following criteria are met: -/// - There is a non-empty environment variable named DOCKER_HOST -/// - Or there is a non-empty environment variable named DOCKER_CONTEXT +/// - There is a non-empty environment variable named `DOCKER_HOST` +/// - Or there is a non-empty environment variable named `DOCKER_CONTEXT` /// - Or there is a file named `$HOME/.docker/config.json` /// - Or a file named `$DOCKER_CONFIG/config.json` /// - The file is JSON and contains a field named `currentContext` /// - The value of `currentContext` is not `default` /// - If multiple criterias are met, we use the following order to define the docker context: -/// - DOCKER_HOST, DOCKER_CONTEXT, $HOME/.docker/config.json, $DOCKER_CONFIG/config.json -/// - (This is the same order docker follows, as DOCKER_HOST and DOCKER_CONTEXT override the +/// - `DOCKER_HOST`, `DOCKER_CONTEXT`, $HOME/.docker/config.json, $`DOCKER_CONFIG/config.json` +/// - (This is the same order docker follows, as `DOCKER_HOST` and `DOCKER_CONTEXT` override the /// config) pub fn module<'a>(context: &'a Context) -> Option> { let mut module = context.new_module("docker_context"); diff --git a/src/modules/dotnet.rs b/src/modules/dotnet.rs index 51a3440b..76c7d8a5 100644 --- a/src/modules/dotnet.rs +++ b/src/modules/dotnet.rs @@ -264,7 +264,7 @@ fn get_local_dotnet_files(context: &Context) -> Result, std::io: fn get_dotnet_file_type(path: &Path) -> Option { let file_name_lower = map_str_to_lower(path.file_name()); - match file_name_lower.as_ref().map(|f| f.as_ref()) { + match file_name_lower.as_ref().map(std::convert::AsRef::as_ref) { Some(GLOBAL_JSON_FILE) => return Some(FileType::GlobalJson), Some(PROJECT_JSON_FILE) => return Some(FileType::ProjectJson), _ => (), @@ -272,7 +272,7 @@ fn get_dotnet_file_type(path: &Path) -> Option { let extension_lower = map_str_to_lower(path.extension()); - match extension_lower.as_ref().map(|f| f.as_ref()) { + match extension_lower.as_ref().map(std::convert::AsRef::as_ref) { Some("sln") => return Some(FileType::SolutionFile), Some("csproj" | "fsproj" | "xproj") => return Some(FileType::ProjectFile), Some("props" | "targets") => return Some(FileType::MsBuildFile), diff --git a/src/modules/env_var.rs b/src/modules/env_var.rs index 85ff8d0d..c2cf828c 100644 --- a/src/modules/env_var.rs +++ b/src/modules/env_var.rs @@ -5,7 +5,7 @@ use crate::configs::env_var::EnvVarConfig; use crate::formatter::StringFormatter; use crate::segment::Segment; -/// Creates env_var_module displayer which displays all configured environmental variables +/// Creates `env_var_module` displayer which displays all configured environmental variables pub fn module<'a>(context: &'a Context) -> Option> { let config_table = context.config.get_env_var_modules()?; let mut env_modules = config_table @@ -22,7 +22,7 @@ pub fn module<'a>(context: &'a Context) -> Option> { Some(env_var_displayer(env_modules, context)) } -/// A utility module to display multiple env_variable modules +/// A utility module to display multiple `env_variable` modules fn env_var_displayer<'a>(modules: Vec, context: &'a Context) -> Module<'a> { let mut module = context.new_module("env_var_displayer"); @@ -37,9 +37,9 @@ fn env_var_displayer<'a>(modules: Vec, context: &'a Context) -> Module<' /// Creates a module with the value of the chosen environment variable /// /// Will display the environment variable's value if all of the following criteria are met: -/// - env_var.disabled is absent or false -/// - env_var.variable is defined -/// - a variable named as the value of env_var.variable is defined +/// - `env_var.disabled` is absent or false +/// - `env_var.variable` is defined +/// - a variable named as the value of `env_var.variable` is defined fn env_var_module<'a>(module_config_path: Vec<&str>, context: &'a Context) -> Option> { let mut module = context.new_module(&module_config_path.join(".")); let config_value = context.config.get_config(&module_config_path); diff --git a/src/modules/gcloud.rs b/src/modules/gcloud.rs index 9b5b3a30..37f39f5d 100644 --- a/src/modules/gcloud.rs +++ b/src/modules/gcloud.rs @@ -121,8 +121,7 @@ pub fn module<'a>(context: &'a Context) -> Option> { .project_aliases .get(project.as_ref()) .copied() - .map(Cow::Borrowed) - .unwrap_or(project) + .map_or(project, Cow::Borrowed) }) .map(Ok), "active" => Some(Ok(Cow::Borrowed(&gcloud_context.config_name))), diff --git a/src/modules/git_commit.rs b/src/modules/git_commit.rs index 71ae94f1..e536ff3f 100644 --- a/src/modules/git_commit.rs +++ b/src/modules/git_commit.rs @@ -93,8 +93,7 @@ fn id_to_hex_abbrev(bytes: &[u8], len: usize) -> String { bytes .iter() .map(|b| format!("{:02x}", b)) - .collect::>() - .join("") + .collect::() .chars() .take(len) .collect() diff --git a/src/modules/hostname.rs b/src/modules/hostname.rs index d1a2d97f..3621dc32 100644 --- a/src/modules/hostname.rs +++ b/src/modules/hostname.rs @@ -9,7 +9,7 @@ use crate::formatter::StringFormatter; /// /// Will display the hostname if all of the following criteria are met: /// - hostname.disabled is absent or false -/// - hostname.ssh_only is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`) +/// - `hostname.ssh_only` is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`) pub fn module<'a>(context: &'a Context) -> Option> { let mut module = context.new_module("hostname"); let config: HostnameConfig = HostnameConfig::try_load(module.config); diff --git a/src/modules/localip.rs b/src/modules/localip.rs index db05df6c..47d899ba 100644 --- a/src/modules/localip.rs +++ b/src/modules/localip.rs @@ -12,7 +12,7 @@ use crate::formatter::StringFormatter; /// /// Will display the ip if all of the following criteria are met: /// - localip.disabled is false -/// - localip.ssh_only is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`) +/// - `localip.ssh_only` is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`) pub fn module<'a>(context: &'a Context) -> Option> { let mut module = context.new_module("localip"); let config: LocalipConfig = LocalipConfig::try_load(module.config); diff --git a/src/modules/nix_shell.rs b/src/modules/nix_shell.rs index 77222d64..3b006558 100644 --- a/src/modules/nix_shell.rs +++ b/src/modules/nix_shell.rs @@ -9,8 +9,8 @@ use crate::formatter::StringFormatter; /// determine if it's inside a nix-shell and the name of it. /// /// The following options are availables: -/// - impure_msg (string) // change the impure msg -/// - pure_msg (string) // change the pure msg +/// - `impure_msg` (string) // change the impure msg +/// - `pure_msg` (string) // change the pure msg /// /// Will display the following: /// - pure (name) // $name == "name" in a pure nix-shell diff --git a/src/modules/pulumi.rs b/src/modules/pulumi.rs index b1ed6d23..f523566d 100644 --- a/src/modules/pulumi.rs +++ b/src/modules/pulumi.rs @@ -276,7 +276,7 @@ mod tests { yaml.sync_all()?; let workspace_path = root.join(".pulumi").join("workspaces"); - let _ = std::fs::create_dir_all(&workspace_path)?; + std::fs::create_dir_all(&workspace_path)?; let workspace_path = &workspace_path.join("starship-test-workspace.json"); let mut workspace = File::create(&workspace_path)?; serde_json::to_writer_pretty( @@ -290,7 +290,7 @@ mod tests { workspace.sync_all()?; let credential_path = root.join(".pulumi"); - let _ = std::fs::create_dir_all(&credential_path)?; + std::fs::create_dir_all(&credential_path)?; let credential_path = &credential_path.join("credentials.json"); let mut credential = File::create(&credential_path)?; serde_json::to_writer_pretty( @@ -343,7 +343,7 @@ mod tests { yaml.sync_all()?; let workspace_path = root.join(".pulumi").join("workspaces"); - let _ = std::fs::create_dir_all(&workspace_path)?; + std::fs::create_dir_all(&workspace_path)?; let workspace_path = &workspace_path.join("starship-test-workspace.json"); let mut workspace = File::create(&workspace_path)?; serde_json::to_writer_pretty( @@ -357,7 +357,7 @@ mod tests { workspace.sync_all()?; let credential_path = root.join(".pulumi"); - let _ = std::fs::create_dir_all(&credential_path)?; + std::fs::create_dir_all(&credential_path)?; let credential_path = &credential_path.join("starship-test-credential.json"); let mut credential = File::create(&credential_path)?; serde_json::to_writer_pretty( diff --git a/src/modules/rust.rs b/src/modules/rust.rs index 5ccc54af..1e46050a 100644 --- a/src/modules/rust.rs +++ b/src/modules/rust.rs @@ -83,7 +83,7 @@ impl RustToolingEnvironmentInfo { } /// Gets the output of running `rustup rustc --version` with a toolchain - /// specified by self.get_env_toolchain_override() + /// specified by `self.get_env_toolchain_override()` fn get_rustup_rustc_version(&self, context: &Context) -> &RustupRunRustcVersionOutcome { self.rustup_rustc_output.get_or_init(|| { let out = if let Some(toolchain) = self.get_env_toolchain_override(context) { @@ -377,8 +377,9 @@ fn format_rustc_version(rustc_version: &str, version_format: &str) -> Option) -> String { default_host_triple - .map(|triple| toolchain.trim_end_matches(&format!("-{}", triple))) - .unwrap_or(toolchain) + .map_or(toolchain, |triple| { + toolchain.trim_end_matches(&format!("-{}", triple)) + }) .to_owned() } @@ -394,17 +395,12 @@ fn format_rustc_version_verbose(stdout: &str, toolchain: Option<&str>) -> Option } let (release, host) = (release?, host?); let version = format_semver(release); - let toolchain = toolchain - .map(ToOwned::to_owned) - .unwrap_or_else(|| host.to_string()); + let toolchain = toolchain.map_or_else(|| host.to_string(), ToOwned::to_owned); Some((version, toolchain)) } fn format_semver(semver: &str) -> String { - format!( - "v{}", - semver.find('-').map(|i| &semver[..i]).unwrap_or(semver) - ) + format!("v{}", semver.find('-').map_or(semver, |i| &semver[..i])) } #[derive(Debug, PartialEq)] @@ -470,10 +466,10 @@ impl RustupSettings { let cwd = strip_dos_path(cwd.to_owned()); self.overrides .iter() - .map(|(dir, toolchain)| (strip_dos_path(dir.to_owned()), toolchain)) + .map(|(dir, toolchain)| (strip_dos_path(dir.clone()), toolchain)) .filter(|(dir, _)| cwd.starts_with(dir)) .max_by_key(|(dir, _)| dir.components().count()) - .map(|(_, name)| name.to_owned()) + .map(|(_, name)| name.clone()) } } diff --git a/src/modules/status.rs b/src/modules/status.rs index 0566db6b..e1c7e8cb 100644 --- a/src/modules/status.rs +++ b/src/modules/status.rs @@ -63,8 +63,7 @@ pub fn module<'a>(context: &'a Context) -> Option> { Ok(segments) => segments .into_iter() .map(|s| s.to_string()) - .collect::>() - .join(""), + .collect::(), Err(_) => "".to_string(), }, ) @@ -330,7 +329,7 @@ mod tests { #[test] fn failure_hex_status() { - let exit_values = [1, 2, 130, -2147467260, 2147500036]; + let exit_values = [1, 2, 130, -2_147_467_260, 2_147_500_036]; let string_values = ["0x1", "0x2", "0x82", "0x80004004", "0x80004004"]; for (exit_value, string_value) in exit_values.iter().zip(string_values) { diff --git a/src/modules/time.rs b/src/modules/time.rs index f66d1825..16258974 100644 --- a/src/modules/time.rs +++ b/src/modules/time.rs @@ -102,9 +102,9 @@ fn format_time_fixed_offset(time_format: &str, utc_time: DateTime) utc_time.format(time_format).to_string() } -/// Returns true if time_now is between time_start and time_end. +/// Returns true if `time_now` is between `time_start` and `time_end`. /// If one of these values is not given, then it is ignored. -/// It also handles cases where time_start and time_end have a midnight in between +/// It also handles cases where `time_start` and `time_end` have a midnight in between fn is_inside_time_range( time_now: NaiveTime, time_start: Option, @@ -124,8 +124,8 @@ fn is_inside_time_range( } } -/// Parses the config's time_range field and returns the starting time and ending time. -/// The range is in the format START_TIME-END_TIME, with START_TIME and END_TIME being optional. +/// Parses the config's `time_range` field and returns the starting time and ending time. +/// The range is in the format START_TIME-END_TIME, with `START_TIME` and `END_TIME` being optional. /// /// If one of the ranges is invalid or not provided, then the corresponding field in the output /// tuple is None @@ -327,8 +327,7 @@ mod tests { let utc_time_offset_str = "+24"; create_offset_time_string(utc_time, utc_time_offset_str, FMT_12) - .err() - .expect("Invalid timezone offset."); + .expect_err("Invalid timezone offset."); } #[test] @@ -337,8 +336,7 @@ mod tests { let utc_time_offset_str = "-24"; create_offset_time_string(utc_time, utc_time_offset_str, FMT_12) - .err() - .expect("Invalid timezone offset."); + .expect_err("Invalid timezone offset."); } #[test] @@ -347,8 +345,7 @@ mod tests { let utc_time_offset_str = "+9001"; create_offset_time_string(utc_time, utc_time_offset_str, FMT_12) - .err() - .expect("Invalid timezone offset."); + .expect_err("Invalid timezone offset."); } #[test] @@ -357,8 +354,7 @@ mod tests { let utc_time_offset_str = "-4242"; create_offset_time_string(utc_time, utc_time_offset_str, FMT_12) - .err() - .expect("Invalid timezone offset."); + .expect_err("Invalid timezone offset."); } #[test] @@ -367,8 +363,7 @@ mod tests { let utc_time_offset_str = "completely wrong config"; create_offset_time_string(utc_time, utc_time_offset_str, FMT_12) - .err() - .expect("Invalid timezone offset."); + .expect_err("Invalid timezone offset."); } #[test] diff --git a/src/modules/utils/directory_win.rs b/src/modules/utils/directory_win.rs index f7de2a85..eeeb422e 100644 --- a/src/modules/utils/directory_win.rs +++ b/src/modules/utils/directory_win.rs @@ -1,4 +1,4 @@ -use std::{ffi::c_void, mem, os::windows::ffi::OsStrExt, path::Path}; +use std::{mem, os::windows::ffi::OsStrExt, path::Path}; use windows::{ core::PCWSTR, @@ -53,7 +53,7 @@ pub fn is_write_allowed(folder_path: &Path) -> std::result::Result } let mut buf = vec![0u8; length as usize]; - let psecurity_descriptor = PSECURITY_DESCRIPTOR(buf.as_mut_ptr() as *mut c_void); + let psecurity_descriptor = PSECURITY_DESCRIPTOR(buf.as_mut_ptr().cast::()); let rc = unsafe { GetFileSecurityW( diff --git a/src/print.rs b/src/print.rs index e624bd5d..0281fce4 100644 --- a/src/print.rs +++ b/src/print.rs @@ -125,7 +125,7 @@ pub fn get_prompt(context: Context) -> String { } // escape \n and ! characters for tcsh - if let Shell::Tcsh = context.shell { + if context.shell == Shell::Tcsh { buf = buf.replace('!', "\\!"); // space is required before newline buf = buf.replace('\n', " \\n"); diff --git a/src/segment.rs b/src/segment.rs index 643298c2..cab7835d 100644 --- a/src/segment.rs +++ b/src/segment.rs @@ -77,7 +77,7 @@ mod fill_seg_tests { ("🟢🔵🟡", "🟢🔵🟡🟢🔵"), ]; - for (text, expected) in inputs.iter() { + for (text, expected) in &inputs { let f = FillSegment { value: String::from(*text), style: Some(style), @@ -97,17 +97,17 @@ pub enum Segment { } impl Segment { - /// Creates new segments from a text with a style; breaking out LineTerminators. - pub fn from_text(style: Option