fix(clippy): fix new clippy lints (#2939)

This commit is contained in:
David Knaack 2021-07-29 20:27:46 +02:00 committed by GitHub
parent e34feee49b
commit af43aeefba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 253 additions and 252 deletions

View File

@ -15,7 +15,7 @@ pub fn create() {
let environment = Environment { let environment = Environment {
os_type: os_info.os_type(), os_type: os_info.os_type(),
os_version: os_info.version().to_owned(), os_version: os_info.version().clone(),
shell_info: get_shell_info(), shell_info: get_shell_info(),
terminal_info: get_terminal_info(), terminal_info: get_terminal_info(),
starship_config: get_starship_config(), starship_config: get_starship_config(),
@ -151,14 +151,17 @@ fn get_shell_info() -> ShellInfo {
let shell = shell.unwrap(); let shell = shell.unwrap();
let version = exec_cmd(&shell, &["--version"], Duration::from_millis(500)) let version = exec_cmd(&shell, &["--version"], Duration::from_millis(500)).map_or_else(
.map(|output| output.stdout.trim().to_string()) || UNKNOWN_VERSION.to_string(),
.unwrap_or_else(|| UNKNOWN_VERSION.to_string()); |output| output.stdout.trim().to_string(),
);
let config = get_config_path(&shell) let config = get_config_path(&shell)
.and_then(|config_path| fs::read_to_string(config_path).ok()) .and_then(|config_path| fs::read_to_string(config_path).ok())
.map(|config| config.trim().to_string()) .map_or_else(
.unwrap_or_else(|| UNKNOWN_CONFIG.to_string()); || UNKNOWN_CONFIG.to_string(),
|config| config.trim().to_string(),
);
ShellInfo { ShellInfo {
name: shell, name: shell,

View File

@ -87,12 +87,12 @@ impl<'a> ModuleConfig<'a> for u64 {
Value::Integer(value) => { Value::Integer(value) => {
// Converting i64 to u64 // Converting i64 to u64
if *value > 0 { if *value > 0 {
Some(*value as u64) Some(*value as Self)
} else { } else {
None None
} }
} }
Value::String(value) => value.parse::<u64>().ok(), Value::String(value) => value.parse::<Self>().ok(),
_ => None, _ => None,
} }
} }
@ -109,12 +109,12 @@ impl<'a> ModuleConfig<'a> for usize {
match config { match config {
Value::Integer(value) => { Value::Integer(value) => {
if *value > 0 { if *value > 0 {
Some(*value as usize) Some(*value as Self)
} else { } else {
None None
} }
} }
Value::String(value) => value.parse::<usize>().ok(), Value::String(value) => value.parse::<Self>().ok(),
_ => None, _ => None,
} }
} }
@ -139,7 +139,7 @@ where
S: Clone, S: Clone,
{ {
fn from_config(config: &'a Value) -> Option<Self> { fn from_config(config: &'a Value) -> Option<Self> {
let mut hm = HashMap::default(); let mut hm = Self::default();
for (x, y) in config.as_table()?.iter() { for (x, y) in config.as_table()?.iter() {
hm.insert(x.clone(), T::from_config(y)?); hm.insert(x.clone(), T::from_config(y)?);
@ -155,7 +155,7 @@ where
S: Clone, S: Clone,
{ {
fn from_config(config: &'a Value) -> Option<Self> { fn from_config(config: &'a Value) -> Option<Self> {
let mut im = IndexMap::default(); let mut im = Self::default();
for (x, y) in config.as_table()?.iter() { for (x, y) in config.as_table()?.iter() {
im.insert(x.clone(), T::from_config(y)?); im.insert(x.clone(), T::from_config(y)?);
@ -185,7 +185,7 @@ where
{ {
fn from_config(config: &'a Value) -> Option<Self> { fn from_config(config: &'a Value) -> Option<Self> {
if let Some(item) = T::from_config(config) { if let Some(item) = T::from_config(config) {
return Some(VecOr(vec![item])); return Some(Self(vec![item]));
} }
let vec = config let vec = config
@ -194,7 +194,7 @@ where
.map(|value| T::from_config(value)) .map(|value| T::from_config(value))
.collect::<Option<Vec<T>>>()?; .collect::<Option<Vec<T>>>()?;
Some(VecOr(vec)) Some(Self(vec))
} }
} }
@ -207,11 +207,11 @@ impl StarshipConfig {
/// Initialize the Config struct /// Initialize the Config struct
pub fn initialize() -> Self { pub fn initialize() -> Self {
if let Some(file_data) = Self::config_from_file() { if let Some(file_data) = Self::config_from_file() {
StarshipConfig { Self {
config: Some(file_data), config: Some(file_data),
} }
} else { } else {
StarshipConfig { Self {
config: Some(Value::Table(toml::value::Table::new())), config: Some(Value::Table(toml::value::Table::new())),
} }
} }

View File

@ -150,7 +150,9 @@ impl<'a> Context<'a> {
// Retrives a environment variable from the os or from a table if in testing mode // Retrives a environment variable from the os or from a table if in testing mode
#[cfg(test)] #[cfg(test)]
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> { pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
self.env.get(key.as_ref()).map(|val| val.to_string()) self.env
.get(key.as_ref())
.map(std::string::ToString::to_string)
} }
#[cfg(not(test))] #[cfg(not(test))]
@ -233,7 +235,7 @@ impl<'a> Context<'a> {
let root = repository let root = repository
.as_ref() .as_ref()
.and_then(|repo| repo.workdir().map(Path::to_path_buf)); .and_then(|repo| repo.workdir().map(Path::to_path_buf));
let state = repository.as_ref().map(|repo| repo.state()); let state = repository.as_ref().map(git2::Repository::state);
let remote = repository let remote = repository
.as_ref() .as_ref()
.and_then(|repo| get_remote_repository_info(repo)); .and_then(|repo| get_remote_repository_info(repo));
@ -344,7 +346,7 @@ impl DirContents {
start.elapsed() start.elapsed()
); );
Ok(DirContents { Ok(Self {
files, files,
file_names, file_names,
folders, folders,
@ -459,7 +461,7 @@ fn get_current_branch(repository: &Repository) -> Option<String> {
.trim() .trim()
.split('/') .split('/')
.last() .last()
.map(|r| r.to_owned()) .map(std::borrow::ToOwned::to_owned)
} else { } else {
None None
}; };

View File

@ -39,8 +39,7 @@ fn parse_variable(variable: Pair<Rule>) -> &str {
fn parse_text(text: Pair<Rule>) -> String { fn parse_text(text: Pair<Rule>) -> String {
text.into_inner() text.into_inner()
.map(|pair| pair.as_str().chars()) .flat_map(|pair| pair.as_str().chars())
.flatten()
.collect() .collect()
} }

View File

@ -49,7 +49,7 @@ impl Error for StringFormatterError {}
impl From<String> for StringFormatterError { impl From<String> for StringFormatterError {
fn from(error: String) -> Self { fn from(error: String) -> Self {
StringFormatterError::Custom(error) Self::Custom(error)
} }
} }
@ -186,7 +186,7 @@ impl<'a> StringFormatter<'a> {
.par_iter_mut() .par_iter_mut()
.filter(|(_, value)| value.is_none()) .filter(|(_, value)| value.is_none())
.for_each(|(key, value)| { .for_each(|(key, value)| {
*value = mapper(key).map(|var| var.map(|var| var.into())); *value = mapper(key).map(|var| var.map(std::convert::Into::into));
}); });
self self
} }
@ -207,8 +207,8 @@ impl<'a> StringFormatter<'a> {
parse_format( parse_format(
textgroup.format, textgroup.format,
style.transpose()?, style.transpose()?,
&variables, variables,
&style_variables, style_variables,
) )
} }
@ -254,7 +254,7 @@ impl<'a> StringFormatter<'a> {
format: textgroup.format, format: textgroup.format,
style: textgroup.style, style: textgroup.style,
}; };
parse_textgroup(textgroup, &variables, &style_variables) parse_textgroup(textgroup, variables, style_variables)
} }
FormatElement::Variable(name) => variables FormatElement::Variable(name) => variables
.get(name.as_ref()) .get(name.as_ref())
@ -292,18 +292,21 @@ impl<'a> StringFormatter<'a> {
format_elements.get_variables().iter().any(|var| { format_elements.get_variables().iter().any(|var| {
variables variables
.get(var.as_ref()) .get(var.as_ref())
.map(|map_result| { // false if can't find the variable in format string
.map_or(false, |map_result| {
let map_result = map_result.as_ref(); let map_result = map_result.as_ref();
map_result map_result
.and_then(|result| result.as_ref().ok()) .and_then(|result| result.as_ref().ok())
.map(|result| match result { // false if the variable is None or Err, or a meta variable
// that shouldn't show
.map_or(false, |result| match result {
// If the variable is a meta variable, also // If the variable is a meta variable, also
// check the format string inside it. // check the format string inside it.
VariableValue::Meta(meta_elements) => { VariableValue::Meta(meta_elements) => {
let meta_variables = let meta_variables =
clone_without_meta(variables); clone_without_meta(variables);
should_show_elements( should_show_elements(
&meta_elements, meta_elements,
&meta_variables, &meta_variables,
) )
} }
@ -314,12 +317,7 @@ impl<'a> StringFormatter<'a> {
segments.iter().any(|x| !x.value.is_empty()) segments.iter().any(|x| !x.value.is_empty())
} }
}) })
// The variable is None or Err, or a meta variable
// that shouldn't show
.unwrap_or(false)
}) })
// Can't find the variable in format string
.unwrap_or(false)
}) })
} }

View File

@ -39,7 +39,7 @@ impl Default for StarshipLogger {
log_file_content: fs::read_to_string(&session_log_file) log_file_content: fs::read_to_string(&session_log_file)
.unwrap_or_default() .unwrap_or_default()
.lines() .lines()
.map(|line| line.to_string()) .map(std::string::ToString::to_string)
.collect(), .collect(),
log_file: OnceCell::new(), log_file: OnceCell::new(),
log_file_path: session_log_file, log_file_path: session_log_file,

View File

@ -44,9 +44,9 @@ fn get_aws_region_from_config(context: &Context, aws_profile: Option<&str>) -> O
let reader = BufReader::new(file); let reader = BufReader::new(file);
let lines = reader.lines().filter_map(Result::ok); let lines = reader.lines().filter_map(Result::ok);
let region_line = if let Some(ref aws_profile) = aws_profile { let region_line = if let Some(aws_profile) = aws_profile {
lines lines
.skip_while(|line| line != &format!("[profile {}]", aws_profile)) .skip_while(|line| line != &format!("[profile {}]", &aws_profile))
.skip(1) .skip(1)
.take_while(|line| !line.starts_with('[')) .take_while(|line| !line.starts_with('['))
.find(|line| line.starts_with("region")) .find(|line| line.starts_with("region"))
@ -76,7 +76,7 @@ fn get_aws_profile_and_region(context: &Context) -> (Option<Profile>, Option<Reg
(Some(p), Some(r)) => (Some(p), Some(r)), (Some(p), Some(r)) => (Some(p), Some(r)),
(None, Some(r)) => (None, Some(r)), (None, Some(r)) => (None, Some(r)),
(Some(ref p), None) => ( (Some(ref p), None) => (
Some(p.to_owned()), Some(p.clone()),
get_aws_region_from_config(context, Some(p)), get_aws_region_from_config(context, Some(p)),
), ),
(None, None) => (None, get_aws_region_from_config(context, None)), (None, None) => (None, get_aws_region_from_config(context, None)),

View File

@ -22,8 +22,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let config: CharacterConfig = CharacterConfig::try_load(module.config); let config: CharacterConfig = CharacterConfig::try_load(module.config);
let props = &context.properties; let props = &context.properties;
let exit_code = props.get("status_code").map(String::as_str).unwrap_or("0"); let exit_code = props.get("status_code").map_or("0", String::as_str);
let keymap = props.get("keymap").map(String::as_str).unwrap_or("viins"); let keymap = props.get("keymap").map_or("viins", String::as_str);
let exit_success = exit_code == "0"; let exit_success = exit_code == "0";
// Match shell "keymap" names to normalized vi modes // Match shell "keymap" names to normalized vi modes

View File

@ -58,12 +58,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let dir_string = repo let dir_string = repo
.and_then(|r| r.root.as_ref()) .and_then(|r| r.root.as_ref())
.filter(|root| *root != &home_dir) .filter(|root| *root != &home_dir)
.and_then(|root| contract_repo_path(&display_dir, root)); .and_then(|root| contract_repo_path(display_dir, root));
// Otherwise use the logical path, automatically contracting // Otherwise use the logical path, automatically contracting
// the home directory if required. // the home directory if required.
let dir_string = let dir_string =
dir_string.unwrap_or_else(|| contract_path(&display_dir, &home_dir, &home_symbol)); dir_string.unwrap_or_else(|| contract_path(display_dir, &home_dir, &home_symbol));
#[cfg(windows)] #[cfg(windows)]
let dir_string = remove_extended_path_prefix(dir_string); let dir_string = remove_extended_path_prefix(dir_string);
@ -79,7 +79,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
// fish-style path contraction together // fish-style path contraction together
if config.fish_style_pwd_dir_length > 0 && config.substitutions.is_empty() { if config.fish_style_pwd_dir_length > 0 && config.substitutions.is_empty() {
// If user is using fish style path, we need to add the segment first // If user is using fish style path, we need to add the segment first
let contracted_home_dir = contract_path(&display_dir, &home_dir, &home_symbol); let contracted_home_dir = contract_path(display_dir, &home_dir, &home_symbol);
to_fish_style( to_fish_style(
config.fish_style_pwd_dir_length as usize, config.fish_style_pwd_dir_length as usize,
contracted_home_dir, contracted_home_dir,
@ -105,7 +105,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
.map(|variable| match variable { .map(|variable| match variable {
"path" => Some(Ok(&displayed_path)), "path" => Some(Ok(&displayed_path)),
"read_only" => { "read_only" => {
if is_readonly_dir(&physical_dir) { if is_readonly_dir(physical_dir) {
Some(Ok(&lock_symbol)) Some(Ok(&lock_symbol))
} else { } else {
None None
@ -330,7 +330,7 @@ mod tests {
let repo_variations = [repo_dir.clone(), repo_dir.canonicalize().unwrap()]; let repo_variations = [repo_dir.clone(), repo_dir.canonicalize().unwrap()];
for src_dir in &src_variations { for src_dir in &src_variations {
for repo_dir in &repo_variations { for repo_dir in &repo_variations {
let output = contract_repo_path(&src_dir, &repo_dir); let output = contract_repo_path(src_dir, repo_dir);
assert_eq!(output, Some("rocket-controls/src".to_string())); assert_eq!(output, Some("rocket-controls/src".to_string()));
} }
} }
@ -494,7 +494,7 @@ mod tests {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?; let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("src/fuel-gauge"); let dir = tmp_dir.path().join("src/fuel-gauge");
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
init_repo(&tmp_dir.path())?; init_repo(tmp_dir.path())?;
let actual = ModuleRenderer::new("directory") let actual = ModuleRenderer::new("directory")
.config(toml::toml! { .config(toml::toml! {

View File

@ -175,7 +175,7 @@ fn estimate_dotnet_version(
/// - The root of the git repository /// - The root of the git repository
/// (If there is one) /// (If there is one)
fn try_find_nearby_global_json(current_dir: &Path, repo_root: Option<&Path>) -> Option<String> { fn try_find_nearby_global_json(current_dir: &Path, repo_root: Option<&Path>) -> Option<String> {
let current_dir_is_repo_root = repo_root.map(|r| r == current_dir).unwrap_or(false); let current_dir_is_repo_root = repo_root.map_or(false, |r| r == current_dir);
let parent_dir = if current_dir_is_repo_root { let parent_dir = if current_dir_is_repo_root {
// Don't scan the parent directory if it's above the root of a git repository // Don't scan the parent directory if it's above the root of a git repository
None None
@ -274,8 +274,8 @@ fn get_dotnet_file_type(path: &Path) -> Option<FileType> {
match extension_lower.as_ref().map(|f| f.as_ref()) { match extension_lower.as_ref().map(|f| f.as_ref()) {
Some("sln") => return Some(FileType::SolutionFile), Some("sln") => return Some(FileType::SolutionFile),
Some("csproj") | Some("fsproj") | Some("xproj") => return Some(FileType::ProjectFile), Some("csproj" | "fsproj" | "xproj") => return Some(FileType::ProjectFile),
Some("props") | Some("targets") => return Some(FileType::MsBuildFile), Some("props" | "targets") => return Some(FileType::MsBuildFile),
_ => (), _ => (),
}; };
@ -354,7 +354,7 @@ mod tests {
#[test] #[test]
fn shows_nothing_in_directory_with_zero_relevant_files() -> io::Result<()> { fn shows_nothing_in_directory_with_zero_relevant_files() -> io::Result<()> {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
expect_output(&workspace.path(), None); expect_output(workspace.path(), None);
workspace.close() workspace.close()
} }
@ -363,7 +363,7 @@ mod tests {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "Directory.Build.props", None)?; touch_path(&workspace, "Directory.Build.props", None)?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 ") Color::Blue.bold().paint(".NET v3.1.103 ")
@ -377,7 +377,7 @@ mod tests {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "Directory.Build.targets", None)?; touch_path(&workspace, "Directory.Build.targets", None)?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 ") Color::Blue.bold().paint(".NET v3.1.103 ")
@ -391,7 +391,7 @@ mod tests {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "Packages.props", None)?; touch_path(&workspace, "Packages.props", None)?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 ") Color::Blue.bold().paint(".NET v3.1.103 ")
@ -404,7 +404,7 @@ mod tests {
fn shows_latest_in_directory_with_solution() -> io::Result<()> { fn shows_latest_in_directory_with_solution() -> io::Result<()> {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "solution.sln", None)?; touch_path(&workspace, "solution.sln", None)?;
expect_output(&workspace.path(), None); expect_output(workspace.path(), None);
workspace.close() workspace.close()
} }
@ -414,7 +414,7 @@ mod tests {
let csproj = make_csproj_with_tfm("TargetFramework", "netstandard2.0"); let csproj = make_csproj_with_tfm("TargetFramework", "netstandard2.0");
touch_path(&workspace, "project.csproj", Some(&csproj))?; touch_path(&workspace, "project.csproj", Some(&csproj))?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 🎯 netstandard2.0 ") Color::Blue.bold().paint(".NET v3.1.103 🎯 netstandard2.0 ")
@ -428,7 +428,7 @@ mod tests {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "project.fsproj", None)?; touch_path(&workspace, "project.fsproj", None)?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 ") Color::Blue.bold().paint(".NET v3.1.103 ")
@ -442,7 +442,7 @@ mod tests {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "project.xproj", None)?; touch_path(&workspace, "project.xproj", None)?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 ") Color::Blue.bold().paint(".NET v3.1.103 ")
@ -456,7 +456,7 @@ mod tests {
let workspace = create_workspace(false)?; let workspace = create_workspace(false)?;
touch_path(&workspace, "project.json", None)?; touch_path(&workspace, "project.json", None)?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!( Some(format!(
"via {}", "via {}",
Color::Blue.bold().paint(".NET v3.1.103 ") Color::Blue.bold().paint(".NET v3.1.103 ")
@ -471,7 +471,7 @@ mod tests {
let global_json = make_pinned_sdk_json("1.2.3"); let global_json = make_pinned_sdk_json("1.2.3");
touch_path(&workspace, "global.json", Some(&global_json))?; touch_path(&workspace, "global.json", Some(&global_json))?;
expect_output( expect_output(
&workspace.path(), workspace.path(),
Some(format!("via {}", Color::Blue.bold().paint(".NET v1.2.3 "))), Some(format!("via {}", Color::Blue.bold().paint(".NET v1.2.3 "))),
); );
workspace.close() workspace.close()

View File

@ -43,7 +43,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
.map(|elixir_version| { .map(|elixir_version| {
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&elixir_version, elixir_version,
config.version_format, config.version_format,
) )
})? })?

View File

@ -35,7 +35,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let elm_version = context.exec_cmd("elm", &["--version"])?.stdout; let elm_version = context.exec_cmd("elm", &["--version"])?.stdout;
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&elm_version.trim(), elm_version.trim(),
config.version_format, config.version_format,
) )
.map(Ok) .map(Ok)

View File

@ -98,7 +98,7 @@ fn get_variable_name<'a>(
fn get_env_value(context: &Context, name: &str, default: Option<&str>) -> Option<String> { fn get_env_value(context: &Context, name: &str, default: Option<&str>) -> Option<String> {
match context.get_env(name) { match context.get_env(name) {
Some(value) => Some(value), Some(value) => Some(value),
None => default.map(|value| value.to_owned()), None => default.map(std::borrow::ToOwned::to_owned),
} }
} }

View File

@ -128,12 +128,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
"account" => account "account" => account
.deref() .deref()
.as_ref() .as_ref()
.map(|(account, _)| (*account).to_owned()) .map(|(account, _)| (*account).clone())
.map(Ok), .map(Ok),
"domain" => account "domain" => account
.deref() .deref()
.as_ref() .as_ref()
.and_then(|(_, domain)| (*domain).to_owned()) .and_then(|(_, domain)| (*domain).clone())
.map(Ok), .map(Ok),
"region" => gcloud_context "region" => gcloud_context
.get_region() .get_region()
@ -141,15 +141,14 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
config config
.region_aliases .region_aliases
.get(&region) .get(&region)
.map(|alias| (*alias).to_owned()) .map_or(region, |alias| (*alias).to_owned())
.unwrap_or(region)
}) })
.map(Ok), .map(Ok),
"project" => context "project" => context
.get_env("CLOUDSDK_CORE_PROJECT") .get_env("CLOUDSDK_CORE_PROJECT")
.or_else(|| gcloud_context.get_project()) .or_else(|| gcloud_context.get_project())
.map(Ok), .map(Ok),
"active" => Some(Ok(gcloud_context.config_name.to_owned())), "active" => Some(Ok(gcloud_context.config_name.clone())),
_ => None, _ => None,
}) })
.parse(None) .parse(None)

View File

@ -50,13 +50,11 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
} }
// Truncate fields if need be // Truncate fields if need be
for e in [ for e in &mut [
&mut graphemes, &mut graphemes,
&mut remote_branch_graphemes, &mut remote_branch_graphemes,
&mut remote_name_graphemes, &mut remote_name_graphemes,
] ] {
.iter_mut()
{
let e = &mut **e; let e = &mut **e;
let trunc_len = len.min(e.len()); let trunc_len = len.min(e.len());
if trunc_len < e.len() { if trunc_len < e.len() {

View File

@ -259,12 +259,12 @@ impl RepoStatus {
} }
fn add(&mut self, s: &str) { fn add(&mut self, s: &str) {
self.conflicted += RepoStatus::is_conflicted(s) as usize; self.conflicted += Self::is_conflicted(s) as usize;
self.deleted += RepoStatus::is_deleted(s) as usize; self.deleted += Self::is_deleted(s) as usize;
self.renamed += RepoStatus::is_renamed(s) as usize; self.renamed += Self::is_renamed(s) as usize;
self.modified += RepoStatus::is_modified(s) as usize; self.modified += Self::is_modified(s) as usize;
self.staged += RepoStatus::is_staged(s) as usize; self.staged += Self::is_staged(s) as usize;
self.untracked += RepoStatus::is_untracked(s) as usize; self.untracked += Self::is_untracked(s) as usize;
} }
fn set_ahead_behind(&mut self, s: &str) { fn set_ahead_behind(&mut self, s: &str) {
@ -350,7 +350,7 @@ mod tests {
fn shows_behind() -> io::Result<()> { fn shows_behind() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
behind(&repo_dir.path())?; behind(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(repo_dir.path()) .path(repo_dir.path())
@ -365,7 +365,7 @@ mod tests {
fn shows_behind_with_count() -> io::Result<()> { fn shows_behind_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
behind(&repo_dir.path())?; behind(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -385,7 +385,7 @@ mod tests {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
File::create(repo_dir.path().join("readme.md"))?.sync_all()?; File::create(repo_dir.path().join("readme.md"))?.sync_all()?;
ahead(&repo_dir.path())?; ahead(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -401,7 +401,7 @@ mod tests {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
File::create(repo_dir.path().join("readme.md"))?.sync_all()?; File::create(repo_dir.path().join("readme.md"))?.sync_all()?;
ahead(&repo_dir.path())?; ahead(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -420,7 +420,7 @@ mod tests {
fn shows_diverged() -> io::Result<()> { fn shows_diverged() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
diverge(&repo_dir.path())?; diverge(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -435,7 +435,7 @@ mod tests {
fn shows_diverged_with_count() -> io::Result<()> { fn shows_diverged_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
diverge(&repo_dir.path())?; diverge(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -454,7 +454,7 @@ mod tests {
fn shows_conflicted() -> io::Result<()> { fn shows_conflicted() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_conflict(&repo_dir.path())?; create_conflict(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -469,7 +469,7 @@ mod tests {
fn shows_conflicted_with_count() -> io::Result<()> { fn shows_conflicted_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_conflict(&repo_dir.path())?; create_conflict(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -488,7 +488,7 @@ mod tests {
fn shows_untracked_file() -> io::Result<()> { fn shows_untracked_file() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_untracked(&repo_dir.path())?; create_untracked(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -503,7 +503,7 @@ mod tests {
fn shows_untracked_file_with_count() -> io::Result<()> { fn shows_untracked_file_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_untracked(&repo_dir.path())?; create_untracked(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -522,7 +522,7 @@ mod tests {
fn doesnt_show_untracked_file_if_disabled() -> io::Result<()> { fn doesnt_show_untracked_file_if_disabled() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_untracked(&repo_dir.path())?; create_untracked(repo_dir.path())?;
create_command("git")? create_command("git")?
.args(&["config", "status.showUntrackedFiles", "no"]) .args(&["config", "status.showUntrackedFiles", "no"])
@ -544,7 +544,7 @@ mod tests {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
barrier(); barrier();
create_stash(&repo_dir.path())?; create_stash(repo_dir.path())?;
create_command("git")? create_command("git")?
.args(&["reset", "--hard", "HEAD"]) .args(&["reset", "--hard", "HEAD"])
@ -566,7 +566,7 @@ mod tests {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
barrier(); barrier();
create_stash(&repo_dir.path())?; create_stash(repo_dir.path())?;
barrier(); barrier();
create_command("git")? create_command("git")?
@ -592,7 +592,7 @@ mod tests {
fn shows_modified() -> io::Result<()> { fn shows_modified() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_modified(&repo_dir.path())?; create_modified(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -607,7 +607,7 @@ mod tests {
fn shows_modified_with_count() -> io::Result<()> { fn shows_modified_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_modified(&repo_dir.path())?; create_modified(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -626,7 +626,7 @@ mod tests {
fn shows_added() -> io::Result<()> { fn shows_added() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_added(&repo_dir.path())?; create_added(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -641,7 +641,7 @@ mod tests {
fn shows_staged_file() -> io::Result<()> { fn shows_staged_file() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_staged(&repo_dir.path())?; create_staged(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -656,7 +656,7 @@ mod tests {
fn shows_staged_file_with_count() -> io::Result<()> { fn shows_staged_file_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_staged(&repo_dir.path())?; create_staged(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -682,7 +682,7 @@ mod tests {
fn shows_renamed_file() -> io::Result<()> { fn shows_renamed_file() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_renamed(&repo_dir.path())?; create_renamed(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -697,7 +697,7 @@ mod tests {
fn shows_renamed_file_with_count() -> io::Result<()> { fn shows_renamed_file_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_renamed(&repo_dir.path())?; create_renamed(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {
@ -716,7 +716,7 @@ mod tests {
fn shows_deleted_file() -> io::Result<()> { fn shows_deleted_file() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_deleted(&repo_dir.path())?; create_deleted(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.path(&repo_dir.path()) .path(&repo_dir.path())
@ -731,7 +731,7 @@ mod tests {
fn shows_deleted_file_with_count() -> io::Result<()> { fn shows_deleted_file_with_count() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?; let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_deleted(&repo_dir.path())?; create_deleted(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status") let actual = ModuleRenderer::new("git_status")
.config(toml::toml! { .config(toml::toml! {

View File

@ -76,8 +76,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
fn get_hg_branch_name(ctx: &Context) -> String { fn get_hg_branch_name(ctx: &Context) -> String {
std::fs::read_to_string(ctx.current_dir.join(".hg").join("branch")) std::fs::read_to_string(ctx.current_dir.join(".hg").join("branch"))
.map(|s| s.trim().into()) .map_or_else(|_| "default".to_string(), |s| s.trim().into())
.unwrap_or_else(|_| "default".to_string())
} }
fn get_hg_current_bookmark(ctx: &Context) -> Option<String> { fn get_hg_current_bookmark(ctx: &Context) -> Option<String> {
@ -134,9 +133,9 @@ mod tests {
fn test_hg_disabled_per_default() -> io::Result<()> { fn test_hg_disabled_per_default() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?; let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path(); let repo_dir = tempdir.path();
run_hg(&["whatever", "blubber"], &repo_dir)?; run_hg(&["whatever", "blubber"], repo_dir)?;
expect_hg_branch_with_config( expect_hg_branch_with_config(
&repo_dir, repo_dir,
// no "disabled=false" in config! // no "disabled=false" in config!
Some(toml::toml! { Some(toml::toml! {
[hg_branch] [hg_branch]
@ -160,7 +159,7 @@ mod tests {
expect_hg_branch_with_config( expect_hg_branch_with_config(
tempdir.path(), tempdir.path(),
None, None,
&[Expect::BranchName(&"default"), Expect::NoTruncation], &[Expect::BranchName("default"), Expect::NoTruncation],
); );
tempdir.close() tempdir.close()
} }
@ -178,11 +177,11 @@ mod tests {
fn test_hg_bookmark() -> io::Result<()> { fn test_hg_bookmark() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?; let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path(); let repo_dir = tempdir.path();
run_hg(&["bookmark", "bookmark-101"], &repo_dir)?; run_hg(&["bookmark", "bookmark-101"], repo_dir)?;
expect_hg_branch_with_config( expect_hg_branch_with_config(
&repo_dir, repo_dir,
None, None,
&[Expect::BranchName(&"bookmark-101"), Expect::NoTruncation], &[Expect::BranchName("bookmark-101"), Expect::NoTruncation],
); );
tempdir.close() tempdir.close()
} }
@ -192,7 +191,7 @@ mod tests {
fn test_default_truncation_symbol() -> io::Result<()> { fn test_default_truncation_symbol() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?; let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path(); let repo_dir = tempdir.path();
run_hg(&["branch", "-f", "branch-name-101"], &repo_dir)?; run_hg(&["branch", "-f", "branch-name-101"], repo_dir)?;
run_hg( run_hg(
&[ &[
"commit", "commit",
@ -201,16 +200,16 @@ mod tests {
"-u", "-u",
"fake user <fake@user>", "fake user <fake@user>",
], ],
&repo_dir, repo_dir,
)?; )?;
expect_hg_branch_with_config( expect_hg_branch_with_config(
&repo_dir, repo_dir,
Some(toml::toml! { Some(toml::toml! {
[hg_branch] [hg_branch]
truncation_length = 14 truncation_length = 14
disabled = false disabled = false
}), }),
&[Expect::BranchName(&"branch-name-10")], &[Expect::BranchName("branch-name-10")],
); );
tempdir.close() tempdir.close()
} }
@ -220,7 +219,7 @@ mod tests {
fn test_configured_symbols() -> io::Result<()> { fn test_configured_symbols() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?; let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path(); let repo_dir = tempdir.path();
run_hg(&["branch", "-f", "branch-name-121"], &repo_dir)?; run_hg(&["branch", "-f", "branch-name-121"], repo_dir)?;
run_hg( run_hg(
&[ &[
"commit", "commit",
@ -229,10 +228,10 @@ mod tests {
"-u", "-u",
"fake user <fake@user>", "fake user <fake@user>",
], ],
&repo_dir, repo_dir,
)?; )?;
expect_hg_branch_with_config( expect_hg_branch_with_config(
&repo_dir, repo_dir,
Some(toml::toml! { Some(toml::toml! {
[hg_branch] [hg_branch]
symbol = "B " symbol = "B "
@ -241,9 +240,9 @@ mod tests {
disabled = false disabled = false
}), }),
&[ &[
Expect::BranchName(&"branch-name-12"), Expect::BranchName("branch-name-12"),
Expect::Symbol(&"B"), Expect::Symbol("B"),
Expect::TruncationSymbol(&"%"), Expect::TruncationSymbol("%"),
], ],
); );
tempdir.close() tempdir.close()
@ -254,7 +253,7 @@ mod tests {
fn test_configured_style() -> io::Result<()> { fn test_configured_style() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?; let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path(); let repo_dir = tempdir.path();
run_hg(&["branch", "-f", "branch-name-131"], &repo_dir)?; run_hg(&["branch", "-f", "branch-name-131"], repo_dir)?;
run_hg( run_hg(
&[ &[
"commit", "commit",
@ -263,20 +262,20 @@ mod tests {
"-u", "-u",
"fake user <fake@user>", "fake user <fake@user>",
], ],
&repo_dir, repo_dir,
)?; )?;
expect_hg_branch_with_config( expect_hg_branch_with_config(
&repo_dir, repo_dir,
Some(toml::toml! { Some(toml::toml! {
[hg_branch] [hg_branch]
style = "underline blue" style = "underline blue"
disabled = false disabled = false
}), }),
&[ &[
Expect::BranchName(&"branch-name-131"), Expect::BranchName("branch-name-131"),
Expect::Style(Color::Blue.underline()), Expect::Style(Color::Blue.underline()),
Expect::TruncationSymbol(&""), Expect::TruncationSymbol(""),
], ],
); );
tempdir.close() tempdir.close()

View File

@ -11,8 +11,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let props = &context.properties; let props = &context.properties;
let num_of_jobs = props let num_of_jobs = props
.get("jobs") .get("jobs")
.map(String::as_str) .map_or("0", String::as_str)
.unwrap_or("0")
.trim() .trim()
.parse::<i64>() .parse::<i64>()
.ok()?; .ok()?;

View File

@ -35,7 +35,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
}) })
.map(|variable| match variable { .map(|variable| match variable {
"version" => { "version" => {
let kotlin_version = get_kotlin_version(context, &config.kotlin_binary)?; let kotlin_version = get_kotlin_version(context, config.kotlin_binary)?;
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&kotlin_version, &kotlin_version,

View File

@ -32,7 +32,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
}) })
.map(|variable| match variable { .map(|variable| match variable {
"version" => { "version" => {
let lua_version = get_lua_version(context, &config.lua_binary)?; let lua_version = get_lua_version(context, config.lua_binary)?;
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&lua_version, &lua_version,

View File

@ -66,7 +66,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
}; };
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&ocaml_version.trim(), ocaml_version.trim(),
config.version_format, config.version_format,
) )
.map(Ok) .map(Ok)
@ -92,7 +92,7 @@ fn get_opam_switch(context: &Context) -> Option<OpamSwitch> {
.exec_cmd("opam", &["switch", "show", "--safe"])? .exec_cmd("opam", &["switch", "show", "--safe"])?
.stdout; .stdout;
parse_opam_switch(&opam_switch.trim()) parse_opam_switch(opam_switch.trim())
} }
fn parse_opam_switch(opam_switch: &str) -> Option<OpamSwitch> { fn parse_opam_switch(opam_switch: &str) -> Option<OpamSwitch> {

View File

@ -41,7 +41,7 @@ fn get_osp_cloud_and_project(context: &Context) -> (Option<Cloud>, Option<Projec
) { ) {
(Some(p), Some(r)) => (Some(p), Some(r)), (Some(p), Some(r)) => (Some(p), Some(r)),
(None, Some(r)) => (None, Some(r)), (None, Some(r)) => (None, Some(r)),
(Some(ref p), None) => (Some(p.to_owned()), get_osp_project_from_config(context, p)), (Some(ref p), None) => (Some(p.clone()), get_osp_project_from_config(context, p)),
(None, None) => (None, None), (None, None) => (None, None),
} }
} }

View File

@ -207,7 +207,7 @@ fn extract_vpkg_version(file_contents: &str) -> Option<String> {
if version == "null" { if version == "null" {
return None; return None;
} }
let formatted_version = format_version(&version); let formatted_version = format_version(version);
Some(formatted_version) Some(formatted_version)
} }
@ -313,7 +313,7 @@ license = "MIT"
"##; "##;
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
let starship_config = toml::toml! { let starship_config = toml::toml! {
[package] [package]
@ -373,7 +373,7 @@ license = "MIT"
"##; "##;
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
let starship_config = toml::toml! { let starship_config = toml::toml! {
[package] [package]
@ -622,7 +622,7 @@ java {
}"; }";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None); expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close() project_dir.close()
} }
@ -641,7 +641,7 @@ java {
}"; }";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None); expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close() project_dir.close()
} }
@ -660,7 +660,7 @@ java {
}"; }";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v0.1.0-rc1"), None); expect_output(&project_dir, Some("v0.1.0-rc1"), None);
project_dir.close() project_dir.close()
} }
@ -678,7 +678,7 @@ java {
}"; }";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, None, None); expect_output(&project_dir, None, None);
project_dir.close() project_dir.close()
} }
@ -711,7 +711,7 @@ java {
end"; end";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v1.2.3"), None); expect_output(&project_dir, Some("v1.2.3"), None);
project_dir.close() project_dir.close()
} }
@ -722,7 +722,7 @@ end";
let config_content = " def project, do: [app: :my_app,version: \"3.2.1\"]"; let config_content = " def project, do: [app: :my_app,version: \"3.2.1\"]";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v3.2.1"), None); expect_output(&project_dir, Some("v3.2.1"), None);
project_dir.close() project_dir.close()
} }
@ -738,7 +738,7 @@ end";
end"; end";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v1.0.0-alpha.3"), None); expect_output(&project_dir, Some("v1.0.0-alpha.3"), None);
project_dir.close() project_dir.close()
} }
@ -754,7 +754,7 @@ end";
end"; end";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v0.9.9-dev+20130417140000.amd64"), None); expect_output(&project_dir, Some("v0.9.9-dev+20130417140000.amd64"), None);
project_dir.close() project_dir.close()
} }
@ -769,7 +769,7 @@ end";
"; ";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v0.2.0"), None); expect_output(&project_dir, Some("v0.2.0"), None);
project_dir.close() project_dir.close()
} }
@ -901,7 +901,7 @@ end";
</project>"; </project>";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, "pom.xml", Some(&pom))?; fill_config(&project_dir, "pom.xml", Some(pom))?;
expect_output(&project_dir, Some("0.3.20-SNAPSHOT"), None); expect_output(&project_dir, Some("0.3.20-SNAPSHOT"), None);
project_dir.close() project_dir.close()
} }
@ -925,7 +925,7 @@ end";
</project>"; </project>";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, "pom.xml", Some(&pom))?; fill_config(&project_dir, "pom.xml", Some(pom))?;
expect_output(&project_dir, None, None); expect_output(&project_dir, None, None);
project_dir.close() project_dir.close()
} }
@ -942,7 +942,7 @@ end";
</project>"; </project>";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, "pom.xml", Some(&pom))?; fill_config(&project_dir, "pom.xml", Some(pom))?;
expect_output(&project_dir, None, None); expect_output(&project_dir, None, None);
project_dir.close() project_dir.close()
} }
@ -963,7 +963,7 @@ end";
</project>"; </project>";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, "pom.xml", Some(&pom))?; fill_config(&project_dir, "pom.xml", Some(pom))?;
expect_output(&project_dir, None, None); expect_output(&project_dir, None, None);
project_dir.close() project_dir.close()
} }
@ -1012,7 +1012,7 @@ Module {
version: '1.2.3' version: '1.2.3'
}"; }";
let project_dir = create_project_dir()?; let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?; fill_config(&project_dir, config_name, Some(config_content))?;
expect_output(&project_dir, Some("v1.2.3"), None); expect_output(&project_dir, Some("v1.2.3"), None);
project_dir.close() project_dir.close()
} }

View File

@ -34,7 +34,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let purs_version = context.exec_cmd("purs", &["--version"])?.stdout; let purs_version = context.exec_cmd("purs", &["--version"])?.stdout;
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&purs_version.trim(), purs_version.trim(),
config.version_format, config.version_format,
) )
.map(Ok) .map(Ok)

View File

@ -75,7 +75,7 @@ fn get_module_version(context: &Context, config: &RustConfig) -> Option<String>
// - `rustup which` // - `rustup which`
if let Some(toolchain) = env_rustup_toolchain(context) if let Some(toolchain) = env_rustup_toolchain(context)
.or_else(|| execute_rustup_override_list(&context.current_dir)) .or_else(|| execute_rustup_override_list(&context.current_dir))
.or_else(|| find_rust_toolchain_file(&context)) .or_else(|| find_rust_toolchain_file(context))
{ {
match execute_rustup_run_rustc_version(&toolchain) { match execute_rustup_run_rustc_version(&toolchain) {
RustupRunRustcVersionOutcome::RustcVersion(rustc_version) => { RustupRunRustcVersionOutcome::RustcVersion(rustc_version) => {
@ -115,7 +115,7 @@ fn extract_toolchain_from_rustup_override_list(stdout: &str, cwd: &Path) -> Opti
} }
stdout stdout
.lines() .lines()
.flat_map(|line| { .filter_map(|line| {
let mut words = line.split_whitespace(); let mut words = line.split_whitespace();
let dir = words.next()?; let dir = words.next()?;
let toolchain = words.next()?; let toolchain = words.next()?;

View File

@ -27,7 +27,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let pipestatus_status = match &context.pipestatus { let pipestatus_status = match &context.pipestatus {
None => PipeStatusStatus::Disabled, None => PipeStatusStatus::Disabled,
Some(ps) => match ps.len() > 1 { Some(ps) => match ps.len() > 1 {
true => PipeStatusStatus::Pipe(&ps), true => PipeStatusStatus::Pipe(ps),
false => PipeStatusStatus::NoPipe, false => PipeStatusStatus::NoPipe,
}, },
}; };
@ -255,7 +255,7 @@ mod tests {
fn failure_status() { fn failure_status() {
let exit_values = [1, 2, 130]; let exit_values = [1, 2, 130];
for status in exit_values.iter() { for status in &exit_values {
let expected = Some(format!( let expected = Some(format!(
"{} ", "{} ",
Color::Red.bold().paint(format!("{}", status)) Color::Red.bold().paint(format!("{}", status))
@ -285,7 +285,7 @@ mod tests {
]; ];
for (status, name) in exit_values.iter().zip(exit_values_name.iter()) { for (status, name) in exit_values.iter().zip(exit_values_name.iter()) {
let expected = name.map(|n| n.to_string()); let expected = name.map(std::string::ToString::to_string);
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -312,7 +312,7 @@ mod tests {
]; ];
for (status, name) in exit_values.iter().zip(exit_values_name.iter()) { for (status, name) in exit_values.iter().zip(exit_values_name.iter()) {
let expected = name.map(|n| n.to_string()); let expected = name.map(std::string::ToString::to_string);
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -341,7 +341,7 @@ mod tests {
]; ];
for (status, name) in exit_values.iter().zip(exit_values_name.iter()) { for (status, name) in exit_values.iter().zip(exit_values_name.iter()) {
let expected = name.map(|n| n.to_string()); let expected = name.map(std::string::ToString::to_string);
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -360,7 +360,7 @@ mod tests {
let exit_values_name = ["🔴", "🚫", "🔍", "🧱", ""]; let exit_values_name = ["🔴", "🚫", "🔍", "🧱", ""];
for (status, name) in exit_values.iter().zip(exit_values_name.iter()) { for (status, name) in exit_values.iter().zip(exit_values_name.iter()) {
let expected = Some(name.to_string()); let expected = Some((*name).to_string());
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -386,7 +386,7 @@ mod tests {
let exit_values_name = ["🔴", "🚫", "🔍", "🔴", "🔴"]; let exit_values_name = ["🔴", "🚫", "🔍", "🔴", "🔴"];
for (status, name) in exit_values.iter().zip(exit_values_name.iter()) { for (status, name) in exit_values.iter().zip(exit_values_name.iter()) {
let expected = Some(name.to_string()); let expected = Some((*name).to_string());
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -425,7 +425,7 @@ mod tests {
let main_exit_code = status[0]; let main_exit_code = status[0];
let pipe_exit_code = &status[1..]; let pipe_exit_code = &status[1..];
let expected = Some(rendered.to_string()); let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -469,7 +469,7 @@ mod tests {
let main_exit_code = status[0]; let main_exit_code = status[0];
let pipe_exit_code = &status[1..]; let pipe_exit_code = &status[1..];
let expected = Some(rendered.to_string()); let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -508,7 +508,7 @@ mod tests {
let main_exit_code = status[0]; let main_exit_code = status[0];
let pipe_exit_code = &status[1..]; let pipe_exit_code = &status[1..];
let expected = Some(rendered.to_string()); let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]
@ -548,7 +548,7 @@ mod tests {
let main_exit_code = status[0]; let main_exit_code = status[0];
let pipe_exit_code = &status[1..]; let pipe_exit_code = &status[1..];
let expected = Some(rendered.to_string()); let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status") let actual = ModuleRenderer::new("status")
.config(toml::toml! { .config(toml::toml! {
[status] [status]

View File

@ -37,7 +37,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
.map(|variable| match variable { .map(|variable| match variable {
"version" => { "version" => {
let terraform_version = get_terraform_version( let terraform_version = get_terraform_version(
&context.exec_cmd("terraform", &["version"])?.stdout.as_str(), context.exec_cmd("terraform", &["version"])?.stdout.as_str(),
)?; )?;
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),

View File

@ -31,17 +31,17 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
); );
let formatted_time_string = if config.utc_time_offset != "local" { let formatted_time_string = if config.utc_time_offset != "local" {
match create_offset_time_string(Utc::now(), &config.utc_time_offset, &time_format) { match create_offset_time_string(Utc::now(), config.utc_time_offset, time_format) {
Ok(formatted_string) => formatted_string, Ok(formatted_string) => formatted_string,
Err(_) => { Err(_) => {
log::warn!( log::warn!(
"Invalid utc_time_offset configuration provided! Falling back to \"local\"." "Invalid utc_time_offset configuration provided! Falling back to \"local\"."
); );
format_time(&time_format, Local::now()) format_time(time_format, Local::now())
} }
} }
} else { } else {
format_time(&time_format, Local::now()) format_time(time_format, Local::now())
}; };
let parsed = StringFormatter::new(config.format).and_then(|formatter| { let parsed = StringFormatter::new(config.format).and_then(|formatter| {
@ -86,7 +86,7 @@ fn create_offset_time_string(
let target_time = utc_time.with_timezone(&timezone_offset); let target_time = utc_time.with_timezone(&timezone_offset);
log::trace!("Time in target timezone now is {}", target_time); log::trace!("Time in target timezone now is {}", target_time);
Ok(format_time_fixed_offset(&time_format, target_time)) Ok(format_time_fixed_offset(time_format, target_time))
} else { } else {
Err("Invalid timezone offset.") Err("Invalid timezone offset.")
} }
@ -290,7 +290,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "-3"; let utc_time_offset_str = "-3";
let actual = create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12).unwrap(); let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "12:36:47 PM"); assert_eq!(actual, "12:36:47 PM");
} }
@ -299,7 +299,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "+5"; let utc_time_offset_str = "+5";
let actual = create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12).unwrap(); let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "08:36:47 PM"); assert_eq!(actual, "08:36:47 PM");
} }
@ -308,7 +308,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "+9.5"; let utc_time_offset_str = "+9.5";
let actual = create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12).unwrap(); let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "01:06:47 AM"); assert_eq!(actual, "01:06:47 AM");
} }
@ -317,7 +317,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "+5.75"; let utc_time_offset_str = "+5.75";
let actual = create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12).unwrap(); let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "09:21:47 PM"); assert_eq!(actual, "09:21:47 PM");
} }
@ -326,7 +326,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "+24"; let utc_time_offset_str = "+24";
create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12) create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.err() .err()
.expect("Invalid timezone offset."); .expect("Invalid timezone offset.");
} }
@ -336,7 +336,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "-24"; let utc_time_offset_str = "-24";
create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12) create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.err() .err()
.expect("Invalid timezone offset."); .expect("Invalid timezone offset.");
} }
@ -346,7 +346,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "+9001"; let utc_time_offset_str = "+9001";
create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12) create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.err() .err()
.expect("Invalid timezone offset."); .expect("Invalid timezone offset.");
} }
@ -356,7 +356,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "-4242"; let utc_time_offset_str = "-4242";
create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12) create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.err() .err()
.expect("Invalid timezone offset."); .expect("Invalid timezone offset.");
} }
@ -366,7 +366,7 @@ mod tests {
let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47); let utc_time: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(15, 36, 47);
let utc_time_offset_str = "completely wrong config"; let utc_time_offset_str = "completely wrong config";
create_offset_time_string(utc_time, &utc_time_offset_str, FMT_12) create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.err() .err()
.expect("Invalid timezone offset."); .expect("Invalid timezone offset.");
} }

View File

@ -24,8 +24,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let is_root = is_root_user(); let is_root = is_root_user();
let show_username = config.show_always let show_username = config.show_always
|| is_root // [1] || is_root // [1]
|| !is_login_user(&context, &username) // [2] || !is_login_user(context, &username) // [2]
|| is_ssh_session(&context); // [3] || is_ssh_session(context); // [3]
if !show_username { if !show_username {
return None; return None;
@ -64,8 +64,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
fn is_login_user(context: &Context, username: &str) -> bool { fn is_login_user(context: &Context, username: &str) -> bool {
context context
.get_env("LOGNAME") .get_env("LOGNAME")
.map(|logname| logname == username) .map_or(true, |logname| logname == username)
.unwrap_or(true)
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]

View File

@ -36,7 +36,7 @@ pub fn is_write_allowed(folder_path: &Path) -> Result<bool, &'static str> {
fn get_supplementary_groups() -> Vec<u32> { fn get_supplementary_groups() -> Vec<u32> {
match nix::unistd::getgroups() { match nix::unistd::getgroups() {
Err(_) => Vec::new(), Err(_) => Vec::new(),
Ok(v) => v.into_iter().map(|i| i.as_raw()).collect(), Ok(v) => v.into_iter().map(nix::unistd::Gid::as_raw).collect(),
} }
} }

View File

@ -4,7 +4,7 @@ use std::iter;
use std::mem; use std::mem;
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
use std::path::Path; use std::path::Path;
use winapi::ctypes::c_void;
use winapi::shared::minwindef::{BOOL, DWORD}; use winapi::shared::minwindef::{BOOL, DWORD};
use winapi::um::handleapi; use winapi::um::handleapi;
use winapi::um::processthreadsapi; use winapi::um::processthreadsapi;
@ -13,7 +13,7 @@ use winapi::um::winnt::{
SecurityImpersonation, BOOLEAN, DACL_SECURITY_INFORMATION, FILE_ALL_ACCESS, SecurityImpersonation, BOOLEAN, DACL_SECURITY_INFORMATION, FILE_ALL_ACCESS,
FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, GENERIC_MAPPING, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, GENERIC_MAPPING,
GROUP_SECURITY_INFORMATION, HANDLE, LPCWSTR, OWNER_SECURITY_INFORMATION, PRIVILEGE_SET, GROUP_SECURITY_INFORMATION, HANDLE, LPCWSTR, OWNER_SECURITY_INFORMATION, PRIVILEGE_SET,
PSECURITY_DESCRIPTOR, STANDARD_RIGHTS_READ, TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY, STANDARD_RIGHTS_READ, TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY,
}; };
/// Checks if the current user has write access right to the `folder_path` /// Checks if the current user has write access right to the `folder_path`
@ -59,7 +59,7 @@ pub fn is_write_allowed(folder_path: &Path) -> std::result::Result<bool, &'stati
securitybaseapi::GetFileSecurityW( securitybaseapi::GetFileSecurityW(
folder_name.as_ptr(), folder_name.as_ptr(),
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
buf.as_mut_ptr() as *mut c_void, buf.as_mut_ptr().cast::<std::ffi::c_void>(),
length, length,
&mut length, &mut length,
) )
@ -105,7 +105,7 @@ pub fn is_write_allowed(folder_path: &Path) -> std::result::Result<bool, &'stati
unsafe { securitybaseapi::MapGenericMask(&mut access_rights, &mut mapping) }; unsafe { securitybaseapi::MapGenericMask(&mut access_rights, &mut mapping) };
let rc = unsafe { let rc = unsafe {
securitybaseapi::AccessCheck( securitybaseapi::AccessCheck(
buf.as_mut_ptr() as PSECURITY_DESCRIPTOR, buf.as_mut_ptr().cast::<std::ffi::c_void>(),
impersonated_token, impersonated_token,
access_rights, access_rights,
&mut mapping, &mut mapping,

View File

@ -54,7 +54,7 @@ mod normalize {
pub fn normalize_path(path: &Path) -> (NormalizedPrefix, &Path) { pub fn normalize_path(path: &Path) -> (NormalizedPrefix, &Path) {
let mut components = path.components(); let mut components = path.components();
if let Some(Component::Prefix(prefix)) = components.next() { if let Some(Component::Prefix(prefix)) = components.next() {
return (normalize_prefix(prefix.kind()), &components.as_path()); return (normalize_prefix(prefix.kind()), components.as_path());
} }
(NormalizedPrefix::None, path) (NormalizedPrefix::None, path)
} }
@ -78,7 +78,7 @@ impl PathExt for Path {
fn without_prefix(&self) -> &Path { fn without_prefix(&self) -> &Path {
let (_, path) = normalize::normalize_path(self); let (_, path) = normalize::normalize_path(self);
&path path
} }
} }
@ -110,40 +110,40 @@ mod windows {
#[test] #[test]
fn normalised_equals() { fn normalised_equals() {
fn test_equals(a: &Path, b: &Path) { fn test_equals(a: &Path, b: &Path) {
assert!(a.normalised_equals(&b)); assert!(a.normalised_equals(b));
assert!(b.normalised_equals(&a)); assert!(b.normalised_equals(a));
} }
// UNC paths // UNC paths
let verbatim_unc = Path::new(r"\\?\UNC\server\share\sub\path"); let verbatim_unc = Path::new(r"\\?\UNC\server\share\sub\path");
let unc = Path::new(r"\\server\share\sub\path"); let unc = Path::new(r"\\server\share\sub\path");
test_equals(&verbatim_unc, &verbatim_unc); test_equals(verbatim_unc, verbatim_unc);
test_equals(&verbatim_unc, &unc); test_equals(verbatim_unc, unc);
test_equals(&unc, &unc); test_equals(unc, unc);
test_equals(&unc, &verbatim_unc); test_equals(unc, verbatim_unc);
// Disk paths // Disk paths
let verbatim_disk = Path::new(r"\\?\C:\test\path"); let verbatim_disk = Path::new(r"\\?\C:\test\path");
let disk = Path::new(r"C:\test\path"); let disk = Path::new(r"C:\test\path");
test_equals(&verbatim_disk, &verbatim_disk); test_equals(verbatim_disk, verbatim_disk);
test_equals(&verbatim_disk, &disk); test_equals(verbatim_disk, disk);
test_equals(&disk, &disk); test_equals(disk, disk);
test_equals(&disk, &verbatim_disk); test_equals(disk, verbatim_disk);
// Other paths // Other paths
let verbatim = Path::new(r"\\?\cat_pics"); let verbatim = Path::new(r"\\?\cat_pics");
let no_prefix = Path::new(r"\cat_pics"); let no_prefix = Path::new(r"\cat_pics");
let device_ns = Path::new(r"\\.\COM42"); let device_ns = Path::new(r"\\.\COM42");
test_equals(&verbatim, &verbatim); test_equals(verbatim, verbatim);
test_equals(&no_prefix, &no_prefix); test_equals(no_prefix, no_prefix);
test_equals(&device_ns, &device_ns); test_equals(device_ns, device_ns);
} }
#[test] #[test]
fn normalised_equals_differing_prefixes() { fn normalised_equals_differing_prefixes() {
fn test_not_equals(a: &Path, b: &Path) { fn test_not_equals(a: &Path, b: &Path) {
assert!(!a.normalised_equals(&b)); assert!(!a.normalised_equals(b));
assert!(!b.normalised_equals(&a)); assert!(!b.normalised_equals(a));
} }
let verbatim_unc = Path::new(r"\\?\UNC\server\share\sub\path"); let verbatim_unc = Path::new(r"\\?\UNC\server\share\sub\path");
@ -154,19 +154,19 @@ mod windows {
let no_prefix = Path::new(r"\cat_pics"); let no_prefix = Path::new(r"\cat_pics");
let device_ns = Path::new(r"\\.\COM42"); let device_ns = Path::new(r"\\.\COM42");
test_not_equals(&verbatim_unc, &verbatim_disk); test_not_equals(verbatim_unc, verbatim_disk);
test_not_equals(&unc, &disk); test_not_equals(unc, disk);
test_not_equals(&disk, &device_ns); test_not_equals(disk, device_ns);
test_not_equals(&device_ns, &verbatim_disk); test_not_equals(device_ns, verbatim_disk);
test_not_equals(&no_prefix, &unc); test_not_equals(no_prefix, unc);
test_not_equals(&no_prefix, &verbatim); test_not_equals(no_prefix, verbatim);
} }
#[test] #[test]
fn normalised_starts_with() { fn normalised_starts_with() {
fn test_starts_with(a: &Path, b: &Path) { fn test_starts_with(a: &Path, b: &Path) {
assert!(a.normalised_starts_with(&b)); assert!(a.normalised_starts_with(b));
assert!(!b.normalised_starts_with(&a)); assert!(!b.normalised_starts_with(a));
} }
// UNC paths // UNC paths
@ -174,20 +174,20 @@ mod windows {
let verbatim_unc_b = Path::new(r"\\?\UNC\server\share\a\b"); let verbatim_unc_b = Path::new(r"\\?\UNC\server\share\a\b");
let unc_a = Path::new(r"\\server\share\a\b\c\d"); let unc_a = Path::new(r"\\server\share\a\b\c\d");
let unc_b = Path::new(r"\\server\share\a\b"); let unc_b = Path::new(r"\\server\share\a\b");
test_starts_with(&verbatim_unc_a, &verbatim_unc_b); test_starts_with(verbatim_unc_a, verbatim_unc_b);
test_starts_with(&unc_a, &unc_b); test_starts_with(unc_a, unc_b);
test_starts_with(&verbatim_unc_a, &unc_b); test_starts_with(verbatim_unc_a, unc_b);
test_starts_with(&unc_a, &verbatim_unc_b); test_starts_with(unc_a, verbatim_unc_b);
// Disk paths // Disk paths
let verbatim_disk_a = Path::new(r"\\?\C:\a\b\c\d"); let verbatim_disk_a = Path::new(r"\\?\C:\a\b\c\d");
let verbatim_disk_b = Path::new(r"\\?\C:\a\b"); let verbatim_disk_b = Path::new(r"\\?\C:\a\b");
let disk_a = Path::new(r"C:\a\b\c\d"); let disk_a = Path::new(r"C:\a\b\c\d");
let disk_b = Path::new(r"C:\a\b"); let disk_b = Path::new(r"C:\a\b");
test_starts_with(&verbatim_disk_a, &verbatim_disk_b); test_starts_with(verbatim_disk_a, verbatim_disk_b);
test_starts_with(&disk_a, &disk_b); test_starts_with(disk_a, disk_b);
test_starts_with(&disk_a, &verbatim_disk_b); test_starts_with(disk_a, verbatim_disk_b);
test_starts_with(&verbatim_disk_a, &disk_b); test_starts_with(verbatim_disk_a, disk_b);
// Other paths // Other paths
let verbatim_a = Path::new(r"\\?\cat_pics\a\b\c\d"); let verbatim_a = Path::new(r"\\?\cat_pics\a\b\c\d");
@ -196,16 +196,16 @@ mod windows {
let device_ns_b = Path::new(r"\\.\COM43\a\b"); let device_ns_b = Path::new(r"\\.\COM43\a\b");
let no_prefix_a = Path::new(r"\a\b\c\d"); let no_prefix_a = Path::new(r"\a\b\c\d");
let no_prefix_b = Path::new(r"\a\b"); let no_prefix_b = Path::new(r"\a\b");
test_starts_with(&verbatim_a, &verbatim_b); test_starts_with(verbatim_a, verbatim_b);
test_starts_with(&device_ns_a, &device_ns_b); test_starts_with(device_ns_a, device_ns_b);
test_starts_with(&no_prefix_a, &no_prefix_b); test_starts_with(no_prefix_a, no_prefix_b);
} }
#[test] #[test]
fn normalised_starts_with_differing_prefixes() { fn normalised_starts_with_differing_prefixes() {
fn test_not_starts_with(a: &Path, b: &Path) { fn test_not_starts_with(a: &Path, b: &Path) {
assert!(!a.normalised_starts_with(&b)); assert!(!a.normalised_starts_with(b));
assert!(!b.normalised_starts_with(&a)); assert!(!b.normalised_starts_with(a));
} }
let verbatim_unc = Path::new(r"\\?\UNC\server\share\a\b\c\d"); let verbatim_unc = Path::new(r"\\?\UNC\server\share\a\b\c\d");
@ -216,12 +216,12 @@ mod windows {
let device_ns = Path::new(r"\\.\COM43\a\b\c\d"); let device_ns = Path::new(r"\\.\COM43\a\b\c\d");
let no_prefix = Path::new(r"\a\b\c\d"); let no_prefix = Path::new(r"\a\b\c\d");
test_not_starts_with(&verbatim_unc, &device_ns); test_not_starts_with(verbatim_unc, device_ns);
test_not_starts_with(&unc, &device_ns); test_not_starts_with(unc, device_ns);
test_not_starts_with(&verbatim_disk, &verbatim); test_not_starts_with(verbatim_disk, verbatim);
test_not_starts_with(&disk, &verbatim); test_not_starts_with(disk, verbatim);
test_not_starts_with(&disk, &unc); test_not_starts_with(disk, unc);
test_not_starts_with(&verbatim_disk, &no_prefix); test_not_starts_with(verbatim_disk, no_prefix);
} }
#[test] #[test]
@ -270,11 +270,11 @@ mod nix {
fn normalised_equals() { fn normalised_equals() {
let path_a = Path::new("/a/b/c/d"); let path_a = Path::new("/a/b/c/d");
let path_b = Path::new("/a/b/c/d"); let path_b = Path::new("/a/b/c/d");
assert!(path_a.normalised_equals(&path_b)); assert!(path_a.normalised_equals(path_b));
assert!(path_b.normalised_equals(&path_a)); assert!(path_b.normalised_equals(path_a));
let path_c = Path::new("/a/b"); let path_c = Path::new("/a/b");
assert!(!path_a.normalised_equals(&path_c)); assert!(!path_a.normalised_equals(path_c));
} }
#[test] #[test]
@ -282,18 +282,18 @@ mod nix {
// Windows path prefixes are not parsed on *nix // Windows path prefixes are not parsed on *nix
let path_a = Path::new(r"\\?\UNC\server\share\a\b\c\d"); let path_a = Path::new(r"\\?\UNC\server\share\a\b\c\d");
let path_b = Path::new(r"\\server\share\a\b\c\d"); let path_b = Path::new(r"\\server\share\a\b\c\d");
assert!(!path_a.normalised_equals(&path_b)); assert!(!path_a.normalised_equals(path_b));
assert!(!path_b.normalised_equals(&path_a)); assert!(!path_b.normalised_equals(path_a));
assert!(path_a.normalised_equals(&path_a)); assert!(path_a.normalised_equals(path_a));
} }
#[test] #[test]
fn normalised_starts_with() { fn normalised_starts_with() {
let path_a = Path::new("/a/b/c/d"); let path_a = Path::new("/a/b/c/d");
let path_b = Path::new("/a/b"); let path_b = Path::new("/a/b");
assert!(path_a.normalised_starts_with(&path_b)); assert!(path_a.normalised_starts_with(path_b));
assert!(!path_b.normalised_starts_with(&path_a)); assert!(!path_b.normalised_starts_with(path_a));
} }
#[test] #[test]
@ -301,10 +301,10 @@ mod nix {
// Windows path prefixes are not parsed on *nix // Windows path prefixes are not parsed on *nix
let path_a = Path::new(r"\\?\UNC\server\share\a\b\c\d"); let path_a = Path::new(r"\\?\UNC\server\share\a\b\c\d");
let path_b = Path::new(r"\\server\share\a\b"); let path_b = Path::new(r"\\server\share\a\b");
assert!(!path_a.normalised_starts_with(&path_b)); assert!(!path_a.normalised_starts_with(path_b));
assert!(!path_b.normalised_starts_with(&path_a)); assert!(!path_b.normalised_starts_with(path_a));
assert!(path_a.normalised_starts_with(&path_a)); assert!(path_a.normalised_starts_with(path_a));
} }
#[test] #[test]

View File

@ -35,7 +35,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let zig_version = context.exec_cmd("zig", &["version"])?.stdout; let zig_version = context.exec_cmd("zig", &["version"])?.stdout;
VersionFormatter::format_module_version( VersionFormatter::format_module_version(
module.get_name(), module.get_name(),
&zig_version.trim(), zig_version.trim(),
config.version_format, config.version_format,
) )
.map(Ok) .map(Ok)

View File

@ -99,7 +99,7 @@ pub fn get_prompt(context: Context) -> String {
.collect::<Vec<Segment>>() .collect::<Vec<Segment>>()
}) })
.collect::<Vec<_>>())) .collect::<Vec<_>>()))
} else if context.is_module_disabled_in_config(&module) { } else if context.is_module_disabled_in_config(module) {
None None
} else { } else {
// Get segments from module // Get segments from module
@ -213,7 +213,7 @@ pub fn explain(args: ArgMatches) {
value: ansi_term::ANSIStrings(&module.ansi_strings()).to_string(), value: ansi_term::ANSIStrings(&module.ansi_strings()).to_string(),
value_len: value.width_graphemes() value_len: value.width_graphemes()
+ format_duration(&module.duration).width_graphemes(), + format_duration(&module.duration).width_graphemes(),
desc: module.get_description().to_owned(), desc: module.get_description().clone(),
duration: format_duration(&module.duration), duration: format_duration(&module.duration),
} }
}) })
@ -301,11 +301,11 @@ fn compute_modules<'a>(context: &'a Context) -> Vec<Module<'a>> {
// Manually add all modules if `$all` is encountered // Manually add all modules if `$all` is encountered
if module == "all" { if module == "all" {
for module in PROMPT_ORDER.iter() { for module in PROMPT_ORDER.iter() {
let modules = handle_module(module, &context, &modules); let modules = handle_module(module, context, &modules);
prompt_order.extend(modules.into_iter()); prompt_order.extend(modules.into_iter());
} }
} else { } else {
let modules = handle_module(module, &context, &modules); let modules = handle_module(module, context, &modules);
prompt_order.extend(modules.into_iter()); prompt_order.extend(modules.into_iter());
} }
} }
@ -331,14 +331,14 @@ fn handle_module<'a>(
if ALL_MODULES.contains(&module) { if ALL_MODULES.contains(&module) {
// Write out a module if it isn't disabled // Write out a module if it isn't disabled
if !context.is_module_disabled_in_config(module) { if !context.is_module_disabled_in_config(module) {
modules.extend(modules::handle(module, &context)); modules.extend(modules::handle(module, context));
} }
} else if module == "custom" { } else if module == "custom" {
// Write out all custom modules, except for those that are explicitly set // Write out all custom modules, except for those that are explicitly set
if let Some(custom_modules) = context.config.get_custom_modules() { if let Some(custom_modules) = context.config.get_custom_modules() {
let custom_modules = custom_modules.iter().filter_map(|(custom_module, config)| { let custom_modules = custom_modules.iter().filter_map(|(custom_module, config)| {
if should_add_implicit_custom_module(custom_module, config, &module_list) { if should_add_implicit_custom_module(custom_module, config, module_list) {
modules::custom::module(custom_module, &context) modules::custom::module(custom_module, context)
} else { } else {
None None
} }
@ -347,9 +347,9 @@ fn handle_module<'a>(
} }
} else if let Some(module) = module.strip_prefix("custom.") { } else if let Some(module) = module.strip_prefix("custom.") {
// Write out a custom module if it isn't disabled (and it exists...) // Write out a custom module if it isn't disabled (and it exists...)
match context.is_custom_module_disabled_in_config(&module) { match context.is_custom_module_disabled_in_config(module) {
Some(true) => (), // Module is disabled, we don't add it to the prompt Some(true) => (), // Module is disabled, we don't add it to the prompt
Some(false) => modules.extend(modules::custom::module(&module, &context)), Some(false) => modules.extend(modules::custom::module(module, context)),
None => match context.config.get_custom_modules() { None => match context.config.get_custom_modules() {
Some(modules) => log::debug!( Some(modules) => log::debug!(
"top level format contains custom module \"{}\", but no configuration was provided. Configuration for the following modules were provided: {:?}", "top level format contains custom module \"{}\", but no configuration was provided. Configuration for the following modules were provided: {:?}",

View File

@ -133,7 +133,12 @@ impl<'a> ModuleRenderer<'a> {
} }
pub fn pipestatus(mut self, status: &[i32]) -> Self { pub fn pipestatus(mut self, status: &[i32]) -> Self {
self.context.pipestatus = Some(status.iter().map(|i| i.to_string()).collect()); self.context.pipestatus = Some(
status
.iter()
.map(std::string::ToString::to_string)
.collect(),
);
self self
} }

View File

@ -66,7 +66,7 @@ impl PartialEq for CommandOutput {
/// Execute a command and return the output on stdout and stderr if successful /// Execute a command and return the output on stdout and stderr if successful
#[cfg(not(test))] #[cfg(not(test))]
pub fn exec_cmd(cmd: &str, args: &[&str], time_limit: Duration) -> Option<CommandOutput> { pub fn exec_cmd(cmd: &str, args: &[&str], time_limit: Duration) -> Option<CommandOutput> {
internal_exec_cmd(&cmd, &args, time_limit) internal_exec_cmd(cmd, args, time_limit)
} }
#[cfg(test)] #[cfg(test)]
@ -271,7 +271,7 @@ CMake suite maintained and supported by Kitware (kitware.com/cmake).\n",
stderr: String::default(), stderr: String::default(),
}), }),
// If we don't have a mocked command fall back to executing the command // If we don't have a mocked command fall back to executing the command
_ => internal_exec_cmd(&cmd, &args, time_limit), _ => internal_exec_cmd(cmd, args, time_limit),
} }
} }