1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-12-01 01:04:00 +00:00

chore(clippy): fix new lints (#4002)

This commit is contained in:
David Knaack 2022-05-23 12:58:27 +02:00 committed by GitHub
parent a0a6c942fe
commit 0ae61c7758
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 114 additions and 124 deletions

View File

@ -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": {

View File

@ -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)
@ -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])),
}
}
}
@ -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'
- '<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
@ -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),
}
}
}

View File

@ -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> {

View File

@ -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(),

View File

@ -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 {

View File

@ -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()
@ -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(),

View File

@ -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> {
@ -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())],

View File

@ -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<Self, StringFormatterError> {
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::<String>()
})
}

View File

@ -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('\'', "''"))

View File

@ -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<ANSIString> {
self.ansi_strings_for_shell(Shell::Unknown, None)

View File

@ -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(

View File

@ -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)

View File

@ -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);

View File

@ -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,
@ -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 {
@ -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! {
@ -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! {
@ -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

View File

@ -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**

View File

@ -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");

View File

@ -264,7 +264,7 @@ 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),
_ => (),
@ -272,7 +272,7 @@ fn get_dotnet_file_type(path: &Path) -> Option<FileType> {
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),

View File

@ -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
@ -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");
@ -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);

View File

@ -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))),

View File

@ -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()

View File

@ -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<Module<'a>> {
let mut module = context.new_module("hostname");
let config: HostnameConfig = HostnameConfig::try_load(module.config);

View File

@ -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<Module<'a>> {
let mut module = context.new_module("localip");
let config: LocalipConfig = LocalipConfig::try_load(module.config);

View File

@ -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

View File

@ -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(

View File

@ -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<Str
fn format_toolchain(toolchain: &str, default_host_triple: Option<&str>) -> 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())
}
}

View File

@ -63,8 +63,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
Ok(segments) => segments
.into_iter()
.map(|s| s.to_string())
.collect::<Vec<String>>()
.join(""),
.collect::<String>(),
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) {

View File

@ -102,9 +102,9 @@ fn format_time_fixed_offset(time_format: &str, utc_time: DateTime<FixedOffset>)
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<NaiveTime>,
@ -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]

View File

@ -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<bool, String>
}
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::<std::ffi::c_void>());
let rc = unsafe {
GetFileSecurityW(

View File

@ -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");

View File

@ -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<T>(style: Option<Style>, value: T) -> Vec<Segment>
/// Creates new segments from a text with a style; breaking out `LineTerminators`.
pub fn from_text<T>(style: Option<Style>, value: T) -> Vec<Self>
where
T: Into<String>,
{
let mut segs: Vec<Segment> = Vec::new();
let mut segs: Vec<Self> = Vec::new();
value.into().split(LINE_TERMINATOR).for_each(|s| {
if !segs.is_empty() {
segs.push(Segment::LineTerm)
segs.push(Self::LineTerm)
}
segs.push(Segment::Text(TextSegment {
segs.push(Self::Text(TextSegment {
value: String::from(s),
style,
}))
@ -120,7 +120,7 @@ impl Segment {
where
T: Into<String>,
{
Segment::Fill(FillSegment {
Self::Fill(FillSegment {
style,
value: value.into(),
})
@ -128,50 +128,50 @@ impl Segment {
pub fn style(&self) -> Option<Style> {
match self {
Segment::Fill(fs) => fs.style,
Segment::Text(ts) => ts.style,
Segment::LineTerm => None,
Self::Fill(fs) => fs.style,
Self::Text(ts) => ts.style,
Self::LineTerm => None,
}
}
pub fn set_style_if_empty(&mut self, style: Option<Style>) {
match self {
Segment::Fill(fs) => {
Self::Fill(fs) => {
if fs.style.is_none() {
fs.style = style
}
}
Segment::Text(ts) => {
Self::Text(ts) => {
if ts.style.is_none() {
ts.style = style
}
}
Segment::LineTerm => {}
Self::LineTerm => {}
}
}
pub fn value(&self) -> &str {
match self {
Segment::Fill(fs) => &fs.value,
Segment::Text(ts) => &ts.value,
Segment::LineTerm => LINE_TERMINATOR_STRING,
Self::Fill(fs) => &fs.value,
Self::Text(ts) => &ts.value,
Self::LineTerm => LINE_TERMINATOR_STRING,
}
}
// Returns the ANSIString of the segment value, not including its prefix and suffix
pub fn ansi_string(&self) -> ANSIString {
match self {
Segment::Fill(fs) => fs.ansi_string(None),
Segment::Text(ts) => ts.ansi_string(),
Segment::LineTerm => ANSIString::from(LINE_TERMINATOR_STRING),
Self::Fill(fs) => fs.ansi_string(None),
Self::Text(ts) => ts.ansi_string(),
Self::LineTerm => ANSIString::from(LINE_TERMINATOR_STRING),
}
}
pub fn width_graphemes(&self) -> usize {
match self {
Segment::Fill(fs) => fs.value.width_graphemes(),
Segment::Text(ts) => ts.value.width_graphemes(),
Segment::LineTerm => 0,
Self::Fill(fs) => fs.value.width_graphemes(),
Self::Text(ts) => ts.value.width_graphemes(),
Self::LineTerm => 0,
}
}
}

View File

@ -51,7 +51,7 @@ pub struct ModuleRenderer<'a> {
}
impl<'a> ModuleRenderer<'a> {
/// Creates a new ModuleRenderer
/// Creates a new `ModuleRenderer`
pub fn new(name: &'a str) -> Self {
// Start logger
Lazy::force(&LOGGER);
@ -91,13 +91,13 @@ impl<'a> ModuleRenderer<'a> {
self
}
/// Adds the variable to the env_mocks of the underlying context
/// Adds the variable to the `env_mocks` of the underlying context
pub fn env<V: Into<String>>(mut self, key: &'a str, val: V) -> Self {
self.context.env.insert(key, val.into());
self
}
/// Adds the command to the commandv_mocks of the underlying context
/// Adds the command to the `command_mocks` of the underlying context
pub fn cmd(mut self, key: &'a str, val: Option<CommandOutput>) -> Self {
self.context.cmd.insert(key, val);
self
@ -161,6 +161,7 @@ impl<'a> ModuleRenderer<'a> {
}
}
#[derive(Clone, Copy)]
pub enum FixtureProvider {
Git,
Hg,

View File

@ -102,7 +102,7 @@ pub fn display_command<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
args: &[U],
) -> String {
std::iter::once(cmd.as_ref())
.chain(args.iter().map(|i| i.as_ref()))
.chain(args.iter().map(std::convert::AsRef::as_ref))
.map(|i| i.to_string_lossy().into_owned())
.collect::<Vec<String>>()
.join(" ")