Skip to content

Commit

Permalink
Allow comments in .python-version (#1038)
Browse files Browse the repository at this point in the history
## Summary

`pyenv` allows comments in `.python-version` files, so Rye will now skip commented-out lines.

Note that not _all_ tools support this. For example, [`mise`](https://github.com/jdx/mise) does not.

Closes #1032.
  • Loading branch information
charliermarsh committed Apr 24, 2024
1 parent 5c0da37 commit 7c01d34
Showing 1 changed file with 34 additions and 2 deletions.
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()));
}
}

0 comments on commit 7c01d34

Please sign in to comment.