Skip to content

Commit

Permalink
Python binding wrap up
Browse files Browse the repository at this point in the history
  • Loading branch information
hadim committed Dec 20, 2023
1 parent 2228f1c commit f4ea4c6
Show file tree
Hide file tree
Showing 10 changed files with 120 additions and 16 deletions.
4 changes: 3 additions & 1 deletion crates/rattler_conda_types/src/version/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,9 @@ fn trailing_dash_underscore_parser(
dash_or_underscore: Option<char>,
) -> IResult<&str, (Option<Component>, Option<char>), ParseVersionErrorKind> {
// Parse a - or _. Return early if it cannot be found.
let (rest, Some(separator)) = opt(one_of::<_,_,(&str, ErrorKind)>("-_"))(input).map_err(|e| e.map(|(_, kind)| ParseVersionErrorKind::Nom(kind)))? else {
let (rest, Some(separator)) = opt(one_of::<_, _, (&str, ErrorKind)>("-_"))(input)
.map_err(|e| e.map(|(_, kind)| ParseVersionErrorKind::Nom(kind)))?
else {
return Ok((input, (None, dash_or_underscore)));
};

Expand Down
2 changes: 1 addition & 1 deletion crates/rattler_lock/src/conda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl TryFrom<LockedDependency> for RepoDataRecord {
..
} = value;
let LockedDependencyKind::Conda(value) = specific else {
return Err(ConversionError::NotACondaRecord)
return Err(ConversionError::NotACondaRecord);
};

let version = version.parse()?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl AuthenticationStorage {
) -> Result<(Url, Option<Authentication>), reqwest::Error> {
let url = url.into_url()?;
let Some(host) = url.host_str() else {
return Ok((url, None))
return Ok((url, None));
};

match self.get(host) {
Expand All @@ -121,7 +121,7 @@ impl AuthenticationStorage {

// Check for credentials under e.g. `*.prefix.dev`
let Some(mut domain) = url.domain() else {
return Ok((url, None))
return Ok((url, None));
};

loop {
Expand Down
4 changes: 3 additions & 1 deletion crates/rattler_solve/src/resolvo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,9 @@ impl<'a> DependencyProvider<SolverMatchSpec<'a>> for CondaDependencyProvider<'a>
}

fn get_dependencies(&self, solvable: SolvableId) -> Dependencies {
let SolverPackageRecord::Record(rec) = self.pool.resolve_solvable(solvable).inner() else { return Dependencies::default() };
let SolverPackageRecord::Record(rec) = self.pool.resolve_solvable(solvable).inner() else {
return Dependencies::default();
};

let mut parse_match_spec_cache = self.parse_match_spec_cache.borrow_mut();
let mut dependencies = Dependencies::default();
Expand Down
5 changes: 5 additions & 0 deletions py-rattler/rattler/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
FetchRepoDataError,
SolverError,
ConvertSubdirError,
VersionBumpError,
)
except ImportError:
# They are only redefined for documentation purposes
Expand Down Expand Up @@ -69,6 +70,9 @@ class SolverError(Exception): # type: ignore[no-redef]
class ConvertSubdirError(Exception): # type: ignore[no-redef]
"""An error that can occur when parsing a platform from a string."""

class VersionBumpError(Exception): # type: ignore[no-redef]
"""An error that can occur when bumping a version."""


__all__ = [
"ActivationError",
Expand All @@ -87,4 +91,5 @@ class ConvertSubdirError(Exception): # type: ignore[no-redef]
"SolverError",
"TransactionError",
"ConvertSubdirError",
"VersionBumpError",
]
56 changes: 52 additions & 4 deletions py-rattler/rattler/version/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,69 @@ def epoch(self) -> Optional[str]:
"""
return self._version.epoch()

def bump(self) -> Version:
def bump_major(self) -> Version:
"""
Returns a new version where the last numerical segment of this version has
Returns a new version where the major segment of this version has
been bumped.
Examples
--------
```python
>>> v = Version('1.0')
>>> v.bump()
>>> v.bump_major()
Version("2.0")
>>>
```
"""
return Version._from_py_version(self._version.bump_major())

def bump_minor(self) -> Version:
"""
Returns a new version where the minor segment of this version has
been bumped.
Examples
--------
```python
>>> v = Version('1.0')
>>> v.bump_minor()
Version("1.1")
>>>
```
"""
return Version._from_py_version(self._version.bump_minor())

def bump_patch(self) -> Version:
"""
Returns a new version where the patch segment of this version has
been bumped.
Examples
--------
```python
>>> v = Version('1.0.5')
>>> v.bump_patch()
Version("1.0.6")
>>>
```
"""
return Version._from_py_version(self._version.bump_patch())

def bump_last(self) -> Version:
"""
Returns a new version where the last segment of this version has
been bumped.
Examples
--------
```python
>>> v = Version('1.0')
>>> v.bump_last()
Version("1.1")
>>>
```
"""
return Version._from_py_version(self._version.bump())
return Version._from_py_version(self._version.bump_last())

@property
def has_local(self) -> bool:
Expand Down
6 changes: 5 additions & 1 deletion py-rattler/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use pyo3::{create_exception, PyErr};
use rattler::install::TransactionError;
use rattler_conda_types::{
ConvertSubdirError, InvalidPackageNameError, ParseArchError, ParseChannelError,
ParseMatchSpecError, ParsePlatformError, ParseVersionError,
ParseMatchSpecError, ParsePlatformError, ParseVersionError, VersionBumpError,
};
use rattler_repodata_gateway::fetch::FetchRepoDataError;
use rattler_shell::activation::ActivationError;
Expand Down Expand Up @@ -48,6 +48,8 @@ pub enum PyRattlerError {
LinkError(String),
#[error(transparent)]
ConverSubdirError(#[from] ConvertSubdirError),
#[error(transparent)]
VersionBumpError(#[from] VersionBumpError),
}

impl From<PyRattlerError> for PyErr {
Expand Down Expand Up @@ -85,6 +87,7 @@ impl From<PyRattlerError> for PyErr {
PyRattlerError::ConverSubdirError(err) => {
ConvertSubdirException::new_err(err.to_string())
}
PyRattlerError::VersionBumpError(err) => VersionBumpException::new_err(err.to_string()),
}
}
}
Expand All @@ -105,3 +108,4 @@ create_exception!(exceptions, SolverException, PyException);
create_exception!(exceptions, TransactionException, PyException);
create_exception!(exceptions, LinkException, PyException);
create_exception!(exceptions, ConvertSubdirException, PyException);
create_exception!(exceptions, VersionBumpException, PyException);
4 changes: 3 additions & 1 deletion py-rattler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use error::{
FetchRepoDataException, InvalidChannelException, InvalidMatchSpecException,
InvalidPackageNameException, InvalidUrlException, InvalidVersionException, IoException,
LinkException, ParseArchException, ParsePlatformException, PyRattlerError, SolverException,
TransactionException,
TransactionException, VersionBumpException,
};
use generic_virtual_package::PyGenericVirtualPackage;
use match_spec::PyMatchSpec;
Expand Down Expand Up @@ -143,5 +143,7 @@ fn rattler(py: Python, m: &PyModule) -> PyResult<()> {
py.get_type::<ConvertSubdirException>(),
)
.unwrap();
m.add("VersionBumpError", py.get_type::<VersionBumpException>())
.unwrap();
Ok(())
}
35 changes: 30 additions & 5 deletions py-rattler/src/version/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,36 @@ impl PyVersion {
}
}

/// Returns a new version where the last numerical segment of this version has been bumped.
pub fn bump(&self, bump_type: VersionBumpType) -> PyResult<Self> {
Ok(Self {
inner: self.inner.bump(bump_type).unwrap(),
})
/// Returns a new version where the major segment of this version has been bumped.
pub fn bump_major(&self) -> PyResult<Self> {
match self.inner.bump(VersionBumpType::Major) {
Ok(v) => Ok(Self { inner: v }),
Err(e) => Err(PyRattlerError::from(e).into()),
}
}

/// Returns a new version where the minor segment of this version has been bumped.
pub fn bump_minor(&self) -> PyResult<Self> {
match self.inner.bump(VersionBumpType::Minor) {
Ok(v) => Ok(Self { inner: v }),
Err(e) => Err(PyRattlerError::from(e).into()),
}
}

/// Returns a new version where the patch segment of this version has been bumped.
pub fn bump_patch(&self) -> PyResult<Self> {
match self.inner.bump(VersionBumpType::Patch) {
Ok(v) => Ok(Self { inner: v }),
Err(e) => Err(PyRattlerError::from(e).into()),
}
}

/// Returns a new version where the last segment of this version has been bumped.
pub fn bump_last(&self) -> PyResult<Self> {
match self.inner.bump(VersionBumpType::Last) {
Ok(v) => Ok(Self { inner: v }),
Err(e) => Err(PyRattlerError::from(e).into()),
}
}

/// Compute the hash of the version.
Expand Down
16 changes: 16 additions & 0 deletions py-rattler/tests/unit/test_version.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest
from rattler import Version
from rattler.exceptions import VersionBumpError


def test_version_dash_normalisation() -> None:
Expand All @@ -17,3 +18,18 @@ def test_version_dash_normalisation() -> None:

with pytest.raises(Exception):
Version("1-.0dev+3.4-")


def test_bump() -> None:
assert Version("0.5.5").bump_major() == Version("1.5.5")
assert Version("0.5.5").bump_minor() == Version("0.6.5")
assert Version("0.5.5").bump_patch() == Version("0.5.6")
assert Version("0.5.5").bump_last() == Version("0.5.6")


def test_bump_fail() -> None:
with pytest.raises(VersionBumpError):
Version("1").bump_minor()

with pytest.raises(VersionBumpError):
Version("1.5").bump_patch()

0 comments on commit f4ea4c6

Please sign in to comment.