Skip to content

Commit

Permalink
eapi: add Eapi.parse() support
Browse files Browse the repository at this point in the history
  • Loading branch information
radhermit committed Dec 15, 2023
1 parent 39d0020 commit c2bcc44
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/pkgcraft/C.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,14 @@ cdef extern from "pkgcraft.h":
# The argument must be a non-null Eapi pointer.
char **pkgcraft_eapi_metadata_keys(const Eapi *eapi, uintptr_t *len)

# Determine if a string is a valid EAPI.
#
# Returns NULL on error.
#
# # Safety
# The argument should point to a UTF-8 string.
const char *pkgcraft_eapi_parse(const char *s)

# Get all known EAPIS.
#
# # Safety
Expand Down
2 changes: 1 addition & 1 deletion src/pkgcraft/dep/version.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ cdef class Version:
def parse(s: str, raised=False):
"""Determine if a string is a valid package version.
This avoids any allocations, only returning the validity status.
This avoids any string allocations, only returning the validity status.
Args:
s: the string to parse
Expand Down
27 changes: 27 additions & 0 deletions src/pkgcraft/eapi.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,33 @@ cdef class Eapi(Indirect):
"""Try to convert an object to an Eapi object."""
return Eapi._from_obj(obj)

@staticmethod
def parse(s: str, raised=False):
"""Determine if a string is a valid EAPI.
This avoids any string allocations, only returning the validity status.
Args:
s: the string to parse
raised: if True, raise an exception when invalid
Returns:
bool: True if the given string represents a valid EAPI, otherwise False.
Raises:
PkgcraftError: on failure if the raised parameter is set to True
>>> from pkgcraft.eapi import Eapi
>>> Eapi.parse('01')
True
>>> Eapi.parse('@1')
False
"""
valid = C.pkgcraft_eapi_parse(s.encode()) is not NULL
if not valid and raised:
raise PkgcraftError
return valid

def has(self, s: str):
"""Check if an EAPI has a given feature.
Expand Down
8 changes: 8 additions & 0 deletions tests/test_eapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest

from pkgcraft.eapi import *
from pkgcraft.error import PkgcraftError

from .misc import OperatorMap

Expand All @@ -22,6 +23,13 @@ def test_globals():


class TestEapi:
def test_parse(self):
assert Eapi.parse("01")
for s in ("@1", "-1", ".1"):
assert not Eapi.parse(s)
with pytest.raises(PkgcraftError, match=f"invalid EAPI: {s}"):
Eapi.parse(s, raised=True)

def test_has(self):
assert not EAPI_LATEST_OFFICIAL.has("RepoIds")
assert EAPI_LATEST.has("RepoIds")
Expand Down

0 comments on commit c2bcc44

Please sign in to comment.