1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-11-16 18:15:16 +00:00
starship/src/modules/python.rs

74 lines
2.3 KiB
Rust
Raw Normal View History

2019-04-25 15:06:18 +00:00
use ansi_term::Color;
use std::process::Command;
2019-05-01 20:34:24 +00:00
use super::{Context, Module};
2019-04-25 15:06:18 +00:00
/// Creates a segment with the current Python version
///
/// Will display the Python version if any of the following criteria are met:
/// - Current directory contains a `.py` file
/// - Current directory contains a `.python-version` file
/// - Current directory contains a `requirements.txt` file
/// - Current directory contains a `pyproject.toml` file
pub fn segment<'a>(context: &'a Context) -> Option<Module<'a>> {
2019-05-12 17:37:23 +00:00
let is_py_project = context
.new_scan_dir()
.set_files(&["requirements.txt", ".python-version", "pyproject.toml"])
2019-05-12 17:37:23 +00:00
.set_extensions(&["py"])
.scan();
2019-04-25 15:06:18 +00:00
if !is_py_project {
return None;
}
match get_python_version() {
Some(python_version) => {
2019-05-01 20:34:24 +00:00
const PYTHON_CHAR: &str = "🐍 ";
let module_color = Color::Yellow.bold();
2019-04-25 15:06:18 +00:00
let mut module = context.new_module("python");
2019-05-01 20:34:24 +00:00
module.set_style(module_color);
2019-04-25 15:06:18 +00:00
let formatted_version = format_python_version(python_version);
2019-05-01 20:34:24 +00:00
module.new_segment("symbol", PYTHON_CHAR);
module.new_segment("version", formatted_version);
2019-04-25 15:06:18 +00:00
2019-05-01 20:34:24 +00:00
Some(module)
2019-04-25 15:06:18 +00:00
}
None => None,
}
}
fn get_python_version() -> Option<String> {
match Command::new("python").arg("--version").output() {
Ok(output) => {
// We have to check both stdout and stderr since for Python versions
// < 3.4, Python reports to stderr and for Python version >= 3.5,
// Python reports to stdout
if output.stdout.is_empty() {
let stderr_string = String::from_utf8(output.stderr).unwrap();
Some(stderr_string)
} else {
let stdout_string = String::from_utf8(output.stdout).unwrap();
Some(stdout_string)
}
}
2019-04-25 15:06:18 +00:00
Err(_) => None,
}
}
fn format_python_version(python_stdout: String) -> String {
format!("v{}", python_stdout.trim_start_matches("Python ").trim())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_python_version() {
let input = String::from("Python 3.7.2");
assert_eq!(format_python_version(input), "v3.7.2");
}
}