Skip to content

Commit

Permalink
refactor: rework Python version retrieval and formatting
Browse files Browse the repository at this point in the history
Align Python version retrieval and formatting with established
Starship conventions.
  • Loading branch information
vladimyr authored Mar 14, 2021
1 parent bdca737 commit 34b0302
Showing 1 changed file with 24 additions and 25 deletions.
49 changes: 24 additions & 25 deletions src/modules/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,31 +69,30 @@ fn get_python_version(context: &Context, config: &PythonConfig) -> Option<String
if config.pyenv_version_name {
return Some(context.exec_cmd("pyenv", &["version-name"])?.stdout);
};
let version = config.python_binary.0.iter().find_map(|binary| {
match context.exec_cmd(binary, &["--version"]) {
Some(output) => {
if output.stdout.is_empty() {
Some(output.stderr)
} else {
Some(output.stdout)
}
let version = config
.python_binary
.0
.iter()
.find_map(|binary| context.exec_cmd(binary, &["--version"]))
.map(|output| {
if output.stdout.is_empty() {
output.stderr
} else {
output.stdout
}
None => None,
}
})?;
Some(format_python_version(&version))
})?;

format_python_version(&version)
}

fn format_python_version(python_stdout: &str) -> String {
format!(
"v{}",
python_stdout
.trim_start_matches("Python ")
.trim()
.split_whitespace()
.next()
.unwrap_or("?")
)
fn format_python_version(python_version: &str) -> Option<String> {
let version = python_version
// split into ["Python", v3.8.6", ...]
.split_whitespace()
// return "v3.8.6"
.nth(1)?;

Some(format!("v{}", version))
}

fn get_python_virtual_env(context: &Context) -> Option<String> {
Expand Down Expand Up @@ -125,19 +124,19 @@ mod tests {
#[test]
fn test_format_python_version() {
let input = "Python 3.7.2";
assert_eq!(format_python_version(input), "v3.7.2");
assert_eq!(format_python_version(input), Some("v3.7.2".to_string()));
}

#[test]
fn test_format_python_version_anaconda() {
let input = "Python 3.6.10 :: Anaconda, Inc.";
assert_eq!(format_python_version(input), "v3.6.10");
assert_eq!(format_python_version(input), Some("v3.6.10".to_string()));
}

#[test]
fn test_format_python_version_pypy() {
let input = "Python 3.7.9 (7e6e2bb30ac5fbdbd443619cae28c51d5c162a02, Nov 24 2020, 10:03:59)\n[PyPy 7.3.3-beta0 with GCC 10.2.0]";
assert_eq!(format_python_version(input), "v3.7.9");
assert_eq!(format_python_version(input), Some("v3.7.9".to_string()));
}

#[test]
Expand Down

0 comments on commit 34b0302

Please sign in to comment.