Skip to content

Commit

Permalink
chore(clippy): fix new lints (starship#4002)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkna authored May 23, 2022
1 parent a0a6c94 commit 0ae61c7
Show file tree
Hide file tree
Showing 32 changed files with 114 additions and 124 deletions.
2 changes: 1 addition & 1 deletion .github/config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
18 changes: 9 additions & 9 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, ValueError> {
let deserializer = ValueDeserializer::new(config);
T::deserialize(deserializer)
Expand Down Expand Up @@ -72,8 +72,8 @@ where
{
let either = Either::<Vec<T>, 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])),
}
}
}
Expand Down Expand Up @@ -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()
}
Expand All @@ -268,7 +268,7 @@ where
- 'bold'
- 'italic'
- 'inverted'
- '<color>' (see the parse_color_string doc for valid color strings)
- '<color>' (see the `parse_color_string` doc for valid color strings)
*/
pub fn parse_style_string(style_string: &str) -> Option<ansi_term::Style> {
style_string
Expand Down Expand Up @@ -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),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/configs/aws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
2 changes: 1 addition & 1 deletion src/configs/starship_root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
5 changes: 2 additions & 3 deletions src/configure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<&str>>) -> Option<CommandOutput> {
commands
.iter()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(),
Expand Down
4 changes: 2 additions & 2 deletions src/formatter/string_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, StringFormatterError> {
Expand All @@ -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())],
Expand Down
7 changes: 4 additions & 3 deletions src/formatter/version.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<Self, StringFormatterError> {
let formatter = StringFormatter::new(format)?;
Expand Down Expand Up @@ -56,7 +57,7 @@ impl<'a> VersionFormatter<'a> {
formatted.map(|segments| {
segments
.iter()
.map(|segment| segment.value())
.map(segment::Segment::value)
.collect::<String>()
})
}
Expand Down
2 changes: 1 addition & 1 deletion src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
self.str_path()
.map(|s| s.replace('\'', "''"))
Expand Down
8 changes: 3 additions & 5 deletions src/module.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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<ANSIString> {
self.ansi_strings_for_shell(Shell::Unknown, None)
Expand Down
2 changes: 1 addition & 1 deletion src/modules/aws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 3 additions & 6 deletions src/modules/c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,9 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
// 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)
Expand Down
2 changes: 1 addition & 1 deletion src/modules/cmake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Module<'a>> {
let mut module = context.new_module("cmake");
let config = CMakeConfig::try_load(module.config);
Expand Down
16 changes: 11 additions & 5 deletions src/modules/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ pub fn module<'a>(name: &str, context: &'a Context) -> Option<Module<'a>> {
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,
Expand Down Expand Up @@ -235,7 +235,7 @@ fn exec_command(cmd: &str, context: &Context, config: &CustomConfig) -> Option<S
}
}

/// If the specified shell refers to PowerShell, adds the arguments "-Command -" to the
/// If the specified shell refers to `PowerShell`, adds the arguments "-Command -" to the
/// given command.
/// Retruns `false` if the shell shell expects scripts as arguments, `true` if as `stdin`.
fn handle_shell(command: &mut Command, shell: &str, shell_args: &[&str]) -> bool {
Expand Down Expand Up @@ -289,7 +289,10 @@ mod tests {
fn render_cmd(cmd: &str) -> io::Result<Option<String>> {
let dir = tempfile::tempdir()?;
let cmd = cmd.to_owned();
let shell = SHELL.iter().map(|s| s.to_owned()).collect::<Vec<_>>();
let shell = SHELL
.iter()
.map(std::borrow::ToOwned::to_owned)
.collect::<Vec<_>>();
let out = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
Expand All @@ -308,7 +311,10 @@ mod tests {
fn render_when(cmd: &str) -> io::Result<bool> {
let dir = tempfile::tempdir()?;
let cmd = cmd.to_owned();
let shell = SHELL.iter().map(|s| s.to_owned()).collect::<Vec<_>>();
let shell = SHELL
.iter()
.map(std::borrow::ToOwned::to_owned)
.collect::<Vec<_>>();
let out = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/modules/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
8 changes: 4 additions & 4 deletions src/modules/docker_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Module<'a>> {
let mut module = context.new_module("docker_context");
Expand Down
4 changes: 2 additions & 2 deletions src/modules/dotnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,15 +264,15 @@ fn get_local_dotnet_files(context: &Context) -> Result<Vec<DotNetFile>, std::io:
fn get_dotnet_file_type(path: &Path) -> Option<FileType> {
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),
_ => (),
};

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),
Expand Down
10 changes: 5 additions & 5 deletions src/modules/env_var.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Module<'a>> {
let config_table = context.config.get_env_var_modules()?;
let mut env_modules = config_table
Expand All @@ -22,7 +22,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
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<Module>, context: &'a Context) -> Module<'a> {
let mut module = context.new_module("env_var_displayer");

Expand All @@ -37,9 +37,9 @@ fn env_var_displayer<'a>(modules: Vec<Module>, 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<Module<'a>> {
let mut module = context.new_module(&module_config_path.join("."));
let config_value = context.config.get_config(&module_config_path);
Expand Down
3 changes: 1 addition & 2 deletions src/modules/gcloud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
.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))),
Expand Down
3 changes: 1 addition & 2 deletions src/modules/git_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ fn id_to_hex_abbrev(bytes: &[u8], len: usize) -> String {
bytes
.iter()
.map(|b| format!("{:02x}", b))
.collect::<Vec<String>>()
.join("")
.collect::<String>()
.chars()
.take(len)
.collect()
Expand Down
Loading

0 comments on commit 0ae61c7

Please sign in to comment.