fix(python): Handle PyPy python version correctly (#2374)

* fix(python): Handle PyPy python version correctly

* refactor: rework Python version retrieval and formatting

Align Python version retrieval and formatting with established
Starship conventions.
This commit is contained in:
Asger Hautop Drewsen 2021-03-14 19:27:19 +01:00 committed by GitHub
parent 50bc5d9134
commit d2946ddff7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 22 deletions

View File

@ -69,29 +69,30 @@ fn get_python_version(context: &Context, config: &PythonConfig) -> Option<String
if config.pyenv_version_name { if config.pyenv_version_name {
return Some(context.exec_cmd("pyenv", &["version-name"])?.stdout); return Some(context.exec_cmd("pyenv", &["version-name"])?.stdout);
}; };
let version = config.python_binary.0.iter().find_map(|binary| { let version = config
match context.exec_cmd(binary, &["--version"]) { .python_binary
Some(output) => { .0
if output.stdout.is_empty() { .iter()
Some(output.stderr) .find_map(|binary| context.exec_cmd(binary, &["--version"]))
} else { .map(|output| {
Some(output.stdout) if output.stdout.is_empty() {
} output.stderr
} else {
output.stdout
} }
None => None, })?;
}
})?; format_python_version(&version)
Some(format_python_version(&version))
} }
fn format_python_version(python_stdout: &str) -> String { fn format_python_version(python_version: &str) -> Option<String> {
format!( let version = python_version
"v{}", // split into ["Python", "3.8.6", ...]
python_stdout .split_whitespace()
.trim_start_matches("Python ") // return "3.8.6"
.trim_end_matches(":: Anaconda, Inc.") .nth(1)?;
.trim()
) Some(format!("v{}", version))
} }
fn get_python_virtual_env(context: &Context) -> Option<String> { fn get_python_virtual_env(context: &Context) -> Option<String> {
@ -123,13 +124,19 @@ mod tests {
#[test] #[test]
fn test_format_python_version() { fn test_format_python_version() {
let input = "Python 3.7.2"; 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] #[test]
fn test_format_python_version_anaconda() { fn test_format_python_version_anaconda() {
let input = "Python 3.6.10 :: Anaconda, Inc."; 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), Some("v3.7.9".to_string()));
} }
#[test] #[test]