Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow comments in .python-version #1038

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 34 additions & 2 deletions rye/src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,7 @@ pub fn get_python_version_request_from_pyenv_pin(root: &Path) -> Option<PythonVe
loop {
here.push(".python-version");
if let Ok(contents) = fs::read_to_string(&here) {
let ver = contents.trim().parse().ok()?;
return Some(ver);
return read_python_version(&contents);
}

// pop filename
Expand All @@ -233,6 +232,20 @@ pub fn get_python_version_request_from_pyenv_pin(root: &Path) -> Option<PythonVe
None
}

/// Return the [`PythonVersionRequest`] from a `.python-version` file.
fn read_python_version(contents: &str) -> Option<PythonVersionRequest> {
// Skip empty lines and comments.
let ver = contents.lines().find(|line| {
let trimmed = line.trim();
!(trimmed.is_empty() || trimmed.starts_with('#'))
})?;

// Parse the version.
let ver = ver.parse().ok()?;

Some(ver)
}

/// Returns the most recent cpython release.
pub fn get_latest_cpython_version() -> Result<PythonVersion, Error> {
latest_available_python_version(&PythonVersionRequest {
Expand Down Expand Up @@ -278,3 +291,22 @@ pub fn write_credentials(doc: &toml_edit::DocumentMut) -> Result<(), Error> {
pub fn get_credentials_filepath() -> Result<PathBuf, Error> {
Ok(get_app_dir().join("credentials"))
}

#[cfg(test)]
mod test {

#[test]
fn test_read_python_version() {
// Parse a simple version.
let ver = super::read_python_version("3.8.1\n");
assert_eq!(ver, Some("3.8.1".parse().unwrap()));

// Skip empty lines.
let ver = super::read_python_version("\n\n3.8.1\n");
assert_eq!(ver, Some("3.8.1".parse().unwrap()));

// Skip comments.
let ver = super::read_python_version("# comment\n3.8.1\n");
assert_eq!(ver, Some("3.8.1".parse().unwrap()));
}
}