instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
pydicom__pynetdicom-516
diff --git a/docs/changelog/v2.0.0.rst b/docs/changelog/v2.0.0.rst index 15c78b248..ee46b8351 100644 --- a/docs/changelog/v2.0.0.rst +++ b/docs/changelog/v2.0.0.rst @@ -4,6 +4,12 @@ ===== +Enhancements +............ + +* Added configuration option :attr:`_config.ALLOW_LONG_DIMSE_AET` to allow + bypassing the length check for elements with a VR of **AE** (:issue:`515`) + Changes ....... diff --git a/docs/reference/config.rst b/docs/reference/config.rst index d1676bd2b..fa9e28c0d 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -13,5 +13,6 @@ Configuration Options (:mod:`pynetdicom._config`) ENFORCE_UID_CONFORMANCE LOG_HANDLER_LEVEL USE_SHORT_DIMSE_AET + ALLOW_LONG_DIMSE_AET LOG_REQUEST_IDENTIFIERS LOG_RESPONSE_IDENTIFIERS diff --git a/pynetdicom/_config.py b/pynetdicom/_config.py index f8fc47958..f07625023 100644 --- a/pynetdicom/_config.py +++ b/pynetdicom/_config.py @@ -52,6 +52,23 @@ Examples """ +ALLOW_LONG_DIMSE_AET = False +"""Allow the use of non-conformant AE titles. + +.. versionadded:: 2.0 + +If ``False`` then elements with a VR of AE in DIMSE messages will have their +length checked to ensure conformance, otherwise no length check will be +performed. + +Examples +-------- + +>>> from pynetdicom import _config +>>> _config.ALL_LONG_AET = True +""" + + LOG_RESPONSE_IDENTIFIERS = True """Log incoming C-FIND, C-GET and C-MOVE response *Identifier* datasets. diff --git a/pynetdicom/apps/qrscp/handlers.py b/pynetdicom/apps/qrscp/handlers.py index 05d946d78..449314b39 100644 --- a/pynetdicom/apps/qrscp/handlers.py +++ b/pynetdicom/apps/qrscp/handlers.py @@ -172,7 +172,7 @@ def handle_get(event, db_path, cli_config, logger): try: ds = dcmread(match.filename) except Exception as exc: - logger.error(f"Error reading file: {fpath}") + logger.error(f"Error reading file: {match.filename}") logger.exception(exc) yield 0xC421, None @@ -264,7 +264,7 @@ def handle_move(event, destinations, db_path, cli_config, logger): try: ds = dcmread(match.filename) except Exception as exc: - logger.error(f"Error reading file: {fpath}") + logger.error(f"Error reading file: {match.filename}") logger.exception(exc) yield 0xC521, None diff --git a/pynetdicom/utils.py b/pynetdicom/utils.py index c12df7fa5..239b3532f 100644 --- a/pynetdicom/utils.py +++ b/pynetdicom/utils.py @@ -127,8 +127,10 @@ def validate_ae_title(ae_title, use_short=False): "AE titles are not allowed to consist entirely of only spaces" ) - # Truncate if longer than 16 characters - ae_title = ae_title[:16] + if not _config.ALLOW_LONG_DIMSE_AET: + # Truncate if longer than 16 characters + ae_title = ae_title[:16] + if not use_short: # Pad out to 16 characters using spaces ae_title = ae_title.ljust(16)
pydicom/pynetdicom
674ec1f93cbbc07f181f42e216d9df9edf56dc3d
diff --git a/pynetdicom/tests/test_utils.py b/pynetdicom/tests/test_utils.py index da278865b..f697f1b0b 100644 --- a/pynetdicom/tests/test_utils.py +++ b/pynetdicom/tests/test_utils.py @@ -97,6 +97,15 @@ class TestValidateAETitle(object): with pytest.raises((TypeError, ValueError)): validate_ae_title(aet) + def test_length_check(self): + """Test validate_ae_title with no length check.""" + assert _config.ALLOW_LONG_DIMSE_AET is False + aet = b"12345678901234567890" + assert 16 == len(validate_ae_title(aet)) + _config.ALLOW_LONG_DIMSE_AET = True + assert 20 == len(validate_ae_title(aet)) + _config.ALLOW_LONG_DIMSE_AET = False + REFERENCE_UID = [ # UID, (enforced, non-enforced conformance)
Add switch for valieate_ae_title in C-MOVE request **Is your feature request related to a problem? Please describe.** I've met a custom DICOM server that allows me to send receiver AE title in C-MOVE request in format "ae_title@IP:port" where ae_title is regular title and IP and port is an address of receiver. It allows them to process C-MOVE requests without maintaining a table of AEs and their addresses. Of course such AE title is longer than 16 bytes allowed by DICOM standard and I can't use this library without patching. **Describe the solution you'd like** I've already made a simplest patch that allows me to switch off the AE title length check in C-MOVE request. Now I'd like to merge it into the main repo to not to maintain a fork. Now it works only for C-MOVE request so I probably need to make it more general. **Describe alternatives you've considered** Now I have to fork the project and maintain it. I also considered monkey patching but it seems too weird. **Additional context** I understand that it's just a non-standard DICOM server and in general project doesn't have to support such things. That's why I ask you to add switch that will just allow users that have such problem to switch off this particular check.
0.0
674ec1f93cbbc07f181f42e216d9df9edf56dc3d
[ "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_length_check" ]
[ "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_str[a-a", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_str[a", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_str[", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_str[ABCDEFGHIJKLMNOPQRSTUVWXYZ-ABCDEFGHIJKLMNOP]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_bytes[a-a", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_bytes[a", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_bytes[", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_good_ae_bytes[ABCDEFGHIJKLMNOPQRSTUVWXYZ-ABCDEFGHIJKLMNOP]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[AE\\\\TITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[AE\\tTITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[AE\\rTITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[AE\\nTITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\t]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\n]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\x0c]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\r]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\x1b]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\x01]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[\\x0e]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[1234]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_str[45.1]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[AE\\TITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[AE\\tTITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[AE\\rTITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[AE\\nTITLE]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\t]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\n]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\x0c]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\r]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\x1b]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\x01]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[\\x0e]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[1234]", "pynetdicom/tests/test_utils.py::TestValidateAETitle::test_bad_ae_bytes[45.1]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[-is_valid0]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[11111111111111111111111111111111111111111111111111111111111111111-is_valid2]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-is_valid3]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-is_valid4]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[0.1.2.04-is_valid5]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[some", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[1111111111111111111111111111111111111111111111111111111111111111-is_valid7]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_true[0.1.2.4-is_valid8]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[-is_valid0]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[11111111111111111111111111111111111111111111111111111111111111111-is_valid2]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-is_valid3]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-is_valid4]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[0.1.2.04-is_valid5]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[some", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[1111111111111111111111111111111111111111111111111111111111111111-is_valid7]", "pynetdicom/tests/test_utils.py::TestValidateUID::test_validate_uid_conformance_false[0.1.2.4-is_valid8]", "pynetdicom/tests/test_utils.py::TestPrettyBytes::test_parameters", "pynetdicom/tests/test_utils.py::TestPrettyBytes::test_bytesio" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-10 23:21:14+00:00
mit
4,935
pydicom__pynetdicom-730
diff --git a/.github/workflows/publish-pypi-deploy.yml b/.github/workflows/publish-pypi-deploy.yml index 4cd253324..5839901de 100644 --- a/.github/workflows/publish-pypi-deploy.yml +++ b/.github/workflows/publish-pypi-deploy.yml @@ -44,8 +44,8 @@ jobs: pip install -i https://test.pypi.org/simple/ pynetdicom - name: Test with pytest - with: - python-version: '3.10' + env: + PYTHON_VERSION: ${{ matrix.python-version }} run: | cd ${HOME} python -m pynetdicom --version diff --git a/docs/changelog/index.rst b/docs/changelog/index.rst index 2f5bf3e74..523d43290 100644 --- a/docs/changelog/index.rst +++ b/docs/changelog/index.rst @@ -8,6 +8,7 @@ Release Notes :maxdepth: 1 v2.1.0 + v2.0.1 v2.0.0 v1.5.7 v1.5.6 diff --git a/docs/changelog/v2.0.1.rst b/docs/changelog/v2.0.1.rst new file mode 100644 index 000000000..82339bc1f --- /dev/null +++ b/docs/changelog/v2.0.1.rst @@ -0,0 +1,10 @@ +.. _v2.0.1: + +2.0.1 +===== + +Changes +....... + +* Revert change to default bind address +* Don't allow passing an address tuple to T_CONNECT initialisation diff --git a/docs/index.rst b/docs/index.rst index 82715381e..5e2544974 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -120,6 +120,7 @@ Release Notes ============= * :doc:`v2.1.0 </changelog/v2.1.0>` +* :doc:`v2.0.1 </changelog/v2.0.0>` * :doc:`v2.0.0 </changelog/v2.0.0>` * :doc:`v1.5.7 </changelog/v1.5.7>` * :doc:`v1.5.6 </changelog/v1.5.6>` diff --git a/pynetdicom/_globals.py b/pynetdicom/_globals.py index d8cd60fd4..79bbef9b9 100644 --- a/pynetdicom/_globals.py +++ b/pynetdicom/_globals.py @@ -99,7 +99,7 @@ STATUS_UNKNOWN: str = "Unknown" # The default address that client sockets are bound to -BIND_ADDRESS = ("127.0.0.1", 0) +BIND_ADDRESS = ("", 0) OptionalUIDType = Optional[Union[str, bytes, UID]] diff --git a/pynetdicom/transport.py b/pynetdicom/transport.py index 06186e7a9..50df9d6ca 100644 --- a/pynetdicom/transport.py +++ b/pynetdicom/transport.py @@ -52,41 +52,64 @@ class T_CONNECT: """A TRANSPORT CONNECTION primitive .. versionadded:: 2.0 + + Attributes + ---------- + request : pynetdicom.pdu_primitives.A_ASSOCIATE + The A-ASSOCIATE (request) primitive that generated the TRANSPORT CONNECTION + primitive. """ - def __init__(self, address: Union[Tuple[str, int], "A_ASSOCIATE"]) -> None: + def __init__(self, request: "A_ASSOCIATE") -> None: """Create a new TRANSPORT CONNECTION primitive. Parameters ---------- - address : Union[Tuple[str, int], pynetdicom.pdu_primitives.A_ASSOCIATE] - The ``(str: IP address, int: port)`` or A-ASSOCIATE (request) primitive to - use when making a connection with a peer. + request : pynetdicom.pdu_primitives.A_ASSOCIATE + The A-ASSOCIATE (request) primitive to use when making a connection with + a peer. """ - self._request = None - self.result = "" - - if isinstance(address, tuple): - self._address = address - elif isinstance(address, A_ASSOCIATE): - self._address = cast(Tuple[str, int], address.called_presentation_address) - self._request = address - else: + self._result = "" + self.request = request + + if not isinstance(request, A_ASSOCIATE): raise TypeError( - f"'address' must be 'Tuple[str, int]' or " - "'pynetdicom.pdu_primitives.A_ASSOCIATE', not " - f"'{address.__class__.__name__}'" + f"'request' must be 'pynetdicom.pdu_primitives.A_ASSOCIATE', not " + f"'{request.__class__.__name__}'" ) @property def address(self) -> Tuple[str, int]: """Return the peer's ``(str: IP address, int: port)``.""" - return self._address + return cast(Tuple[str, int], self.request.called_presentation_address) @property - def request(self) -> Optional[A_ASSOCIATE]: - """Return the A-ASSOCIATE (request) primitive, or ``None`` if not available.""" - return self._request + def result(self) -> str: + """Return the result of the connection attempt as :class:`str`. + + Parameters + ---------- + str + The result of the connection attempt, ``"Evt2"`` if the connection + succeeded, ``"Evt17"`` if it failed. + + Returns + ------- + str + The result of the connection attempt, ``"Evt2"`` if the connection + succeeded, ``"Evt17"`` if it failed. + """ + if self._result == "": + raise ValueError("A connection attempt has not yet been made") + + return self._result + + @result.setter + def result(self, value: str) -> None: + if value not in ("Evt2", "Evt17"): + raise ValueError(f"Invalid connection result '{value}'") + + self._result = value class AssociationSocket: @@ -190,7 +213,7 @@ class AssociationSocket: self.event_queue.put("Evt17") def connect(self, primitive: T_CONNECT) -> None: - """Try and connect to a remote at `address`. + """Try and connect to a remote using connection details from `primitive`. .. versionchanged:: 2.0
pydicom/pynetdicom
3ce1bc45ea8d963242beed70133ed34933a637c6
diff --git a/pynetdicom/tests/test_transport.py b/pynetdicom/tests/test_transport.py index b57288951..47cb4f06f 100644 --- a/pynetdicom/tests/test_transport.py +++ b/pynetdicom/tests/test_transport.py @@ -62,19 +62,11 @@ class TestTConnect: def test_bad_addr_raises(self): """Test a bad init parameter raises exception""" msg = ( - r"'address' must be 'Tuple\[str, int\]' or " - r"'pynetdicom.pdu_primitives.A_ASSOCIATE', not 'NoneType'" + r"'request' must be 'pynetdicom.pdu_primitives.A_ASSOCIATE', not 'NoneType'" ) with pytest.raises(TypeError, match=msg): T_CONNECT(None) - def test_address_tuple(self): - """Test init with a tuple""" - conn = T_CONNECT(("123", 12)) - assert conn.address == ("123", 12) - assert conn.request is None - assert conn.result == "" - def test_address_request(self): """Test init with an A-ASSOCIATE primitive""" request = A_ASSOCIATE() @@ -82,7 +74,26 @@ class TestTConnect: conn = T_CONNECT(request) assert conn.address == ("123", 12) assert conn.request is request - assert conn.result == "" + + msg = r"A connection attempt has not yet been made" + with pytest.raises(ValueError, match=msg): + conn.result + + def test_result_setter(self): + """Test setting the result value.""" + request = A_ASSOCIATE() + request.called_presentation_address = ("123", 12) + conn = T_CONNECT(request) + + msg = r"Invalid connection result 'foo'" + with pytest.raises(ValueError, match=msg): + conn.result = "foo" + + assert conn._result == "" + + for result in ("Evt2", "Evt17"): + conn.result = result + assert conn.result == result class TestAssociationSocket: @@ -161,7 +172,9 @@ class TestAssociationSocket: sock.close() assert sock.socket is None # Tries to connect, sets to None if fails - sock.connect(T_CONNECT(("localhost", 11112))) + request = A_ASSOCIATE() + request.called_presentation_address = ("123", 12) + sock.connect(T_CONNECT(request)) assert sock.event_queue.get() == "Evt17" assert sock.socket is None
T_CONNECT doesn't work with only Tuple[str, int] Whoops. I meant to emulate the previous behaviour for `AssociationSocket.connect()`, but it obviously won't work since it puts the T_CONNECT A-ASSOCIATE primitive on the DUL's `to_provider_queue`.
0.0
3ce1bc45ea8d963242beed70133ed34933a637c6
[ "pynetdicom/tests/test_transport.py::TestTConnect::test_bad_addr_raises", "pynetdicom/tests/test_transport.py::TestTConnect::test_address_request", "pynetdicom/tests/test_transport.py::TestTConnect::test_result_setter" ]
[ "pynetdicom/tests/test_transport.py::TestAssociationSocket::test_close_socket_none", "pynetdicom/tests/test_transport.py::TestAssociationSocket::test_get_local_addr", "pynetdicom/tests/test_transport.py::TestAssociationSocket::test_multiple_pdu_req", "pynetdicom/tests/test_transport.py::TestAssociationSocket::test_multiple_pdu_acc", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_not_server_not_client", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_not_server_yes_client", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_yes_server_not_client", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_yes_server_yes_client", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_transfer", "pynetdicom/tests/test_transport.py::TestTLS::test_no_ssl_scp", "pynetdicom/tests/test_transport.py::TestTLS::test_no_ssl_scu" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-12-28 20:39:52+00:00
mit
4,936
pydicom__pynetdicom-766
diff --git a/docs/changelog/v2.1.0.rst b/docs/changelog/v2.1.0.rst index 07c30038b..2a9df97cf 100644 --- a/docs/changelog/v2.1.0.rst +++ b/docs/changelog/v2.1.0.rst @@ -7,9 +7,12 @@ Fixes ..... * Fixed reserved A-ASSOCIATE-AC parameters being tested (:issue:`746`) +* Fixed datasets not transferring correctly when using + :attr:`~pynetdicom._config.STORE_RECV_CHUNKED_DATASET` (:issue:`756`) Enhancements ............ + Changes ....... diff --git a/pynetdicom/dimse.py b/pynetdicom/dimse.py index caf8a8a38..a92d1c97e 100644 --- a/pynetdicom/dimse.py +++ b/pynetdicom/dimse.py @@ -324,6 +324,8 @@ class DIMSEServiceProvider: # Reset the DIMSE message, ready for the next one self.message.encoded_command_set = BytesIO() self.message.data_set = BytesIO() + self.message._data_set_file = None + self.message._data_set_path = None self.message = None def send_msg(self, primitive: DimsePrimitiveType, context_id: int) -> None: diff --git a/pynetdicom/dimse_messages.py b/pynetdicom/dimse_messages.py index a307cfcd4..76eec93c2 100644 --- a/pynetdicom/dimse_messages.py +++ b/pynetdicom/dimse_messages.py @@ -418,9 +418,6 @@ class DIMSEMessage: # xxxxxx11 - Command information, the last fragment control_header_byte = data[0] - # LOGGER.debug('Control header byte %s', control_header_byte) - # print(f'Control header byte {control_header_byte}') - # COMMAND SET # P-DATA fragment contains Command Set information # (control_header_byte is xxxxxx01 or xxxxxx11) @@ -497,6 +494,7 @@ class DIMSEMessage: # number of P-DATA primitives. if self._data_set_file: self._data_set_file.write(data[1:]) + self._data_set_file.file.flush() else: cast(BytesIO, self.data_set).write(data[1:]) diff --git a/pynetdicom/dimse_primitives.py b/pynetdicom/dimse_primitives.py index daa100bb9..0d9b20e28 100644 --- a/pynetdicom/dimse_primitives.py +++ b/pynetdicom/dimse_primitives.py @@ -21,11 +21,13 @@ from pynetdicom.utils import set_ae, decode_bytes, set_uid if TYPE_CHECKING: # pragma: no cover + from io import BufferedWriter from typing import Protocol # Python 3.8+ class NTF(Protocol): # Protocol for a NamedTemporaryFile name: str + file: BufferedWriter def write(self, data: bytes) -> bytes: ...
pydicom/pynetdicom
ddc34625e08f0f9a083a31619aa99aa431ee2bc3
diff --git a/pynetdicom/tests/test_service_storage.py b/pynetdicom/tests/test_service_storage.py index 3fd41ad55..682ef983c 100644 --- a/pynetdicom/tests/test_service_storage.py +++ b/pynetdicom/tests/test_service_storage.py @@ -472,6 +472,7 @@ class TestStorageServiceClass: handlers = [(evt.EVT_C_STORE, handle)] self.ae = ae = AE() + ae.maximum_pdu_size = 256 ae.add_supported_context(CTImageStorage) ae.add_requested_context(CTImageStorage) scp = ae.start_server(("localhost", 11112), block=False, evt_handlers=handlers) @@ -492,6 +493,8 @@ class TestStorageServiceClass: ds = attrs["dataset"] assert "CompressedSamples^CT1" == ds.PatientName + assert "DataSetTrailingPadding" in ds + assert len(ds.DataSetTrailingPadding) == 126 scp.shutdown()
PixelData truncated when _config.STORE_RECV_CHUNKED_DATASET is enabled **Describe the bug** We are running a Storage SCP service using pynetdicom on Windows 10. We are seeing some images stored with truncated PixelData when setting `_config.STORE_RECV_CHUNKED_DATASET = True`. This issue was seen in the field using data sent from a modality and later reproduced with `storescu`. The PixelData is correct when using a Storage SCP with the config setting disabled. **Expected behavior** We expect the PixelData to be the correct length. **Steps To Reproduce** 1. Create a storescp python script in Windows with the following code: ``` #!/usr/local/bin/python from pynetdicom import AE, evt, AllStoragePresentationContexts, _config, debug_logger debug_logger() _config.STORE_RECV_CHUNKED_DATASET = True # Implement a handler for evt.EVT_C_STORE def handle_store(event): from pydicom import dcmread """Handle a C-STORE request event.""" with open(event.dataset_path, 'rb') as fh: ds = dcmread(fh) ds.save_as(ds.SOPInstanceUID, write_like_original = False) # Return a 'Success' status return 0x0000 handlers = [(evt.EVT_C_STORE, handle_store)] # Initialise the Application Entity ae = AE() # Support presentation contexts for all storage SOP Classes ae.supported_contexts = AllStoragePresentationContexts # Start listening for incoming association requests ae.start_server(('', 104), evt_handlers=handlers) ``` 2. Send an example file to the scp: [example.zip](https://github.com/pydicom/pynetdicom/files/8514505/example.zip) ``` python -m pynetdicom storescu -v 127.0.0.1 104 .\example.dcm ``` 3. Note that the resulting output file will have truncated PixelData: ``` (7fe0, 0010) Pixel Data OW: Array of 130116 elements ``` Should be: ``` (7fe0, 0010) Pixel Data OW: Array of 131072 elements ``` **Storage SCP Debug log**: [debug.txt](https://github.com/pydicom/pynetdicom/files/8514604/debug.txt) **Your environment** ``` Windows-10-10.0.19041-SP0 Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] pydicom 2.3.0 pynetdicom 2.0.1 ```
0.0
ddc34625e08f0f9a083a31619aa99aa431ee2bc3
[ "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_dataset_path", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_dataset_path_windows_unlink", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_move_origin", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_sop_extended", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_event_ds_modify" ]
[ "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_status_enum", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_failed_ds_decode", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_dataset", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_dataset_multi", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_int", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_invalid", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_no_status", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_exception_default", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_exception", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_context", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_assoc", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_request", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_dataset" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-23 03:52:44+00:00
mit
4,937
pyiron__pyiron_base-1138
diff --git a/pyiron_base/database/filetable.py b/pyiron_base/database/filetable.py index 2c44d0ed..e2c7bec5 100644 --- a/pyiron_base/database/filetable.py +++ b/pyiron_base/database/filetable.py @@ -534,9 +534,15 @@ class FileTable(IsDatabase, metaclass=FileTableSingleton): ) ] ) + sanitized_paths = self._fileindex.dataframe.path.str.replace("\\", "/") + # The files_list is generated using project path values + # In pyiron, these are all forced to be posix-like with / + # But _fileindex is of type PyFileIndex, which does _not_ modify paths + # so to get the two compatible for an isin check, we need to sanitize the + # _fileindex.dataframe.path results df_new = self._fileindex.dataframe[ ~self._fileindex.dataframe.is_directory - & ~self._fileindex.dataframe.path.isin(files_lst) + & ~sanitized_paths.isin(files_lst) ] else: files_lst, working_dir_lst = [], [] @@ -565,7 +571,11 @@ class FileTable(IsDatabase, metaclass=FileTableSingleton): "status": get_job_status_from_file(hdf5_file=path, job_name=job), "job": job, "subjob": "/" + job, - "project": os.path.dirname(path) + "/", + "project": os.path.dirname(path).replace("\\", "/") + "/", + # pyiron Project paths are forced to be posix-like with / instead of \ + # in order for the contains and endswith tests down in _get_job_table + # to work on windows, we need to make sure that the file table obeys + # this conversion "timestart": time, "timestop": time, "totalcputime": 0.0, diff --git a/pyiron_base/jobs/datamining.py b/pyiron_base/jobs/datamining.py index 9906b525..27cc533e 100644 --- a/pyiron_base/jobs/datamining.py +++ b/pyiron_base/jobs/datamining.py @@ -683,14 +683,19 @@ class TableJob(GenericJob): with self.project_hdf5.open("input") as hdf5_input: if "project" in hdf5_input.list_nodes(): project_dict = hdf5_input["project"] - project = self.project.__class__( - path=project_dict["path"], - user=project_dict["user"], - sql_query=project_dict["sql_query"], - ) - project._filter = project_dict["filter"] - project._inspect_mode = project_dict["inspect_mode"] - self.analysis_project = project + if os.path.exists(project_dict["path"]): + project = self.project.__class__( + path=project_dict["path"], + user=project_dict["user"], + sql_query=project_dict["sql_query"], + ) + project._filter = project_dict["filter"] + project._inspect_mode = project_dict["inspect_mode"] + self.analysis_project = project + else: + self._logger.warning( + f"Could not instantiate analysis_project, no such path {project_dict['path']}." + ) if "filter" in hdf5_input.list_nodes(): if hdf_version == "0.1.0": self.pyiron_table._filter_function_str = hdf5_input["filter"] diff --git a/pyiron_base/jobs/job/extension/server/runmode.py b/pyiron_base/jobs/job/extension/server/runmode.py index f9b3bed6..1854b227 100644 --- a/pyiron_base/jobs/job/extension/server/runmode.py +++ b/pyiron_base/jobs/job/extension/server/runmode.py @@ -26,7 +26,6 @@ run_mode_lst = [ "thread", "worker", "srun", - "flux", "interactive", "interactive_non_modal", ] diff --git a/pyiron_base/jobs/job/generic.py b/pyiron_base/jobs/job/generic.py index b7f690cb..978801e7 100644 --- a/pyiron_base/jobs/job/generic.py +++ b/pyiron_base/jobs/job/generic.py @@ -154,7 +154,6 @@ class GenericJob(JobCore): self._compress_by_default = False self._python_only_job = False self._write_work_dir_warnings = True - self._flux_executor = None self.interactive_cache = None self.error = GenericError(job=self) @@ -210,15 +209,6 @@ class GenericJob(JobCore): self._executable_activate() self._executable.executable_path = exe - @property - def flux_executor(self): - return self._flux_executor - - @flux_executor.setter - def flux_executor(self, exe): - self.server.run_mode.flux = True - self._flux_executor = exe - @property def server(self): """ @@ -700,9 +690,9 @@ class GenericJob(JobCore): if repair and self.job_id and not self.status.finished: self._run_if_repair() elif status == "initialized": - return self._run_if_new(debug=debug) + self._run_if_new(debug=debug) elif status == "created": - return self._run_if_created() + self._run_if_created() elif status == "submitted": run_job_with_status_submitted(job=self) elif status == "running": @@ -1201,7 +1191,7 @@ class GenericJob(JobCore): Args: debug (bool): Debug Mode """ - return run_job_with_status_initialized(job=self, debug=debug) + run_job_with_status_initialized(job=self, debug=debug) def _run_if_created(self): """ diff --git a/pyiron_base/jobs/job/runfunction.py b/pyiron_base/jobs/job/runfunction.py index 80274024..895e738c 100644 --- a/pyiron_base/jobs/job/runfunction.py +++ b/pyiron_base/jobs/job/runfunction.py @@ -7,19 +7,10 @@ import os import posixpath import subprocess -from jinja2 import Template - from pyiron_base.utils.deprecate import deprecate from pyiron_base.jobs.job.wrapper import JobWrapper from pyiron_base.state import state -try: - import flux.job - - flux_available = True -except ImportError: - flux_available = False - """ The function job.run() inside pyiron is executed differently depending on the status of the job object. This module @@ -48,7 +39,6 @@ of the server object attached to the job object: job.server.run_mode interactive_non_modal: run_job_with_runmode_interactive_non_modal queue: run_job_with_runmode_queue srun: run_job_with_runmode_srun - flux: run_job_with_runmode_flux thread: only affects children of a GenericMaster worker: only affects children of a GenericMaster @@ -86,7 +76,7 @@ def run_job_with_status_initialized(job, debug=False): print("job exists already and therefore was not created!") else: job.save() - return job.run() + job.run() def run_job_with_status_created(job): @@ -112,16 +102,6 @@ def run_job_with_status_created(job): job.run_static() elif job.server.run_mode.srun: run_job_with_runmode_srun(job=job) - elif job.server.run_mode.flux: - if job.server.gpus is not None: - gpus_per_slot = int(job.server.gpus / job.server.cores) - else: - gpus_per_slot = None - return run_job_with_runmode_flux( - job=job, - executor=job.flux_executor, - gpus_per_slot=gpus_per_slot, - ) elif ( job.server.run_mode.non_modal or job.server.run_mode.thread @@ -451,53 +431,6 @@ def run_job_with_runmode_srun(job): ) -def run_job_with_runmode_flux(job, executor, gpus_per_slot=None): - if not flux_available: - raise ModuleNotFoundError( - "No module named 'flux'. Running in flux mode is only available on Linux;" - "For CPU jobs, please use `conda install -c conda-forge flux-core`; for " - "GPU support you will additionally need " - "`conda install -c conda-forge flux-sched libhwloc=*=cuda*`" - ) - if not state.database.database_is_disabled: - executable_template = Template( - """\ -#!/bin/bash -python -m pyiron_base.cli wrapper -p {{working_directory}} -j {{job_id}} -""" - ) - exeuctable_str = executable_template.render( - working_directory=job.working_directory, - job_id=str(job.job_id), - ) - job_name = "pi_" + str(job.job_id) - else: - executable_template = Template( - """\ -#!/bin/bash -python -m pyiron_base.cli wrapper -p {{working_directory}} -f {{file_name}}{{h5_path}} -""" - ) - exeuctable_str = executable_template.render( - working_directory=job.working_directory, - file_name=job.project_hdf5.file_name, - h5_path=job.project_hdf5.h5_path, - ) - job_name = "pi_" + job.job_name - - jobspec = flux.job.JobspecV1.from_batch_command( - jobname=job_name, - script=exeuctable_str, - num_nodes=1, - cores_per_slot=1, - gpus_per_slot=gpus_per_slot, - num_slots=job.server.cores, - ) - jobspec.cwd = job.project_hdf5.working_directory - jobspec.environment = dict(os.environ) - return executor.submit(jobspec) - - def run_time_decorator(func): def wrapper(job): if not state.database.database_is_disabled and job.job_id is not None: diff --git a/pyiron_base/project/maintenance.py b/pyiron_base/project/maintenance.py index d0232688..fa5c34bf 100644 --- a/pyiron_base/project/maintenance.py +++ b/pyiron_base/project/maintenance.py @@ -99,7 +99,7 @@ class LocalMaintenance: recursive=recursive, progress=progress, convert_to_object=False, **kwargs ): hdf = job.project_hdf5 - hdf.rewrite_hdf(job.name) + hdf.rewrite_hdf5(job.name) class UpdateMaintenance: @@ -119,9 +119,9 @@ class UpdateMaintenance: configuration. """ mayor, minor = start_version.split(".")[0:2] - if mayor != 0: + if int(mayor) != 0: raise ValueError("Updates to version >0.x.y is not possible.") - if minor < 4: + if int(minor) < 4: self.base_v0_3_to_v0_4(project) def base_v0_3_to_v0_4(self, project=None):
pyiron/pyiron_base
0b6399ddad6ab4a734282b08ac8e024bebd973f4
diff --git a/tests/database/test_filetable.py b/tests/database/test_filetable.py index bdc04834..d95c182c 100644 --- a/tests/database/test_filetable.py +++ b/tests/database/test_filetable.py @@ -6,9 +6,10 @@ from os import mkdir, rmdir from os.path import abspath, dirname, join from time import time -from pyiron_base._tests import PyironTestCase +from pyiron_base._tests import PyironTestCase, ToyJob from pyiron_base.database.filetable import FileTable +from pyiron_base.project.generic import Project class TestFileTable(PyironTestCase): @@ -60,3 +61,30 @@ class TestFileTable(PyironTestCase): ft is another_ft, msg="New paths should create new FileTable instances" ) + + def test_job_table(self): + pr = Project(dirname(__file__) + "test_filetable_test_job_table") + job = pr.create_job(job_type=ToyJob, job_name="toy_1") + job.run() + self.assertEqual(len(pr.job_table()), 1) + + with self.subTest("Check if the file table can see the job and see it once"): + ft = FileTable(index_from=pr.path) + self.assertEqual( + len(pr.job_table()), + len(ft._job_table), + msg="We expect to see exactly the same job(s) that is in the project's " + "database job table" + ) + + ft.update() + self.assertEqual( + len(pr.job_table()), + len(ft._job_table), + msg="update is called in each _get_job_table call, and if path " + "comparisons fail -- e.g. because you're on windows but pyiron " + "Projects force all the paths to use \\ instead of /, then the " + "update can (and was before the PR where this test got added) " + "duplicate jobs in the job table." + ) + pr.remove_jobs(recursive=True, progress=False, silently=True) diff --git a/tests/project/test_maintenance.py b/tests/project/test_maintenance.py new file mode 100644 index 00000000..ad08d3f6 --- /dev/null +++ b/tests/project/test_maintenance.py @@ -0,0 +1,74 @@ +import numpy as np +from pyiron_base._tests import TestWithFilledProject +from pyiron_base import GenericJob + + +def _test_array(start=0): + return np.arange(start, start + 100, dtype=object).reshape(5, 20) + + +class TestMaintenance(TestWithFilledProject): + def setUp(self) -> None: + super().setUp() + job: GenericJob = self.project["toy_1"] + job["user/some"] = _test_array(5) + job["user/some"] = _test_array() + self.initial_toy_1_hdf_file_size = job.project_hdf5.file_size(job.project_hdf5) + + def _assert_setup(self): + job_hdf = self.project["toy_1"].project_hdf5 + array = self.project["toy_1/user/some"] + self.assertEqual(array, _test_array()) + self.assertAlmostEqual( + job_hdf.file_size(job_hdf), self.initial_toy_1_hdf_file_size + ) + + def _assert_hdf_rewrite(self): + job_hdf = self.project["toy_1"].project_hdf5 + array = self.project["toy_1/user/some"] + self.assertEqual(array, _test_array()) + self.assertLess(job_hdf.file_size(job_hdf), self.initial_toy_1_hdf_file_size) + + def test_repository_status(self): + df = self.project.maintenance.get_repository_status() + self.assertIn( + "pyiron_base", + df.Module.values, + "Environment dependent, but pyiron_base should be in there!", + ) + + def test_local_defragment_storage(self): + self._assert_setup() + self.project.maintenance.local.defragment_storage() + self._assert_hdf_rewrite() + + def test_update_base_to_current(self): + self._assert_setup() + + with self.subTest("Version bigger 0"): + with self.assertRaises(ValueError): + self.project.maintenance.update.base_to_current("1.0.2") + self._assert_setup() + + with self.subTest(msg="Version not smaller 4, no action expected!"): + self.project.maintenance.update.base_to_current("0.4.3") + self._assert_setup() + + with self.subTest(msg="Version < 0.4: should run"): + self.project.maintenance.update.base_to_current("0.3.999") + self._assert_hdf_rewrite() + + def test_update_v03_to_v04_None(self): + self._assert_setup() + self.project.maintenance.update.base_v0_3_to_v0_4() + self._assert_hdf_rewrite() + + def test_update_v03_to_v04_self(self): + self._assert_setup() + self.project.maintenance.update.base_v0_3_to_v0_4(project=self.project) + self._assert_hdf_rewrite() + + def test_update_v03_to_v04_str(self): + self._assert_setup() + self.project.maintenance.update.base_v0_3_to_v0_4(project=self.project.path) + self._assert_hdf_rewrite() diff --git a/tests/table/test_datamining.py b/tests/table/test_datamining.py index 3d99c843..76e33bf0 100644 --- a/tests/table/test_datamining.py +++ b/tests/table/test_datamining.py @@ -5,8 +5,10 @@ import unittest import numpy as np +import pyiron_base from pyiron_base._tests import TestWithProject, ToyJob + class TestProjectData(TestWithProject): @classmethod @@ -21,7 +23,7 @@ class TestProjectData(TestWithProject): def setUp(self): super().setUp() - self.table = self.project.create.table('test_table') + self.table: pyiron_base.TableJob = self.project.create.table('test_table') self.table.filter_function = lambda j: j.name in ["test_a", "test_b"] self.table.add['name'] = lambda j: j.name self.table.add['array'] = lambda j: np.arange(8) @@ -30,6 +32,10 @@ class TestProjectData(TestWithProject): def tearDown(self): self.project.remove_job(self.table.name) + def test_analysis_project(self): + self.assertIs(self.project, self.table.analysis_project) + self.assertEqual(self.project.path, self.project.load(self.table.name).analysis_project.path) + def test_filter(self): """Filter functions should restrict jobs included in the table."""
table job of packed Project fails to load data I just stubbled across an unintended behavior for table jobs which have been `pack`ed and are now tried to be loaded in completely different environment (e.g. binder) without access to the original analysis project (not even the path can be build..., which causes the error in my case). I suggest to check if the project paths exists before trying to make a `Project` there... https://github.com/pyiron/pyiron_base/blob/0b6399ddad6ab4a734282b08ac8e024bebd973f4/pyiron_base/jobs/datamining.py#L684-L693
0.0
0b6399ddad6ab4a734282b08ac8e024bebd973f4
[ "tests/project/test_maintenance.py::TestMaintenance::test_local_defragment_storage", "tests/project/test_maintenance.py::TestMaintenance::test_update_base_to_current" ]
[ "tests/database/test_filetable.py::TestFileTable::test_docstrings", "tests/database/test_filetable.py::TestFileTable::test_job_table", "tests/database/test_filetable.py::TestFileTable::test_re_initialization", "tests/project/test_maintenance.py::TestMaintenance::test_docstrings", "tests/project/test_maintenance.py::TestMaintenance::test_repository_status", "tests/project/test_maintenance.py::TestMaintenance::test_update_v03_to_v04_None", "tests/project/test_maintenance.py::TestMaintenance::test_update_v03_to_v04_self", "tests/project/test_maintenance.py::TestMaintenance::test_update_v03_to_v04_str", "tests/table/test_datamining.py::TestProjectData::test_analysis_project", "tests/table/test_datamining.py::TestProjectData::test_docstrings", "tests/table/test_datamining.py::TestProjectData::test_filter", "tests/table/test_datamining.py::TestProjectData::test_filter_reload", "tests/table/test_datamining.py::TestProjectData::test_numpy_reload" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-06-16 20:55:09+00:00
bsd-3-clause
4,938
pyiron__pyiron_base-641
diff --git a/.ci_support/environment.yml b/.ci_support/environment.yml index beac99e4..ade41f2b 100644 --- a/.ci_support/environment.yml +++ b/.ci_support/environment.yml @@ -15,8 +15,7 @@ dependencies: - pint =0.18 - psutil =5.9.0 - pyfileindex =0.0.6 -- pysqa =0.0.15 +- pysqa =0.0.16 - pytables =3.6.1 - sqlalchemy =1.4.31 - tqdm =4.62.3 -- openssl <2 diff --git a/pyiron_base/job/generic.py b/pyiron_base/job/generic.py index 16317797..959a0d8f 100644 --- a/pyiron_base/job/generic.py +++ b/pyiron_base/job/generic.py @@ -737,6 +737,12 @@ class GenericJob(JobCore): if self.server.cores == 1 or not self.executable.mpi: executable = str(self.executable) shell = True + elif isinstance(self.executable.executable_path, list): + executable = self.executable.executable_path[:] + [ + str(self.server.cores), + str(self.server.threads), + ] + shell = False else: executable = [ self.executable.executable_path, diff --git a/pyiron_base/job/script.py b/pyiron_base/job/script.py index 8121aefa..cba7abf2 100644 --- a/pyiron_base/job/script.py +++ b/pyiron_base/job/script.py @@ -218,6 +218,7 @@ class ScriptJob(GenericJob): self.__name__ = "Script" self._script_path = None self.input = DataContainer(table_name="custom_dict") + self._enable_mpi4py = False @property def script_path(self): @@ -240,13 +241,40 @@ class ScriptJob(GenericJob): if isinstance(path, str): self._script_path = self._get_abs_path(path) self.executable = self._executable_command( - working_directory=self.working_directory, script_path=self._script_path + working_directory=self.working_directory, + script_path=self._script_path, + enable_mpi4py=self._enable_mpi4py, + cores=self.server.cores, ) + if self._enable_mpi4py: + self.executable._mpi = True else: raise TypeError( "path should be a string, but ", path, " is a ", type(path), " instead." ) + def enable_mpi4py(self): + if not self._enable_mpi4py: + self.executable = self._executable_command( + working_directory=self.working_directory, + script_path=self._script_path, + enable_mpi4py=True, + cores=self.server.cores, + ) + self.executable._mpi = True + self._enable_mpi4py = True + + def disable_mpi4py(self): + if self._enable_mpi4py: + self.executable = self._executable_command( + working_directory=self.working_directory, + script_path=self._script_path, + enable_mpi4py=False, + cores=self.server.cores, + ) + self.executable._mpi = False + self._enable_mpi4py = False + def validate_ready_to_run(self): if self.script_path is None: raise TypeError( @@ -346,13 +374,17 @@ class ScriptJob(GenericJob): pass @staticmethod - def _executable_command(working_directory, script_path): + def _executable_command( + working_directory, script_path, enable_mpi4py=False, cores=1 + ): """ internal function to generate the executable command to either use jupyter or python Args: working_directory (str): working directory of the current job script_path (str): path to the script which should be executed in the working directory + enable_mpi4py (bool): flag to enable mpi4py + cores (int): number of cores to use Returns: str: executable command @@ -364,8 +396,10 @@ class ScriptJob(GenericJob): "jupyter nbconvert --ExecutePreprocessor.timeout=9999999 --to notebook --execute " + path ) - elif file_name[-3:] == ".py": + elif file_name[-3:] == ".py" and not enable_mpi4py: return "python " + path + elif file_name[-3:] == ".py" and enable_mpi4py: + return ["mpirun", "-np", str(cores), "python", path] else: raise ValueError("Filename not recognized: ", path) diff --git a/pyiron_base/job/util.py b/pyiron_base/job/util.py index 7b4642c6..e7e32ec4 100644 --- a/pyiron_base/job/util.py +++ b/pyiron_base/job/util.py @@ -160,6 +160,7 @@ def _rename_job(job, new_job_name): job.project.db.item_update( {"job": new_job_name, "subjob": new_location.h5_path}, job.job_id ) + old_job_name = job.name job._name = new_job_name job.project_hdf5.copy_to(destination=new_location, maintain_name=False) job.project_hdf5.remove_file() @@ -167,6 +168,11 @@ def _rename_job(job, new_job_name): if os.path.exists(old_working_directory): shutil.move(old_working_directory, job.working_directory) os.rmdir("/".join(old_working_directory.split("/")[:-1])) + if os.path.exists(os.path.join(job.working_directory, old_job_name + ".tar.bz2")): + os.rename( + os.path.join(job.working_directory, old_job_name + ".tar.bz2"), + os.path.join(job.working_directory, job.job_name + ".tar.bz2"), + ) def _is_valid_job_name(job_name): diff --git a/pyiron_base/job/worker.py b/pyiron_base/job/worker.py index 068dd82b..3a85adaa 100644 --- a/pyiron_base/job/worker.py +++ b/pyiron_base/job/worker.py @@ -5,6 +5,7 @@ Worker Class to execute calculation in an asynchronous way """ import os +import psutil import time from datetime import datetime from multiprocessing import Pool @@ -181,6 +182,7 @@ class WorkerJob(PythonTemplateJob): self.project_hdf5.create_working_directory() log_file = os.path.join(self.working_directory, "worker.log") active_job_ids = [] + process = psutil.Process(os.getpid()) with Pool(processes=int(self.server.cores / self.cores_per_job)) as pool: while True: # Check the database if there are more calculation to execute @@ -238,6 +240,9 @@ class WorkerJob(PythonTemplateJob): + str(len(df)) + " " + str(len(df_sub)) + + " " + + str(process.memory_info().rss / 1024 / 1024 / 1024) + + "GB" + "\n" ) @@ -256,6 +261,7 @@ class WorkerJob(PythonTemplateJob): working_directory = self.working_directory log_file = os.path.join(working_directory, "worker.log") file_memory_lst = [] + process = psutil.Process(os.getpid()) with Pool(processes=int(self.server.cores / self.cores_per_job)) as pool: while True: file_lst = [ @@ -282,6 +288,9 @@ class WorkerJob(PythonTemplateJob): + str(len(file_memory_lst)) + " " + str(len(file_lst)) + + " " + + str(process.memory_info().rss / 1024 / 1024 / 1024) + + "GB" + "\n" ) @@ -329,5 +338,10 @@ class WorkerJob(PythonTemplateJob): ) log_str += "\n" f.write(log_str) + if ( + not state.database.database_is_disabled + and state.database.get_job_status(job_id=self.job_id) == "aborted" + ): + raise ValueError("The worker job was aborted.") time.sleep(interval_in_s) self.status.collect = True diff --git a/setup.py b/setup.py index 5a36179a..f468ca83 100644 --- a/setup.py +++ b/setup.py @@ -39,7 +39,7 @@ setup( 'pint==0.18', 'psutil==5.9.0', 'pyfileindex==0.0.6', - 'pysqa==0.0.15', + 'pysqa==0.0.16', 'sqlalchemy==1.4.31', 'tables==3.6.1', 'tqdm==4.62.3'
pyiron/pyiron_base
de58bc461c5bee662f307c34fd3a554bc4a54249
diff --git a/tests/job/test_genericJob.py b/tests/job/test_genericJob.py index 4c1ddba3..ca00e46e 100644 --- a/tests/job/test_genericJob.py +++ b/tests/job/test_genericJob.py @@ -70,30 +70,78 @@ class TestGenericJob(TestWithFilledProject): def test_job_name(self): cwd = self.file_location - ham = self.project.create.job.ScriptJob("job_single_debug") - self.assertEqual("job_single_debug", ham.job_name) - self.assertEqual("/job_single_debug", ham.project_hdf5.h5_path) - self.assertEqual("/".join([cwd, self.project_name, "job_single_debug.h5"]), ham.project_hdf5.file_name) - ham.job_name = "job_single_move" - ham.to_hdf() - self.assertEqual("/job_single_move", ham.project_hdf5.h5_path) - self.assertEqual("/".join([cwd, self.project_name, "job_single_move.h5"]), ham.project_hdf5.file_name) - self.assertTrue(os.path.isfile(ham.project_hdf5.file_name)) - ham.project_hdf5.remove_file() - self.assertFalse(os.path.isfile(ham.project_hdf5.file_name)) - ham = self.project.create.job.ScriptJob("job_single_debug_2") - ham.to_hdf() - self.assertEqual("job_single_debug_2", ham.job_name) - self.assertEqual("/job_single_debug_2", ham.project_hdf5.h5_path) - self.assertEqual("/".join([cwd, self.project_name, "job_single_debug_2.h5"]), ham.project_hdf5.file_name) - self.assertTrue(os.path.isfile(ham.project_hdf5.file_name)) - ham.job_name = "job_single_move_2" - self.assertEqual("/job_single_move_2", ham.project_hdf5.h5_path) - self.assertEqual("/".join([cwd, self.project_name, "job_single_move_2.h5"]), ham.project_hdf5.file_name) - self.assertTrue(os.path.isfile(ham.project_hdf5.file_name)) - ham.project_hdf5.remove_file() - self.assertFalse(os.path.isfile("/".join([cwd, self.project_name, "job_single_debug_2.h5"]))) - self.assertFalse(os.path.isfile(ham.project_hdf5.file_name)) + with self.subTest("ensure create is working"): + ham = self.project.create.job.ScriptJob("job_single_debug") + self.assertEqual("job_single_debug", ham.job_name) + self.assertEqual("/job_single_debug", ham.project_hdf5.h5_path) + self.assertEqual("/".join([cwd, self.project_name, "job_single_debug.h5"]), ham.project_hdf5.file_name) + self.assertEqual( + "/".join([cwd, self.project_name, "job_single_debug_hdf5/job_single_debug"]), + ham.working_directory + ) + with self.subTest("test move"): + ham.job_name = "job_single_move" + ham.to_hdf() + self.assertEqual("/job_single_move", ham.project_hdf5.h5_path) + self.assertEqual("/".join([cwd, self.project_name, "job_single_move.h5"]), ham.project_hdf5.file_name) + self.assertEqual( + "/".join([cwd, self.project_name, "job_single_move_hdf5/job_single_move"]), + ham.working_directory + ) + self.assertTrue(os.path.isfile(ham.project_hdf5.file_name)) + ham.project_hdf5.create_working_directory() + self.assertTrue(os.path.exists(ham.working_directory)) + with self.subTest("test remove"): + ham.project_hdf5.remove_file() + self.assertFalse(os.path.isfile(ham.project_hdf5.file_name)) + + with self.subTest('ensure create is working'): + ham = self.project.create.job.ScriptJob("job_single_debug_2") + ham.to_hdf() + self.assertEqual("job_single_debug_2", ham.job_name) + self.assertEqual("/job_single_debug_2", ham.project_hdf5.h5_path) + self.assertEqual("/".join([cwd, self.project_name, "job_single_debug_2.h5"]), ham.project_hdf5.file_name) + self.assertTrue(os.path.isfile(ham.project_hdf5.file_name)) + with self.subTest('Add files to working directory'): + ham.project_hdf5.create_working_directory() + self.assertEqual( + "/".join([cwd, self.project_name, "job_single_debug_2_hdf5/job_single_debug_2"]), + ham.working_directory + ) + self.assertTrue(os.path.exists(ham.working_directory)) + with open(os.path.join(ham.working_directory, 'test_file'), 'w') as f: + f.write("Content") + self.assertEqual(ham.list_files(), ['test_file']) + with self.subTest("Compress"): + ham.compress() + self.assertFalse(os.path.exists(os.path.join(ham.working_directory, 'test_file'))) + self.assertTrue(os.path.exists(os.path.join(ham.working_directory, ham.job_name + '.tar.bz2'))) + with self.subTest("Decompress"): + ham.decompress() + self.assertTrue(os.path.exists(os.path.join(ham.working_directory, 'test_file'))) + ham.compress() + with self.subTest("test move"): + ham.job_name = "job_single_move_2" + self.assertEqual( + "/".join([cwd, self.project_name, "job_single_move_2_hdf5/job_single_move_2"]), + ham.working_directory + ) + self.assertFalse(os.path.exists( + "/".join([cwd, self.project_name, "job_single_debug_2_hdf5/job_single_debug_2"]) + )) + self.assertTrue(os.path.exists(os.path.join(ham.working_directory, ham.job_name + '.tar.bz2')), + msg="Job compressed archive not renamed.") + self.assertTrue(os.path.exists(ham.working_directory)) + self.assertEqual("/job_single_move_2", ham.project_hdf5.h5_path) + self.assertEqual("/".join([cwd, self.project_name, "job_single_move_2.h5"]), ham.project_hdf5.file_name) + self.assertTrue(os.path.isfile(ham.project_hdf5.file_name)) + with self.subTest("Decompress 2"): + ham.decompress() + self.assertTrue(os.path.exists(os.path.join(ham.working_directory, 'test_file'))) + with self.subTest("test remove"): + ham.project_hdf5.remove_file() + self.assertFalse(os.path.isfile("/".join([cwd, self.project_name, "job_single_debug_2.h5"]))) + self.assertFalse(os.path.isfile(ham.project_hdf5.file_name)) def test_move(self): pr_a = self.project.open("project_a")
`decompress` doesn't work after job name change It's because [this line](https://github.com/pyiron/pyiron_base/blob/7ba3283c0926234829ba78a7eedd541b72056e3f/pyiron_base/job/util.py#L280) in `def decompress` requires the job name, even though the job name change doesn't change the tar file.
0.0
de58bc461c5bee662f307c34fd3a554bc4a54249
[ "tests/job/test_genericJob.py::TestGenericJob::test_job_name" ]
[ "tests/job/test_genericJob.py::TestGenericJob::test__check_ham_state", "tests/job/test_genericJob.py::TestGenericJob::test__check_if_job_exists", "tests/job/test_genericJob.py::TestGenericJob::test__create_working_directory", "tests/job/test_genericJob.py::TestGenericJob::test__runtime", "tests/job/test_genericJob.py::TestGenericJob::test__type_from_hdf", "tests/job/test_genericJob.py::TestGenericJob::test__type_to_hdf", "tests/job/test_genericJob.py::TestGenericJob::test__write_run_wrapper", "tests/job/test_genericJob.py::TestGenericJob::test_append", "tests/job/test_genericJob.py::TestGenericJob::test_child_ids", "tests/job/test_genericJob.py::TestGenericJob::test_child_ids_finished", "tests/job/test_genericJob.py::TestGenericJob::test_child_ids_running", "tests/job/test_genericJob.py::TestGenericJob::test_childs_from_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_childs_to_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_clear_job", "tests/job/test_genericJob.py::TestGenericJob::test_collect_logfiles", "tests/job/test_genericJob.py::TestGenericJob::test_collect_output", "tests/job/test_genericJob.py::TestGenericJob::test_compress", "tests/job/test_genericJob.py::TestGenericJob::test_copy", "tests/job/test_genericJob.py::TestGenericJob::test_copy_to", "tests/job/test_genericJob.py::TestGenericJob::test_db_entry", "tests/job/test_genericJob.py::TestGenericJob::test_docstrings", "tests/job/test_genericJob.py::TestGenericJob::test_error", "tests/job/test_genericJob.py::TestGenericJob::test_executable", "tests/job/test_genericJob.py::TestGenericJob::test_get", "tests/job/test_genericJob.py::TestGenericJob::test_get_from_table", "tests/job/test_genericJob.py::TestGenericJob::test_get_pandas", "tests/job/test_genericJob.py::TestGenericJob::test_hdf5", "tests/job/test_genericJob.py::TestGenericJob::test_id", "tests/job/test_genericJob.py::TestGenericJob::test_index", "tests/job/test_genericJob.py::TestGenericJob::test_inspect", "tests/job/test_genericJob.py::TestGenericJob::test_iter_childs", "tests/job/test_genericJob.py::TestGenericJob::test_job_file_name", "tests/job/test_genericJob.py::TestGenericJob::test_job_info_str", "tests/job/test_genericJob.py::TestGenericJob::test_load", "tests/job/test_genericJob.py::TestGenericJob::test_master_id", "tests/job/test_genericJob.py::TestGenericJob::test_move", "tests/job/test_genericJob.py::TestGenericJob::test_open_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_parent_id", "tests/job/test_genericJob.py::TestGenericJob::test_pop", "tests/job/test_genericJob.py::TestGenericJob::test_project", "tests/job/test_genericJob.py::TestGenericJob::test_reload_empty_job", "tests/job/test_genericJob.py::TestGenericJob::test_remove", "tests/job/test_genericJob.py::TestGenericJob::test_rename", "tests/job/test_genericJob.py::TestGenericJob::test_rename_nested_job", "tests/job/test_genericJob.py::TestGenericJob::test_restart", "tests/job/test_genericJob.py::TestGenericJob::test_return_codes", "tests/job/test_genericJob.py::TestGenericJob::test_run", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_appended", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_collect", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_created", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_finished", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_manually", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_modal", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_new", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_non_modal", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_queue", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_refresh", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_running", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_submitted", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_suspended", "tests/job/test_genericJob.py::TestGenericJob::test_save", "tests/job/test_genericJob.py::TestGenericJob::test_server", "tests/job/test_genericJob.py::TestGenericJob::test_show_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_status", "tests/job/test_genericJob.py::TestGenericJob::test_structure", "tests/job/test_genericJob.py::TestGenericJob::test_suspend", "tests/job/test_genericJob.py::TestGenericJob::test_to_from_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_to_from_hdf_childshdf", "tests/job/test_genericJob.py::TestGenericJob::test_to_from_hdf_serial", "tests/job/test_genericJob.py::TestGenericJob::test_update_master", "tests/job/test_genericJob.py::TestGenericJob::test_version", "tests/job/test_genericJob.py::TestGenericJob::test_write_input" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-19 20:37:48+00:00
bsd-3-clause
4,939
pyiron__pyiron_base-787
diff --git a/.ci_support/environment.yml b/.ci_support/environment.yml index 1386182d..e688fc73 100644 --- a/.ci_support/environment.yml +++ b/.ci_support/environment.yml @@ -9,7 +9,7 @@ dependencies: - gitpython =3.1.27 - h5io =0.1.7 - h5py =3.7.0 -- numpy =1.23.0 +- numpy =1.23.1 - pandas =1.4.3 - pathlib2 =2.3.7.post1 - pint =0.19.2 diff --git a/pyiron_base/generic/flattenedstorage.py b/pyiron_base/generic/flattenedstorage.py index 50476a14..3a66b81e 100644 --- a/pyiron_base/generic/flattenedstorage.py +++ b/pyiron_base/generic/flattenedstorage.py @@ -19,6 +19,7 @@ __date__ = "Jul 16, 2020" import copy +import warnings from typing import Callable, Iterable, List, Tuple, Any import numpy as np diff --git a/pyiron_base/job/generic.py b/pyiron_base/job/generic.py index 61f41709..afd96fcf 100644 --- a/pyiron_base/job/generic.py +++ b/pyiron_base/job/generic.py @@ -184,6 +184,10 @@ class GenericJob(JobCore): self.project_hdf5.file_name, job_name + "/status" ) self._status = JobStatus(initial_status=initial_status) + if "job_id" in self.list_nodes(): + self._job_id = h5io.read_hdf5( + self.project_hdf5.file_name, job_name + "/job_id" + ) else: self._status = JobStatus() self._restart_file_list = list() @@ -741,6 +745,10 @@ class GenericJob(JobCore): delete_existing_job=delete_existing_job, run_again=run_again, ) + elif status == "aborted": + raise ValueError( + "Running an aborted job with `delete_existing_job=False` is meaningless." + ) except Exception: self.drop_status_to_aborted() raise @@ -1105,6 +1113,12 @@ class GenericJob(JobCore): if not state.database.database_is_disabled: job_id = self.project.db.add_item_dict(self.db_entry()) self._job_id = job_id + h5io.write_hdf5( + self.project_hdf5.file_name, + job_id, + title=self.job_name + "/job_id", + overwrite="update", + ) self.refresh_job_status() else: job_id = self.job_name @@ -1229,15 +1243,6 @@ class GenericJob(JobCore): if not (self.status.finished or self.status.suspended): self.status.aborted = True - def _run_manually(self, _manually_print=True): - """ - Internal helper function to run a job manually. - - Args: - _manually_print (bool): [True/False] print command for execution - default=True - """ - run_job_with_runmode_manually(job=self, _manually_print=_manually_print) - def _run_if_new(self, debug=False): """ Internal helper function the run if new function is called when the job status is 'initialized'. It prepares diff --git a/pyiron_base/job/runfunction.py b/pyiron_base/job/runfunction.py index d16f674d..a38881c6 100644 --- a/pyiron_base/job/runfunction.py +++ b/pyiron_base/job/runfunction.py @@ -260,12 +260,12 @@ def run_job_with_runmode_manually(job, _manually_print=True): _manually_print (bool): [True/False] print command for execution - default=True """ if _manually_print: + abs_working = posixpath.abspath(job.project_hdf5.working_directory) print( "You have selected to start the job manually. " - "To run it, go into the working directory {} and " - "call 'python run_job.py' ".format( - posixpath.abspath(job.project_hdf5.working_directory) - ) + + "To run it, go into the working directory {} and ".format(abs_working) + + "call 'python -m pyiron_base.cli wrapper -p {}".format(abs_working) + + " -j {} ' ".format(job.job_id) ) diff --git a/pyiron_base/server/queuestatus.py b/pyiron_base/server/queuestatus.py index a890c653..912cad14 100644 --- a/pyiron_base/server/queuestatus.py +++ b/pyiron_base/server/queuestatus.py @@ -263,11 +263,11 @@ def update_from_remote(project, recursive=True, ignore_exceptions=False): df_queue = state.queue_adapter.get_status_of_my_jobs() if ( len(df_queue) > 0 - and len(df_queue[df_queue.jobname.str.startswith("pi_")]) > 0 + and len(df_queue[df_queue.jobname.str.contains(QUEUE_SCRIPT_PREFIX)]) > 0 ): - df_queue = df_queue[df_queue.jobname.str.startswith("pi_")] + df_queue = df_queue[df_queue.jobname.str.contains(QUEUE_SCRIPT_PREFIX)] df_queue["pyiron_id"] = df_queue.apply( - lambda x: int(x["jobname"].split("pi_")[1]), axis=1 + lambda x: int(x["jobname"].split(QUEUE_SCRIPT_PREFIX)[-1]), axis=1 ) jobs_now_running_lst = df_queue[ df_queue.status == "running" diff --git a/setup.py b/setup.py index ae9a8674..303bea7b 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ setup( 'gitpython==3.1.27', 'h5io==0.1.7', 'h5py==3.7.0', - 'numpy==1.23.0', + 'numpy==1.23.1', 'pandas==1.4.3', 'pathlib2==2.3.7.post1', 'pint==0.19.2',
pyiron/pyiron_base
d4f57c36affa9d69efc9ea121f582f3da247bc1c
diff --git a/tests/job/test_genericJob.py b/tests/job/test_genericJob.py index 1e73f5dc..720d3e26 100644 --- a/tests/job/test_genericJob.py +++ b/tests/job/test_genericJob.py @@ -282,8 +282,8 @@ class TestGenericJob(TestWithFilledProject): self.assertRaises(ValueError, job.run) self.assertTrue(job.status.aborted) self.assertIsNone(job.job_id) - with self.subTest("run without delete_existing_job does not change anything."): - job.run() + with self.subTest("run without delete_existing_job raises a RuntimeError."): + self.assertRaises(ValueError, job.run) self.assertTrue(job.status.aborted) with self.subTest("changing input and run(delete_existing_job=True) should run"): job.input.data_in = 10 diff --git a/tests/job/test_script.py b/tests/job/test_script.py index d80d2c15..3d6d636b 100644 --- a/tests/job/test_script.py +++ b/tests/job/test_script.py @@ -39,7 +39,7 @@ class TestScriptJob(TestWithCleanProject): with open(self.simple_script, 'w') as f: f.write("print(42)") self.job.script_path = self.simple_script - self.job.run() + self.job.run(delete_existing_job=True) def test_project_data(self): self.project.data.in_ = 6
run() does not raise an error when called on an aborted job. Instead it just silently returns.
0.0
d4f57c36affa9d69efc9ea121f582f3da247bc1c
[ "tests/job/test_genericJob.py::TestGenericJob::test_run_with_delete_existing_job_for_aborted_jobs" ]
[ "tests/job/test_genericJob.py::TestGenericJob::test__check_ham_state", "tests/job/test_genericJob.py::TestGenericJob::test__check_if_job_exists", "tests/job/test_genericJob.py::TestGenericJob::test__create_working_directory", "tests/job/test_genericJob.py::TestGenericJob::test__runtime", "tests/job/test_genericJob.py::TestGenericJob::test__type_from_hdf", "tests/job/test_genericJob.py::TestGenericJob::test__type_to_hdf", "tests/job/test_genericJob.py::TestGenericJob::test__write_run_wrapper", "tests/job/test_genericJob.py::TestGenericJob::test_append", "tests/job/test_genericJob.py::TestGenericJob::test_child_ids", "tests/job/test_genericJob.py::TestGenericJob::test_child_ids_finished", "tests/job/test_genericJob.py::TestGenericJob::test_child_ids_running", "tests/job/test_genericJob.py::TestGenericJob::test_childs_from_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_childs_to_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_clear_job", "tests/job/test_genericJob.py::TestGenericJob::test_collect_logfiles", "tests/job/test_genericJob.py::TestGenericJob::test_collect_output", "tests/job/test_genericJob.py::TestGenericJob::test_compress", "tests/job/test_genericJob.py::TestGenericJob::test_copy", "tests/job/test_genericJob.py::TestGenericJob::test_copy_to", "tests/job/test_genericJob.py::TestGenericJob::test_db_entry", "tests/job/test_genericJob.py::TestGenericJob::test_docstrings", "tests/job/test_genericJob.py::TestGenericJob::test_error", "tests/job/test_genericJob.py::TestGenericJob::test_executable", "tests/job/test_genericJob.py::TestGenericJob::test_get", "tests/job/test_genericJob.py::TestGenericJob::test_get_from_table", "tests/job/test_genericJob.py::TestGenericJob::test_get_pandas", "tests/job/test_genericJob.py::TestGenericJob::test_hdf5", "tests/job/test_genericJob.py::TestGenericJob::test_id", "tests/job/test_genericJob.py::TestGenericJob::test_index", "tests/job/test_genericJob.py::TestGenericJob::test_inspect", "tests/job/test_genericJob.py::TestGenericJob::test_iter_childs", "tests/job/test_genericJob.py::TestGenericJob::test_job_file_name", "tests/job/test_genericJob.py::TestGenericJob::test_job_info_str", "tests/job/test_genericJob.py::TestGenericJob::test_job_name", "tests/job/test_genericJob.py::TestGenericJob::test_load", "tests/job/test_genericJob.py::TestGenericJob::test_master_id", "tests/job/test_genericJob.py::TestGenericJob::test_move", "tests/job/test_genericJob.py::TestGenericJob::test_open_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_parent_id", "tests/job/test_genericJob.py::TestGenericJob::test_pop", "tests/job/test_genericJob.py::TestGenericJob::test_project", "tests/job/test_genericJob.py::TestGenericJob::test_reload_empty_job", "tests/job/test_genericJob.py::TestGenericJob::test_remove", "tests/job/test_genericJob.py::TestGenericJob::test_rename", "tests/job/test_genericJob.py::TestGenericJob::test_rename_nested_job", "tests/job/test_genericJob.py::TestGenericJob::test_restart", "tests/job/test_genericJob.py::TestGenericJob::test_return_codes", "tests/job/test_genericJob.py::TestGenericJob::test_run", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_appended", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_collect", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_created", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_finished", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_manually", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_modal", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_new", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_non_modal", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_queue", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_refresh", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_running", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_submitted", "tests/job/test_genericJob.py::TestGenericJob::test_run_if_suspended", "tests/job/test_genericJob.py::TestGenericJob::test_save", "tests/job/test_genericJob.py::TestGenericJob::test_server", "tests/job/test_genericJob.py::TestGenericJob::test_show_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_status", "tests/job/test_genericJob.py::TestGenericJob::test_structure", "tests/job/test_genericJob.py::TestGenericJob::test_suspend", "tests/job/test_genericJob.py::TestGenericJob::test_to_from_hdf", "tests/job/test_genericJob.py::TestGenericJob::test_to_from_hdf_childshdf", "tests/job/test_genericJob.py::TestGenericJob::test_to_from_hdf_serial", "tests/job/test_genericJob.py::TestGenericJob::test_update_master", "tests/job/test_genericJob.py::TestGenericJob::test_version", "tests/job/test_genericJob.py::TestGenericJob::test_write_input", "tests/job/test_script.py::TestScriptJob::test_docstrings", "tests/job/test_script.py::TestScriptJob::test_project_data", "tests/job/test_script.py::TestScriptJob::test_script_path" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-07-06 07:25:31+00:00
bsd-3-clause
4,940
pyiron__pyiron_base-823
diff --git a/pyiron_base/interfaces/has_hdf.py b/pyiron_base/interfaces/has_hdf.py index 94e7b268..656d003c 100644 --- a/pyiron_base/interfaces/has_hdf.py +++ b/pyiron_base/interfaces/has_hdf.py @@ -23,6 +23,8 @@ class _WithHDF: __slots__ = ("_hdf", "_group_name") def __init__(self, hdf, group_name=None): + if group_name in hdf.list_nodes(): + raise ValueError(f"{group_name} is a node and not a group!") self._hdf = hdf self._group_name = group_name @@ -209,7 +211,10 @@ class HasHDF(ABC): group_name if group_name is not None else self._get_hdf_group_name() ) with _WithHDF(hdf, group_name) as hdf: - if len(hdf.list_dirs()) > 0 and group_name is None: + if ( + group_name is None + and (len(hdf.list_nodes()) > 0 or len(hdf.list_dirs())) > 0 + ): raise ValueError("HDF group must be empty when group_name is not set.") self._to_hdf(hdf) self._store_type_to_hdf(hdf) diff --git a/pyiron_base/interfaces/object.py b/pyiron_base/interfaces/object.py index 078b66c2..5f48e42e 100644 --- a/pyiron_base/interfaces/object.py +++ b/pyiron_base/interfaces/object.py @@ -27,15 +27,27 @@ __date__ = "Mar 23, 2021" class HasStorage(HasHDF, ABC): """ A base class for objects that use HDF5 data serialization via the `DataContainer` class. + + Unless you know what you are doing sub classes should pass the `group_name` argument to :meth:`~.__init__` or + override :meth:`~.get_hdf_group_name()` to force a default name for the HDF group the object should write itself to. """ - def __init__(self, *args, **kwargs): + def __init__(self, *args, group_name=None, **kwargs): + """ + + Args: + group_name (str): default name of the HDF group where the whole object should be written to. + """ self._storage = DataContainer(table_name="storage") + self._group_name = group_name @property def storage(self) -> DataContainer: return self._storage + def _get_hdf_group_name(self) -> str: + return self._group_name + def _to_hdf(self, hdf: ProjectHDFio): self.storage.to_hdf(hdf=hdf) diff --git a/pyiron_base/jobs/job/template.py b/pyiron_base/jobs/job/template.py index fa73ad58..576e14f9 100644 --- a/pyiron_base/jobs/job/template.py +++ b/pyiron_base/jobs/job/template.py @@ -24,7 +24,7 @@ __date__ = "May 15, 2020" class TemplateJob(GenericJob, HasStorage): def __init__(self, project, job_name): GenericJob.__init__(self, project, job_name) - HasStorage.__init__(self) + HasStorage.__init__(self, group_name="") self.storage.create_group("input") self.storage.create_group("output") @@ -38,11 +38,11 @@ class TemplateJob(GenericJob, HasStorage): def to_hdf(self, hdf=None, group_name=None): GenericJob.to_hdf(self, hdf=hdf, group_name=group_name) - HasStorage.to_hdf(self, hdf=self.project_hdf5, group_name="") + HasStorage.to_hdf(self, hdf=self.project_hdf5) def from_hdf(self, hdf=None, group_name=None): GenericJob.from_hdf(self, hdf=hdf, group_name=group_name) - HasStorage.from_hdf(self, hdf=self.project_hdf5, group_name="") + HasStorage.from_hdf(self, hdf=self.project_hdf5) class PythonTemplateJob(TemplateJob): diff --git a/pyiron_base/storage/datacontainer.py b/pyiron_base/storage/datacontainer.py index b33fbeca..21004574 100644 --- a/pyiron_base/storage/datacontainer.py +++ b/pyiron_base/storage/datacontainer.py @@ -790,16 +790,22 @@ class DataContainer(MutableMapping, HasGroups, HasHDF): def _to_hdf(self, hdf): hdf["READ_ONLY"] = self.read_only + written_keys = _internal_hdf_nodes.copy() for i, (k, v) in enumerate(self.items()): if isinstance(k, str) and "__index_" in k: raise ValueError("Key {} clashes with internal use!".format(k)) k = "{}__index_{}".format(k if isinstance(k, str) else "", i) + written_keys.append(k) # pandas objects also have a to_hdf method that is entirely unrelated to ours if hasattr(v, "to_hdf") and not isinstance( v, (pandas.DataFrame, pandas.Series) ): + # if v will be written as a group, but a node of the same name k exists already in the file, h5py will + # complain, so delete it first + if k in hdf.list_nodes(): + del hdf[k] v.to_hdf(hdf=hdf, group_name=k) else: # if the value doesn't know how to serialize itself, assume @@ -811,6 +817,12 @@ class DataContainer(MutableMapping, HasGroups, HasHDF): "Error saving {} (key {}): DataContainer doesn't support saving elements " 'of type "{}" to HDF!'.format(v, k, type(v)) ) from None + for n in hdf.list_nodes(): + if n not in written_keys: + del hdf[n] + for g in hdf.list_groups(): + if g not in written_keys: + del hdf[g] def _from_hdf(self, hdf, version=None): self.clear() @@ -916,7 +928,7 @@ class DataContainer(MutableMapping, HasGroups, HasHDF): if not self._lazy and not recursive: return - # values are loaded from HDF once they are accessed via __getitem__, which is implicetly called by values() + # values are loaded from HDF once they are accessed via __getitem__, which is implicitly called by values() for v in self.values(): if recursive and isinstance(v, DataContainer): v._force_load() diff --git a/pyiron_base/storage/hdfio.py b/pyiron_base/storage/hdfio.py index 5e787c3c..198dc767 100644 --- a/pyiron_base/storage/hdfio.py +++ b/pyiron_base/storage/hdfio.py @@ -260,7 +260,7 @@ class FileHDFio(HasGroups, MutableMapping): h5io.write_hdf5( self.file_name, value, - title=posixpath.join(self.h5_path, key), + title=self._get_h5_path(key), overwrite="update", use_json=use_json, ) @@ -275,7 +275,7 @@ class FileHDFio(HasGroups, MutableMapping): if self.file_exists: try: with open_hdf5(self.file_name, mode="a") as store: - del store[key] + del store[self._get_h5_path(key)] except (AttributeError, KeyError): pass @@ -531,7 +531,7 @@ class FileHDFio(HasGroups, MutableMapping): Returns: FileHDFio: FileHDFio object pointing to the new group """ - full_name = posixpath.join(self.h5_path, name) + full_name = self._get_h5_path(name) with open_hdf5(self.file_name, mode="a") as h: try: h.create_group(full_name, track_order=track_order) @@ -570,7 +570,7 @@ class FileHDFio(HasGroups, MutableMapping): if h5_rel_path.strip() == ".": h5_rel_path = "" if h5_rel_path.strip() != "": - new_h5_path.h5_path = posixpath.join(new_h5_path.h5_path, h5_rel_path) + new_h5_path.h5_path = self._get_h5_path(h5_rel_path) new_h5_path.history.append(h5_rel_path) return new_h5_path
pyiron/pyiron_base
4529ed291a98d1c601cae5180bde200f5f915182
diff --git a/tests/generic/test_datacontainer.py b/tests/generic/test_datacontainer.py index 98f66bad..60ef96f9 100644 --- a/tests/generic/test_datacontainer.py +++ b/tests/generic/test_datacontainer.py @@ -39,7 +39,13 @@ class TestDataContainer(TestWithCleanProject): ]} ], table_name="input") cls.pl["tail"] = DataContainer([2, 4, 8]) - cls.hdf = cls.project.create_hdf(cls.project.path, "test") + + def setUp(self): + self.hdf = self.project.create_hdf(self.project.path, "test") + + def tearDown(self): + self.hdf.remove_file() + self.hdf = None # Init tests def test_init_none(self): @@ -397,7 +403,7 @@ class TestDataContainer(TestWithCleanProject): self.assertTrue("READ_ONLY" in self.hdf["read_only_f"].list_nodes(), "read-only parameter not saved in HDF") self.assertEqual( self.pl.read_only, - self.hdf[self.pl.table_name]["READ_ONLY"], + self.hdf["read_only_f"]["READ_ONLY"], "read-only parameter not correctly written to HDF" ) @@ -460,6 +466,7 @@ class TestDataContainer(TestWithCleanProject): def test_hdf_empty_group(self): """Writing a list without table_name or group_name should only work if the HDF group is empty.""" l = DataContainer([1, 2, 3]) + self.hdf["dummy"] = True with self.assertRaises(ValueError, msg="No exception when writing to full hdf group."): l.to_hdf(self.hdf) h = self.hdf.create_group("empty_group") @@ -630,6 +637,53 @@ class TestDataContainer(TestWithCleanProject): self.assertTrue(not isinstance(ll._store[0], HDFStub), "Loaded value not stored back into container!") + def test_overwrite_with_group(self): + """Writing to HDF second time after replacing a node by a group should not raise an error.""" + d = DataContainer({"test": 42}) + d.to_hdf(hdf=self.hdf, group_name="overwrite") + del d.test + d.create_group("test") + d.test.foo = 42 + try: + d.to_hdf(hdf=self.hdf, group_name="overwrite") + except Exception as e: + self.fail(f"to_hdf raised \"{e}\"!") + + def test_overwrite_with_node(self): + """Writing to HDF second time after replacing a group by a node should not raise an error.""" + d = DataContainer({"test": {"foo": 42}}) + d.to_hdf(hdf=self.hdf, group_name="overwrite") + del d.test + d.create_group("test") + d.test = 42 + try: + d.to_hdf(hdf=self.hdf, group_name="overwrite") + except Exception as e: + self.fail(f"to_hdf raised \"{e}\"!") + + def test_overwrite_no_dangling_items(self): + """Writing to HDF a second time should leave only items in HDF that are currently in the container.""" + d = self.pl.copy() + d.to_hdf(self.hdf) + del d[len(d) - 1] + d.to_hdf(self.hdf) + items = [k for k in self.hdf[d.table_name].list_nodes() if "__index_" in k] \ + + [k for k in self.hdf[d.table_name].list_groups() if "__index_" in k] + self.assertEqual(len(d), len(items), + "Number of items in HDF does not match length of container!") + + def test_overwrite_ordering(self): + """Writing to HDF a second time with different item order should not leave other items in the HDF.""" + d = self.pl.copy() + d.to_hdf(self.hdf) + d = DataContainer(list(reversed(list(d.values()))), + table_name=d.table_name) + d.to_hdf(self.hdf) + items = [k for k in self.hdf[d.table_name].list_nodes() if "__index_" in k] \ + + [k for k in self.hdf[d.table_name].list_groups() if "__index_" in k] + self.assertEqual(len(d), len(items), + "Number of items in HDF does not match length of container!") + class TestInputList(PyironTestCase): diff --git a/tests/generic/test_fileHDFio.py b/tests/generic/test_fileHDFio.py index a35aa4f5..f9a08627 100644 --- a/tests/generic/test_fileHDFio.py +++ b/tests/generic/test_fileHDFio.py @@ -293,6 +293,14 @@ class TestFileHDFio(PyironTestCase): self.to_be_removed_hdf.remove_file() self.assertFalse(os.path.isfile(path)) + def test_delitem(self): + """After deleting an entry, it should not be accessible anymore.""" + with self.full_hdf5.open("content") as opened_hdf: + opened_hdf["dummy"] = 42 + del opened_hdf["dummy"] + self.assertNotIn("dummy", opened_hdf.list_nodes(), msg="Entry still in HDF after del!") + + def test_get_from_table(self): pass
Overwriting `None` by atomistic structure in project data raises error The following lines work perfectly: ```python from pyiron_atomistics import Project pr = Project('TEST') pr.data.something = None pr.data.write() pr.data.something = [1, 2, 3] pr.data.write() pr = Project('TEST') print(pr.data.something) ``` Output: ```python >>> [1, 2, 3] ``` However, the following lines raise an error: ```python from pyiron_atomistics import Project pr = Project('TEST') pr.data.something = None pr.data.write() pr.data.something = pr.create.structure.bulk('Fe') pr.data.write() ``` ```python-traceback --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_2091/4008969041.py in <cell line: 7>() 5 pr.data.something = pr.create.structure.bulk('Fe') 6 # pr.data.something = [1, 2, 3] ----> 7 pr.data.write() ~/dev_sam/pyiron_base/pyiron_base/project/data.py in write(self) 58 def write(self): 59 """Write data to project-level storage.""" ---> 60 self.to_hdf(ProjectHDFio(self._project, file_name="project_data")) ~/dev_sam/pyiron_base/pyiron_base/interfaces/has_hdf.py in to_hdf(self, hdf, group_name) 212 if len(hdf.list_dirs()) > 0 and group_name is None: 213 raise ValueError("HDF group must be empty when group_name is not set.") --> 214 self._to_hdf(hdf) 215 self._store_type_to_hdf(hdf) 216 ~/dev_sam/pyiron_base/pyiron_base/storage/datacontainer.py in _to_hdf(self, hdf) 801 v, (pandas.DataFrame, pandas.Series) 802 ): --> 803 v.to_hdf(hdf=hdf, group_name=k) 804 else: 805 # if the value doesn't know how to serialize itself, assume ~/dev_sam/pyiron_atomistics/pyiron_atomistics/atomistics/structure/atoms.py in to_hdf(self, hdf, group_name) 460 with hdf.open(group_name) as hdf_structure: 461 # time_start = time.time() --> 462 hdf_structure["TYPE"] = str(type(self)) 463 for el in self.species: 464 if isinstance(el.tags, dict): ~/dev_sam/pyiron_base/pyiron_base/storage/hdfio.py in __setitem__(self, key, value) 258 elif isinstance(value, tuple): 259 value = list(value) --> 260 h5io.write_hdf5( 261 self.file_name, 262 value, /u/system/SLES12/soft/pyiron/dev/anaconda3/lib/python3.8/site-packages/h5io/_h5io.py in write_hdf5(fname, data, overwrite, compression, title, slash, use_json) 109 del fid[title] 110 cleanup_data = [] --> 111 _triage_write(title, data, fid, comp_kw, str(type(data)), 112 cleanup_data, slash=slash, title=title, 113 use_json=use_json) /u/system/SLES12/soft/pyiron/dev/anaconda3/lib/python3.8/site-packages/h5io/_h5io.py in _triage_write(key, value, root, comp_kw, where, cleanup_data, slash, title, use_json) 182 value = np.frombuffer(value.encode('ASCII'), np.uint8) 183 title = 'ascii' --> 184 _create_titled_dataset(root, key, title, value, comp_kw) 185 elif isinstance(value, np.ndarray): 186 if not (value.dtype == np.dtype('object') and /u/system/SLES12/soft/pyiron/dev/anaconda3/lib/python3.8/site-packages/h5io/_h5io.py in _create_titled_dataset(root, key, title, data, comp_kw) 46 """Helper to create a titled dataset in h5py""" 47 comp_kw = {} if comp_kw is None else comp_kw ---> 48 out = root.create_dataset(key, data=data, **comp_kw) 49 out.attrs['TITLE'] = title 50 return out /u/system/SLES12/soft/pyiron/dev/anaconda3/lib/python3.8/site-packages/h5py/_hl/group.py in create_dataset(self, name, shape, dtype, data, **kwds) 157 if b'/' in name.lstrip(b'/'): 158 parent_path, name = name.rsplit(b'/', 1) --> 159 group = self.require_group(parent_path) 160 161 dsid = dataset.make_new_dset(group, shape, dtype, data, name, **kwds) /u/system/SLES12/soft/pyiron/dev/anaconda3/lib/python3.8/site-packages/h5py/_hl/group.py in require_group(self, name) 314 grp = self[name] 315 if not isinstance(grp, Group): --> 316 raise TypeError("Incompatible object (%s) already exists" % grp.__class__.__name__) 317 return grp 318 TypeError: Incompatible object (Dataset) already exists ``` Not sure if it's a feature or a bug. EDIT: ghost edit by @niklassiemer adding the traceback formatting (python-traceback)
0.0
4529ed291a98d1c601cae5180bde200f5f915182
[ "tests/generic/test_datacontainer.py::TestDataContainer::test_hdf_empty_group", "tests/generic/test_datacontainer.py::TestDataContainer::test_overwrite_no_dangling_items", "tests/generic/test_datacontainer.py::TestDataContainer::test_overwrite_ordering", "tests/generic/test_datacontainer.py::TestDataContainer::test_overwrite_with_group", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_delitem", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_show_hdf" ]
[ "tests/generic/test_datacontainer.py::TestDataContainer::test_create_group", "tests/generic/test_datacontainer.py::TestDataContainer::test_deep_copy", "tests/generic/test_datacontainer.py::TestDataContainer::test_del_attr", "tests/generic/test_datacontainer.py::TestDataContainer::test_del_item", "tests/generic/test_datacontainer.py::TestDataContainer::test_docstrings", "tests/generic/test_datacontainer.py::TestDataContainer::test_extend", "tests/generic/test_datacontainer.py::TestDataContainer::test_force_stubs", "tests/generic/test_datacontainer.py::TestDataContainer::test_from_hdf", "tests/generic/test_datacontainer.py::TestDataContainer::test_from_hdf_group", "tests/generic/test_datacontainer.py::TestDataContainer::test_from_hdf_readonly", "tests/generic/test_datacontainer.py::TestDataContainer::test_get_attr", "tests/generic/test_datacontainer.py::TestDataContainer::test_get_item", "tests/generic/test_datacontainer.py::TestDataContainer::test_get_nested", "tests/generic/test_datacontainer.py::TestDataContainer::test_get_sempath", "tests/generic/test_datacontainer.py::TestDataContainer::test_get_string_int", "tests/generic/test_datacontainer.py::TestDataContainer::test_groups_nodes", "tests/generic/test_datacontainer.py::TestDataContainer::test_hdf_complex_members", "tests/generic/test_datacontainer.py::TestDataContainer::test_hdf_empty_list", "tests/generic/test_datacontainer.py::TestDataContainer::test_hdf_no_wrap", "tests/generic/test_datacontainer.py::TestDataContainer::test_hdf_pandas", "tests/generic/test_datacontainer.py::TestDataContainer::test_init_dict", "tests/generic/test_datacontainer.py::TestDataContainer::test_init_list", "tests/generic/test_datacontainer.py::TestDataContainer::test_init_none", "tests/generic/test_datacontainer.py::TestDataContainer::test_init_set", "tests/generic/test_datacontainer.py::TestDataContainer::test_init_tuple", "tests/generic/test_datacontainer.py::TestDataContainer::test_insert", "tests/generic/test_datacontainer.py::TestDataContainer::test_lazy_copy", "tests/generic/test_datacontainer.py::TestDataContainer::test_mark", "tests/generic/test_datacontainer.py::TestDataContainer::test_numpy_array", "tests/generic/test_datacontainer.py::TestDataContainer::test_overwrite_with_node", "tests/generic/test_datacontainer.py::TestDataContainer::test_read_only", "tests/generic/test_datacontainer.py::TestDataContainer::test_read_write_consistency", "tests/generic/test_datacontainer.py::TestDataContainer::test_recursive_append", "tests/generic/test_datacontainer.py::TestDataContainer::test_repr_json", "tests/generic/test_datacontainer.py::TestDataContainer::test_search", "tests/generic/test_datacontainer.py::TestDataContainer::test_set_append", "tests/generic/test_datacontainer.py::TestDataContainer::test_set_errors", "tests/generic/test_datacontainer.py::TestDataContainer::test_set_item", "tests/generic/test_datacontainer.py::TestDataContainer::test_set_some_keys", "tests/generic/test_datacontainer.py::TestDataContainer::test_shallow_copy", "tests/generic/test_datacontainer.py::TestDataContainer::test_stub", "tests/generic/test_datacontainer.py::TestDataContainer::test_stub_sublasses", "tests/generic/test_datacontainer.py::TestDataContainer::test_subclass_preservation", "tests/generic/test_datacontainer.py::TestDataContainer::test_to_hdf_group", "tests/generic/test_datacontainer.py::TestDataContainer::test_to_hdf_items", "tests/generic/test_datacontainer.py::TestDataContainer::test_to_hdf_name", "tests/generic/test_datacontainer.py::TestDataContainer::test_to_hdf_readonly", "tests/generic/test_datacontainer.py::TestDataContainer::test_to_hdf_type", "tests/generic/test_datacontainer.py::TestDataContainer::test_update", "tests/generic/test_datacontainer.py::TestDataContainer::test_update_blacklist", "tests/generic/test_datacontainer.py::TestDataContainer::test_wrap_hdf", "tests/generic/test_datacontainer.py::TestInputList::test_deprecation_warning", "tests/generic/test_datacontainer.py::TestInputList::test_docstrings", "tests/generic/test_fileHDFio.py::TestFileHDFio::test__convert_dtype_obj_array", "tests/generic/test_fileHDFio.py::TestFileHDFio::test__is_convertable_dtype_object_array", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_array_type_conversion", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_base_name", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_close", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_copy", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_docstrings", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_file_name", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_file_size", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_get", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_get_from_table", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_get_item", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_get_pandas", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_get_size", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_groups", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_h5_path", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_hd_copy", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_is_empty", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_is_root", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_list_all", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_list_groups", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_list_nodes", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_listdirs", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_open", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_put", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_ragged_array", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_remove_file", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_remove_group", "tests/generic/test_fileHDFio.py::TestFileHDFio::test_to_object", "tests/generic/test_fileHDFio.py::TestProjectHDFio::test_close", "tests/generic/test_fileHDFio.py::TestProjectHDFio::test_content", "tests/generic/test_fileHDFio.py::TestProjectHDFio::test_docstrings", "tests/generic/test_fileHDFio.py::TestProjectHDFio::test_import_class", "tests/generic/test_fileHDFio.py::TestProjectHDFio::test_remove_file", "tests/generic/test_fileHDFio.py::TestProjectHDFio::test_rewrite_hdf5" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-08-09 15:19:33+00:00
bsd-3-clause
4,941
pyiron__pyiron_base-956
diff --git a/pyiron_base/jobs/job/path.py b/pyiron_base/jobs/job/path.py index 0d2efc66..b05f39e5 100644 --- a/pyiron_base/jobs/job/path.py +++ b/pyiron_base/jobs/job/path.py @@ -22,19 +22,12 @@ __status__ = "production" __date__ = "Sep 1, 2017" -class JobPathBase(JobCore): +class JobPath(JobCore): """ The JobPath class is derived from the JobCore and is used as a lean version of the GenericJob class. Instead of loading the full pyiron object the JobPath class only provides access to the HDF5 file, which should be enough for most analysis. - Args: - db (DatabaseAccess): database object - job_id (int): Job ID - optional, but either a job ID or a database entry db_entry has to be provided. - db_entry (dict): database entry {"job":, "subjob":, "projectpath":, "project":, "hamilton":, "hamversion":, - "status":} and optional entries are {"id":, "masterid":, "parentid":} - user (str): current unix/linux/windows user who is running pyiron - Attributes: .. attribute:: job_name @@ -109,6 +102,12 @@ class JobPathBase(JobCore): """ def __init__(self, job_path): + """ + Load a job from the given path. + + Args: + job_path (str): path to the job, must be of the form /path/to/file.h5/job_name + """ job_path_lst = job_path.replace("\\", "/").split(".h5") if len(job_path_lst) != 2: raise ValueError @@ -125,9 +124,53 @@ class JobPathBase(JobCore): h5_path=h5_path, mode="r", ) - super(JobPathBase, self).__init__( - project=hdf_project, job_name=job_path_lst[1].split("/")[-1] - ) + super().__init__(project=hdf_project, job_name=job_path_lst[1].split("/")[-1]) + + @classmethod + def from_job_id(cls, db, job_id): + """ + Load a job path from a database connection and the job id. + + Args: + db (DatabaseAccess): database connection + job_id (int): Job ID in the database + """ + db_entry = db.get_item_by_id(job_id) + if db_entry is None: + raise ValueError("job ID {0} does not exist!".format(job_id)) + + return cls.from_db_entry(db_entry) + + @classmethod + def from_db_entry(cls, db_entry): + """ + Load a job path from a database entry. + + Args: + db_entry (dict): database entry {"job":, "subjob":, "projectpath":, "project":, "hamilton":, "hamversion":, + "status":} and optional entries are {"id":, "masterid":, "parentid":} + """ + hdf5_file = db_entry["subjob"].split("/")[1] + ".h5" + job_path = db_entry["projectpath"] + if job_path is None: + job_path = "" + job_path += db_entry["project"] + hdf5_file + db_entry["subjob"] + job = cls(job_path=job_path) + + if "hamilton" in db_entry.keys(): + job.__name__ = db_entry["hamilton"] + if "hamversion" in db_entry.keys(): + job.__version__ = db_entry["hamversion"] + + if "id" in db_entry.keys(): + job._job_id = db_entry["id"] + if "status" in db_entry.keys(): + job._status = db_entry["status"] + if "masterid" in db_entry.keys(): + job._master_id = db_entry["masterid"] + if "parentid" in db_entry.keys(): + job._parent_id = db_entry["parentid"] + return job @property def is_root(self): @@ -358,117 +401,3 @@ class JobPathBase(JobCore): self.project_hdf5._store.close() except AttributeError: pass - - -class JobPath(JobPathBase): - """ - The JobPath class is derived from the JobCore and is used as a lean version of the GenericJob class. Instead of - loading the full pyiron object the JobPath class only provides access to the HDF5 file, which should be enough - for most analysis. - - Args: - db (DatabaseAccess): database object - job_id (int): Job ID - optional, but either a job ID or a database entry db_entry has to be provided. - db_entry (dict): database entry {"job":, "subjob":, "projectpath":, "project":, "hamilton":, "hamversion":, - "status":} and optional entries are {"id":, "masterid":, "parentid":} - user (str): current unix/linux/windows user who is running pyiron - - Attributes: - - .. attribute:: job_name - - name of the job, which has to be unique within the project - - .. attribute:: status - - execution status of the job, can be one of the following [initialized, appended, created, submitted, running, - aborted, collect, suspended, refresh, busy, finished] - - .. attribute:: job_id - - unique id to identify the job in the pyiron database - - .. attribute:: parent_id - - job id of the predecessor job - the job which was executed before the current one in the current job series - - .. attribute:: master_id - - job id of the master job - a meta job which groups a series of jobs, which are executed either in parallel or in - serial. - - .. attribute:: child_ids - - list of child job ids - only meta jobs have child jobs - jobs which list the meta job as their master - - .. attribute:: project - - Project instance the jobs is located in - - .. attribute:: project_hdf5 - - ProjectHDFio instance which points to the HDF5 file the job is stored in - - .. attribute:: job_info_str - - short string to describe the job by it is job_name and job ID - mainly used for logging - - .. attribute:: working_directory - - working directory of the job is executed in - outside the HDF5 file - - .. attribute:: path - - path to the job as a combination of absolute file system path and path within the HDF5 file. - - .. attribute:: is_root - - boolean if the HDF5 object is located at the root level of the HDF5 file - - .. attribute:: is_open - - boolean if the HDF5 file is currently opened - if an active file handler exists - - .. attribute:: is_empty - - boolean if the HDF5 file is empty - - .. attribute:: base_name - - name of the HDF5 file but without any file extension - - .. attribute:: file_path - - directory where the HDF5 file is located - - .. attribute:: h5_path - - path inside the HDF5 file - also stored as absolute path - """ - - def __init__(self, db, job_id=None, db_entry=None, user=None): - if db_entry is None and db is not None: - db_entry = db.get_item_by_id(job_id) - if db_entry is None: - raise ValueError("job ID {0} does not exist!".format(job_id)) - hdf5_file = db_entry["subjob"].split("/")[1] + ".h5" - if db_entry["projectpath"] is not None: - job_path = db_entry["projectpath"] - else: - job_path = "" - job_path += db_entry["project"] + hdf5_file + db_entry["subjob"] - super(JobPath, self).__init__(job_path=job_path) - - if "hamilton" in db_entry.keys(): - self.__name__ = db_entry["hamilton"] - if "hamversion" in db_entry.keys(): - self.__version__ = db_entry["hamversion"] - - if "id" in db_entry.keys(): - self._job_id = db_entry["id"] - if "status" in db_entry.keys(): - self._status = db_entry["status"] - if "masterid" in db_entry.keys(): - self._master_id = db_entry["masterid"] - if "parentid" in db_entry.keys(): - self._parent_id = db_entry["parentid"] diff --git a/pyiron_base/project/generic.py b/pyiron_base/project/generic.py index 7b802c34..b85ad7c8 100644 --- a/pyiron_base/project/generic.py +++ b/pyiron_base/project/generic.py @@ -8,10 +8,10 @@ The project object is the central import point of pyiron - all other objects can import os import posixpath import shutil +import stat from tqdm.auto import tqdm import pandas import pint -import importlib import math import numpy as np @@ -831,18 +831,17 @@ class Project(ProjectPath, HasGroups): Returns: GenericJob, JobCore: Either the full GenericJob object or just a reduced JobCore object """ - jobpath = getattr( - importlib.import_module("pyiron_base.jobs.job.path"), "JobPath" - ) + from pyiron_base.jobs.job.path import JobPath + if job_id is not None: - job = jobpath(db=self.db, job_id=job_id, user=self.user) + job = JobPath.from_job_id(db=self.db, job_id=job_id) if convert_to_object: job = job.to_object() job.reset_job_id(job_id=job_id) job.set_input_to_read_only() return job elif db_entry is not None: - job = jobpath(db=self.db, db_entry=db_entry) + job = JobPath.from_db_entry(db_entry) if convert_to_object: job = job.to_object() job.set_input_to_read_only() @@ -1184,7 +1183,13 @@ class Project(ProjectPath, HasGroups): # dirs and files return values of the iterator are not updated when removing files, so we need to # manually call listdir if len(os.listdir(root)) == 0: - os.rmdir(root) + root = root.rstrip(os.sep) + # the project was symlinked before being deleted + if os.path.islink(root): + os.rmdir(os.readlink(root)) + os.remove(root) + else: + os.rmdir(root) else: raise EnvironmentError("remove() is not available in view_mode!") @@ -1294,9 +1299,9 @@ class Project(ProjectPath, HasGroups): Returns: GenericJob, JobCore: Either the full GenericJob object or just a reduced JobCore object """ - job = getattr( - importlib.import_module("pyiron_base.jobs.job.path"), "JobPathBase" - )(job_path=job_path) + from pyiron_base.jobs.job.path import JobPath + + job = JobPath(job_path) if convert_to_object: job = job.to_object() job.set_input_to_read_only() @@ -1676,6 +1681,66 @@ class Project(ProjectPath, HasGroups): ) setattr(cls, name, property(lambda self: tools(self))) + def symlink(self, target_dir): + """ + Move underlying project folder to target and create a symlink to it. + + The project itself does not change and is not updated in the database. Instead the project folder is moved into + a subdirectory of target_dir with the same name as the project and a symlink is placed in the previous project path + pointing to the newly created one. + + If self.path is already a symlink pointing inside target_dir, this method will silently return. + + Args: + target_dir (str): new parent folder for the project + + Raises: + OSError: when calling this method on non-unix systems + RuntimeError: the project path is already a symlink to somewhere else + RuntimeError: the project path has submitted or running jobs inside it, wait until after they are finished + RuntimeError: target already contains a subdirectory with the project name and it is not empty + """ + target = os.path.join(target_dir, self.name) + destination = self.path + if destination[-1] == "/": + destination = destination[:-1] + if stat.S_ISLNK(os.lstat(destination).st_mode): + if os.readlink(destination) == target: + return + raise RuntimeError( + "Refusing to symlink and move a project that is already symlinked!" + ) + if os.name != "posix": + raise OSError("Symlinking projects is only supported on unix systems!") + if len(self.job_table().query('status.isin(["submitted", "running"])')) > 0: + raise RuntimeError( + "Refusing to symlink and move a project that has submitted or running jobs!" + ) + os.makedirs(target_dir, exist_ok=True) + if os.path.exists(target): + if len(os.listdir(target)) > 0: + raise RuntimeError( + "Refusing to symlink and move a project to non-empty directory!" + ) + else: + os.rmdir(target) + shutil.move(self.path, target_dir) + os.symlink(target, destination) + + def unlink(self): + """ + If the project folder is symlinked somewhere else remove the link and restore the original folder. + + If it is not symlinked, silently return. + """ + path = self.path.rstrip(os.sep) + if not stat.S_ISLNK(os.lstat(path).st_mode): + return + + target = os.readlink(path) + os.unlink(path) + shutil.move(target, path) + class Creator: def __init__(self, project): diff --git a/pyiron_base/state/install.py b/pyiron_base/state/install.py index b3b7b634..d220d8f6 100644 --- a/pyiron_base/state/install.py +++ b/pyiron_base/state/install.py @@ -141,7 +141,9 @@ def install_pyiron( zip_file (str): name of the compressed file project_path (str): the location where pyiron is going to store the pyiron projects resource_directory (str): the location where the resouces (executables, potentials, ...) for pyiron are stored. - giturl_for_zip_file (str): url for the zipped resources file on github + giturl_for_zip_file (str/None): url for the zipped resources file on github. + (Default points to pyiron's github resource repository. If None, leaves the + resources directory *empty*.) git_folder_name (str): name of the extracted folder """ _write_config_file( @@ -149,9 +151,12 @@ def install_pyiron( project_path=project_path, resource_path=resource_directory, ) - _download_resources( - zip_file=zip_file, - resource_directory=resource_directory, - giturl_for_zip_file=giturl_for_zip_file, - git_folder_name=git_folder_name, - ) + if giturl_for_zip_file is not None: + _download_resources( + zip_file=zip_file, + resource_directory=resource_directory, + giturl_for_zip_file=giturl_for_zip_file, + git_folder_name=git_folder_name, + ) + else: + os.mkdir(resource_directory)
pyiron/pyiron_base
685fa919d25c5e844e4b29548b6291892482f8fe
diff --git a/tests/project/test_project.py b/tests/project/test_project.py index 7acf1212..cf533063 100644 --- a/tests/project/test_project.py +++ b/tests/project/test_project.py @@ -3,8 +3,9 @@ # Distributed under the terms of "New BSD License", see the LICENSE file. import unittest -from os.path import dirname, join, abspath -from os import remove +from os.path import dirname, join, abspath, exists, islink +import os +import tempfile import pint from pyiron_base.project.generic import Project from pyiron_base._tests import PyironTestCase, TestWithProject, TestWithFilledProject, ToyJob @@ -20,7 +21,7 @@ class TestProjectData(PyironTestCase): @classmethod def tearDownClass(cls): try: - remove(join(cls.file_location, "pyiron.log")) + os.remove(join(cls.file_location, "pyiron.log")) except FileNotFoundError: pass @@ -127,6 +128,59 @@ class TestProjectOperations(TestWithFilledProject): self.assertIn('pyiron_base', df.Module.values) [email protected](os.name=="posix", "symlinking is only available on posix platforms") +class TestProjectSymlink(TestWithFilledProject): + """ + Test that Project.symlink creates a symlink and unlink removes it again. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.temp = tempfile.TemporaryDirectory() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + cls.temp.cleanup() + + def test_symlink(self): + + nodes = self.project.list_nodes() + groups = self.project.list_groups() + + self.project.symlink(self.temp.name) + + try: + self.project.symlink(self.temp.name) + except Exception as e: + self.fail(f"symlinking twice should have no effect, but raised {e}!") + + with self.assertRaises(RuntimeError, msg="symlinking to another folder should raise an error"): + self.project.symlink("asdf") + + path = self.project.path.rstrip(os.sep) + self.assertTrue(islink(path), "symlink() did not create a symlink!") + self.assertEqual(os.readlink(path), join(self.temp.name, self.project.name), + "symlink() created a wrong symlink!") + + self.assertCountEqual(nodes, self.project.list_nodes(), "not all nodes present after symlink!") + self.assertCountEqual(groups, self.project.list_groups(), "not all groups present after symlink!") + + self.project.unlink() + + self.assertTrue(exists(self.project.path), "unlink() did not restore original directory!") + self.assertFalse(islink(path), "unlink() did not remove symlink!") + + self.assertCountEqual(nodes, self.project.list_nodes(), "not all nodes present after unlink!") + self.assertCountEqual(groups, self.project.list_groups(), "not all groups present after unlink!") + + try: + self.project.unlink() + except Exception as e: + self.fail(f"unlinking twice should have no effect, but raised {e}!") + + class TestToolRegistration(TestWithProject): def setUp(self) -> None: self.tools = BaseTools(self.project) diff --git a/tests/project/test_projectPath.py b/tests/project/test_projectPath.py index 7a6a752c..00d999be 100644 --- a/tests/project/test_projectPath.py +++ b/tests/project/test_projectPath.py @@ -18,13 +18,14 @@ class TestProjectPath(PyironTestCase): else: cls.current_dir = os.path.dirname(os.path.abspath(__file__)) cls.settings_configuration = state.settings.configuration.copy() - cls.project_path = ProjectPath(path=cls.current_dir) - cls.project_path = cls.project_path.open("test_project_path") def setUp(self) -> None: - state.settings.configuration["project_paths"] = [self.current_dir] + state.settings.configuration["project_paths"] = [self.current_dir + "/"] state.settings.configuration["project_check_enabled"] = True + self.project_path = ProjectPath(path=self.current_dir) + self.project_path = self.project_path.open("test_project_path") + def tearDown(self) -> None: state.settings.configuration.update(self.settings_configuration) @@ -67,7 +68,7 @@ class TestProjectPath(PyironTestCase): ) def test_root_path(self): - root_paths = self.settings_configuration["project_paths"] + root_paths = state.settings.configuration["project_paths"] self.assertIn( self.project_path.root_path, root_paths, @@ -75,7 +76,7 @@ class TestProjectPath(PyironTestCase): ) def test_project_path(self): - root_paths = self.settings_configuration["project_paths"] + root_paths = state.settings.configuration["project_paths"] self.assertIn( self.current_dir + "/test_project_path/", [root_path + self.project_path.project_path for root_path in root_paths], diff --git a/tests/state/test_install.py b/tests/state/test_install.py index 733fc675..d4a6e0fd 100644 --- a/tests/state/test_install.py +++ b/tests/state/test_install.py @@ -30,6 +30,7 @@ class TestInstall(PyironTestCase): config_file_name=os.path.join(self.execution_path, "config"), resource_directory=os.path.join(self.execution_path, "resources"), project_path=os.path.join(self.execution_path, "project"), + giturl_for_zip_file=None, ) with open(os.path.join(self.execution_path, "config"), "r") as f:
Bug in ProjectPath tests? Shouldn't [this line](https://github.com/pyiron/pyiron_base/blob/685fa919d25c5e844e4b29548b6291892482f8fe/tests/project/test_projectPath.py#L78) be `root_paths = state.settings.configuration["project_paths"]`? In `setUpClass` we have `cls.settings_configuration = state.settings.configuration.copy()`, then in `setUp` we have `state.settings.configuration["project_paths"] = [self.current_dir]; state.settings.configuration["project_check_enabled"] = True`, and finally in the test we're setting `root_paths = self.settings_configuration["project_paths"]` and expecting it to be non-empty. Now, this passes on the remote CI, but in `pyironconfig.py` we're explicitly setting `TOP_LEVEL_DIRS` (i.e. `project_paths`), so maybe that allows it to get by even though it's comparing to the wrong thing? On my local machine, where `project_paths = []` and `project_check_enabled = False`, this test fails, exactly because `root_paths == []`. I get the exact same failure in `test_root_path` for [exactly the same (suspected) reason](https://github.com/pyiron/pyiron_base/blob/685fa919d25c5e844e4b29548b6291892482f8fe/tests/project/test_projectPath.py#L70)
0.0
685fa919d25c5e844e4b29548b6291892482f8fe
[ "tests/project/test_project.py::TestProjectSymlink::test_symlink", "tests/state/test_install.py::TestInstall::test_install" ]
[ "tests/project/test_project.py::TestProjectData::test_create_job_name", "tests/project/test_project.py::TestProjectData::test_data", "tests/project/test_project.py::TestProjectData::test_docstrings", "tests/project/test_project.py::TestProjectData::test_iterjobs", "tests/project/test_project.py::TestProjectOperations::test__size_conversion", "tests/project/test_project.py::TestProjectOperations::test_docstrings", "tests/project/test_project.py::TestProjectOperations::test_filtered_job_table", "tests/project/test_project.py::TestProjectOperations::test_get_iter_jobs", "tests/project/test_project.py::TestProjectOperations::test_job_table", "tests/project/test_project.py::TestProjectOperations::test_maintenance_get_repository_status", "tests/project/test_project.py::TestProjectOperations::test_size", "tests/project/test_project.py::TestProjectSymlink::test_docstrings", "tests/project/test_project.py::TestToolRegistration::test_docstrings", "tests/project/test_project.py::TestToolRegistration::test_registration", "tests/project/test_projectPath.py::TestProjectPath::test__get_project_from_path", "tests/project/test_projectPath.py::TestProjectPath::test_close", "tests/project/test_projectPath.py::TestProjectPath::test_copy", "tests/project/test_projectPath.py::TestProjectPath::test_docstrings", "tests/project/test_projectPath.py::TestProjectPath::test_open", "tests/project/test_projectPath.py::TestProjectPath::test_path", "tests/project/test_projectPath.py::TestProjectPath::test_project_path", "tests/project/test_projectPath.py::TestProjectPath::test_removedirs", "tests/project/test_projectPath.py::TestProjectPath::test_root_path", "tests/state/test_install.py::TestInstall::test_docstrings" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-12-20 22:12:41+00:00
bsd-3-clause
4,942
pylhc__generic_parser-4
diff --git a/generic_parser/entrypoint_parser.py b/generic_parser/entrypoint_parser.py index 5db3606..cacd5c3 100644 --- a/generic_parser/entrypoint_parser.py +++ b/generic_parser/entrypoint_parser.py @@ -330,7 +330,9 @@ class EntryPoint(object): "As entrypoint does not use 'const', the use is prohibited.") if param.get("flags", None) is None: - raise ParameterError(f"Parameter '{arg_name:s}' does not have flags.") + # if flags aren't supplied, it defaults to the name + LOG.debug(f'Missing flags parameter. Defaulting to --{arg_name}') + param['flags'] = [f'--{arg_name}'] def _read_config(self, cfgfile_path, section=None): """ Get content from config file""" diff --git a/requirements.txt b/requirements.txt index 84ca099..541393c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ -pytest>=3.6 +pytest>=5.2 pytest-cov>=2.6 -hypothesis>=3.23.0 +hypothesis>=4.36.2 travis-sphinx>=2.1.0 Sphinx>=1.8.1 sphinx-rtd-theme>=0.4.3 +attrs>=19.2.0
pylhc/generic_parser
8dd3a55075a3586eb88636b893c7c159105234c7
diff --git a/tests/test_entrypoint.py b/tests/test_entrypoint.py index 6617584..291f9b7 100644 --- a/tests/test_entrypoint.py +++ b/tests/test_entrypoint.py @@ -69,11 +69,6 @@ def test_wrong_param_creation_name(): EntryPoint([{"flags": "--flag"}]) -def test_wrong_param_creation_flags(): - with pytest.raises(ParameterError): - EntryPoint([{"name": "test"}]) - - def test_wrong_param_creation_other(): with pytest.raises(TypeError): EntryPoint([{"name": "test", "flags": "--flag", "other": "unknown"}]) @@ -87,6 +82,32 @@ def test_choices_not_iterable(): }]) +def test_missing_flag_replaced_by_name(): + ep = EntryPoint([{"name": "test"}]) + + assert len(ep.parameter[0]) == 2 + assert ep.parameter[0]['flags'] == ['--test'] + assert ep.parameter[0]['name'] == 'test' + + +def test_missing_flag_replaced_by_name_in_multiple_lists(): + ep = EntryPoint([{"name": "test"}, + {"name": "thermos_coffee"}, + {"name": "tee_kessel", "flags": ['--tee_kessel']}]) + + assert len(ep.parameter[0]) == 2 + assert ep.parameter[0]['flags'] == ['--test'] + assert ep.parameter[0]['name'] == 'test' + + assert len(ep.parameter[1]) == 2 + assert ep.parameter[1]['flags'] == ['--thermos_coffee'] + assert ep.parameter[1]['name'] == 'thermos_coffee' + + assert len(ep.parameter[2]) == 2 + assert ep.parameter[2]['flags'] == ['--tee_kessel'] + assert ep.parameter[2]['name'] == 'tee_kessel' + + # Argument Tests
Use name as flag When creating parameters: If no flags are given, the name should be used as flag, preceded by "--"
0.0
8dd3a55075a3586eb88636b893c7c159105234c7
[ "tests/test_entrypoint.py::test_missing_flag_replaced_by_name", "tests/test_entrypoint.py::test_missing_flag_replaced_by_name_in_multiple_lists" ]
[ "tests/test_entrypoint.py::test_strict_wrapper_fail", "tests/test_entrypoint.py::test_class_wrapper_fail", "tests/test_entrypoint.py::test_normal_wrapper_fail", "tests/test_entrypoint.py::test_class_functions", "tests/test_entrypoint.py::test_instance_functions", "tests/test_entrypoint.py::test_wrong_param_creation_name", "tests/test_entrypoint.py::test_wrong_param_creation_other", "tests/test_entrypoint.py::test_choices_not_iterable", "tests/test_entrypoint.py::test_strict_pass", "tests/test_entrypoint.py::test_strict_fail", "tests/test_entrypoint.py::test_as_kwargs", "tests/test_entrypoint.py::test_as_string", "tests/test_entrypoint.py::test_as_config", "tests/test_entrypoint.py::test_all_missing", "tests/test_entrypoint.py::test_required_missing", "tests/test_entrypoint.py::test_wrong_choice", "tests/test_entrypoint.py::test_wrong_type", "tests/test_entrypoint.py::test_wrong_type_in_list", "tests/test_entrypoint.py::test_not_enough_length", "tests/test_entrypoint.py::test_save_options", "tests/test_entrypoint.py::test_save_cli_options", "tests/test_entrypoint.py::test_multiclass_class", "tests/test_entrypoint.py::test_dict_as_string_class", "tests/test_entrypoint.py::test_bool_or_str_class", "tests/test_entrypoint.py::test_bool_or_list_class", "tests/test_entrypoint.py::test_multiclass", "tests/test_entrypoint.py::test_dict_as_string", "tests/test_entrypoint.py::test_bool_or_str", "tests/test_entrypoint.py::test_bool_or_str_cfg", "tests/test_entrypoint.py::test_bool_or_list", "tests/test_entrypoint.py::test_bool_or_list_cfg", "tests/test_entrypoint.py::test_split_listargs", "tests/test_entrypoint.py::test_split_dictargs" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-10-11 11:56:26+00:00
mit
4,943
pylhc__optics_functions-25
diff --git a/optics_functions/coupling.py b/optics_functions/coupling.py index efa91e1..d4e6397 100644 --- a/optics_functions/coupling.py +++ b/optics_functions/coupling.py @@ -12,11 +12,11 @@ from contextlib import suppress from typing import Sequence import numpy as np +from pandas import DataFrame, Series from tfs import TfsDataFrame -from optics_functions.constants import (ALPHA, BETA, GAMMA, - X, Y, TUNE, DELTA, - MINIMUM, PI2, PHASE_ADV, S, LENGTH) +from optics_functions.constants import (ALPHA, BETA, GAMMA, X, Y, TUNE, DELTA, + MINIMUM, PI2, PHASE_ADV, S, LENGTH, IMAG, REAL) from optics_functions.rdt import calculate_rdts from optics_functions.utils import split_complex_columns, timeit @@ -26,8 +26,11 @@ COUPLING_RDTS = ["F1001", "F1010"] LOG = logging.getLogger(__name__) -def coupling_via_rdts(df: TfsDataFrame, complex_columns: bool = True, **kwargs): - """ Returns the coupling term. +# Coupling --------------------------------------------------------------------- + + +def coupling_via_rdts(df: TfsDataFrame, complex_columns: bool = True, **kwargs) -> TfsDataFrame: + """Returns the coupling terms. .. warning:: This function changes sign of the real part of the RDTs compared to @@ -54,17 +57,16 @@ def coupling_via_rdts(df: TfsDataFrame, complex_columns: bool = True, **kwargs): if not complex_columns: df_res = split_complex_columns(df_res, COUPLING_RDTS) - return df_res -def coupling_via_cmatrix(df: TfsDataFrame, complex_columns: bool = True, - output: Sequence[str] = ("rdts", "gamma", "cmatrix")): - """ Calculates C matrix then Coupling and Gamma from it. +def coupling_via_cmatrix(df: DataFrame, complex_columns: bool = True, + output: Sequence[str] = ("rdts", "gamma", "cmatrix")) -> DataFrame: + """Calculates C matrix then Coupling and Gamma from it. See [CalagaBetatronCoupling2005]_ . Args: - df (TfsDataFrame): Twiss Dataframe + df (DataFrame): Twiss Dataframe complex_columns (bool): Output complex values in single column of type complex. If ``False``, split complex columns into two real-valued columns. @@ -75,13 +77,14 @@ def coupling_via_cmatrix(df: TfsDataFrame, complex_columns: bool = True, New TfsDataFrame with columns as specified in 'output'. """ LOG.info("Calculating coupling from c-matrix.") - df_res = TfsDataFrame(index=df.index) + df_res = DataFrame(index=df.index) with timeit("CMatrix calculation", print_fun=LOG.debug): n = len(df) gx, r, inv_gy = np.zeros((n, 2, 2)), np.zeros((n, 2, 2)), np.zeros((n, 2, 2)) - # rs form after -J R^T J == inv(R)*det|R| == C + # Eq. (16) C = 1 / (1 + |R|) * -J R J + # rs form after -J R^T J r[:, 0, 0] = df["R22"] r[:, 0, 1] = -df["R12"] r[:, 1, 0] = -df["R21"] @@ -89,27 +92,26 @@ def coupling_via_cmatrix(df: TfsDataFrame, complex_columns: bool = True, r *= 1 / np.sqrt(1 + np.linalg.det(r)[:, None, None]) - # Cbar = Gx * C * Gy^-1 (Eq. (5) in reference) - sqrtbetax = np.sqrt(df[f"{BETA}{X}"]) - sqrtbetay = np.sqrt(df[f"{BETA}{Y}"]) + # Cbar = Gx * C * Gy^-1, Eq. (5) + sqrt_betax = np.sqrt(df[f"{BETA}{X}"]) + sqrt_betay = np.sqrt(df[f"{BETA}{Y}"]) - gx[:, 0, 0] = 1 / sqrtbetax + gx[:, 0, 0] = 1 / sqrt_betax gx[:, 1, 0] = df[f"{ALPHA}{X}"] * gx[:, 0, 0] - gx[:, 1, 1] = sqrtbetax + gx[:, 1, 1] = sqrt_betax - inv_gy[:, 1, 1] = 1 / sqrtbetay + inv_gy[:, 1, 1] = 1 / sqrt_betay inv_gy[:, 1, 0] = -df[f"{ALPHA}{Y}"] * inv_gy[:, 1, 1] - inv_gy[:, 0, 0] = sqrtbetay + inv_gy[:, 0, 0] = sqrt_betay c = np.matmul(gx, np.matmul(r, inv_gy)) gamma = np.sqrt(1 - np.linalg.det(c)) if "rdts" in output: + # Eq. (9) and Eq. (10) denom = 1 / (4 * gamma) - df_res.loc[:, "F1001"] = ((c[:, 0, 0] + c[:, 1, 1]) * 1j + - (c[:, 0, 1] - c[:, 1, 0])) * denom - df_res.loc[:, "F1010"] = ((c[:, 0, 0] - c[:, 1, 1]) * 1j + - (-c[:, 0, 1]) - c[:, 1, 0]) * denom + df_res.loc[:, "F1001"] = denom * (+c[:, 0, 1] - c[:, 1, 0] + (c[:, 0, 0] + c[:, 1, 1]) * 1j) + df_res.loc[:, "F1010"] = denom * (-c[:, 0, 1] - c[:, 1, 0] + (c[:, 0, 0] - c[:, 1, 1]) * 1j) LOG.info(f"Average coupling amplitude |F1001|: {df_res['F1001'].abs().mean():g}") LOG.info(f"Average coupling amplitude |F1010|: {df_res['F1010'].abs().mean():g}") @@ -117,10 +119,10 @@ def coupling_via_cmatrix(df: TfsDataFrame, complex_columns: bool = True, df_res = split_complex_columns(df_res, COUPLING_RDTS) if "cmatrix" in output: - df_res.loc[:, "C11"] = c[:, 0, 0] - df_res.loc[:, "C12"] = c[:, 0, 1] - df_res.loc[:, "C21"] = c[:, 1, 0] - df_res.loc[:, "C22"] = c[:, 1, 1] + df_res["C11"] = c[:, 0, 0] + df_res["C12"] = c[:, 0, 1] + df_res["C21"] = c[:, 1, 0] + df_res["C22"] = c[:, 1, 1] if "gamma" in output: df_res.loc[:, GAMMA] = gamma @@ -129,8 +131,88 @@ def coupling_via_cmatrix(df: TfsDataFrame, complex_columns: bool = True, return df_res -def closest_tune_approach(df: TfsDataFrame, qx: float = None, qy: float = None, method: str = "calaga"): - """ Calculates the closest tune approach from coupling resonances. +# R-Matrix --------------------------------------------------------------------- + + +def rmatrix_from_coupling(df: DataFrame, complex_columns: bool = True) -> DataFrame: + """Calculates the R-matrix from a DataFrame containing the coupling columns + as well as alpha and beta columns. This is the inverse of + :func:`optics_functions.coupling.coupling_via_cmatrix`. + See [CalagaBetatronCoupling2005]_ . + + Args: + df (DataFrame): Twiss Dataframe + complex_columns (bool): Tells the function if the coupling input columns + are complex-valued or split into real and + imaginary parts. + + Returns: + New DataFrame containing the R-columns. + """ + LOG.info("Calculating r-matrix from coupling rdts.") + df_res = DataFrame(index=df.index) + + with timeit("R-Matrix calculation", print_fun=LOG.debug): + if complex_columns: + df = split_complex_columns(df, COUPLING_RDTS, drop=False) + + n = len(df) + + # From Eq. (5) in reference: + inv_gx, jcj, gy = np.zeros((n, 2, 2)), np.zeros((n, 2, 2)), np.zeros((n, 2, 2)) + + sqrt_betax = np.sqrt(df[f"{BETA}{X}"]) + sqrt_betay = np.sqrt(df[f"{BETA}{Y}"]) + + inv_gx[:, 1, 1] = 1 / sqrt_betax + inv_gx[:, 1, 0] = -df[f"{ALPHA}{X}"] * inv_gx[:, 1, 1] + inv_gx[:, 0, 0] = sqrt_betax + + gy[:, 0, 0] = 1 / sqrt_betay + gy[:, 1, 0] = df[f"{ALPHA}{Y}"] * gy[:, 0, 0] + gy[:, 1, 1] = sqrt_betay + + # Eq. (15) + if complex_columns: + abs_squared_diff = df["F1001"].abs()**2 - df["F1010"].abs()**2 + else: + abs_squared_diff = (df[f"F1001{REAL}"]**2 + df[f"F1001{IMAG}"]**2 - + df[f"F1010{REAL}"]**2 - df[f"F1010{IMAG}"]**2) + + gamma = np.sqrt(1.0 / (1.0 + 4.0 * abs_squared_diff)) + + # Eq. (11) and Eq. (12) + cbar = np.zeros((n, 2, 2)) + cbar[:, 0, 0] = (df[f"F1001{IMAG}"] + df[f"F1010{IMAG}"]).to_numpy() + cbar[:, 0, 1] = -(df[f"F1010{REAL}"] - df[f"F1001{REAL}"]).to_numpy() + cbar[:, 1, 0] = -(df[f"F1010{REAL}"] + df[f"F1001{REAL}"]).to_numpy() + cbar[:, 1, 1] = (df[f"F1001{IMAG}"] - df[f"F1010{IMAG}"]).to_numpy() + cbar = 2 * gamma.to_numpy()[:, None, None] * cbar + + # Gx^-1 * Cbar * Gy = C (Eq. (5) inverted) + c = np.matmul(inv_gx, np.matmul(cbar, gy)) + + # from above: -J R^T J == inv(R)*det|R| == C + # therefore -J C^T J = R + jcj[:, 0, 0] = c[:, 1, 1] + jcj[:, 0, 1] = -c[:, 0, 1] + jcj[:, 1, 0] = -c[:, 1, 0] + jcj[:, 1, 1] = c[:, 0, 0] + + rmat = jcj * np.sqrt(1 / (1 - np.linalg.det(jcj))[:, None, None]) + df_res["R11"] = rmat[:, 0, 0] + df_res["R12"] = rmat[:, 0, 1] + df_res["R21"] = rmat[:, 1, 0] + df_res["R22"] = rmat[:, 1, 1] + + return df_res + + +# Closest Tune Approach -------------------------------------------------------- + +def closest_tune_approach(df: TfsDataFrame, qx: float = None, qy: float = None, + method: str = "calaga") -> TfsDataFrame: + """Calculates the closest tune approach from coupling resonances. A complex F1001 column is assumed to be present in the DataFrame. This can be calculated by :func:`~optics_functions.rdt.rdts` @@ -157,7 +239,7 @@ def closest_tune_approach(df: TfsDataFrame, qx: float = None, qy: float = None, Choices: 'calaga', 'franchi', 'persson' and 'persson_alt'. Returns: - New DataFrame with closest tune approach (DELTAQMIN) column. + New TfsDataFrame with closest tune approach (DELTAQMIN) column. The value is real for 'calaga' and 'franchi' methods, """ method_map = { @@ -181,35 +263,36 @@ def closest_tune_approach(df: TfsDataFrame, qx: float = None, qy: float = None, return df_res -def _cta_franchi(df: TfsDataFrame, qx_frac: float, qy_frac: float): +def _cta_franchi(df: TfsDataFrame, qx_frac: float, qy_frac: float) -> Series: """ Closest tune approach calculated by Eq. (1) in [PerssonImprovedControlCoupling2014]_ . """ - return 4 * (qx_frac - qy_frac) * df['F1001'].abs() + return 4 * (qx_frac - qy_frac) * df["F1001"].abs() -def _cta_persson_alt(df: TfsDataFrame, qx_frac: float, qy_frac: float): - """ Closest tune approach calculated by Eq. (2) in [PerssonImprovedControlCoupling2014]_ . - - The exp(i(Qx-Qy)s/R) term is omitted. """ +def _cta_persson_alt(df: TfsDataFrame, qx_frac: float, qy_frac: float) -> Series: + """Closest tune approach calculated by Eq. (2) in [PerssonImprovedControlCoupling2014]_ . + The exp(i(Qx-Qy)s/R) term is omitted. + """ deltaq = qx_frac - qy_frac # fractional tune split - return 4 * deltaq * df['F1001'] * np.exp(-1j * (df[f"{PHASE_ADV}{X}"] - df[f"{PHASE_ADV}{Y}"])) + return 4 * deltaq * df["F1001"] * np.exp(-1j * (df[f"{PHASE_ADV}{X}"] - df[f"{PHASE_ADV}{Y}"])) -def _cta_persson(df: TfsDataFrame, qx_frac: float, qy_frac: float): +def _cta_persson(df: TfsDataFrame, qx_frac: float, qy_frac: float) -> Series: """ Closest tune approach calculated by Eq. (2) in [PerssonImprovedControlCoupling2014]_ . """ deltaq = qx_frac - qy_frac # fractional tune split - return 4 * deltaq * df['F1001'] * np.exp(1j * - ((deltaq * df[S] / (df.headers[LENGTH] / PI2)) - (df[f"{PHASE_ADV}{X}"] - df[f"{PHASE_ADV}{Y}"]))) - + exponential_term = ((deltaq * df[S] / (df.headers[LENGTH] / PI2)) - (df[f"{PHASE_ADV}{X}"] - df[f"{PHASE_ADV}{Y}"])) + return 4 * deltaq * df['F1001'] * np.exp(1j * exponential_term) -def _cta_calaga(df: TfsDataFrame, qx_frac: float, qy_frac: float): - """ Closest tune approach calculated by Eq. (27) in [CalagaBetatronCoupling2005]_ . +def _cta_calaga(df: TfsDataFrame, qx_frac: float, qy_frac: float) -> Series: + """Closest tune approach calculated by Eq. (27) in [CalagaBetatronCoupling2005]_ . If F1010 is not given, it is assumed to be zero. """ f_diff = df["F1001"].abs() ** 2 with suppress(KeyError): f_diff -= df["1010"].abs() ** 2 - return ((np.cos(PI2 * qx_frac) - np.cos(PI2 * qy_frac)) - / (np.pi * (np.sin(PI2 * qx_frac) + np.sin(PI2 * qy_frac))) - * (4 * np.sqrt(f_diff) / (1 + 4*f_diff))) + return ( + (np.cos(PI2 * qx_frac) - np.cos(PI2 * qy_frac)) + / (np.pi * (np.sin(PI2 * qx_frac) + np.sin(PI2 * qy_frac))) + * (4 * np.sqrt(f_diff) / (1 + 4 * f_diff)) + ) diff --git a/optics_functions/utils.py b/optics_functions/utils.py index 49dfad8..b06e601 100644 --- a/optics_functions/utils.py +++ b/optics_functions/utils.py @@ -11,14 +11,13 @@ import logging import string from contextlib import contextmanager from time import time -from typing import Sequence, Tuple, Iterable +from typing import Iterable, Sequence, Tuple import numpy as np import pandas as pd from tfs import TfsDataFrame -from optics_functions.constants import (REAL, IMAG, PLANES, PHASE_ADV, - X, Y, S, NAME, DELTA_ORBIT) +from optics_functions.constants import DELTA_ORBIT, IMAG, NAME, PHASE_ADV, PLANES, REAL, S, X, Y LOG = logging.getLogger(__name__) D = DELTA_ORBIT @@ -26,12 +25,14 @@ D = DELTA_ORBIT # DataFrames ------------------------------------------------------------------- -def prepare_twiss_dataframe(df_twiss: TfsDataFrame, - df_errors: pd.DataFrame = None, - invert_signs_madx: bool = False, - max_order: int = 16, - join: str = "inner") -> TfsDataFrame: - """ Prepare dataframe to use with the optics functions. +def prepare_twiss_dataframe( + df_twiss: TfsDataFrame, + df_errors: pd.DataFrame = None, + invert_signs_madx: bool = False, + max_order: int = 16, + join: str = "inner", +) -> TfsDataFrame: + """Prepare dataframe to use with the optics functions. - Adapt Beam 4 signs. - Add missing K(S)L and orbit columns. @@ -87,14 +88,14 @@ def prepare_twiss_dataframe(df_twiss: TfsDataFrame, for name, df_old in (("twiss", df_twiss), ("errors", df_errors)): dropped_columns = set(df_old.columns) - set(df.columns) if dropped_columns: - LOG.warning(f"The following {name}-columns were" - f" dropped on merge: {seq2str(dropped_columns)}") + LOG.warning(f"The following {name}-columns were dropped on merge: {seq2str(dropped_columns)}") return df -def split_complex_columns(df: pd.DataFrame, columns: Sequence[str], - drop: bool = True) -> TfsDataFrame: - """ Splits the given complex columns into two real-values columns containing the +def split_complex_columns( + df: pd.DataFrame, columns: Sequence[str], drop: bool = True +) -> TfsDataFrame: + """Splits the given complex columns into two real-values columns containing the real and imaginary parts of the original columns. Args: @@ -115,28 +116,46 @@ def split_complex_columns(df: pd.DataFrame, columns: Sequence[str], return df -def switch_signs_for_beam4(df_twiss: pd.DataFrame, - df_errors: pd.DataFrame = None) -> Tuple[TfsDataFrame, TfsDataFrame]: - """ Switch the signs for Beam 4 optics. +def merge_complex_columns( + df: pd.DataFrame, columns: Sequence[str], drop: bool = True +) -> TfsDataFrame: + """Merges the given real and imag columns into complex columns. + + Args: + df (pd.DataFrame): DataFrame containing the original columns. + columns (Sequence[str]): List of complex columns names to be created. + drop (bool): Original columns are not present in resulting DataFrame. + + Returns: + Original TfsDataFrame with added columns. + """ + df = df.copy() + for column in columns: + df[column] = df[f"{column}{REAL}"] + 1j * df[f"{column}{IMAG}"] + + if drop: + df = df.drop(columns=[f"{column}{part}" for column in columns for part in (REAL, IMAG)]) + return df + + +def switch_signs_for_beam4( + df_twiss: pd.DataFrame, df_errors: pd.DataFrame = None +) -> Tuple[TfsDataFrame, TfsDataFrame]: + """Switch the signs for Beam 4 optics. This is due to the switch in direction for this beam and (anti-) symmetry after a rotation of 180deg around the y-axis of magnets, combined with the fact that the KL values in MAD-X twiss do not change sign, but in the errors they do (otherwise it would compensate). Magnet orders that show anti-symmetry are: a1 (K0SL), b2 (K1L), a3 (K2SL), b4 (K3L) etc. Also the sign for (delta) X is switched back to have the same orientation as beam2.""" - LOG.debug( - f"Switching signs for X and K(S)L values when needed, to match Beam 4 to Beam 2." - ) + LOG.debug(f"Switching signs for X and K(S)L values when needed, to match Beam 4 to Beam 2.") df_twiss, df_errors = df_twiss.copy(), df_errors.copy() df_twiss[X] = -df_twiss[X] if df_errors is not None: df_errors[f"{D}{X}"] = -df_errors[f"{D}{X}"] max_order = ( - df_errors.columns.str.extract(r"^K(\d+)S?L$", expand=False) - .dropna() - .astype(int) - .max() + df_errors.columns.str.extract(r"^K(\d+)S?L$", expand=False).dropna().astype(int).max() ) for order in range(max_order + 1): name = f"K{order:d}{'' if order % 2 else 'S'}L" # odd -> '', even -> S @@ -149,7 +168,7 @@ def switch_signs_for_beam4(df_twiss: pd.DataFrame, def get_all_phase_advances(df: pd.DataFrame) -> dict: - """ Calculate phase advances between all elements. + """Calculate phase advances between all elements. Will result in a elements x elements matrix, that might be very large! Args: @@ -175,7 +194,7 @@ def get_all_phase_advances(df: pd.DataFrame) -> dict: def dphi(data: np.ndarray, q: float) -> np.ndarray: - """ Return dphi from phase advances in data, see Eq. (8) in [FranchiAnalyticFormulas2017]_ . + """Return dphi from phase advances in data, see Eq. (8) in [FranchiAnalyticFormulas2017]_ . Args: data (DataFrame, Series): Phase-Advance data. @@ -201,7 +220,7 @@ def tau(data: np.ndarray, q: float) -> np.ndarray: def dphi_at_element(df: pd.DataFrame, element: str, qx: float, qy: float) -> dict: - """ Return dphis for both planes at the given element. + """Return dphis for both planes at the given element. See Eq. (8) in [FranchiAnalyticFormulas2017]_ . Args: @@ -239,7 +258,7 @@ def add_missing_columns(df: pd.DataFrame, columns: Iterable) -> pd.DataFrame: @contextmanager def timeit(text: str = "Time used {:.3f}s", print_fun=LOG.debug): - """ Timing context with logging/printing output. + """Timing context with logging/printing output. Args: text (str): Text to print. If it contains an unnamed format key, this @@ -282,8 +301,6 @@ def set_name_index(df: pd.DataFrame, df_name="") -> pd.DataFrame: df = df.set_index(NAME) if not all(isinstance(indx, str) for indx in df.index): - raise TypeError( - f"Index of the {df_name} Dataframe should be string (i.e. from {NAME})" - ) + raise TypeError(f"Index of the {df_name} Dataframe should be string (i.e. from {NAME})") return df
pylhc/optics_functions
f94ae1df49ba18eede1a62adc6a1081318ec8fbb
diff --git a/tests/unit/test_coupling.py b/tests/unit/test_coupling.py index c3731e0..aa4ce44 100644 --- a/tests/unit/test_coupling.py +++ b/tests/unit/test_coupling.py @@ -6,7 +6,7 @@ import tfs from optics_functions.constants import NAME, S, ALPHA, Y, BETA, X, GAMMA, REAL, IMAG, TUNE, PHASE_ADV from optics_functions.coupling import (closest_tune_approach, coupling_via_rdts, - coupling_via_cmatrix, COUPLING_RDTS) + coupling_via_cmatrix, COUPLING_RDTS, rmatrix_from_coupling) from optics_functions.utils import prepare_twiss_dataframe from tests.unit.test_rdt import arrays_are_close_almost_everywhere @@ -23,9 +23,10 @@ def test_cmatrix(): assert all(c in df_res.columns for c in ("F1001", "F1010", "C11", "C12", "C21", "C22", GAMMA)) assert not df_res.isna().any().any() - detC = (df_res["C11"]*df_res["C22"] - df_res["C12"]*df_res["C21"]) + # Checks based on CalagaBetatronCoupling2005 + detC = (df_res["C11"] * df_res["C22"] - df_res["C12"] * df_res["C21"]) fsq_diff = np.abs(df_res["F1001"])**2 - np.abs(df_res["F1010"])**2 - f_term = 1/(1+4*fsq_diff) + f_term = 1/(1 + 4 * fsq_diff) g_sq = df_res[GAMMA]**2 assert all(np.abs(detC + g_sq - 1) < 1e-15) assert all(np.abs(detC / (4 * g_sq) - fsq_diff) < 1e-15) # Eq. (13) @@ -33,6 +34,29 @@ def test_cmatrix(): assert all(np.abs(g_sq - f_term) < 1e-15) # Eq. (14) [email protected] [email protected]('source', ['real', 'fake']) +def test_rmatrix_to_coupling_to_rmatrix(source): + if source == "fake": + n = 5 + np.random.seed(487423872) + df = get_df(n) + else: + df = tfs.read(INPUT / "coupling_bump" / f"twiss.lhc.b1.coupling_bump.tfs", index=NAME) + + df_coupling = coupling_via_cmatrix(df) + for col in ("ALFX", "BETX", "ALFY", "BETY"): + df_coupling[col] = df[col] + + df_res = rmatrix_from_coupling(df_coupling) + + for col in ("R11", "R12", "R21", "R22"): + # For debugging: + # print(col) + # print(max(np.abs(df[col] - df_res[col]))) + assert all(np.abs(df[col] - df_res[col]) < 5e-15) + + @pytest.mark.basic def test_real_output(): n = 7 diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 68162a5..96efe9a 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -10,7 +10,7 @@ from optics_functions.constants import PHASE_ADV, Y, X, REAL, IMAG, NAME, DELTA_ from optics_functions.utils import (add_missing_columns, dphi, get_all_phase_advances, tau, seq2str, i_pow, prepare_twiss_dataframe, switch_signs_for_beam4, - get_format_keys, dphi_at_element, split_complex_columns) + get_format_keys, dphi_at_element, split_complex_columns, merge_complex_columns) INPUT = Path(__file__).parent.parent / "inputs" @@ -93,6 +93,21 @@ def test_split_complex_columns(): assert (fun(df[col]) == df_split[f"{col}{part}"]).all() [email protected] +def test_merge_complex_columns(): + df = pd.DataFrame([1+2j, 3j + 4], columns=["Col"], index=["A", "B"]) + df_split = split_complex_columns(df, df.columns, drop=True) + + df_merged = merge_complex_columns(df_split, df.columns, drop=False) + assert len(df_merged.columns) == 3 + + df_merged = merge_complex_columns(df_split, df.columns, drop=True) + assert len(df_merged.columns) == 1 + + for col in df.columns: + assert (df[col] == df_merged[col]).all() + + @pytest.mark.basic def test_dphi(): n, qx, qy = 5, 4, 5
Implement calculation from Coupling to R matrix This is the inverse of the coupling from r matrix calculation
0.0
f94ae1df49ba18eede1a62adc6a1081318ec8fbb
[ "tests/unit/test_coupling.py::test_cmatrix", "tests/unit/test_coupling.py::test_rmatrix_to_coupling_to_rmatrix[real]", "tests/unit/test_coupling.py::test_rmatrix_to_coupling_to_rmatrix[fake]", "tests/unit/test_coupling.py::test_real_output", "tests/unit/test_coupling.py::test_coupling_rdt_bump_cmatrix_compare", "tests/unit/test_utils.py::test_add_missing_columns", "tests/unit/test_utils.py::test_i_pow", "tests/unit/test_utils.py::test_seq2str", "tests/unit/test_utils.py::test_get_format_keys", "tests/unit/test_utils.py::test_get_all_phaseadvances", "tests/unit/test_utils.py::test_split_complex_columns", "tests/unit/test_utils.py::test_merge_complex_columns", "tests/unit/test_utils.py::test_dphi", "tests/unit/test_utils.py::test_tau", "tests/unit/test_utils.py::test_dphi_at_element", "tests/unit/test_utils.py::test_prepare_twiss_dataframe", "tests/unit/test_utils.py::test_prepare_twiss_dataframe_inner", "tests/unit/test_utils.py::test_prepare_twiss_dataframe_outer", "tests/unit/test_utils.py::test_prepare_twiss_dataframe_no_error", "tests/unit/test_utils.py::test_prepare_twiss_dataframe_beams", "tests/unit/test_utils.py::test_switch_signs_for_beam4", "tests/unit/test_utils.py::test_switch_signs_for_beam4_madx_data" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-30 19:10:49+00:00
mit
4,944
pylover__sunrise-13
diff --git a/sunrise/actions.py b/sunrise/actions.py index f70b909..44ca2dd 100644 --- a/sunrise/actions.py +++ b/sunrise/actions.py @@ -16,6 +16,7 @@ class Calculator(Action): self.operator = { 'Add': '+', 'Sub': '-', + 'subtract': '-', }[operator] if operator not in self.operators else operator self.numbers = [a, b] @@ -30,7 +31,13 @@ patterns = [ ), ( re.compile( - r'(?P<operator>Add|Sub)\s*(?P<a>\d+)\s*(with|by)\s*(?P<b>\d+)' + r'(?P<operator>Add)\s*(?P<a>\d+)\s*(with|by)\s*(?P<b>\d+)' + ), + Calculator + ), + ( + re.compile( + r'(?P<operator>Sub|subtract)\s*(?P<b>\d+)\s*(from)\s*(?P<a>\d+)' ), Calculator ),
pylover/sunrise
6cd8d347895f0afee892552f1379ac6d3385c369
diff --git a/tests/test_calculator.py b/tests/test_calculator.py index 7c837ea..36be715 100644 --- a/tests/test_calculator.py +++ b/tests/test_calculator.py @@ -4,5 +4,7 @@ from sunrise import do def test_parser(): assert '6' == do('2 + 4') assert '6' == do('Add 2 by 4') + assert '2' == do('subtract 2 from 4') + assert '2' == do('4 - 2')
Add subtraction styles to calculator class.
0.0
6cd8d347895f0afee892552f1379ac6d3385c369
[ "tests/test_calculator.py::test_parser" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-09-10 06:52:20+00:00
mit
4,945
pymoca__pymoca-258
diff --git a/src/pymoca/backends/sympy/generator.py b/src/pymoca/backends/sympy/generator.py index f8692b9..b19ea87 100644 --- a/src/pymoca/backends/sympy/generator.py +++ b/src/pymoca/backends/sympy/generator.py @@ -179,11 +179,12 @@ class {{tree.name}}(OdeModel): self.src[tree] = "{:s}".format(val) def exitComponentRef(self, tree: ast.ComponentRef): - # prevent name clash with builtins name = tree.name.replace('.', '__') while name in BUILTINS: name = name + '_' + if name == 'time': + name = 'self.t' self.src[tree] = name def exitSymbol(self, tree: ast.Symbol): @@ -191,7 +192,6 @@ class {{tree.name}}(OdeModel): name = tree.name.replace('.', '__') while name in BUILTINS: name = name + '_' - self.src[tree] = name def exitEquation(self, tree: ast.Equation):
pymoca/pymoca
0e5a471ff3506d8dc04c8d0774b36a19ea3b9861
diff --git a/test/gen_sympy_test.py b/test/gen_sympy_test.py index 25bad9e..55b38c2 100644 --- a/test/gen_sympy_test.py +++ b/test/gen_sympy_test.py @@ -142,6 +142,32 @@ class GenSympyTest(unittest.TestCase): # res = e.simulate() self.flush() + def test_time_builtin(self): + """Tests Modelica `time` used in a model""" + with open(os.path.join(MODEL_DIR, 'SpringSystem.mo'), 'r') as f: + txt = f.read() + ast_tree = parser.parse(txt) + forced_spring_model = ''' + model ForcedSpringSystem "SpringSystem with time-varying input force" + SpringSystem sys; + equation + sys.u = 100.0*sin(2*time); + end ForcedSpringSystem; + ''' + system_ast = parser.parse(forced_spring_model) + ast_tree.extend(system_ast) + flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='ForcedSpringSystem')) + print(flat_tree) + text = gen_sympy.generate(ast_tree, 'ForcedSpringSystem') + with open(os.path.join(GENERATED_DIR, 'ForcedSpringSystem.py'), 'w') as f: + f.write(text) + from test.generated.ForcedSpringSystem import ForcedSpringSystem as ForcedSpringSystem + e = ForcedSpringSystem() + e.linearize_symbolic() + e.linearize() + # noinspection PyUnusedLocal + res = e.simulate(x0=[1.0, 1.0]) + self.flush() if __name__ == "__main__": unittest.main()
Modelica time is not supported by the SymPy backend As discussed in #255, the Modelica Reference to the simulation time is not supported by the SymPy backend. In a flat Modelica model, the time variable may be used in generators, such as line 12 from the attached example: `sine__y = sine__offset + sine__amplitude * sin(6.283185307179586 * sine__f * time + sine__phase);` The time variable will not be defined in the declaration section of the model/class when compiling the MO file to an MOF file via omc and is thus not part of the symbols in the ast. The pymoca.sympy.generator creates a time variable "t", but does not link the "time" variable, that is present in the ast only in the equations but not as a symbol, to this variable "t". Possible solutions are: 1. The inclusion of "time" in the list of symbols of the ast, in every case or only when it is used in an equation, or 2. The declaration of a time variable in pymoca.sympy.generator, which would then be somehow linked to the variable "t", created in the pymoca.sympy.runtime.OdeModel class (an easy but inelegant way could be to create a state or variable for "time" in exitClass() in pymoca.sympy.generator and then linking it to "t" within SymPy by symbolic equivalence).
0.0
0e5a471ff3506d8dc04c8d0774b36a19ea3b9861
[ "test/gen_sympy_test.py::GenSympyTest::test_time_builtin" ]
[ "test/gen_sympy_test.py::GenSympyTest::test_aircraft", "test/gen_sympy_test.py::GenSympyTest::test_quad", "test/gen_sympy_test.py::GenSympyTest::test_spring" ]
{ "failed_lite_validators": [ "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2022-12-13 00:52:40+00:00
bsd-3-clause
4,946
pymor__pymor-1479
diff --git a/src/pymor/vectorarrays/block.py b/src/pymor/vectorarrays/block.py index 3aa9eb29a..9fdb31fbd 100644 --- a/src/pymor/vectorarrays/block.py +++ b/src/pymor/vectorarrays/block.py @@ -65,6 +65,9 @@ class BlockVectorArray(VectorArray): return 0 def __getitem__(self, ind): + if isinstance(ind, Number) and (ind >= len(self) or ind < -len(self)): + raise IndexError('VectorArray index out of range') + assert self.check_ind(ind) return BlockVectorArrayView(self, ind) def __delitem__(self, ind): diff --git a/src/pymor/vectorarrays/interface.py b/src/pymor/vectorarrays/interface.py index f2871ef06..7825d088a 100644 --- a/src/pymor/vectorarrays/interface.py +++ b/src/pymor/vectorarrays/interface.py @@ -664,14 +664,22 @@ class VectorArray(BasicObject): return len({i if i >= 0 else l+i for i in ind}) def normalize_ind(self, ind): - """Normalize given indices such that they are independent of the array length.""" + """Normalize given indices such that they are independent of the array length. + + Does not check validity of the indices. + """ + l = len(self) if type(ind) is slice: - return slice(*ind.indices(len(self))) + start, stop, step = ind.indices(l) + if start == stop: + return slice(0, 0, 1) + assert start >= 0 + assert stop >= 0 or (step < 0 and stop >= -1) + return slice(start, None if stop == -1 else stop, step) elif not hasattr(ind, '__len__'): - ind = ind if 0 <= ind else len(self)+ind + ind = ind if 0 <= ind else l+ind return slice(ind, ind+1) else: - l = len(self) return [i if 0 <= i else l+i for i in ind] def sub_index(self, ind, ind_ind): diff --git a/src/pymor/vectorarrays/list.py b/src/pymor/vectorarrays/list.py index 8537648dd..23bd976bc 100644 --- a/src/pymor/vectorarrays/list.py +++ b/src/pymor/vectorarrays/list.py @@ -385,6 +385,7 @@ class ListVectorArray(VectorArray): def __getitem__(self, ind): if isinstance(ind, Number) and (ind >= len(self) or ind < -len(self)): raise IndexError('VectorArray index out of range') + assert self.check_ind(ind) return ListVectorArrayView(self, ind) def __delitem__(self, ind): diff --git a/src/pymor/vectorarrays/mpi.py b/src/pymor/vectorarrays/mpi.py index 9bb24aa4f..64dbb0c3e 100644 --- a/src/pymor/vectorarrays/mpi.py +++ b/src/pymor/vectorarrays/mpi.py @@ -13,6 +13,8 @@ The implementations are based on the event loop provided by :mod:`pymor.tools.mpi`. """ +from numbers import Number + import numpy as np from pymor.core.pickle import unpicklable @@ -54,12 +56,16 @@ class MPIVectorArray(VectorArray): return mpi.call(mpi.method_call, self.obj_id, '__len__') def __getitem__(self, ind): + if isinstance(ind, Number) and (ind >= len(self) or ind < -len(self)): + raise IndexError('VectorArray index out of range') + assert self.check_ind(ind) U = type(self)(mpi.call(mpi.method_call_manage, self.obj_id, '__getitem__', ind), self.space) U.is_view = True return U def __delitem__(self, ind): + assert self.check_ind(ind) mpi.call(mpi.method_call, self.obj_id, '__delitem__', ind) def copy(self, deep=False): diff --git a/src/pymor/vectorarrays/numpy.py b/src/pymor/vectorarrays/numpy.py index e4e2c0981..67de3d149 100644 --- a/src/pymor/vectorarrays/numpy.py +++ b/src/pymor/vectorarrays/numpy.py @@ -70,6 +70,7 @@ class NumpyVectorArray(VectorArray): def __getitem__(self, ind): if isinstance(ind, Number) and (ind >= self._len or ind < -self._len): raise IndexError('VectorArray index out of range') + assert self.check_ind(ind) return NumpyVectorArrayView(self, ind) def __delitem__(self, ind): @@ -451,7 +452,6 @@ class NumpyVectorArrayView(NumpyVectorArray): is_view = True def __init__(self, array, ind): - assert array.check_ind(ind) self.base = array self.ind = array.normalize_ind(ind) self.space = array.space
pymor/pymor
1112c1000985afb5e9e2c7cf04efb63eb4c3b28b
diff --git a/src/pymortests/strategies.py b/src/pymortests/strategies.py index 07ad9d0b6..0f17d2542 100644 --- a/src/pymortests/strategies.py +++ b/src/pymortests/strategies.py @@ -254,20 +254,15 @@ def valid_inds(v, length=None, random_module=None): yield [] -# TODO: remove old assumptions on slice values -def _filtered_slices(length): - def _filter(sl): - return sl.step is None or sl.step > 0 - return hyst.slices(length).filter(_filter) - - @hyst.composite def valid_indices(draw, array_strategy, length=None): v = draw(array_strategy) ints = hyst.integers(min_value=-len(v), max_value=max(len(v)-1, 0)) indices = hyst.nothing() if length is None: - indices = indices | hyst.just([]) | hyst.lists(ints, max_size=2*len(v)) | _filtered_slices(len(v)) + indices = indices | hyst.just([]) | hyst.lists(ints, max_size=2*len(v)) + else: + indices = indices | hyst.slices(length) if len(v) > 0: inds = [-len(v), 0, len(v) - 1] if len(v) == length: @@ -317,13 +312,13 @@ def st_valid_inds_of_same_length(draw, v1, v2): # `| hynp.integer_array_indices(shape=(LEN_X,))` if len1 == len2: ints = hyst.integers(min_value=-len1, max_value=max(len1 - 1, 0)) - slicer = _filtered_slices(len1) | hyst.lists(ints, max_size=len1) + slicer = hyst.slices(len1) | hyst.lists(ints, max_size=len1) ret = ret | hyst.tuples(hyst.shared(slicer, key="st_valid_inds_of_same_length"), hyst.shared(slicer, key="st_valid_inds_of_same_length")) if len1 > 0 and len2 > 0: mlen = min(len1, len2) ints = hyst.integers(min_value=-mlen, max_value=max(mlen - 1, 0)) - slicer = _filtered_slices(mlen) | ints | hyst.lists(ints, max_size=mlen) + slicer = hyst.slices(mlen) | ints | hyst.lists(ints, max_size=mlen) ret = ret | hyst.tuples(hyst.shared(slicer, key="st_valid_inds_of_same_length_uneven"), hyst.shared(slicer, key="st_valid_inds_of_same_length_uneven")) return draw(ret) @@ -383,8 +378,8 @@ def st_valid_inds_of_different_length(draw, v1, v2): len1, len2 = len(v1), len(v2) # TODO we should include integer arrays here - val1 = _filtered_slices(len1) # | hynp.integer_array_indices(shape=(len1,)) - val2 = _filtered_slices(len2) # | hynp.integer_array_indices(shape=(len1,)) + val1 = hyst.slices(len1) # | hynp.integer_array_indices(shape=(len1,)) + val2 = hyst.slices(len2) # | hynp.integer_array_indices(shape=(len1,)) ret = hyst.tuples(val1, val2).filter(_filter) return draw(ret) diff --git a/src/pymortests/vectorarray.py b/src/pymortests/vectorarray.py index 28a0c972c..ad462ce85 100644 --- a/src/pymortests/vectorarray.py +++ b/src/pymortests/vectorarray.py @@ -315,6 +315,15 @@ def test_copy_repeated_index(vector_array): pass [email protected]_vector_arrays(index_strategy=pyst.valid_indices) +def test_normalize_ind(vectors_and_indices): + v, ind = vectors_and_indices + assert v.check_ind(ind) + normalized = v.normalize_ind(ind) + assert v.len_ind(normalized) == v.len_ind(ind) + assert v.len_ind_unique(normalized) == v.len_ind_unique(ind) + + @pyst.given_vector_arrays(count=2, index_strategy=pyst.pairs_both_lengths) def test_append(vectors_and_indices): (v1, v2), (_, ind) = vectors_and_indices
Remove slicing restrictions for vectorarray tests Historically index tests were performed with a set of manually constructed `slice` objects. When rewriting the tests to instead draw slices from a hypothesis strategy it became necessary to add a filter to mimic the properties of the manual examples, or be drowned by test failures. Notably this filter excludes negative step sizes. It's unclear whether the assertions simply are defective or if real failures are among them. And I currently do not have time to look into this further. Anybody interested should check out the `vectorarray_tests_unrestricted_slicing` branch and run the tests there.
0.0
1112c1000985afb5e9e2c7cf04efb63eb4c3b28b
[ "src/pymortests/vectorarray.py::test_inner_self", "src/pymortests/vectorarray.py::test_axpy_self" ]
[ "src/pymortests/vectorarray.py::test_sub_incompatible", "src/pymortests/vectorarray.py::test_scla", "src/pymortests/vectorarray.py::test_imul", "src/pymortests/vectorarray.py::test_add_incompatible", "src/pymortests/vectorarray.py::test_axpy", "src/pymortests/vectorarray.py::test_normalize_ind", "src/pymortests/vectorarray.py::test_random_normal", "src/pymortests/vectorarray.py::test_COW", "src/pymortests/vectorarray.py::test_zeros", "src/pymortests/vectorarray.py::test_norm2", "src/pymortests/vectorarray.py::test_wrong_ind_raises_exception", "src/pymortests/vectorarray.py::test_del", "src/pymortests/vectorarray.py::test_norm", "src/pymortests/vectorarray.py::test_lincomb_2d", "src/pymortests/vectorarray.py::test_dofs", "src/pymortests/vectorarray.py::test_pairwise_inner_incompatible", "src/pymortests/vectorarray.py::test_append_self", "src/pymortests/vectorarray.py::test_axpy_incompatible", "src/pymortests/vectorarray.py::test_copy_repeated_index", "src/pymortests/vectorarray.py::test_iadd", "src/pymortests/vectorarray.py::test_append", "src/pymortests/vectorarray.py::test_axpy_wrong_coefficients", "src/pymortests/vectorarray.py::test_iter", "src/pymortests/vectorarray.py::test_mul_wrong_factor", "src/pymortests/vectorarray.py::test_isub", "src/pymortests/vectorarray.py::test_amax", "src/pymortests/vectorarray.py::test_from_numpy", "src/pymortests/vectorarray.py::test_sub", "src/pymortests/vectorarray.py::test_lincomb_wrong_coefficients", "src/pymortests/vectorarray.py::test_inner", "src/pymortests/vectorarray.py::test_imul_wrong_factor", "src/pymortests/vectorarray.py::test_full", "src/pymortests/vectorarray.py::test_axpy_one_x", "src/pymortests/vectorarray.py::test_lincomb_1d", "src/pymortests/vectorarray.py::test_add", "src/pymortests/vectorarray.py::test_print", "src/pymortests/vectorarray.py::test_append_incompatible", "src/pymortests/vectorarray.py::test_sup_norm", "src/pymortests/vectorarray.py::test_scal_wrong_coefficients", "src/pymortests/vectorarray.py::test_empty", "src/pymortests/vectorarray.py::test_random_uniform", "src/pymortests/vectorarray.py::test_gramian", "src/pymortests/vectorarray.py::test_neg", "src/pymortests/vectorarray.py::test_inner_incompatible", "src/pymortests/vectorarray.py::test_space", "src/pymortests/vectorarray.py::test_getitem_repeated", "src/pymortests/vectorarray.py::test_isub_incompatible", "src/pymortests/vectorarray.py::test_copy", "src/pymortests/vectorarray.py::test_shape", "src/pymortests/vectorarray.py::test_pickle", "src/pymortests/vectorarray.py::test_pairwise_inner_self", "src/pymortests/vectorarray.py::test_iadd_incompatible", "src/pymortests/vectorarray.py::test_components_wrong_dof_indices", "src/pymortests/vectorarray.py::test_mul", "src/pymortests/vectorarray.py::test_pairwise_inner", "src/pymortests/vectorarray.py::test_ones" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-11-29 09:03:28+00:00
bsd-3-clause
4,947
pymor__pymor-577
diff --git a/src/pymor/algorithms/gram_schmidt.py b/src/pymor/algorithms/gram_schmidt.py index 2e65b2e15..114a5e06b 100644 --- a/src/pymor/algorithms/gram_schmidt.py +++ b/src/pymor/algorithms/gram_schmidt.py @@ -10,10 +10,10 @@ from pymor.core.logger import getLogger @defaults('atol', 'rtol', 'reiterate', 'reiteration_threshold', 'check', 'check_tol') -def gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, +def gram_schmidt(A, product=None, return_R=False, atol=1e-13, rtol=1e-13, offset=0, reiterate=True, reiteration_threshold=1e-1, check=True, check_tol=1e-3, copy=True): - """Orthonormalize a |VectorArray| using the stabilized Gram-Schmidt algorithm. + """Orthonormalize a |VectorArray| using the modified Gram-Schmidt algorithm. Parameters ---------- @@ -22,6 +22,8 @@ def gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, product The inner product |Operator| w.r.t. which to orthonormalize. If `None`, the Euclidean product is used. + return_R + If `True`, the R matrix from QR decomposition is returned. atol Vectors of norm smaller than `atol` are removed from the array. rtol @@ -45,7 +47,10 @@ def gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, Returns ------- - The orthonormalized |VectorArray|. + Q + The orthonormalized |VectorArray|. + R + The upper-triangular/trapezoidal matrix (if `compute_R` is `True`). """ logger = getLogger('pymor.algorithms.gram_schmidt.gram_schmidt') @@ -54,7 +59,8 @@ def gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, A = A.copy() # main loop - remove = [] + R = np.eye(len(A)) + remove = [] # indices of to be removed vectors for i in range(offset, len(A)): # first calculate norm initial_norm = A[i].norm(product)[0] @@ -65,41 +71,41 @@ def gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, continue if i == 0: - A[0].scal(1/initial_norm) - + A[0].scal(1 / initial_norm) + R[i, i] = initial_norm else: - first_iteration = True norm = initial_norm # If reiterate is True, reiterate as long as the norm of the vector changes - # strongly during orthonormalization (due to Andreas Buhr). - while first_iteration or reiterate and norm/old_norm < reiteration_threshold: - - if first_iteration: - first_iteration = False - else: - logger.info(f'Orthonormalizing vector {i} again') - + # strongly during orthogonalization (due to Andreas Buhr). + while True: # orthogonalize to all vectors left for j in range(i): if j in remove: continue - p = A[i].pairwise_inner(A[j], product)[0] + p = A[j].pairwise_inner(A[i], product)[0] A[i].axpy(-p, A[j]) + R[j, i] += p # calculate new norm old_norm, norm = norm, A[i].norm(product)[0] - # remove vector if it got too small: - if norm / initial_norm < rtol: - logger.info(f"Removing linear dependent vector {i}") + # remove vector if it got too small + if norm < rtol * initial_norm: + logger.info(f"Removing linearly dependent vector {i}") remove.append(i) break - if norm > 0: - A[i].scal(1 / norm) + # check if reorthogonalization should be done + if reiterate and norm < reiteration_threshold * old_norm: + logger.info(f"Orthonormalizing vector {i} again") + else: + A[i].scal(1 / norm) + R[i, i] = norm + break if remove: del A[remove] + R = np.delete(R, remove, axis=0) if check: error_matrix = A[offset:len(A)].inner(A, product) @@ -107,12 +113,16 @@ def gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, if error_matrix.size > 0: err = np.max(np.abs(error_matrix)) if err >= check_tol: - raise AccuracyError(f'result not orthogonal (max err={err})') + raise AccuracyError(f"result not orthogonal (max err={err})") - return A + if return_R: + return A, R + else: + return A -def gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshold=1e-1, check=True, check_tol=1e-3, +def gram_schmidt_biorth(V, W, product=None, + reiterate=True, reiteration_threshold=1e-1, check=True, check_tol=1e-3, copy=True): """Biorthonormalize a pair of |VectorArrays| using the biorthonormal Gram-Schmidt process. @@ -161,16 +171,10 @@ def gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshol if i == 0: V[0].scal(1 / initial_norm) else: - first_iteration = True norm = initial_norm # If reiterate is True, reiterate as long as the norm of the vector changes # strongly during projection. - while first_iteration or reiterate and norm / old_norm < reiteration_threshold: - if first_iteration: - first_iteration = False - else: - logger.info(f'Projecting vector V[{i}] again') - + while True: for j in range(i): # project by (I - V[j] * W[j]^T * E) p = W[j].pairwise_inner(V[i], product)[0] @@ -179,8 +183,12 @@ def gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshol # calculate new norm old_norm, norm = norm, V[i].norm(product)[0] - if norm > 0: - V[i].scal(1 / norm) + # check if reorthogonalization should be done + if reiterate and norm < reiteration_threshold * old_norm: + logger.info(f"Projecting vector V[{i}] again") + else: + V[i].scal(1 / norm) + break # calculate norm of W[i] initial_norm = W[i].norm(product)[0] @@ -189,16 +197,10 @@ def gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshol if i == 0: W[0].scal(1 / initial_norm) else: - first_iteration = True norm = initial_norm # If reiterate is True, reiterate as long as the norm of the vector changes # strongly during projection. - while first_iteration or reiterate and norm / old_norm < reiteration_threshold: - if first_iteration: - first_iteration = False - else: - logger.info(f'Projecting vector W[{i}] again') - + while True: for j in range(i): # project by (I - W[j] * V[j]^T * E) p = V[j].pairwise_inner(W[i], product)[0] @@ -207,8 +209,12 @@ def gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshol # calculate new norm old_norm, norm = norm, W[i].norm(product)[0] - if norm > 0: - W[i].scal(1 / norm) + # check if reorthogonalization should be done + if reiterate and norm < reiteration_threshold * old_norm: + logger.info(f"Projecting vector W[{i}] again") + else: + W[i].scal(1 / norm) + break # rescale V[i] p = W[i].pairwise_inner(V[i], product)[0] @@ -220,6 +226,6 @@ def gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshol if error_matrix.size > 0: err = np.max(np.abs(error_matrix)) if err >= check_tol: - raise AccuracyError(f'Result not biorthogonal (max err={err})') + raise AccuracyError(f"result not biorthogonal (max err={err})") return V, W
pymor/pymor
f441a7917f3c30219abdbed99143a4bf31abc613
diff --git a/src/pymortests/algorithms/gram_schmidt.py b/src/pymortests/algorithms/gram_schmidt.py index 82debb6aa..285081e30 100644 --- a/src/pymortests/algorithms/gram_schmidt.py +++ b/src/pymortests/algorithms/gram_schmidt.py @@ -24,6 +24,22 @@ def test_gram_schmidt(vector_array): assert np.all(almost_equal(onb, U)) +def test_gram_schmidt_with_R(vector_array): + U = vector_array + + V = U.copy() + onb, R = gram_schmidt(U, return_R=True, copy=True) + assert np.all(almost_equal(U, V)) + assert np.allclose(onb.dot(onb), np.eye(len(onb))) + assert np.all(almost_equal(U, onb.lincomb(U.dot(onb)), rtol=1e-13)) + assert np.all(almost_equal(V, onb.lincomb(R.T))) + + onb2, R2 = gram_schmidt(U, return_R=True, copy=False) + assert np.all(almost_equal(onb, onb2)) + assert np.all(R == R2) + assert np.all(almost_equal(onb, U)) + + def test_gram_schmidt_with_product(operator_with_arrays_and_products): _, _, U, _, p, _ = operator_with_arrays_and_products @@ -38,6 +54,22 @@ def test_gram_schmidt_with_product(operator_with_arrays_and_products): assert np.all(almost_equal(onb, U)) +def test_gram_schmidt_with_product_and_R(operator_with_arrays_and_products): + _, _, U, _, p, _ = operator_with_arrays_and_products + + V = U.copy() + onb, R = gram_schmidt(U, product=p, return_R=True, copy=True) + assert np.all(almost_equal(U, V)) + assert np.allclose(p.apply2(onb, onb), np.eye(len(onb))) + assert np.all(almost_equal(U, onb.lincomb(p.apply2(U, onb)), rtol=1e-13)) + assert np.all(almost_equal(U, onb.lincomb(R.T))) + + onb2, R2 = gram_schmidt(U, product=p, return_R=True, copy=False) + assert np.all(almost_equal(onb, onb2)) + assert np.all(R == R2) + assert np.all(almost_equal(onb, U)) + + def test_gram_schmidt_biorth(vector_array): U = vector_array if U.dim < 2:
gram_schmidt doesn't return the R matrix Currently, `gram_schmidt` only returns the Q matrix. The R matrix is used in the [shift selection for the LRADI method](https://github.com/pymor/pymor/blob/1aeccb428700fa140cb6faa7490bdaf87a9754a3/src/pymor/algorithms/lyapunov.py#L285-L287) and in the [rational Krylov subspace method for Lyapunov equations](http://www.dm.unibo.it/~simoncin/rksm.m) (related to #387). It might also be useful for computing an SVD of a vectorarray (Q * svd(R)).
0.0
f441a7917f3c30219abdbed99143a4bf31abc613
[ "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[0-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[1-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_R[2-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>24]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>25]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>26]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>27]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>28]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>29]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>30]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>31]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>32]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>33]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>34]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>35]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product_and_R[<lambda>36]" ]
[ "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[0-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[1-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt[2-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>24]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>25]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>26]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>27]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>28]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>29]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>30]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>31]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>32]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>33]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>34]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>35]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_with_product[<lambda>36]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[0-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[1-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>0]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>1]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>2]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>3]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>4]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>5]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>6]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>7]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>8]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>9]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>10]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>11]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>12]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>13]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>14]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>15]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth[2-<lambda>16]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>24]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>25]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>26]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>27]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>28]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>29]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>30]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>31]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>32]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>33]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>34]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>35]", "src/pymortests/algorithms/gram_schmidt.py::test_gram_schmidt_biorth_with_product[<lambda>36]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-01-31 19:07:41+00:00
bsd-3-clause
4,948
pymzml__pymzML-258
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b1834c7..ae7c981 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.5.0 + rev: v3.3.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer diff --git a/pymzml/spec.py b/pymzml/spec.py index 8d81573..9740fa8 100755 --- a/pymzml/spec.py +++ b/pymzml/spec.py @@ -160,26 +160,6 @@ class MS_Spectrum(object): else: raise Exception("Unknown data Type ({0})".format(d_type)) - @property - def precursors(self): - """ - List the precursor information of this spectrum, if available. - - Returns: - precursor(list): list of precursor ids for this spectrum. - """ - if self._precursors is None: - precursors = self.element.findall( - "./{ns}precursorList/{ns}precursor".format(ns=self.ns) - ) - self._precursors = [] - for prec in precursors: - spec_ref = prec.get("spectrumRef") - self._precursors.append( - regex_patterns.SPECTRUM_ID_PATTERN.search(spec_ref).group(1) - ) - return self._precursors - def _get_encoding_parameters(self, array_type): """ Find the correct parameter for decoding and return them as tuple. @@ -409,7 +389,6 @@ class Spectrum(MS_Spectrum): "_index", "_measured_precision", "_peaks", - "_precursors", "_profile", "_reprofiled_peaks", "_t_mass_set", @@ -936,10 +915,14 @@ class Spectrum(MS_Spectrum): selected_precursor_cs = self.element.findall( ".//*[@accession='MS:1000041']" ) + precursors = self.element.findall( + "./{ns}precursorList/{ns}precursor".format(ns=self.ns) + ) mz_values = [] i_values = [] charges = [] + ids = [] for obj in selected_precursor_mzs: mz = obj.get("value") mz_values.append(float(mz)) @@ -949,10 +932,19 @@ class Spectrum(MS_Spectrum): for obj in selected_precursor_cs: c = obj.get("value") charges.append(int(c)) + for prec in precursors: + spec_ref = prec.get("spectrumRef") + if spec_ref is not None: + ids.append( + regex_patterns.SPECTRUM_ID_PATTERN.search(spec_ref).group(1) + ) + else: + ids.append(None) + # ids.append() self._selected_precursors = [] for pos, mz in enumerate(mz_values): dict_2_save = {"mz": mz} - for key, list_of_values in [("i", i_values), ("charge", charges)]: + for key, list_of_values in [("i", i_values), ("charge", charges), ('precursor id', ids)]: try: dict_2_save[key] = list_of_values[pos] except: @@ -960,6 +952,26 @@ class Spectrum(MS_Spectrum): self._selected_precursors.append(dict_2_save) return self._selected_precursors + + @property + def precursors(self): + """ + List the precursor information of this spectrum, if available. + Returns: + precursor(list): list of precursor ids for this spectrum. + """ + self.deprecation_warning(sys._getframe().f_code.co_name) + if self._precursors is None: + precursors = self.element.findall( + "./{ns}precursorList/{ns}precursor".format(ns=self.ns) + ) + self._precursors = [] + for prec in precursors: + spec_ref = prec.get("spectrumRef") + self._precursors.append( + regex_patterns.SPECTRUM_ID_PATTERN.search(spec_ref).group(1) + ) + return self._precursors def remove_precursor_peak(self): peaks = self.peaks("centroided") @@ -1627,6 +1639,7 @@ class Spectrum(MS_Spectrum): "removeNoise": "remove_noise", "newPlot": "new_plot", "centroidedPeaks": "peaks", + "precursors": "selected_precursors", } warnings.warn( """
pymzml/pymzML
58910ef30ef32375fe07a5a192ddeea9b3c6b6d5
diff --git a/tests/ms2_spec_test.py b/tests/ms2_spec_test.py index 42aab35..9984dcf 100755 --- a/tests/ms2_spec_test.py +++ b/tests/ms2_spec_test.py @@ -47,7 +47,7 @@ class SpectrumMS2Test(unittest.TestCase): self.assertIsInstance(selected_precursor[0]["i"], float) self.assertIsInstance(selected_precursor[0]["charge"], int) self.assertEqual( - selected_precursor, [{"mz": 443.711242675781, "i": 0.0, "charge": 2}] + selected_precursor, [{"mz": 443.711242675781, "i": 0.0, "charge": 2, 'precursor id': None}] ) def test_ion_mode(self):
Cannot get precursor information from MS3 spectra Hi! Thank you for this software--it's been tremendously useful for my work. **Describe the bug** Cannot get precursor information from Spectrum object. **To Reproduce** Steps to reproduce the behavior: ``` import pymzml run = pymzml.run.Reader('KL-NB1-12_A.mzML', MS_precisions={1: 1e-6, 2: 1e-6, 3: 1e-6}) # get some spectrum, ms3, with MS level == 3 ms3.precursors ``` ``` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-6-25a2f3d1799b> in <module> ----> 1 ms3.precursors /usr/local/miniconda3/lib/python3.8/site-packages/pymzml/spec.py in precursors(self) 169 precursor(list): list of precursor ids for this spectrum. 170 """ --> 171 if self._precursors is None: 172 precursors = self.element.findall( 173 "./{ns}precursorList/{ns}precursor".format(ns=self.ns) AttributeError: 'Spectrum' object has no attribute '_precursors' ``` **Expected behavior** spectrum.precursors should return a list of SpectrumRef ids. **Desktop (please complete the following information):** - OS: Linux 5.4.0-53-generic #59-Ubuntu SMP x86_64 GNU/Linux **Additional context** It appears that the issue is self._precursors is never initialized in the Spectrum class. Adding `self._precursors = None` appears to fix.
0.0
58910ef30ef32375fe07a5a192ddeea9b3c6b6d5
[ "tests/ms2_spec_test.py::SpectrumMS2Test::test_select_precursors" ]
[ "tests/ms2_spec_test.py::SpectrumMS2Test::test_ion_mode", "tests/ms2_spec_test.py::SpectrumMS2Test::test_ion_mode_non_existent", "tests/ms2_spec_test.py::SpectrumMS2Test::test_remove_precursor_peak", "tests/ms2_spec_test.py::SpectrumMS2Test::test_scan_time" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-04 20:12:21+00:00
mit
4,949
pynamodb__PynamoDB-1189
diff --git a/pynamodb/attributes.py b/pynamodb/attributes.py index c0f182b..ce750bf 100644 --- a/pynamodb/attributes.py +++ b/pynamodb/attributes.py @@ -268,7 +268,7 @@ class Attribute(Generic[_T]): def set( self, value: Union[_T, 'Attribute[_T]', '_Increment', '_Decrement', '_IfNotExists', '_ListAppend'] - ) -> 'SetAction': + ) -> Union['SetAction', 'RemoveAction']: return Path(self).set(value) def remove(self) -> 'RemoveAction': diff --git a/pynamodb/expressions/operand.py b/pynamodb/expressions/operand.py index 9420788..8f7987e 100644 --- a/pynamodb/expressions/operand.py +++ b/pynamodb/expressions/operand.py @@ -298,9 +298,14 @@ class Path(_NumericOperand, _ListAppendOperand, _ConditionOperand): def __or__(self, other): return _IfNotExists(self, self._to_operand(other)) - def set(self, value: Any) -> SetAction: - # Returns an update action that sets this attribute to the given value - return SetAction(self, self._to_operand(value)) + def set(self, value: Any) -> Union[SetAction, RemoveAction]: + # Returns an update action that sets this attribute to the given value. + # For attributes that may not be empty (e.g. sets), this may result + # in a remove action. + operand = self._to_operand(value) + if isinstance(operand, Value) and next(iter(operand.value.values())) is None: + return RemoveAction(self) + return SetAction(self, operand) def remove(self) -> RemoveAction: # Returns an update action that removes this attribute from the item
pynamodb/PynamoDB
12e127f5a8214e9e46d5208f6af1e9801acfc64e
diff --git a/tests/integration/model_integration_test.py b/tests/integration/model_integration_test.py index 340ca72..9a54ccc 100644 --- a/tests/integration/model_integration_test.py +++ b/tests/integration/model_integration_test.py @@ -102,6 +102,10 @@ def test_model_integration(ddb_url): for item in TestModel.view_index.query('foo', TestModel.view > 0): print("Item queried from index: {}".format(item.view)) + query_obj.update([TestModel.scores.set([])]) + query_obj.refresh() + assert query_obj.scores is None + print(query_obj.update([TestModel.view.add(1)], condition=TestModel.forum.exists())) TestModel.delete_table() diff --git a/tests/test_expressions.py b/tests/test_expressions.py index 4d314bb..698366f 100644 --- a/tests/test_expressions.py +++ b/tests/test_expressions.py @@ -479,6 +479,13 @@ class UpdateExpressionTestCase(TestCase): assert self.placeholder_names == {'foo': '#0'} assert self.expression_attribute_values == {':0': {'S': 'bar'}} + def test_set_action_as_remove(self): + action = self.set_attribute.set([]) + expression = action.serialize(self.placeholder_names, self.expression_attribute_values) + assert expression == "#0" + assert self.placeholder_names == {'foo_set': '#0'} + assert self.expression_attribute_values == {} + def test_set_action_attribute_container(self): # Simulate initialization from inside an AttributeContainer my_map_attribute = MapAttribute[str, str](attr_name='foo') @@ -620,6 +627,15 @@ class UpdateExpressionTestCase(TestCase): ':2': {'NS': ['1']} } + def test_update_set_to_empty(self): + update = Update( + self.set_attribute.set([]), + ) + expression = update.serialize(self.placeholder_names, self.expression_attribute_values) + assert expression == "REMOVE #0" + assert self.placeholder_names == {'foo_set': '#0'} + assert self.expression_attribute_values == {} + def test_update_skips_empty_clauses(self): update = Update(self.attribute.remove()) expression = update.serialize(self.placeholder_names, self.expression_attribute_values)
Setting <UnicodeSetAttribute>.set([]) (empty list) throws "Nonetype is not iterable" error. During an update operation a UnicodeSet field may have it's value changed back to empty e.g. [] The following code fails: ``` (Pdb) actions = [] (Pdb) actions.append(attr.set([])) (Pdb) record.update(actions) ``` `*** TypeError: 'NoneType' object is not iterable` The following two examples work: ``` (Pdb) actions = [] (Pdb) actions.append(attr.set(None)) (Pdb) record.update(actions) ``` ``` (Pdb) actions = [] (Pdb) actions.append(attr.set(['foo', 'bar'])) (Pdb) record.update(actions) ``` Is this a bug?
0.0
12e127f5a8214e9e46d5208f6af1e9801acfc64e
[ "tests/test_expressions.py::UpdateExpressionTestCase::test_set_action_as_remove", "tests/test_expressions.py::UpdateExpressionTestCase::test_update_set_to_empty" ]
[ "tests/integration/model_integration_test.py::test_can_inherit_version_attribute", "tests/test_expressions.py::PathTestCase::test_attribute_name", "tests/test_expressions.py::PathTestCase::test_document_path", "tests/test_expressions.py::PathTestCase::test_index_attribute_name", "tests/test_expressions.py::PathTestCase::test_index_document_path", "tests/test_expressions.py::PathTestCase::test_index_invalid", "tests/test_expressions.py::PathTestCase::test_index_map_attribute", "tests/test_expressions.py::ActionTestCase::test_action", "tests/test_expressions.py::ActionTestCase::test_action_eq", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_project_expression_with_attribute_names", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_project_expression_with_document_paths", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_invalid_attribute_raises", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_not_a_list", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_repeated_names", "tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_with_attributes", "tests/test_expressions.py::ConditionExpressionTestCase::test_and", "tests/test_expressions.py::ConditionExpressionTestCase::test_attribute_comparison", "tests/test_expressions.py::ConditionExpressionTestCase::test_begins_with", "tests/test_expressions.py::ConditionExpressionTestCase::test_between", "tests/test_expressions.py::ConditionExpressionTestCase::test_compound_logic", "tests/test_expressions.py::ConditionExpressionTestCase::test_condition_eq", "tests/test_expressions.py::ConditionExpressionTestCase::test_contains", "tests/test_expressions.py::ConditionExpressionTestCase::test_contains_attribute", "tests/test_expressions.py::ConditionExpressionTestCase::test_contains_list", "tests/test_expressions.py::ConditionExpressionTestCase::test_contains_number_set", "tests/test_expressions.py::ConditionExpressionTestCase::test_contains_string_set", "tests/test_expressions.py::ConditionExpressionTestCase::test_does_not_exist", "tests/test_expressions.py::ConditionExpressionTestCase::test_dotted_attribute_name", "tests/test_expressions.py::ConditionExpressionTestCase::test_double_indexing", "tests/test_expressions.py::ConditionExpressionTestCase::test_equal", "tests/test_expressions.py::ConditionExpressionTestCase::test_exists", "tests/test_expressions.py::ConditionExpressionTestCase::test_greater_than", "tests/test_expressions.py::ConditionExpressionTestCase::test_greater_than_or_equal", "tests/test_expressions.py::ConditionExpressionTestCase::test_in", "tests/test_expressions.py::ConditionExpressionTestCase::test_indexing", "tests/test_expressions.py::ConditionExpressionTestCase::test_invalid_and", "tests/test_expressions.py::ConditionExpressionTestCase::test_invalid_indexing", "tests/test_expressions.py::ConditionExpressionTestCase::test_invalid_or", "tests/test_expressions.py::ConditionExpressionTestCase::test_invalid_rand", "tests/test_expressions.py::ConditionExpressionTestCase::test_is_type", "tests/test_expressions.py::ConditionExpressionTestCase::test_less_than", "tests/test_expressions.py::ConditionExpressionTestCase::test_less_than_or_equal", "tests/test_expressions.py::ConditionExpressionTestCase::test_list_comparison", "tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_dereference", "tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_dereference_via_indexing", "tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_dereference_via_indexing_missing_attribute", "tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_indexing", "tests/test_expressions.py::ConditionExpressionTestCase::test_map_comparison", "tests/test_expressions.py::ConditionExpressionTestCase::test_map_comparison_rhs", "tests/test_expressions.py::ConditionExpressionTestCase::test_not", "tests/test_expressions.py::ConditionExpressionTestCase::test_not_equal", "tests/test_expressions.py::ConditionExpressionTestCase::test_or", "tests/test_expressions.py::ConditionExpressionTestCase::test_rand", "tests/test_expressions.py::ConditionExpressionTestCase::test_size", "tests/test_expressions.py::ConditionExpressionTestCase::test_sizes", "tests/test_expressions.py::ConditionExpressionTestCase::test_typed_list_indexing", "tests/test_expressions.py::UpdateExpressionTestCase::test_add_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_add_action_list", "tests/test_expressions.py::UpdateExpressionTestCase::test_add_action_serialized", "tests/test_expressions.py::UpdateExpressionTestCase::test_add_action_set", "tests/test_expressions.py::UpdateExpressionTestCase::test_append_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_conditional_set_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_decrement_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_decrement_action_value", "tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action_non_set", "tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action_serialized", "tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action_set", "tests/test_expressions.py::UpdateExpressionTestCase::test_increment_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_increment_action_value", "tests/test_expressions.py::UpdateExpressionTestCase::test_prepend_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_remove_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_remove_action_list_element", "tests/test_expressions.py::UpdateExpressionTestCase::test_set_action", "tests/test_expressions.py::UpdateExpressionTestCase::test_set_action_attribute_container", "tests/test_expressions.py::UpdateExpressionTestCase::test_update", "tests/test_expressions.py::UpdateExpressionTestCase::test_update_empty", "tests/test_expressions.py::UpdateExpressionTestCase::test_update_skips_empty_clauses" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-07-12 04:53:38+00:00
mit
4,950
pynamodb__PynamoDB-700
diff --git a/docs/awsaccess.rst b/docs/awsaccess.rst index 6a72c45..38e26ae 100644 --- a/docs/awsaccess.rst +++ b/docs/awsaccess.rst @@ -22,6 +22,7 @@ If for some reason you can't use conventional AWS configuration methods, you can class Meta: aws_access_key_id = 'my_access_key_id' aws_secret_access_key = 'my_secret_access_key' + aws_session_token = 'my_session_token' # Optional, only for temporary credentials like those received when assuming a role Finally, see the `AWS CLI documentation <http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-installing-credentials>`_ for more details on how to pass credentials to botocore. \ No newline at end of file diff --git a/pynamodb/connection/table.py b/pynamodb/connection/table.py index 9b6d5c4..a804136 100644 --- a/pynamodb/connection/table.py +++ b/pynamodb/connection/table.py @@ -22,7 +22,8 @@ class TableConnection(object): max_pool_connections=None, extra_headers=None, aws_access_key_id=None, - aws_secret_access_key=None): + aws_secret_access_key=None, + aws_session_token=None): self._hash_keyname = None self._range_keyname = None self.table_name = table_name @@ -37,7 +38,8 @@ class TableConnection(object): if aws_access_key_id and aws_secret_access_key: self.connection.session.set_credentials(aws_access_key_id, - aws_secret_access_key) + aws_secret_access_key, + aws_session_token) def get_meta_table(self, refresh=False): """ diff --git a/pynamodb/connection/table.pyi b/pynamodb/connection/table.pyi index 2d1c7c1..c52576d 100644 --- a/pynamodb/connection/table.pyi +++ b/pynamodb/connection/table.pyi @@ -20,6 +20,7 @@ class TableConnection: extra_headers: Optional[MutableMapping[Text, Text]] = ..., aws_access_key_id: Optional[str] = ..., aws_secret_access_key: Optional[str] = ..., + aws_access_token: Optional[str] = ..., ) -> None: ... def get_operation_kwargs( @@ -81,4 +82,3 @@ class TableConnection: def update_time_to_live(self, ttl_attr_name: Text): ... def update_table(self, read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ..., global_secondary_index_updates: Optional[Any] = ...): ... def create_table(self, attribute_definitions: Optional[Any] = ..., key_schema: Optional[Any] = ..., read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ..., global_secondary_indexes: Optional[Any] = ..., local_secondary_indexes: Optional[Any] = ..., stream_specification: Optional[Any] = ...): ... - diff --git a/pynamodb/models.py b/pynamodb/models.py index 1481127..fe7a485 100644 --- a/pynamodb/models.py +++ b/pynamodb/models.py @@ -208,6 +208,8 @@ class MetaModel(AttributeContainerMeta): setattr(attr_obj, 'aws_access_key_id', None) if not hasattr(attr_obj, 'aws_secret_access_key'): setattr(attr_obj, 'aws_secret_access_key', None) + if not hasattr(attr_obj, 'aws_session_token'): + setattr(attr_obj, 'aws_session_token', None) elif isinstance(attr_obj, Index): attr_obj.Meta.model = cls if not hasattr(attr_obj.Meta, "index_name"): @@ -1042,7 +1044,8 @@ class Model(AttributeContainer): max_pool_connections=cls.Meta.max_pool_connections, extra_headers=cls.Meta.extra_headers, aws_access_key_id=cls.Meta.aws_access_key_id, - aws_secret_access_key=cls.Meta.aws_secret_access_key) + aws_secret_access_key=cls.Meta.aws_secret_access_key, + aws_session_token=cls.Meta.aws_session_token) return cls._connection def _deserialize(self, attrs):
pynamodb/PynamoDB
cf98a35b596194187d7ab4de055b5e0547b39574
diff --git a/tests/test_table_connection.py b/tests/test_table_connection.py index 73deeac..caab960 100644 --- a/tests/test_table_connection.py +++ b/tests/test_table_connection.py @@ -45,6 +45,19 @@ class ConnectionTestCase(TestCase): self.assertEqual(credentials.access_key, 'access_key_id') self.assertEqual(credentials.secret_key, 'secret_access_key') + def test_connection_session_set_credentials_with_session_token(self): + conn = TableConnection( + self.test_table_name, + aws_access_key_id='access_key_id', + aws_secret_access_key='secret_access_key', + aws_session_token='session_token') + + credentials = conn.connection.session.get_credentials() + + self.assertEqual(credentials.access_key, 'access_key_id') + self.assertEqual(credentials.secret_key, 'secret_access_key') + self.assertEqual(credentials.token, 'session_token') + def test_create_table(self): """ TableConnection.create_table
There is no mechanism for passing a session token Using STS, I should be able to assume a role and pass the `aws_access_key_id` `aws_secret_access_key` and `session_token` to my model. Currently there is no mechanism to pass the session_token to a Model (without mucking with env variables)
0.0
cf98a35b596194187d7ab4de055b5e0547b39574
[ "tests/test_table_connection.py::ConnectionTestCase::test_connection_session_set_credentials_with_session_token" ]
[ "tests/test_table_connection.py::ConnectionTestCase::test_batch_get_item", "tests/test_table_connection.py::ConnectionTestCase::test_batch_write_item", "tests/test_table_connection.py::ConnectionTestCase::test_connection_session_set_credentials", "tests/test_table_connection.py::ConnectionTestCase::test_create_connection", "tests/test_table_connection.py::ConnectionTestCase::test_create_table", "tests/test_table_connection.py::ConnectionTestCase::test_delete_item", "tests/test_table_connection.py::ConnectionTestCase::test_delete_table", "tests/test_table_connection.py::ConnectionTestCase::test_describe_table", "tests/test_table_connection.py::ConnectionTestCase::test_get_item", "tests/test_table_connection.py::ConnectionTestCase::test_put_item", "tests/test_table_connection.py::ConnectionTestCase::test_query", "tests/test_table_connection.py::ConnectionTestCase::test_scan", "tests/test_table_connection.py::ConnectionTestCase::test_update_item", "tests/test_table_connection.py::ConnectionTestCase::test_update_table", "tests/test_table_connection.py::ConnectionTestCase::test_update_time_to_live" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-03 16:59:53+00:00
mit
4,951
pynamodb__PynamoDB-864
diff --git a/docs/polymorphism.rst b/docs/polymorphism.rst index 6a341d7..9d29b96 100644 --- a/docs/polymorphism.rst +++ b/docs/polymorphism.rst @@ -6,7 +6,6 @@ Polymorphism PynamoDB supports polymorphism through the use of discriminators. A discriminator is a value that is written to DynamoDB that identifies the python class being stored. -(Note: currently discriminators are only supported on MapAttribute subclasses; support for model subclasses coming soon.) Discriminator Attributes ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,3 +48,32 @@ A class can also be registered manually: Discriminator values are written to DynamoDB. Changing the value after items have been saved to the database can result in deserialization failures. In order to read items with an old discriminator value, the old value must be manually registered. + + +Model Discriminators +^^^^^^^^^^^^^^^^^^^^ + +Model classes also support polymorphism through the use of discriminators. +(Note: currently discriminator attributes cannot be used as the hash or range key of a table.) + +.. code-block:: python + + class ParentModel(Model): + class Meta: + table_name = 'polymorphic_table' + id = UnicodeAttribute(hash_key=True) + cls = DiscriminatorAttribute() + + class FooModel(ParentModel, discriminator='Foo'): + foo = UnicodeAttribute() + + class BarModel(ParentModel, discriminator='Bar'): + bar = UnicodeAttribute() + + BarModel(id='Hello', bar='World!').serialize() + # {'id': {'S': 'Hello'}, 'cls': {'S': 'Bar'}, 'bar': {'S': 'World!'}} +.. note:: + + Read operations that are performed on a class that has a discriminator value are slightly modified to ensure that only instances of the class are returned. + Query and scan operations transparently add a filter condition to ensure that only items with a matching discriminator value are returned. + Get and batch get operations will raise a ``ValueError`` if the returned item(s) are not a subclass of the model being read. diff --git a/docs/release_notes.rst b/docs/release_notes.rst index 9112b4e..106e22b 100644 --- a/docs/release_notes.rst +++ b/docs/release_notes.rst @@ -1,7 +1,7 @@ Release Notes ============= -v5.0.0b1 +v5.0.0b2 ------------------- :date: 2020-xx-xx diff --git a/pynamodb/__init__.py b/pynamodb/__init__.py index 4439b51..fa730ba 100644 --- a/pynamodb/__init__.py +++ b/pynamodb/__init__.py @@ -7,4 +7,4 @@ A simple abstraction over DynamoDB """ __author__ = 'Jharrod LaFon' __license__ = 'MIT' -__version__ = '5.0.0b1' +__version__ = '5.0.0b2' diff --git a/pynamodb/attributes.py b/pynamodb/attributes.py index 30aab73..a2262a7 100644 --- a/pynamodb/attributes.py +++ b/pynamodb/attributes.py @@ -41,6 +41,7 @@ _T = TypeVar('_T') _KT = TypeVar('_KT', bound=str) _VT = TypeVar('_VT') _MT = TypeVar('_MT', bound='MapAttribute') +_ACT = TypeVar('_ACT', bound = 'AttributeContainer') _A = TypeVar('_A', bound='Attribute') @@ -259,9 +260,6 @@ class AttributeContainerMeta(GenericMeta): raise ValueError("{} has more than one discriminator attribute: {}".format( cls.__name__, ", ".join(discriminators))) cls._discriminator = discriminators[0] if discriminators else None - # TODO(jpinner) add support for model polymorphism - if cls._discriminator and not issubclass(cls, MapAttribute): - raise NotImplementedError("Discriminators are not yet supported in model classes.") if discriminator_value is not None: if not cls._discriminator: raise ValueError("{} does not have a discriminator attribute".format(cls.__name__)) @@ -372,6 +370,22 @@ class AttributeContainer(metaclass=AttributeContainerMeta): value = attr.deserialize(attr.get_value(attribute_value)) setattr(self, name, value) + @classmethod + def _instantiate(cls: Type[_ACT], attribute_values: Dict[str, Dict[str, Any]]) -> _ACT: + discriminator_attr = cls._get_discriminator_attribute() + if discriminator_attr: + discriminator_attribute_value = attribute_values.pop(discriminator_attr.attr_name, None) + if discriminator_attribute_value: + discriminator_value = discriminator_attr.get_value(discriminator_attribute_value) + stored_cls = discriminator_attr.deserialize(discriminator_value) + if not issubclass(stored_cls, cls): + raise ValueError("Cannot instantiate a {} from the returned class: {}".format( + cls.__name__, stored_cls.__name__)) + cls = stored_cls + instance = cls(_user_instantiated=False) + AttributeContainer.deserialize(instance, attribute_values) + return instance + def __eq__(self, other: Any) -> bool: # This is required so that MapAttribute can call this method. return self is other @@ -940,16 +954,7 @@ class MapAttribute(Attribute[Mapping[_KT, _VT]], AttributeContainer): """ if not self.is_raw(): # If this is a subclass of a MapAttribute (i.e typed), instantiate an instance - cls = type(self) - discriminator_attr = cls._get_discriminator_attribute() - if discriminator_attr: - discriminator_attribute_value = values.pop(discriminator_attr.attr_name, None) - if discriminator_attribute_value: - discriminator_value = discriminator_attr.get_value(discriminator_attribute_value) - cls = discriminator_attr.deserialize(discriminator_value) - instance = cls() - AttributeContainer.deserialize(instance, values) - return instance + return self._instantiate(values) return { k: DESERIALIZE_CLASS_MAP[attr_type].deserialize(attr_value) diff --git a/pynamodb/models.py b/pynamodb/models.py index 17a62c8..227a34d 100644 --- a/pynamodb/models.py +++ b/pynamodb/models.py @@ -5,9 +5,28 @@ import random import time import logging import warnings +import sys from inspect import getmembers -from typing import Any, Dict, Generic, Iterable, Iterator, List, Optional, Sequence, Mapping, Type, TypeVar, Text, \ - Tuple, Union, cast +from typing import Any +from typing import Dict +from typing import Generic +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Mapping +from typing import Optional +from typing import Sequence +from typing import Text +from typing import Tuple +from typing import Type +from typing import TypeVar +from typing import Union +from typing import cast + +if sys.version_info >= (3, 8): + from typing import Protocol +else: + from typing_extensions import Protocol from pynamodb.expressions.update import Action from pynamodb.exceptions import DoesNotExist, TableDoesNotExist, TableError, InvalidStateError, PutError @@ -151,7 +170,7 @@ class BatchWrite(Generic[_T]): unprocessed_items = data.get(UNPROCESSED_ITEMS, {}).get(self.model.Meta.table_name) -class MetaModel(AttributeContainerMeta): +class MetaProtocol(Protocol): table_name: str read_capacity_units: Optional[int] write_capacity_units: Optional[int] @@ -169,14 +188,17 @@ class MetaModel(AttributeContainerMeta): billing_mode: Optional[str] stream_view_type: Optional[str] + +class MetaModel(AttributeContainerMeta): """ Model meta class - - This class is just here so that index queries have nice syntax. - Model.index.query() """ - def __init__(self, name: str, bases: Any, attrs: Dict[str, Any]) -> None: - super().__init__(name, bases, attrs) + def __new__(cls, name, bases, namespace, discriminator=None): + # Defined so that the discriminator can be set in the class definition. + return super().__new__(cls, name, bases, namespace) + + def __init__(self, name, bases, namespace, discriminator=None) -> None: + super().__init__(name, bases, namespace, discriminator) cls = cast(Type['Model'], self) for attr_name, attribute in cls.get_attributes().items(): if attribute.is_hash_key: @@ -200,8 +222,8 @@ class MetaModel(AttributeContainerMeta): raise ValueError("{} has more than one TTL attribute: {}".format( cls.__name__, ", ".join(ttl_attr_names))) - if isinstance(attrs, dict): - for attr_name, attr_obj in attrs.items(): + if isinstance(namespace, dict): + for attr_name, attr_obj in namespace.items(): if attr_name == META_CLASS_NAME: if not hasattr(attr_obj, REGION): setattr(attr_obj, REGION, get_settings_value('region')) @@ -234,9 +256,9 @@ class MetaModel(AttributeContainerMeta): # create a custom Model.DoesNotExist derived from pynamodb.exceptions.DoesNotExist, # so that "except Model.DoesNotExist:" would not catch other models' exceptions - if 'DoesNotExist' not in attrs: + if 'DoesNotExist' not in namespace: exception_attrs = { - '__module__': attrs.get('__module__'), + '__module__': namespace.get('__module__'), '__qualname__': f'{cls.__qualname__}.{"DoesNotExist"}', } cls.DoesNotExist = type('DoesNotExist', (DoesNotExist, ), exception_attrs) @@ -260,7 +282,7 @@ class Model(AttributeContainer, metaclass=MetaModel): DoesNotExist: Type[DoesNotExist] = DoesNotExist _version_attribute_name: Optional[str] = None - Meta: MetaModel + Meta: MetaProtocol def __init__( self, @@ -520,9 +542,7 @@ class Model(AttributeContainer, metaclass=MetaModel): if data is None: raise ValueError("Received no data to construct object") - model = cls(_user_instantiated=False) - model.deserialize(data) - return model + return cls._instantiate(data) @classmethod def count( @@ -556,6 +576,11 @@ class Model(AttributeContainer, metaclass=MetaModel): else: hash_key = cls._serialize_keys(hash_key)[0] + # If this class has a discriminator value, filter the query to only return instances of this class. + discriminator_attr = cls._get_discriminator_attribute() + if discriminator_attr and discriminator_attr.get_discriminator(cls): + filter_condition &= discriminator_attr == cls + query_args = (hash_key,) query_kwargs = dict( range_key_condition=range_key_condition, @@ -616,6 +641,11 @@ class Model(AttributeContainer, metaclass=MetaModel): else: hash_key = cls._serialize_keys(hash_key)[0] + # If this class has a discriminator value, filter the query to only return instances of this class. + discriminator_attr = cls._get_discriminator_attribute() + if discriminator_attr and discriminator_attr.get_discriminator(cls): + filter_condition &= discriminator_attr == cls + if page_size is None: page_size = limit @@ -668,6 +698,11 @@ class Model(AttributeContainer, metaclass=MetaModel): :param rate_limit: If set then consumed capacity will be limited to this amount per second :param attributes_to_get: If set, specifies the properties to include in the projection expression """ + # If this class has a discriminator value, filter the scan to only return instances of this class. + discriminator_attr = cls._get_discriminator_attribute() + if discriminator_attr and discriminator_attr.get_discriminator(cls): + filter_condition &= discriminator_attr == cls + if page_size is None: page_size = limit diff --git a/setup.py b/setup.py index 27830e0..8686807 100644 --- a/setup.py +++ b/setup.py @@ -3,6 +3,7 @@ from setuptools import setup, find_packages install_requires = [ 'botocore>=1.12.54', + 'typing-extensions>=3.7; python_version<"3.8"' ] setup(
pynamodb/PynamoDB
5c8862e72556bf2329e72c1c282030f7648b50fa
diff --git a/tests/test_discriminator.py b/tests/test_discriminator.py index 4ed13e5..347a468 100644 --- a/tests/test_discriminator.py +++ b/tests/test_discriminator.py @@ -28,13 +28,18 @@ class RenamedValue(TypedValue, discriminator='custom_name'): value = UnicodeAttribute() -class DiscriminatorTestModel(Model): +class DiscriminatorTestModel(Model, discriminator='Parent'): class Meta: host = 'http://localhost:8000' table_name = 'test' hash_key = UnicodeAttribute(hash_key=True) value = TypedValue() values = ListAttribute(of=TypedValue) + type = DiscriminatorAttribute() + + +class ChildModel(DiscriminatorTestModel, discriminator='Child'): + value = UnicodeAttribute() class TestDiscriminatorAttribute: @@ -46,6 +51,7 @@ class TestDiscriminatorAttribute: dtm.values = [NumberValue(name='bar', value=5), RenamedValue(name='baz', value='World')] assert dtm.serialize() == { 'hash_key': {'S': 'foo'}, + 'type': {'S': 'Parent'}, 'value': {'M': {'cls': {'S': 'StringValue'}, 'name': {'S': 'foo'}, 'value': {'S': 'Hello'}}}, 'values': {'L': [ {'M': {'cls': {'S': 'NumberValue'}, 'name': {'S': 'bar'}, 'value': {'N': '5'}}}, @@ -56,6 +62,7 @@ class TestDiscriminatorAttribute: def test_deserialize(self): item = { 'hash_key': {'S': 'foo'}, + 'type': {'S': 'Parent'}, 'value': {'M': {'cls': {'S': 'StringValue'}, 'name': {'S': 'foo'}, 'value': {'S': 'Hello'}}}, 'values': {'L': [ {'M': {'cls': {'S': 'NumberValue'}, 'name': {'S': 'bar'}, 'value': {'N': '5'}}}, @@ -96,8 +103,28 @@ class TestDiscriminatorAttribute: class RenamedValue2(TypedValue, discriminator='custom_name'): pass - def test_model(self): - with pytest.raises(NotImplementedError): - class DiscriminatedModel(Model): - hash_key = UnicodeAttribute(hash_key=True) - _cls = DiscriminatorAttribute() +class TestDiscriminatorModel: + + def test_serialize(self): + cm = ChildModel() + cm.hash_key = 'foo' + cm.value = 'bar' + cm.values = [] + assert cm.serialize() == { + 'hash_key': {'S': 'foo'}, + 'type': {'S': 'Child'}, + 'value': {'S': 'bar'}, + 'values': {'L': []} + } + + def test_deserialize(self): + item = { + 'hash_key': {'S': 'foo'}, + 'type': {'S': 'Child'}, + 'value': {'S': 'bar'}, + 'values': {'L': []} + } + cm = DiscriminatorTestModel.from_raw_data(item) + assert isinstance(cm, ChildModel) + assert cm.hash_key == 'foo' + assert cm.value == 'bar' diff --git a/tests/test_model.py b/tests/test_model.py index 680ebd5..10d1584 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -25,7 +25,7 @@ from pynamodb.indexes import ( IncludeProjection, KeysOnlyProjection, Index ) from pynamodb.attributes import ( - UnicodeAttribute, NumberAttribute, BinaryAttribute, UTCDateTimeAttribute, + DiscriminatorAttribute, UnicodeAttribute, NumberAttribute, BinaryAttribute, UTCDateTimeAttribute, UnicodeSetAttribute, NumberSetAttribute, BinarySetAttribute, MapAttribute, BooleanAttribute, ListAttribute, TTLAttribute, VersionAttribute) from .data import ( @@ -1543,6 +1543,69 @@ class ModelTestCase(TestCase): self.assertEqual(params, req.call_args[0][1]) self.assertTrue(len(queried) == len(items)) + def test_query_with_discriminator(self): + class ParentModel(Model): + class Meta: + table_name = 'polymorphic_table' + id = UnicodeAttribute(hash_key=True) + cls = DiscriminatorAttribute() + + class ChildModel(ParentModel, discriminator='Child'): + foo = UnicodeAttribute() + + with patch(PATCH_METHOD) as req: + req.return_value = { + "Table": { + "AttributeDefinitions": [ + { + "AttributeName": "id", + "AttributeType": "S" + } + ], + "CreationDateTime": 1.363729002358E9, + "ItemCount": 0, + "KeySchema": [ + { + "AttributeName": "id", + "KeyType": "HASH" + } + ], + "ProvisionedThroughput": { + "NumberOfDecreasesToday": 0, + "ReadCapacityUnits": 5, + "WriteCapacityUnits": 5 + }, + "TableName": "polymorphic_table", + "TableSizeBytes": 0, + "TableStatus": "ACTIVE" + } + } + ChildModel('hi', foo='there').save() + + with patch(PATCH_METHOD) as req: + req.return_value = {'Count': 0, 'ScannedCount': 0, 'Items': []} + for item in ChildModel.query('foo'): + pass + params = { + 'KeyConditionExpression': '#0 = :0', + 'FilterExpression': '#1 = :1', + 'ExpressionAttributeNames': { + '#0': 'id', + '#1': 'cls' + }, + 'ExpressionAttributeValues': { + ':0': { + 'S': u'foo' + }, + ':1': { + 'S': u'Child' + } + }, + 'ReturnConsumedCapacity': 'TOTAL', + 'TableName': 'polymorphic_table' + } + self.assertEqual(params, req.call_args[0][1]) + def test_scan_limit_with_page_size(self): with patch(PATCH_METHOD) as req: items = []
Polymorphism? Can dynamodb and pynamodb do polymorphism? I have searched can't find any example class BaseModel(Model): class meta: table_name = "BaseTable" ... id = UnicodeAttribute(hash_key=True) type = UnicodeAttribute(range_key=True) class Child1Model(BaseModel): id = UnicodeAttribute(hash_key=True) type = UnicodeAttribute(range_key=True) child1data..... class Child2Model(BaseModel): id = UnicodeAttribute(hash_key=True) type = UnicodeAttribute(range_key=True) child2data.... I tried it wouldn't let me do this. even if I added class meta, i am not sure how it would work. any idea? thanks.
0.0
5c8862e72556bf2329e72c1c282030f7648b50fa
[ "tests/test_discriminator.py::TestDiscriminatorAttribute::test_serialize", "tests/test_discriminator.py::TestDiscriminatorAttribute::test_deserialize", "tests/test_discriminator.py::TestDiscriminatorAttribute::test_condition_expression", "tests/test_discriminator.py::TestDiscriminatorAttribute::test_multiple_discriminator_values", "tests/test_discriminator.py::TestDiscriminatorAttribute::test_multiple_discriminator_classes", "tests/test_discriminator.py::TestDiscriminatorModel::test_serialize", "tests/test_discriminator.py::TestDiscriminatorModel::test_deserialize", "tests/test_model.py::ModelTestCase::test_batch_get", "tests/test_model.py::ModelTestCase::test_batch_write", "tests/test_model.py::ModelTestCase::test_batch_write_raises_put_error", "tests/test_model.py::ModelTestCase::test_batch_write_with_unprocessed", "tests/test_model.py::ModelTestCase::test_boolean_serializes_as_bool", "tests/test_model.py::ModelTestCase::test_car_model_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_car_model_with_null_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_complex_key", "tests/test_model.py::ModelTestCase::test_complex_model_is_complex", "tests/test_model.py::ModelTestCase::test_complex_model_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_count", "tests/test_model.py::ModelTestCase::test_count_no_hash_key", "tests/test_model.py::ModelTestCase::test_create_model", "tests/test_model.py::ModelTestCase::test_delete", "tests/test_model.py::ModelTestCase::test_delete_doesnt_do_validation_on_null_attributes", "tests/test_model.py::ModelTestCase::test_deserializing_bool_false_works", "tests/test_model.py::ModelTestCase::test_deserializing_map_four_layers_deep_works", "tests/test_model.py::ModelTestCase::test_deserializing_new_style_bool_true_works", "tests/test_model.py::ModelTestCase::test_explicit_raw_map_serialize_pass", "tests/test_model.py::ModelTestCase::test_filter_count", "tests/test_model.py::ModelTestCase::test_get", "tests/test_model.py::ModelTestCase::test_global_index", "tests/test_model.py::ModelTestCase::test_index_count", "tests/test_model.py::ModelTestCase::test_index_multipage_count", "tests/test_model.py::ModelTestCase::test_index_queries", "tests/test_model.py::ModelTestCase::test_invalid_car_model_with_null_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_invalid_map_model_raises", "tests/test_model.py::ModelTestCase::test_list_of_map_works_like_list_of_map", "tests/test_model.py::ModelTestCase::test_list_works_like_list", "tests/test_model.py::ModelTestCase::test_local_index", "tests/test_model.py::ModelTestCase::test_model_attrs", "tests/test_model.py::ModelTestCase::test_model_subclass_attributes_inherited_on_create", "tests/test_model.py::ModelTestCase::test_model_version_attribute_save", "tests/test_model.py::ModelTestCase::test_model_with_invalid_data_does_not_validate", "tests/test_model.py::ModelTestCase::test_model_with_list", "tests/test_model.py::ModelTestCase::test_model_with_list_of_map", "tests/test_model.py::ModelTestCase::test_model_with_list_of_map_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_model_with_list_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_model_with_maps", "tests/test_model.py::ModelTestCase::test_model_with_maps_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_model_with_maps_with_nulls_retrieve_from_db", "tests/test_model.py::ModelTestCase::test_model_with_maps_with_snake_to_camel_case_attributes", "tests/test_model.py::ModelTestCase::test_model_with_nulls_validates", "tests/test_model.py::ModelTestCase::test_model_works_like_model", "tests/test_model.py::ModelTestCase::test_multiple_indices_share_non_key_attribute", "tests/test_model.py::ModelTestCase::test_no_table_name_exception", "tests/test_model.py::ModelTestCase::test_old_style_model_exception", "tests/test_model.py::ModelTestCase::test_overidden_defaults", "tests/test_model.py::ModelTestCase::test_overridden_attr_name", "tests/test_model.py::ModelTestCase::test_projections", "tests/test_model.py::ModelTestCase::test_query", "tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_and_page_size", "tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_multiple_page", "tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_single_page", "tests/test_model.py::ModelTestCase::test_query_limit_identical_to_available_items_single_page", "tests/test_model.py::ModelTestCase::test_query_limit_less_than_available_and_page_size", "tests/test_model.py::ModelTestCase::test_query_limit_less_than_available_items_multiple_page", "tests/test_model.py::ModelTestCase::test_query_with_discriminator", "tests/test_model.py::ModelTestCase::test_query_with_exclusive_start_key", "tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map", "tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_deserialize", "tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_from_raw_data_works", "tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_serialize_pass", "tests/test_model.py::ModelTestCase::test_raw_map_deserializes", "tests/test_model.py::ModelTestCase::test_raw_map_from_raw_data_works", "tests/test_model.py::ModelTestCase::test_raw_map_serialize_fun_one", "tests/test_model.py::ModelTestCase::test_refresh", "tests/test_model.py::ModelTestCase::test_save", "tests/test_model.py::ModelTestCase::test_scan", "tests/test_model.py::ModelTestCase::test_scan_limit", "tests/test_model.py::ModelTestCase::test_scan_limit_with_page_size", "tests/test_model.py::ModelTestCase::test_update", "tests/test_model.py::ModelTestCase::test_version_attribute_increments_on_update", "tests/test_model.py::ModelInitTestCase::test_connection_inheritance", "tests/test_model.py::ModelInitTestCase::test_deserialized", "tests/test_model.py::ModelInitTestCase::test_deserialized_with_invalid_type", "tests/test_model.py::ModelInitTestCase::test_deserialized_with_ttl", "tests/test_model.py::ModelInitTestCase::test_get_ttl_attribute", "tests/test_model.py::ModelInitTestCase::test_get_ttl_attribute_fails", "tests/test_model.py::ModelInitTestCase::test_inherit_metaclass", "tests/test_model.py::ModelInitTestCase::test_multiple_hash_keys", "tests/test_model.py::ModelInitTestCase::test_multiple_range_keys", "tests/test_model.py::ModelInitTestCase::test_multiple_ttl_attributes", "tests/test_model.py::ModelInitTestCase::test_multiple_version_attributes", "tests/test_model.py::ModelInitTestCase::test_raw_map_attribute_with_dict_init", "tests/test_model.py::ModelInitTestCase::test_raw_map_attribute_with_initialized_instance_init", "tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_dict_init", "tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_initialized_instance_init", "tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_map_attribute_member_with_initialized_instance_init", "tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_map_attributes_member_with_dict_init" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-09 02:57:28+00:00
mit
4,952
pyout__pyout-40
diff --git a/pyout/elements.py b/pyout/elements.py index 160a1f8..700f53d 100644 --- a/pyout/elements.py +++ b/pyout/elements.py @@ -28,6 +28,12 @@ schema = { {"$ref": "#/definitions/interval"}], "default": "black", "scope": "field"}, + "missing": { + "description": "Text to display for missing values", + "type": "string", + "default": "", + "scope": "column" + }, "underline": { "description": "Whether text is underlined", "oneOf": [{"type": "boolean"}, @@ -52,6 +58,7 @@ schema = { "properties": {"align": {"$ref": "#/definitions/align"}, "bold": {"$ref": "#/definitions/bold"}, "color": {"$ref": "#/definitions/color"}, + "missing": {"$ref": "#/definitions/missing"}, "transform": {"$ref": "#/definitions/transform"}, "underline": {"$ref": "#/definitions/underline"}, "width": {"$ref": "#/definitions/width"}}, diff --git a/pyout/field.py b/pyout/field.py index 9dee4fc..bb20027 100644 --- a/pyout/field.py +++ b/pyout/field.py @@ -145,6 +145,42 @@ class Field(object): return result +class Nothing(object): + """Internal class to represent missing values. + + This is used instead of a built-ins like None, "", or 0 to allow + us to unambiguously identify a missing value. In terms of + methods, it tries to mimic the string `text` (an empty string by + default) because that behavior is the most useful internally for + formatting the output. + + Parameters + ---------- + text : str, optional + Text to use for string representation of this object. + """ + + def __init__(self, text=""): + self._text = text + + def __str__(self): + return self._text + + def __add__(self, right): + return str(self) + right + + def __radd__(self, left): + return left + str(self) + + def __bool__(self): + return False + + __nonzero__ = __bool__ # py2 + + def __format__(self, format_spec): + return str.__format__(self._text, format_spec) + + class StyleFunctionError(Exception): """Signal that a style function failed. """ @@ -224,6 +260,8 @@ class StyleProcessors(object): """Return a processor for a style's "transform" function. """ def transform_fn(_, result): + if isinstance(result, Nothing): + return result try: return function(result) except: @@ -292,7 +330,11 @@ class StyleProcessors(object): A function. """ def by_interval_lookup_fn(value, result): - value = float(value) + try: + value = float(value) + except TypeError: + return result + for start, end, lookup_value in intervals: if start is None: start = float("-inf") diff --git a/pyout/tabular.py b/pyout/tabular.py index a63713f..ec16773 100644 --- a/pyout/tabular.py +++ b/pyout/tabular.py @@ -13,7 +13,9 @@ from multiprocessing.dummy import Pool from blessings import Terminal from pyout import elements -from pyout.field import Field, StyleProcessors +from pyout.field import Field, StyleProcessors, Nothing + +NOTHING = Nothing() class TermProcessors(StyleProcessors): @@ -133,7 +135,7 @@ class Tabular(object): self._init_style = style self._style = None - + self._nothings = {} # column => missing value self._autowidth_columns = {} if columns is not None: @@ -171,6 +173,12 @@ class Tabular(object): elements.validate(self._style) + for col in self._columns: + if "missing" in self._style[col]: + self._nothings[col] = Nothing(self._style[col]["missing"]) + else: + self._nothings[col] = NOTHING + def _setup_fields(self): self._fields = {} for column in self._columns: @@ -181,7 +189,7 @@ class Tabular(object): is_auto = style_width == "auto" or _safe_get(style_width, "auto") if is_auto: - width = _safe_get(style_width, "min", 1) + width = _safe_get(style_width, "min", 0) wmax = _safe_get(style_width, "max") self._autowidth_columns[column] = {"max": wmax} @@ -234,7 +242,7 @@ class Tabular(object): return dict(zip(self._columns, row)) def _attrs_to_dict(self, row): - return {c: getattr(row, c) for c in self._columns} + return {c: getattr(row, c, self._nothings[c]) for c in self._columns} def _choose_normalizer(self, row): if isinstance(row, Mapping): @@ -416,7 +424,7 @@ class Tabular(object): if isinstance(value, tuple): initial, fn = value else: - initial = "" + initial = NOTHING # Value could be a normal (non-callable) value or a # callable with no initial value. fn = value @@ -526,6 +534,16 @@ class Tabular(object): row = self._normalizer(row) callables = self._strip_callables(row) + # Fill in any missing values. Note: If the un-normalized data is an + # object, we already handle this in its normalizer, _attrs_to_dict. + # When the data is given as a dict, we do it here instead of its + # normalizer because there may be multi-column tuple keys. + if self._normalizer == self._identity: + for column in self._columns: + if column in row: + continue + row[column] = self._nothings[column] + with self._write_lock(): if not self._rows: self._maybe_write_header()
pyout/pyout
558c1fc9b760146b5a9b794f7a8c8dab2b378863
diff --git a/pyout/tests/test_field.py b/pyout/tests/test_field.py index 2a36ff1..0c1f9fa 100644 --- a/pyout/tests/test_field.py +++ b/pyout/tests/test_field.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import pytest -from pyout.field import Field, StyleProcessors +from pyout.field import Field, Nothing, StyleProcessors def test_field_base(): @@ -37,6 +37,17 @@ def test_field_processors(): field.add("pre", "not registered key") [email protected]("text", ["", "-"], ids=["text=''", "text='-'"]) +def test_something_about_nothing(text): + nada = Nothing(text=text) + assert not nada + + assert str(nada) == text + assert "{:5}".format(nada) == "{:5}".format(text) + assert "x" + nada == "x" + text + assert nada + "x" == text + "x" + + def test_truncate_mark_true(): fn = StyleProcessors.truncate(7, marker=True) diff --git a/pyout/tests/test_tabular.py b/pyout/tests/test_tabular.py index d695b83..1964f88 100644 --- a/pyout/tests/test_tabular.py +++ b/pyout/tests/test_tabular.py @@ -51,6 +51,48 @@ def test_tabular_write_color(): assert eq_repr(fd.getvalue(), expected) +@patch("pyout.tabular.Terminal", TestTerminal) +def test_tabular_write_empty_string(): + fd = StringIO() + out = Tabular(stream=fd) + out({"name": ""}) + assert eq_repr(fd.getvalue(), "\n") + + +@patch("pyout.tabular.Terminal", TestTerminal) +def test_tabular_write_missing_column(): + fd = StringIO() + out = Tabular(columns=["name", "status"], stream=fd) + out({"name": "solo"}) + assert eq_repr(fd.getvalue(), "solo \n") + + +@patch("pyout.tabular.Terminal", TestTerminal) +def test_tabular_write_missing_column_missing_text(): + fd = StringIO() + out = Tabular(columns=["name", "status"], + style={"status": + {"missing": "-"}}, + stream=fd) + out({"name": "solo"}) + assert eq_repr(fd.getvalue(), "solo -\n") + + +@patch("pyout.tabular.Terminal", TestTerminal) +def test_tabular_write_missing_column_missing_object_data(): + class Data(object): + name = "solo" + data = Data() + + fd = StringIO() + out = Tabular(columns=["name", "status"], + style={"status": + {"missing": "-"}}, + stream=fd) + out(data) + assert eq_repr(fd.getvalue(), "solo -\n") + + @patch("pyout.tabular.Terminal", TestTerminal) def test_tabular_write_columns_from_orderdict_row(): fd = StringIO() @@ -601,6 +643,27 @@ def test_tabular_write_intervals_bold(): assert eq_repr(fd.getvalue(), expected) + +@patch("pyout.tabular.Terminal", TestTerminal) +def test_tabular_write_intervals_missing(): + fd = StringIO() + out = Tabular(style={"name": {"width": 3}, + "percent": {"bold": {"interval": + [[30, 50, False], + [50, 80, True]]}, + "width": 2}}, + stream=fd, force_styling=True) + out(OrderedDict([("name", "foo"), + ("percent", 78)])) + # Interval lookup function can handle a missing value. + out(OrderedDict([("name", "bar")])) + + expected = "foo " + unicode_cap("bold") + \ + "78" + unicode_cap("sgr0") + "\n" + \ + "bar \n" + assert eq_repr(fd.getvalue(), expected) + + @patch("pyout.tabular.Terminal", TestTerminal) def test_tabular_write_transform(): fd = StringIO() @@ -888,6 +951,26 @@ def test_tabular_write_callable_values(): assert len([ln for ln in lines if ln.endswith("baz over ")]) == 1 [email protected](10) +@patch("pyout.tabular.Terminal", TestTerminal) +def test_tabular_write_callable_transform_nothing(): + delay0 = Delayed(3) + + fd = StringIO() + out = Tabular(["name", "status"], + style={"status": {"transform": lambda n: n + 2}}, + stream=fd) + with out: + # The unspecified initial value is set to Nothing(). The + # transform function above, which is designed to take a + # number, won't be called with it. + out({"name": "foo", "status": delay0.run}) + assert eq_repr(fd.getvalue(), "foo \n") + delay0.now = True + lines = fd.getvalue().splitlines() + assert len([ln for ln in lines if ln.endswith("foo 5")]) == 1 + + @pytest.mark.timeout(10) @patch("pyout.tabular.Terminal", TestTerminal) def test_tabular_write_callable_values_multi_return():
Allow for incomplete records So it must not crash -- instead it should place some "default" or specified "absent" value (e.g. `""` or `"-"`) Those values which were not provided should not be passed into the summary callables??? we might just provide `exclude_absent` decorator for summary transformers
0.0
558c1fc9b760146b5a9b794f7a8c8dab2b378863
[ "pyout/tests/test_field.py::test_field_base", "pyout/tests/test_field.py::test_field_update", "pyout/tests/test_field.py::test_field_processors", "pyout/tests/test_field.py::test_something_about_nothing[text='']", "pyout/tests/test_field.py::test_something_about_nothing[text='-']", "pyout/tests/test_field.py::test_truncate_mark_true", "pyout/tests/test_field.py::test_truncate_mark_string", "pyout/tests/test_field.py::test_truncate_mark_short", "pyout/tests/test_field.py::test_truncate_nomark", "pyout/tests/test_field.py::test_style_value_type", "pyout/tests/test_field.py::test_style_processor_translate", "pyout/tests/test_tabular.py::test_tabular_write_color", "pyout/tests/test_tabular.py::test_tabular_write_empty_string", "pyout/tests/test_tabular.py::test_tabular_write_missing_column", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_text", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_object_data", "pyout/tests/test_tabular.py::test_tabular_write_columns_from_orderdict_row", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[sequence]", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[dict]", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list", "pyout/tests/test_tabular.py::test_tabular_write_header", "pyout/tests/test_tabular.py::test_tabular_write_data_as_object", "pyout/tests/test_tabular.py::test_tabular_write_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_header_with_style", "pyout/tests/test_tabular.py::test_tabular_nondefault_separator", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list_no_columns", "pyout/tests/test_tabular.py::test_tabular_write_style_override", "pyout/tests/test_tabular.py::test_tabular_default_style", "pyout/tests/test_tabular.py::test_tabular_write_multicolor", "pyout/tests/test_tabular.py::test_tabular_write_align", "pyout/tests/test_tabular.py::test_tabular_rewrite", "pyout/tests/test_tabular.py::test_tabular_rewrite_notfound", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_id", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_value", "pyout/tests/test_tabular.py::test_tabular_rewrite_with_ids_property", "pyout/tests/test_tabular.py::test_tabular_rewrite_auto_width", "pyout/tests/test_tabular.py::test_tabular_rewrite_data_as_list", "pyout/tests/test_tabular.py::test_tabular_repaint", "pyout/tests/test_tabular.py::test_tabular_repaint_with_header", "pyout/tests/test_tabular.py::test_tabular_write_label_color", "pyout/tests/test_tabular.py::test_tabular_write_label_bold", "pyout/tests/test_tabular.py::test_tabular_write_label_bold_false", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_open_ended", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_outside_intervals", "pyout/tests/test_tabular.py::test_tabular_write_intervals_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_missing", "pyout/tests/test_tabular.py::test_tabular_write_transform", "pyout/tests/test_tabular.py::test_tabular_write_transform_with_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_transform_on_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_func_error", "pyout/tests/test_tabular.py::test_tabular_write_width_truncate_long", "pyout/tests/test_tabular.py::test_tabular_write_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=True]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=False]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=\\u2026]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_auto_false_exception", "pyout/tests/test_tabular.py::test_tabular_write_callable_values", "pyout/tests/test_tabular.py::test_tabular_write_callable_transform_nothing", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multi_return", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=tuple]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=dict]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[gen_func]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[generator]", "pyout/tests/test_tabular.py::test_tabular_write_generator_values_multireturn", "pyout/tests/test_tabular.py::test_tabular_write_wait_noop_if_nothreads" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-02-09 22:16:40+00:00
mit
4,953
pyout__pyout-48
diff --git a/CHANGELOG.md b/CHANGELOG.md index 58115f6..1942ecc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,8 @@ TODO Summary The only associated user-facing change is the rename of `pyout.SCHEMA` to `pyout.schema`. +- The style attribute "label" has been renamed to "lookup". + ### Deprecated ### Fixed ### Removed diff --git a/pyout/elements.py b/pyout/elements.py index 700f53d..d88c4b8 100644 --- a/pyout/elements.py +++ b/pyout/elements.py @@ -15,7 +15,7 @@ schema = { "bold": { "description": "Whether text is bold", "oneOf": [{"type": "boolean"}, - {"$ref": "#/definitions/label"}, + {"$ref": "#/definitions/lookup"}, {"$ref": "#/definitions/interval"}], "default": False, "scope": "field"}, @@ -24,7 +24,7 @@ schema = { "oneOf": [{"type": "string", "enum": ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"]}, - {"$ref": "#/definitions/label"}, + {"$ref": "#/definitions/lookup"}, {"$ref": "#/definitions/interval"}], "default": "black", "scope": "field"}, @@ -37,7 +37,7 @@ schema = { "underline": { "description": "Whether text is underlined", "oneOf": [{"type": "boolean"}, - {"$ref": "#/definitions/label"}, + {"$ref": "#/definitions/lookup"}, {"$ref": "#/definitions/interval"}], "default": False, "scope": "field"}, @@ -76,10 +76,10 @@ schema = { {"type": ["string", "boolean"]}], "additionalItems": False}]}}, "additionalProperties": False}, - "label": { + "lookup": { "description": "Map a value to a style", "type": "object", - "properties": {"label": {"type": "object"}}, + "properties": {"lookup": {"type": "object"}}, "additionalProperties": False}, "transform": { "description": """An arbitrary function. diff --git a/pyout/field.py b/pyout/field.py index 3b0664c..12cc4a7 100644 --- a/pyout/field.py +++ b/pyout/field.py @@ -360,13 +360,13 @@ class StyleProcessors(object): Returns ------- - str, {"simple", "label", "interval"} + str, {"simple", "lookup", "interval"} """ try: keys = list(value.keys()) except AttributeError: return "simple" - if keys in [["label"], ["interval"]]: + if keys in [["lookup"], ["interval"]]: return keys[0] raise ValueError("Type of `value` could not be determined") @@ -412,7 +412,7 @@ class StyleProcessors(object): yield self.by_key(key) elif key_type is str: yield self.by_key(column_style[key]) - elif vtype == "label": + elif vtype == "lookup": yield self.by_lookup(column_style[key][vtype], attr_key) elif vtype == "interval": yield self.by_interval_lookup(column_style[key][vtype],
pyout/pyout
9b85940318d2b583a2e7f4bc1fd8474d08aab679
diff --git a/pyout/tests/test_field.py b/pyout/tests/test_field.py index 0c1f9fa..b4d72a1 100644 --- a/pyout/tests/test_field.py +++ b/pyout/tests/test_field.py @@ -82,7 +82,7 @@ def test_style_value_type(): assert fn(True) == "simple" assert fn("red") == "simple" - assert fn({"label": {"BAD": "red"}}) == "label" + assert fn({"lookup": {"BAD": "red"}}) == "lookup" interval = {"interval": [(0, 50, "red"), (50, 80, "yellow")]} assert fn(interval) == "interval" diff --git a/pyout/tests/test_tabular.py b/pyout/tests/test_tabular.py index 49affe1..aa342e8 100644 --- a/pyout/tests/test_tabular.py +++ b/pyout/tests/test_tabular.py @@ -517,10 +517,10 @@ def test_tabular_repaint_with_header(): @patch("pyout.tabular.Terminal", TestTerminal) -def test_tabular_write_label_color(): +def test_tabular_write_lookup_color(): fd = StringIO() out = Tabular(style={"name": {"width": 3}, - "status": {"color": {"label": {"BAD": "red"}}, + "status": {"color": {"lookup": {"BAD": "red"}}, "width": 6}}, stream=fd, force_styling=True) out(OrderedDict([("name", "foo"), @@ -535,10 +535,10 @@ def test_tabular_write_label_color(): @patch("pyout.tabular.Terminal", TestTerminal) -def test_tabular_write_label_bold(): +def test_tabular_write_lookup_bold(): fd = StringIO() out = Tabular(style={"name": {"width": 3}, - "status": {"bold": {"label": {"BAD": True}}, + "status": {"bold": {"lookup": {"BAD": True}}, "width": 6}}, stream=fd, force_styling=True) out(OrderedDict([("name", "foo"), @@ -553,10 +553,10 @@ def test_tabular_write_label_bold(): @patch("pyout.tabular.Terminal", TestTerminal) -def test_tabular_write_label_bold_false(): +def test_tabular_write_lookup_bold_false(): fd = StringIO() out = Tabular(style={"name": {"width": 3}, - "status": {"bold": {"label": {"BAD": False}}, + "status": {"bold": {"lookup": {"BAD": False}}, "width": 6}}, stream=fd, force_styling=True) out(OrderedDict([("name", "foo"), @@ -570,9 +570,9 @@ def test_tabular_write_label_bold_false(): @patch("pyout.tabular.Terminal", TestTerminal) -def test_tabular_write_label_non_hashable(): +def test_tabular_write_lookup_non_hashable(): fd = StringIO() - out = Tabular(style={"status": {"color": {"label": {"BAD": "red"}}}}, + out = Tabular(style={"status": {"color": {"lookup": {"BAD": "red"}}}}, stream=fd) out(OrderedDict([("status", [0, 1])])) expected = ("[0, 1]\n")
"label" -> "enum" or alike? Although originally `enum` is for enumerating and in our case to assign arbitrary style values, I feel that it might be a better fit instead of a `label`. just an idea, feel free to close
0.0
9b85940318d2b583a2e7f4bc1fd8474d08aab679
[ "pyout/tests/test_field.py::test_style_value_type", "pyout/tests/test_tabular.py::test_tabular_write_lookup_color", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold_false", "pyout/tests/test_tabular.py::test_tabular_write_lookup_non_hashable" ]
[ "pyout/tests/test_field.py::test_field_base", "pyout/tests/test_field.py::test_field_update", "pyout/tests/test_field.py::test_field_processors", "pyout/tests/test_field.py::test_something_about_nothing[text='']", "pyout/tests/test_field.py::test_something_about_nothing[text='-']", "pyout/tests/test_field.py::test_truncate_mark_true", "pyout/tests/test_field.py::test_truncate_mark_string", "pyout/tests/test_field.py::test_truncate_mark_short", "pyout/tests/test_field.py::test_truncate_nomark", "pyout/tests/test_field.py::test_style_processor_translate", "pyout/tests/test_tabular.py::test_tabular_write_color", "pyout/tests/test_tabular.py::test_tabular_write_empty_string", "pyout/tests/test_tabular.py::test_tabular_write_missing_column", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_text", "pyout/tests/test_tabular.py::test_tabular_write_list_value", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_object_data", "pyout/tests/test_tabular.py::test_tabular_write_columns_from_orderdict_row", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[sequence]", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[dict]", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list", "pyout/tests/test_tabular.py::test_tabular_write_header", "pyout/tests/test_tabular.py::test_tabular_write_data_as_object", "pyout/tests/test_tabular.py::test_tabular_write_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_header_with_style", "pyout/tests/test_tabular.py::test_tabular_nondefault_separator", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list_no_columns", "pyout/tests/test_tabular.py::test_tabular_write_style_override", "pyout/tests/test_tabular.py::test_tabular_default_style", "pyout/tests/test_tabular.py::test_tabular_write_multicolor", "pyout/tests/test_tabular.py::test_tabular_write_align", "pyout/tests/test_tabular.py::test_tabular_rewrite", "pyout/tests/test_tabular.py::test_tabular_rewrite_notfound", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_id", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_value", "pyout/tests/test_tabular.py::test_tabular_rewrite_with_ids_property", "pyout/tests/test_tabular.py::test_tabular_rewrite_auto_width", "pyout/tests/test_tabular.py::test_tabular_rewrite_data_as_list", "pyout/tests/test_tabular.py::test_tabular_repaint", "pyout/tests/test_tabular.py::test_tabular_repaint_with_header", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_open_ended", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_outside_intervals", "pyout/tests/test_tabular.py::test_tabular_write_intervals_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_missing", "pyout/tests/test_tabular.py::test_tabular_write_transform", "pyout/tests/test_tabular.py::test_tabular_write_transform_with_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_transform_on_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_func_error", "pyout/tests/test_tabular.py::test_tabular_write_width_truncate_long", "pyout/tests/test_tabular.py::test_tabular_write_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=True]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=False]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=\\u2026]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_auto_false_exception", "pyout/tests/test_tabular.py::test_tabular_write_callable_values", "pyout/tests/test_tabular.py::test_tabular_write_callable_transform_nothing", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multi_return", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=tuple]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=dict]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[gen_func]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[generator]", "pyout/tests/test_tabular.py::test_tabular_write_generator_values_multireturn", "pyout/tests/test_tabular.py::test_tabular_write_wait_noop_if_nothreads" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-02-11 16:40:57+00:00
mit
4,954
pyout__pyout-72
diff --git a/CHANGELOG.md b/CHANGELOG.md index f7307f7..bd4a517 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Fixed +- The output was corrupted when a callback function tried to update a + line that was no longer visible on the screen. + - When a table did not include a summary, "incremental" and "final" mode added "None" as the last row. diff --git a/pyout/interface.py b/pyout/interface.py index d40097c..71d8687 100644 --- a/pyout/interface.py +++ b/pyout/interface.py @@ -30,6 +30,9 @@ class Stream(object): def width(self): """Maximum line width. """ + @abc.abstractproperty + def height(self): + """Maximum number of rows that are visible.""" @abc.abstractmethod def write(self, text): @@ -190,12 +193,34 @@ class Writer(object): # possible for the summary lines to shrink. lgr.debug("Clearing summary") self._stream.clear_last_lines(last_summary_len) + else: + last_summary_len = 0 + content, status, summary = self._content.update(row, style) + + single_row_updated = False if isinstance(status, int): - lgr.debug("Overwriting line %d with %r", status, row) - self._stream.overwrite_line(self._last_content_len - status, - content) - else: + height = self._stream.height + if height is None: # non-tty + n_visible = self._last_content_len + else: + n_visible = min( + height - last_summary_len - 1, # -1 for current line. + self._last_content_len) + + n_back = self._last_content_len - status + if n_back > n_visible: + lgr.debug("Cannot move back %d rows for update; " + "only %d visible rows", + n_back, n_visible) + status = "repaint" + content = six.text_type(self._content) + else: + lgr.debug("Overwriting line %d with %r", status, row) + self._stream.overwrite_line(n_back, content) + single_row_updated = True + + if not single_row_updated: if status == "repaint": lgr.debug("Repainting the whole thing. Blame row %r", row) self._stream.move_to(self._last_content_len) diff --git a/pyout/tabular.py b/pyout/tabular.py index f5068f2..52cf315 100644 --- a/pyout/tabular.py +++ b/pyout/tabular.py @@ -24,6 +24,7 @@ class TerminalStream(interface.Stream): def __init__(self): self.term = Terminal() + self._height = self.term.height @property def width(self): @@ -31,6 +32,12 @@ class TerminalStream(interface.Stream): """ return self.term.width + @property + def height(self): + """Terminal height. + """ + return self._height + def write(self, text): """Write `text` to terminal. """
pyout/pyout
7e6097dd505e1d57be47bc4ec723ccdc1623047f
diff --git a/pyout/tests/test_tabular.py b/pyout/tests/test_tabular.py index 8a4d172..8664f0f 100644 --- a/pyout/tests/test_tabular.py +++ b/pyout/tests/test_tabular.py @@ -37,14 +37,36 @@ class Terminal(blessings.Terminal): def width(self): return 100 + @property + def height(self): + return 20 + + +class TerminalNonInteractive(Terminal): + + @property + def width(self): + return None + + @property + def height(self): + return None + class Tabular(TheRealTabular): """Test-specific subclass of pyout.Tabular. """ def __init__(self, *args, **kwargs): - with patch("pyout.interface.sys.stdout.isatty", return_value=True): - with patch("pyout.tabular.Terminal", Terminal): + interactive = kwargs.pop("interactive", True) + if interactive: + term = Terminal + else: + term = TerminalNonInteractive + + with patch("pyout.interface.sys.stdout.isatty", + return_value=interactive): + with patch("pyout.tabular.Terminal", term): super(Tabular, self).__init__(*args, **kwargs) @property @@ -894,6 +916,53 @@ def test_tabular_write_callable_values_multi_return(): assert_contains_nc(lines, "foo done /tmp/a") [email protected](10) [email protected]("nrows", [20, 21]) [email protected]("interactive", [True, False]) +def test_tabular_callback_to_hidden_row(nrows, interactive): + if sys.version_info < (3,): + try: + import jsonschema + except ImportError: + pass + else: + # Ideally we'd also check if the tests are running under + # coverage, but I don't know a way to do that. + pytest.xfail( + "Hangs for unknown reason in py2/coverage/jsonschema run") + + delay = Delayed("OK") + out = Tabular(interactive=interactive, + style={"status": {"aggregate": len}}) + # Make sure we're in update mode even for interactive=False. + out.mode = "update" + with out: + for i in range(1, nrows + 1): + status = delay.run if i == 3 else "s{:02d}".format(i) + out(OrderedDict([("name", "foo{:02d}".format(i)), + ("status", status)])) + delay.now = True + + lines = out.stdout.splitlines() + # The test terminal height is 20. The summary line takes up one + # line and the current line takes up another, so we have 18 + # available rows. Row 3 goes off the screen when we have 21 rows. + + if nrows > 20 and interactive: + # No leading escape codes because it was part of a whole repaint. + nexpected_plain = 1 + nexpected_updated = 0 + else: + nexpected_plain = 0 + nexpected_updated = 1 + + assert len([l for l in lines if l == "foo03 OK "]) == nexpected_plain + + cuu1 = unicode_cap("cuu1") + updated = [l for l in lines if l.startswith(cuu1) and "foo03 OK " in l] + assert len(updated) == nexpected_updated + + @pytest.mark.timeout(10) @pytest.mark.parametrize("result", [{"status": "done", "path": "/tmp/a"},
breeding emtpy lines while listing output which leaves the screen just do smth like ``` datalad install ///openfmri datalad install openfmri/ds000{011,11*} datalad ls -rLa openfmri ``` - there is a bunch of empty lines at the end of the listing before "EXITED" reported by datalad exiting the loop. Feels like a counter of some kind is incorrect while accounting for stuff which left the screen already - if you scroll terminal up - you will see some full terminal height empty spaces with one line of the listing at the bottom. Ideally I expect that output either be completely redrawn (thus repeating previously output lines) or just continuing listing with possibly adjusted formatting (e.g. the widths of the fields). - when I have used it on my local `openfmri` superdataset installation then there were also smaller periods of emptiness if you scroll terminal up
0.0
7e6097dd505e1d57be47bc4ec723ccdc1623047f
[ "pyout/tests/test_tabular.py::test_tabular_callback_to_hidden_row[True-21]" ]
[ "pyout/tests/test_tabular.py::test_tabular_write_color", "pyout/tests/test_tabular.py::test_tabular_write_empty_string", "pyout/tests/test_tabular.py::test_tabular_write_missing_column", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_text", "pyout/tests/test_tabular.py::test_tabular_write_list_value", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_object_data", "pyout/tests/test_tabular.py::test_tabular_write_columns_from_orderdict_row", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[sequence]", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[dict]", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list", "pyout/tests/test_tabular.py::test_tabular_write_header", "pyout/tests/test_tabular.py::test_tabular_write_data_as_object", "pyout/tests/test_tabular.py::test_tabular_write_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_header_with_style", "pyout/tests/test_tabular.py::test_tabular_nondefault_separator", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list_no_columns", "pyout/tests/test_tabular.py::test_tabular_write_style_override", "pyout/tests/test_tabular.py::test_tabular_default_style", "pyout/tests/test_tabular.py::test_tabular_write_multicolor", "pyout/tests/test_tabular.py::test_tabular_write_empty_string_nostyle", "pyout/tests/test_tabular.py::test_tabular_write_style_flanking", "pyout/tests/test_tabular.py::test_tabular_write_align", "pyout/tests/test_tabular.py::test_tabular_rewrite", "pyout/tests/test_tabular.py::test_tabular_rewrite_with_header", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_id", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_value", "pyout/tests/test_tabular.py::test_tabular_rewrite_auto_width", "pyout/tests/test_tabular.py::test_tabular_non_hashable_id_error", "pyout/tests/test_tabular.py::test_tabular_write_lookup_color", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold_false", "pyout/tests/test_tabular.py::test_tabular_write_lookup_non_hashable", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_open_ended", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_outside_intervals", "pyout/tests/test_tabular.py::test_tabular_write_intervals_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_missing", "pyout/tests/test_tabular.py::test_tabular_write_transform", "pyout/tests/test_tabular.py::test_tabular_write_transform_with_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_transform_on_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_func_error", "pyout/tests/test_tabular.py::test_tabular_write_width_truncate_long", "pyout/tests/test_tabular.py::test_tabular_write_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=True]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=False]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=\\u2026]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_auto_false_exception", "pyout/tests/test_tabular.py::test_tabular_fixed_width_exceeds_total", "pyout/tests/test_tabular.py::test_tabular_auto_width_exceeds_total", "pyout/tests/test_tabular.py::test_tabular_auto_width_exceeds_total_multiline", "pyout/tests/test_tabular.py::test_tabular_write_callable_values", "pyout/tests/test_tabular.py::test_tabular_write_callable_transform_nothing", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multi_return", "pyout/tests/test_tabular.py::test_tabular_callback_to_hidden_row[True-20]", "pyout/tests/test_tabular.py::test_tabular_callback_to_hidden_row[False-20]", "pyout/tests/test_tabular.py::test_tabular_callback_to_hidden_row[False-21]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=tuple]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=dict]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[gen_func]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[generator]", "pyout/tests/test_tabular.py::test_tabular_write_generator_values_multireturn", "pyout/tests/test_tabular.py::test_tabular_write_wait_noop_if_nothreads", "pyout/tests/test_tabular.py::test_tabular_write_delayed[dict]", "pyout/tests/test_tabular.py::test_tabular_write_delayed[list]", "pyout/tests/test_tabular.py::test_tabular_write_delayed[attrs]", "pyout/tests/test_tabular.py::test_tabular_summary", "pyout/tests/test_tabular.py::test_tabular_shrinking_summary", "pyout/tests/test_tabular.py::test_tabular_mode_invalid", "pyout/tests/test_tabular.py::test_tabular_mode_default", "pyout/tests/test_tabular.py::test_tabular_mode_after_write", "pyout/tests/test_tabular.py::test_tabular_mode_incremental", "pyout/tests/test_tabular.py::test_tabular_mode_final", "pyout/tests/test_tabular.py::test_tabular_mode_final_summary" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-12-15 16:14:14+00:00
mit
4,955
pyout__pyout-92
diff --git a/pyout/field.py b/pyout/field.py index e9d49e8..9935f7b 100644 --- a/pyout/field.py +++ b/pyout/field.py @@ -195,6 +195,14 @@ class Nothing(object): return self._text.__format__(format_spec) +def _pass_nothing_through(proc): + """Make processor function `proc` skip Nothing objects. + """ + def wrapped(value, result): + return result if isinstance(value, Nothing) else proc(value, result) + return wrapped + + class StyleFunctionError(Exception): """Signal that a style function failed. """ @@ -241,9 +249,6 @@ class StyleProcessors(object): """Return a processor for a style's "transform" function. """ def transform_fn(_, result): - if isinstance(result, Nothing): - return result - lgr.debug("Transforming %r with %r", result, function) try: return function(result) @@ -309,10 +314,13 @@ class StyleProcessors(object): def proc(value, result): try: lookup_value = mapping[value] - except (KeyError, TypeError): - # ^ TypeError is included in case the user passes non-hashable - # values. - return result + except KeyError: + lgr.debug("by_lookup: Key %r not found in mapping %s", + value, mapping) + lookup_value = None + except TypeError: + lgr.debug("by_lookup: Key %r not hashable", value) + lookup_value = None if not lookup_value: return result @@ -345,6 +353,8 @@ class StyleProcessors(object): def proc(value, result): if not isinstance(value, six.string_types): + lgr.debug("by_re_lookup: Skipping non-string value %r", + value) return result for r, lookup_value in regexps: if r.search(value): @@ -379,7 +389,8 @@ class StyleProcessors(object): def proc(value, result): try: value = float(value) - except TypeError: + except Exception as exc: + lgr.debug("by_interval_lookup: Skipping %r: %s", value, exc) return result for start, end, lookup_value in intervals: @@ -409,7 +420,8 @@ class StyleProcessors(object): A generator object. """ if "transform" in column_style: - yield self.transform(column_style["transform"]) + yield _pass_nothing_through( + self.transform(column_style["transform"])) def post_from_style(self, column_style): """Yield post-format processors based on `column_style`. @@ -442,7 +454,7 @@ class StyleProcessors(object): if vtype == "re_lookup": args.append(sum(getattr(re, f) for f in column_style.get("re_flags", []))) - yield fn(*args) + yield _pass_nothing_through(fn(*args)) yield flanks.join_flanks
pyout/pyout
b1a2ec4d63669b219d91b0fd528e996dd50fe711
diff --git a/pyout/tests/test_tabular.py b/pyout/tests/test_tabular.py index a29e01e..550a96e 100644 --- a/pyout/tests/test_tabular.py +++ b/pyout/tests/test_tabular.py @@ -468,6 +468,23 @@ def test_tabular_write_re_lookup_bold(): assert_eq_repr(out.stdout, expected) +def test_tabular_write_intervals_wrong_type(): + out = Tabular(style={"name": {"width": 3}, + "percent": {"color": {"interval": + [[0, 50, "red"], + [50, 80, "yellow"], + [80, 100, "green"]]}, + "width": 8}}) + out(OrderedDict([("name", "foo"), + ("percent", 88)])) + out(OrderedDict([("name", "bar"), + ("percent", "notfloat")])) + + expected = ["foo " + capres("green", "88") + " ", + "bar notfloat"] + assert_contains_nc(out.stdout.splitlines(), *expected) + + def test_tabular_write_intervals_color(): out = Tabular(style={"name": {"width": 3}, "percent": {"color": {"interval":
gets stuck or pukes error if there is "interval" but value is a string torturing pyout via dandi I have ``` "errors": dict( color=dict( interval=[ [0, 1, "green"], [1, None, "red"], ] ), aggregate=lambda x: "{} with errors".format(sum(map(bool, x))), ), ``` and if I yield an empty string as a value - usually stalls, but once actually crashed and gave me error ``` $> dandi upload -i local -c upload2 -t /tmp --validation skip /tmp/nwb_test_data/v2.0.0/test_*nwb PATH SIZE ERRORS UPLOAD STATUS MESSAGE Traceback (most recent call last): File "/home/yoh/proj/dandi/dandi-cli/venvs/dev3/bin/dandi", line 11, in <module> load_entry_point('dandi', 'console_scripts', 'dandi')() File "/home/yoh/proj/misc/click/click/core.py", line 828, in __call__ return self.main(*args, **kwargs) File "/home/yoh/proj/misc/click/click/core.py", line 781, in main rv = self.invoke(ctx) File "/home/yoh/proj/misc/click/click/core.py", line 1227, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/yoh/proj/misc/click/click/core.py", line 1046, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/yoh/proj/misc/click/click/core.py", line 590, in invoke return callback(*args, **kwargs) File "/home/yoh/proj/dandi/dandi-cli/dandi/cli/command.py", line 462, in upload out(rec) File "/home/yoh/proj/repronim/pyout/pyout/interface.py", line 384, in __call__ self._write(row, style) File "/home/yoh/proj/repronim/pyout/pyout/interface.py", line 236, in _write self._write_fn(row, style) File "/home/yoh/proj/repronim/pyout/pyout/interface.py", line 249, in _write_update content, status, summary = self._content.update(row, style) File "/home/yoh/proj/repronim/pyout/pyout/common.py", line 701, in update content, status = super(ContentWithSummary, self).update(row, style) File "/home/yoh/proj/repronim/pyout/pyout/common.py", line 672, in update return six.text_type(self), "repaint" File "/home/yoh/proj/repronim/pyout/pyout/common.py", line 611, in __str__ return "".join(self._render(self.rows)) File "/home/yoh/proj/repronim/pyout/pyout/common.py", line 601, in _render line, adj = self.fields.render(row, **kwds) File "/home/yoh/proj/repronim/pyout/pyout/common.py", line 523, in render for c in self.columns if not hidden[c]] File "/home/yoh/proj/repronim/pyout/pyout/common.py", line 523, in <listcomp> for c in self.columns if not hidden[c]] File "/home/yoh/proj/repronim/pyout/pyout/field.py", line 158, in __call__ result = fn(value, result) File "/home/yoh/proj/repronim/pyout/pyout/field.py", line 381, in proc value = float(value) ValueError: could not convert string to float: (dev3) 1 37143 ->1 [2].....................................:Fri 18 Oct 2019 12:31:28 PM EDT:. (git)hopa:~/proj/dandi/dandi-cli[nf-upload]git $> dandi upload -i local -c upload2 -t /tmp --validation skip /tmp/nwb_test_data/v2.0.0/test_*nwb PATH SIZE ERRORS UPLOAD STATUS MESSAGE nwb_test_data/v2.0.0/test_append.nwb 43.1 kB ^[[a^C Aborted! ``` from traceback above seems like might relate to use of `interval` since otherwise there should be no reason for float conversion
0.0
b1a2ec4d63669b219d91b0fd528e996dd50fe711
[ "pyout/tests/test_tabular.py::test_tabular_write_intervals_wrong_type" ]
[ "pyout/tests/test_tabular.py::test_tabular_write_color", "pyout/tests/test_tabular.py::test_tabular_write_empty_string", "pyout/tests/test_tabular.py::test_tabular_write_missing_column", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_text", "pyout/tests/test_tabular.py::test_tabular_write_list_value", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_object_data", "pyout/tests/test_tabular.py::test_tabular_write_columns_from_orderdict_row", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[sequence]", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[dict]", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list", "pyout/tests/test_tabular.py::test_tabular_width_no_style", "pyout/tests/test_tabular.py::test_tabular_write_header", "pyout/tests/test_tabular.py::test_tabular_write_data_as_object", "pyout/tests/test_tabular.py::test_tabular_write_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_header_with_style", "pyout/tests/test_tabular.py::test_tabular_nondefault_separator", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list_no_columns", "pyout/tests/test_tabular.py::test_tabular_write_style_override", "pyout/tests/test_tabular.py::test_tabular_default_style", "pyout/tests/test_tabular.py::test_tabular_write_multicolor", "pyout/tests/test_tabular.py::test_tabular_write_empty_string_nostyle", "pyout/tests/test_tabular.py::test_tabular_write_style_flanking", "pyout/tests/test_tabular.py::test_tabular_write_align", "pyout/tests/test_tabular.py::test_tabular_rewrite", "pyout/tests/test_tabular.py::test_tabular_rewrite_with_header", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_id", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_value", "pyout/tests/test_tabular.py::test_tabular_rewrite_auto_width", "pyout/tests/test_tabular.py::test_tabular_non_hashable_id_error", "pyout/tests/test_tabular.py::test_tabular_write_lookup_color", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold_false", "pyout/tests/test_tabular.py::test_tabular_write_lookup_non_hashable", "pyout/tests/test_tabular.py::test_tabular_write_re_lookup_color", "pyout/tests/test_tabular.py::test_tabular_write_re_lookup_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_open_ended", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_catchall_range", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_outside_intervals", "pyout/tests/test_tabular.py::test_tabular_write_intervals_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_missing", "pyout/tests/test_tabular.py::test_tabular_write_transform", "pyout/tests/test_tabular.py::test_tabular_write_transform_with_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_transform_on_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_func_error", "pyout/tests/test_tabular.py::test_tabular_write_width_truncate_long", "pyout/tests/test_tabular.py::test_tabular_write_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=True]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=False]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=\\u2026]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_incompatible_width_exception", "pyout/tests/test_tabular.py::test_tabular_fixed_width_exceeds_total", "pyout/tests/test_tabular.py::test_tabular_auto_width_exceeds_total", "pyout/tests/test_tabular.py::test_tabular_auto_width_exceeds_total_multiline", "pyout/tests/test_tabular.py::test_tabular_write_callable_values", "pyout/tests/test_tabular.py::test_tabular_write_callable_transform_nothing", "pyout/tests/test_tabular.py::test_tabular_write_callable_re_lookup_non_string", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multi_return", "pyout/tests/test_tabular.py::test_tabular_callback_to_hidden_row[20]", "pyout/tests/test_tabular.py::test_tabular_callback_to_hidden_row[21]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=tuple]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=dict]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[gen_func]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[generator]", "pyout/tests/test_tabular.py::test_tabular_write_generator_values_multireturn", "pyout/tests/test_tabular.py::test_tabular_write_wait_noop_if_nothreads", "pyout/tests/test_tabular.py::test_tabular_write_delayed[dict]", "pyout/tests/test_tabular.py::test_tabular_write_delayed[list]", "pyout/tests/test_tabular.py::test_tabular_write_delayed[attrs]", "pyout/tests/test_tabular.py::test_tabular_write_inspect_with_getitem", "pyout/tests/test_tabular.py::test_tabular_summary", "pyout/tests/test_tabular.py::test_tabular_shrinking_summary", "pyout/tests/test_tabular.py::test_tabular_mode_invalid", "pyout/tests/test_tabular.py::test_tabular_mode_default", "pyout/tests/test_tabular.py::test_tabular_mode_after_write", "pyout/tests/test_tabular.py::test_tabular_mode_update_noninteractive", "pyout/tests/test_tabular.py::test_tabular_mode_incremental", "pyout/tests/test_tabular.py::test_tabular_mode_final", "pyout/tests/test_tabular.py::test_tabular_mode_final_summary" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-18 20:46:02+00:00
mit
4,956
pyout__pyout-99
diff --git a/CHANGELOG.md b/CHANGELOG.md index ae31082..b55a868 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. the proportion of the table. For example, setting the "max" key to 0.5 means that the key should exceed half of the total table width. +- When operating non-interactively, by default the width is now + expanded to accommodate the content. To force a particular table + width in this situation, set the table's width using the "width_" + style attribute. ## [0.4.1] - 2019-10-02 diff --git a/pyout/common.py b/pyout/common.py index 0bf2484..0aaac98 100644 --- a/pyout/common.py +++ b/pyout/common.py @@ -371,6 +371,10 @@ class StyleFields(object): visible = self.visible_columns autowidth_columns = self.autowidth_columns width_table = self.style["width_"] + if width_table is None: + # The table is unbounded (non-interactive). + return + if len(visible) > width_table: raise elements.StyleError( "Number of visible columns exceeds available table width") @@ -431,7 +435,10 @@ class StyleFields(object): width_table = self.style["width_"] width_fixed = self.width_fixed - width_auto = width_table - width_fixed + if width_table is None: + width_auto = float("inf") + else: + width_auto = width_table - width_fixed if not autowidth_columns: return False @@ -502,7 +509,7 @@ class StyleFields(object): available characters the column should claim at a time. This is only in effect after each column has claimed one, and the specific column has claimed its minimum. - available : int + available : int or float('inf') Width available to be assigned. Returns @@ -551,7 +558,7 @@ class StyleFields(object): claim, available, column) if available == 0: break - lgr.debug("Available width after assigned: %d", available) + lgr.debug("Available width after assigned: %s", available) lgr.debug("Assigned widths: %r", assigned) return assigned diff --git a/pyout/elements.py b/pyout/elements.py index 716a325..fef77f4 100644 --- a/pyout/elements.py +++ b/pyout/elements.py @@ -215,9 +215,13 @@ schema = { "scope": "table"}, "width_": { "description": """Total width of table. - This is typically not set directly by the user.""", - "default": 90, - "type": "integer", + This is typically not set directly by the user. With the default + null value, the width is set to the stream's width for interactive + streams and as wide as needed to fit the content for + non-interactive streams.""", + "default": None, + "oneOf": [{"type": "integer"}, + {"type": "null"}], "scope": "table"} }, # All other keys are column names. diff --git a/pyout/interface.py b/pyout/interface.py index 3050cf4..805108c 100644 --- a/pyout/interface.py +++ b/pyout/interface.py @@ -125,7 +125,7 @@ class Writer(object): self.mode = "final" style = style or {} - if "width_" not in style and self._stream.width: + if style.get("width_") is None: lgr.debug("Setting width to stream width: %s", self._stream.width) style["width_"] = self._stream.width
pyout/pyout
818dff17cec5a5759cb7fa124a8927708bbe981d
diff --git a/pyout/tests/test_tabular.py b/pyout/tests/test_tabular.py index 945840b..fbb67b3 100644 --- a/pyout/tests/test_tabular.py +++ b/pyout/tests/test_tabular.py @@ -133,6 +133,36 @@ def test_tabular_width_no_style(): assert out.stdout == "a" * 97 + "...\n" +def test_tabular_width_non_interactive_default(): + out = Tabular(["name", "status"], interactive=False) + a = "a" * 70 + b = "b" * 100 + with out: + out([a, b]) + assert out.stdout == "{} {}\n".format(a, b) + + +def test_tabular_width_non_interactive_width_override(): + out = Tabular(["name", "status"], + style={"width_": 31, + "default_": {"width": {"marker": "…"}}}, + interactive=False) + with out: + out(["a" * 70, "b" * 100]) + stdout = out.stdout + assert stdout == "{} {}\n".format("a" * 14 + "…", "b" * 14 + "…") + + +def test_tabular_width_non_interactive_col_max(): + out = Tabular(["name", "status"], + style={"status": {"width": {"max": 20, "marker": "…"}}}, + interactive=False) + with out: + out(["a" * 70, "b" * 100]) + stdout = out.stdout + assert stdout == "{} {}\n".format("a" * 70, "b" * 19 + "…") + + def test_tabular_write_header(): out = Tabular(["name", "status"], style={"header_": {},
Make width as large as needed in "final" mode If stdout it not a tty ATM pytout seems to limit to some predetermined width: ```shell $> datalad ls -r ~/datalad -L | cat [3] - 3355 done gitk --all PATH TYPE BRANCH DESCRIBE DATE CLEAN ANNEX(PRESENT) ANNEX(WORKTREE) /home/yoh/datalad annex master 2018-09-17... - 31.3 MB 23.8 MB /home/yoh/data... annex master 0.0.2... 2018-06-08... X 0 Bytes 0 Bytes /home/yoh/data... annex master 2018-06-08... X 0 Bytes 0 Bytes ... ``` but since delivering the "final" rendering -- why not to make it as wide as needed? Also then It would correspond to the final version of the "update" mode output
0.0
818dff17cec5a5759cb7fa124a8927708bbe981d
[ "pyout/tests/test_tabular.py::test_tabular_width_non_interactive_default", "pyout/tests/test_tabular.py::test_tabular_width_non_interactive_col_max" ]
[ "pyout/tests/test_tabular.py::test_tabular_write_color", "pyout/tests/test_tabular.py::test_tabular_write_empty_string", "pyout/tests/test_tabular.py::test_tabular_write_missing_column", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_text", "pyout/tests/test_tabular.py::test_tabular_write_list_value", "pyout/tests/test_tabular.py::test_tabular_write_missing_column_missing_object_data", "pyout/tests/test_tabular.py::test_tabular_write_columns_from_orderdict_row", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[sequence]", "pyout/tests/test_tabular.py::test_tabular_write_columns_orderdict_mapping[dict]", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list", "pyout/tests/test_tabular.py::test_tabular_width_no_style", "pyout/tests/test_tabular.py::test_tabular_width_non_interactive_width_override", "pyout/tests/test_tabular.py::test_tabular_write_header", "pyout/tests/test_tabular.py::test_tabular_write_data_as_object", "pyout/tests/test_tabular.py::test_tabular_write_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_header_with_style", "pyout/tests/test_tabular.py::test_tabular_nondefault_separator", "pyout/tests/test_tabular.py::test_tabular_write_data_as_list_no_columns", "pyout/tests/test_tabular.py::test_tabular_write_style_override", "pyout/tests/test_tabular.py::test_tabular_default_style", "pyout/tests/test_tabular.py::test_tabular_write_multicolor", "pyout/tests/test_tabular.py::test_tabular_write_all_whitespace_nostyle", "pyout/tests/test_tabular.py::test_tabular_write_style_flanking", "pyout/tests/test_tabular.py::test_tabular_write_align", "pyout/tests/test_tabular.py::test_tabular_rewrite", "pyout/tests/test_tabular.py::test_tabular_rewrite_with_header", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_id", "pyout/tests/test_tabular.py::test_tabular_rewrite_multi_value", "pyout/tests/test_tabular.py::test_tabular_rewrite_auto_width", "pyout/tests/test_tabular.py::test_tabular_non_hashable_id_error", "pyout/tests/test_tabular.py::test_tabular_write_lookup_color", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold", "pyout/tests/test_tabular.py::test_tabular_write_lookup_bold_false", "pyout/tests/test_tabular.py::test_tabular_write_lookup_non_hashable", "pyout/tests/test_tabular.py::test_tabular_write_re_lookup_color", "pyout/tests/test_tabular.py::test_tabular_write_re_lookup_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_wrong_type", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_open_ended", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_catchall_range", "pyout/tests/test_tabular.py::test_tabular_write_intervals_color_outside_intervals", "pyout/tests/test_tabular.py::test_tabular_write_intervals_bold", "pyout/tests/test_tabular.py::test_tabular_write_intervals_missing", "pyout/tests/test_tabular.py::test_tabular_write_transform", "pyout/tests/test_tabular.py::test_tabular_write_transform_with_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_transform_on_header", "pyout/tests/test_tabular.py::test_tabular_write_transform_func_error", "pyout/tests/test_tabular.py::test_tabular_write_width_truncate_long", "pyout/tests/test_tabular.py::test_tabular_write_autowidth", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=True]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=False]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max[marker=\\u2026]", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_max_with_header", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_min_frac", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_max_frac", "pyout/tests/test_tabular.py::test_tabular_write_fixed_width_frac", "pyout/tests/test_tabular.py::test_tabular_write_autowidth_different_data_types_same_output", "pyout/tests/test_tabular.py::test_tabular_write_incompatible_width_exception", "pyout/tests/test_tabular.py::test_tabular_fixed_width_exceeds_total", "pyout/tests/test_tabular.py::test_tabular_number_of_columns_exceeds_total_width", "pyout/tests/test_tabular.py::test_tabular_auto_width_exceeds_total", "pyout/tests/test_tabular.py::test_tabular_auto_width_exceeds_total_multiline", "pyout/tests/test_tabular.py::test_tabular_write_callable_values", "pyout/tests/test_tabular.py::test_tabular_write_callable_transform_nothing", "pyout/tests/test_tabular.py::test_tabular_write_callable_re_lookup_non_string", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multi_return", "pyout/tests/test_tabular.py::test_tabular_callback_to_offscreen_row[20]", "pyout/tests/test_tabular.py::test_tabular_callback_to_offscreen_row[21]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=tuple]", "pyout/tests/test_tabular.py::test_tabular_write_callable_values_multicol_key_infer_column[result=dict]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[gen_func]", "pyout/tests/test_tabular.py::test_tabular_write_generator_function_values[generator]", "pyout/tests/test_tabular.py::test_tabular_write_generator_values_multireturn", "pyout/tests/test_tabular.py::test_tabular_write_wait_noop_if_nothreads", "pyout/tests/test_tabular.py::test_tabular_write_delayed[dict]", "pyout/tests/test_tabular.py::test_tabular_write_delayed[list]", "pyout/tests/test_tabular.py::test_tabular_write_delayed[attrs]", "pyout/tests/test_tabular.py::test_tabular_write_inspect_with_getitem", "pyout/tests/test_tabular.py::test_tabular_hidden_column", "pyout/tests/test_tabular.py::test_tabular_hidden_if_missing_column", "pyout/tests/test_tabular.py::test_tabular_hidden_col_takes_back_auto_space", "pyout/tests/test_tabular.py::test_tabular_summary", "pyout/tests/test_tabular.py::test_tabular_shrinking_summary", "pyout/tests/test_tabular.py::test_tabular_mode_invalid", "pyout/tests/test_tabular.py::test_tabular_mode_default", "pyout/tests/test_tabular.py::test_tabular_mode_after_write", "pyout/tests/test_tabular.py::test_tabular_mode_update_noninteractive", "pyout/tests/test_tabular.py::test_tabular_mode_incremental", "pyout/tests/test_tabular.py::test_tabular_mode_final", "pyout/tests/test_tabular.py::test_tabular_mode_final_summary" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-11-06 21:24:45+00:00
mit
4,957
pypa__auditwheel-287
diff --git a/auditwheel/policy/__init__.py b/auditwheel/policy/__init__.py index 22879c0..a9d59d0 100644 --- a/auditwheel/policy/__init__.py +++ b/auditwheel/policy/__init__.py @@ -1,7 +1,8 @@ import sys import json import platform as _platform_module -from typing import Optional, List +from collections import defaultdict +from typing import Dict, List, Optional, Set from os.path import join, dirname, abspath import logging @@ -23,9 +24,42 @@ def get_arch_name() -> str: _ARCH_NAME = get_arch_name() +def _validate_pep600_compliance(policies) -> None: + symbol_versions: Dict[str, Dict[str, Set[str]]] = {} + lib_whitelist: Set[str] = set() + for policy in sorted(policies, key=lambda x: x['priority'], reverse=True): + if policy['name'] == 'linux': + continue + if not lib_whitelist.issubset(set(policy['lib_whitelist'])): + diff = lib_whitelist - set(policy["lib_whitelist"]) + raise ValueError( + 'Invalid "policy.json" file. Missing whitelist libraries in ' + f'"{policy["name"]}" compared to previous policies: {diff}' + ) + lib_whitelist.update(policy['lib_whitelist']) + for arch in policy['symbol_versions'].keys(): + symbol_versions_arch = symbol_versions.get(arch, defaultdict(set)) + for prefix in policy['symbol_versions'][arch].keys(): + policy_symbol_versions = set( + policy['symbol_versions'][arch][prefix]) + if not symbol_versions_arch[prefix].issubset( + policy_symbol_versions): + diff = symbol_versions_arch[prefix] - \ + policy_symbol_versions + raise ValueError( + 'Invalid "policy.json" file. Symbol versions missing ' + f'in "{policy["name"]}_{arch}" for "{prefix}" ' + f'compared to previous policies: {diff}' + ) + symbol_versions_arch[prefix].update( + policy['symbol_versions'][arch][prefix]) + symbol_versions[arch] = symbol_versions_arch + + with open(join(dirname(abspath(__file__)), 'policy.json')) as f: _POLICIES = [] _policies_temp = json.load(f) + _validate_pep600_compliance(_policies_temp) for _p in _policies_temp: if _ARCH_NAME in _p['symbol_versions'].keys() or _p['name'] == 'linux': if _p['name'] != 'linux': diff --git a/auditwheel/policy/policy.json b/auditwheel/policy/policy.json index 7c9b722..bce6fb9 100644 --- a/auditwheel/policy/policy.json +++ b/auditwheel/policy/policy.json @@ -9,8 +9,8 @@ "symbol_versions": { "i686": { "CXXABI": ["1.3", "1.3.1"], - "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "3.4.4", "4.0.0", "4.2.0"], - "GLIBC": ["2.0", "2.1", "2.1.1", "2.1.2", "2.1.3", "2.2", "2.2.1", "2.2.2", "2.2.3", "2.2.4", "2.2.5", "2.2.6", "2.3", "2.3.2", "2.3.3", "2.3.4", "2.4", "2.5"], + "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "4.0.0", "4.2.0"], + "GLIBC": ["2.0", "2.1", "2.1.1", "2.1.2", "2.1.3", "2.2", "2.2.1", "2.2.2", "2.2.3", "2.2.4", "2.2.6", "2.3", "2.3.2", "2.3.3", "2.3.4", "2.4", "2.5"], "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8"] }, "x86_64": { @@ -21,7 +21,6 @@ } }, "lib_whitelist": [ - "libpanelw.so.5", "libncursesw.so.5", "libgcc_s.so.1", "libstdc++.so.6", "libm.so.6", "libdl.so.2", "librt.so.1",
pypa/auditwheel
22c84515fee79d9d866bf1e62d33cff6f9d0e68e
diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py index 8a512e0..c926929 100644 --- a/tests/unit/test_policy.py +++ b/tests/unit/test_policy.py @@ -3,7 +3,7 @@ from unittest.mock import patch import pytest from auditwheel.policy import get_arch_name, get_policy_name, \ - get_priority_by_name, get_replace_platforms + get_priority_by_name, get_replace_platforms, _validate_pep600_compliance @patch("auditwheel.policy._platform_module.machine") @@ -43,6 +43,59 @@ def test_replacement_platform(name, expected): assert get_replace_platforms(name) == expected +def test_pep600_compliance(): + _validate_pep600_compliance([{ + "name": "manylinux1", "priority": 100, "symbol_versions": { + "i686": {"CXXABI": ["1.3"]}, + }, + "lib_whitelist": ["libgcc_s.so.1"] + }, { + "name": "manylinux2010", "priority": 90, "symbol_versions": { + "i686": {"CXXABI": ["1.3", "1.3.1"]}, + }, + "lib_whitelist": ["libgcc_s.so.1", "libstdc++.so.6"], + }]) + + _validate_pep600_compliance([{ + "name": "manylinux1", "priority": 100, "symbol_versions": { + "i686": {"CXXABI": ["1.3"]}, + "x86_64": {"CXXABI": ["1.3"]}, + }, + "lib_whitelist": ["libgcc_s.so.1"] + }, { + "name": "manylinux2010", "priority": 90, "symbol_versions": { + "i686": {"CXXABI": ["1.3", "1.3.1"]}, + }, + "lib_whitelist": ["libgcc_s.so.1", "libstdc++.so.6"], + }]) + + with pytest.raises(ValueError, match="manylinux2010_i686.*CXXABI.*1.3.2"): + _validate_pep600_compliance([{ + "name": "manylinux1", "priority": 100, "symbol_versions": { + "i686": {"CXXABI": ["1.3", "1.3.2"]}, + }, + "lib_whitelist": ["libgcc_s.so.1"] + }, { + "name": "manylinux2010", "priority": 90, "symbol_versions": { + "i686": {"CXXABI": ["1.3", "1.3.1"]}, + }, + "lib_whitelist": ["libgcc_s.so.1", "libstdc++.so.6"], + }]) + + with pytest.raises(ValueError, match="manylinux2010.*libstdc\+\+\.so\.6"): + _validate_pep600_compliance([{ + "name": "manylinux1", "priority": 100, "symbol_versions": { + "i686": {"CXXABI": ["1.3"]}, + }, + "lib_whitelist": ["libgcc_s.so.1", "libstdc++.so.6"] + }, { + "name": "manylinux2010", "priority": 90, "symbol_versions": { + "i686": {"CXXABI": ["1.3", "1.3.1"]}, + }, + "lib_whitelist": ["libgcc_s.so.1"], + }]) + + class TestPolicyAccess: def test_get_by_priority(self):
ncurses 5 -> 6 transition means we probably need to drop some libraries from the manylinux whitelist The [PEP 513 whitelist](https://www.python.org/dev/peps/pep-0513/#the-manylinux1-policy) includes `libpanelw.so.5` and `libncursesw.so.5`, both of which are part of ncurses version 5. But apparently the new hostness is [ncurses 6, which breaks ABI with ncurses 5](https://www.gnu.org/software/ncurses/). I'm told that Fedora 24 and successors have already switched to ncurses 6, with the ncurses 5 libraries being available in a compatibility package, but not installed by default. So... I guess these have to be dropped from the whitelist.
0.0
22c84515fee79d9d866bf1e62d33cff6f9d0e68e
[ "tests/unit/test_policy.py::test_32bits_arch_name[armv6l-armv6l]", "tests/unit/test_policy.py::test_32bits_arch_name[armv7l-armv7l]", "tests/unit/test_policy.py::test_32bits_arch_name[i686-i686]", "tests/unit/test_policy.py::test_32bits_arch_name[x86_64-i686]", "tests/unit/test_policy.py::test_64bits_arch_name[aarch64-aarch64]", "tests/unit/test_policy.py::test_64bits_arch_name[ppc64le-ppc64le]", "tests/unit/test_policy.py::test_64bits_arch_name[x86_64-x86_64]", "tests/unit/test_policy.py::test_replacement_platform[linux_aarch64-expected0]", "tests/unit/test_policy.py::test_replacement_platform[manylinux1_ppc64le-expected1]", "tests/unit/test_policy.py::test_replacement_platform[manylinux2014_x86_64-expected2]", "tests/unit/test_policy.py::test_replacement_platform[manylinux_2_24_x86_64-expected3]", "tests/unit/test_policy.py::test_pep600_compliance", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority_missing", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority_duplicate", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name_missing", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name_duplicate" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-18 20:43:34+00:00
mit
4,958
pypa__auditwheel-300
diff --git a/auditwheel/policy/policy.json b/auditwheel/policy/policy.json index a490df4..0ed5d38 100644 --- a/auditwheel/policy/policy.json +++ b/auditwheel/policy/policy.json @@ -154,6 +154,56 @@ "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22"] } }, + "lib_whitelist": [ + "libgcc_s.so.1", + "libstdc++.so.6", + "libm.so.6", "libdl.so.2", "librt.so.1", + "libc.so.6", "libnsl.so.1", "libutil.so.1", "libpthread.so.0", + "libX11.so.6", "libXext.so.6", "libXrender.so.1", "libICE.so.6", + "libSM.so.6", "libGL.so.1", "libgobject-2.0.so.0", + "libgthread-2.0.so.0", "libglib-2.0.so.0", "libresolv.so.2" + ]}, + {"name": "manylinux_2_27", + "aliases": [], + "priority": 65, + "symbol_versions": { + "i686": { + "CXXABI": ["1.3", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.8", "1.3.9", "1.3.10", "1.3.11", "FLOAT128", "TM_1"], + "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "4.0.0", "4.2.0", "4.3.0", "4.4.0", "4.5.0", "4.7.0", "4.8.0", "7.0.0"], + "GLIBC": ["2.0", "2.1", "2.1.1", "2.1.2", "2.1.3", "2.2", "2.2.1", "2.2.2", "2.2.3", "2.2.4", "2.2.6", "2.3", "2.3.2", "2.3.3", "2.3.4", "2.4", "2.5", "2.6", "2.7", "2.8", "2.9", "2.10", "2.11", "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.22", "2.23", "2.24", "2.25", "2.26", "2.27"], + "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22", "3.4.23", "3.4.24"] + }, + "x86_64": { + "CXXABI": ["1.3", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.8", "1.3.9", "1.3.10", "1.3.11", "FLOAT128", "TM_1"], + "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "3.4.4", "4.0.0", "4.2.0", "4.3.0", "4.7.0", "4.8.0", "7.0.0"], + "GLIBC": ["2.2.5", "2.2.6", "2.3", "2.3.2", "2.3.3", "2.3.4", "2.4", "2.5", "2.6", "2.7", "2.8", "2.9", "2.10", "2.11", "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.22", "2.23", "2.24", "2.25", "2.26", "2.27"], + "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22", "3.4.23", "3.4.24"] + }, + "aarch64": { + "CXXABI": ["1.3", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.8", "1.3.9", "1.3.10", "1.3.11", "TM_1"], + "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "3.4.4", "4.0.0", "4.2.0", "4.3.0", "4.5.0", "4.7.0", "7.0.0"], + "GLIBC": ["2.0", "2.17", "2.18", "2.22", "2.23", "2.24", "2.25", "2.26", "2.27"], + "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22", "3.4.23", "3.4.24"] + }, + "ppc64le": { + "CXXABI": ["1.3", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.8", "1.3.9", "1.3.10", "1.3.11", "LDBL_1.3", "TM_1"], + "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "3.4.4", "4.0.0", "4.2.0", "4.3.0", "4.7.0", "7.0.0"], + "GLIBC": ["2.0", "2.17", "2.18", "2.22", "2.23", "2.24", "2.25", "2.26", "2.27"], + "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22", "3.4.23", "3.4.24", "LDBL_3.4", "LDBL_3.4.10", "LDBL_3.4.21", "LDBL_3.4.7"] + }, + "s390x": { + "CXXABI": ["1.3", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.8", "1.3.9", "1.3.10", "1.3.11", "LDBL_1.3", "TM_1"], + "GCC": ["3.0", "3.3", "3.3.1", "3.4", "3.4.2", "3.4.4", "4.0.0", "4.1.0", "4.2.0", "4.3.0", "4.7.0", "7.0.0"], + "GLIBC": ["2.2", "2.2.1", "2.2.2", "2.2.3", "2.2.4", "2.2.6", "2.3", "2.3.2", "2.3.3", "2.3.4", "2.4", "2.5", "2.6", "2.7", "2.8", "2.9", "2.10", "2.11", "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.19", "2.22", "2.23", "2.24", "2.25", "2.26", "2.27"], + "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22", "3.4.23", "3.4.24", "LDBL_3.4", "LDBL_3.4.10", "LDBL_3.4.21", "LDBL_3.4.7"] + }, + "armv7l": { + "CXXABI": ["1.3", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.8", "1.3.9", "1.3.10", "1.3.11", "ARM_1.3.3", "TM_1"], + "GCC": ["3.0", "3.3", "3.3.1", "3.3.4", "3.4", "3.4.2", "3.5", "4.0.0", "4.2.0", "4.3.0", "4.7.0", "7.0.0"], + "GLIBC": ["2.0", "2.4", "2.5", "2.6", "2.7", "2.8", "2.9", "2.10", "2.11", "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.22", "2.23", "2.24", "2.25", "2.26", "2.27"], + "GLIBCXX": ["3.4", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.7", "3.4.8", "3.4.9", "3.4.10", "3.4.11", "3.4.12", "3.4.13", "3.4.14", "3.4.15", "3.4.16", "3.4.17", "3.4.18", "3.4.19", "3.4.20", "3.4.21", "3.4.22", "3.4.23", "3.4.24"] + } + }, "lib_whitelist": [ "libgcc_s.so.1", "libstdc++.so.6",
pypa/auditwheel
bcf80837381beb88b62607dd87722ccbdc316fc3
diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py index 11b2632..6694ad7 100644 --- a/tests/unit/test_policy.py +++ b/tests/unit/test_policy.py @@ -100,6 +100,7 @@ class TestPolicyAccess: def test_get_by_priority(self): _arch = get_arch_name() + assert get_policy_name(65) == f'manylinux_2_27_{_arch}' assert get_policy_name(70) == f'manylinux_2_24_{_arch}' assert get_policy_name(80) == f'manylinux_2_17_{_arch}' if _arch in {'x86_64', 'i686'}: @@ -120,6 +121,7 @@ class TestPolicyAccess: def test_get_by_name(self): _arch = get_arch_name() + assert get_priority_by_name(f"manylinux_2_27_{_arch}") == 65 assert get_priority_by_name(f"manylinux_2_24_{_arch}") == 70 assert get_priority_by_name(f"manylinux2014_{_arch}") == 80 assert get_priority_by_name(f"manylinux_2_17_{_arch}") == 80
Add manylinux_2_27 policy Hey team! We at @robotpy build wheels on Ubuntu 18.04 (as our upstream targets 18.04). We've been manually tagging our wheels as `manylinux_2_27` as we wanted to get our wheels on PyPI quickly early this year. It'd be awesome if we could use auditwheel instead to check that our wheels are actually compliant.
0.0
bcf80837381beb88b62607dd87722ccbdc316fc3
[ "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name" ]
[ "tests/unit/test_policy.py::test_32bits_arch_name[armv6l-armv6l]", "tests/unit/test_policy.py::test_32bits_arch_name[armv7l-armv7l]", "tests/unit/test_policy.py::test_32bits_arch_name[i686-i686]", "tests/unit/test_policy.py::test_32bits_arch_name[x86_64-i686]", "tests/unit/test_policy.py::test_64bits_arch_name[aarch64-aarch64]", "tests/unit/test_policy.py::test_64bits_arch_name[ppc64le-ppc64le]", "tests/unit/test_policy.py::test_64bits_arch_name[x86_64-x86_64]", "tests/unit/test_policy.py::test_replacement_platform[linux_aarch64-expected0]", "tests/unit/test_policy.py::test_replacement_platform[manylinux1_ppc64le-expected1]", "tests/unit/test_policy.py::test_replacement_platform[manylinux2014_x86_64-expected2]", "tests/unit/test_policy.py::test_replacement_platform[manylinux_2_24_x86_64-expected3]", "tests/unit/test_policy.py::test_pep600_compliance", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority_missing", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority_duplicate", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name_missing", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name_duplicate" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-03-27 11:32:09+00:00
mit
4,959
pypa__auditwheel-343
diff --git a/README.rst b/README.rst index 8b6047d..02bbaae 100644 --- a/README.rst +++ b/README.rst @@ -127,7 +127,7 @@ Limitations Testing ------- -The tests can be run with ``tox``, which will automatically install +The tests can be run with ``nox``, which will automatically install test dependencies. Some of the integration tests also require a running and accessible Docker diff --git a/src/auditwheel/main_repair.py b/src/auditwheel/main_repair.py index c4fafa7..1e0ae58 100644 --- a/src/auditwheel/main_repair.py +++ b/src/auditwheel/main_repair.py @@ -31,7 +31,10 @@ below. epilog += f" (aliased by {', '.join(p['aliases'])})" epilog += "\n" highest_policy = get_policy_name(POLICY_PRIORITY_HIGHEST) - help = "Vendor in external shared library dependencies of a wheel." + help = """Vendor in external shared library dependencies of a wheel. +If multiple wheels are specified, an error processing one +wheel will abort processing of subsequent wheels. +""" p = sub_parsers.add_parser( "repair", help=help, @@ -39,7 +42,7 @@ below. epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter, ) - p.add_argument("WHEEL_FILE", help="Path to wheel file.") + p.add_argument("WHEEL_FILE", help="Path to wheel file.", nargs="+") p.add_argument( "--plat", action=EnvironmentDefault, @@ -101,72 +104,73 @@ def execute(args, p): from .repair import repair_wheel from .wheel_abi import NonPlatformWheel, analyze_wheel_abi - if not isfile(args.WHEEL_FILE): - p.error("cannot access %s. No such file" % args.WHEEL_FILE) + for wheel_file in args.WHEEL_FILE: + if not isfile(wheel_file): + p.error("cannot access %s. No such file" % wheel_file) - logger.info("Repairing %s", basename(args.WHEEL_FILE)) + logger.info("Repairing %s", basename(wheel_file)) - if not exists(args.WHEEL_DIR): - os.makedirs(args.WHEEL_DIR) + if not exists(args.WHEEL_DIR): + os.makedirs(args.WHEEL_DIR) - try: - wheel_abi = analyze_wheel_abi(args.WHEEL_FILE) - except NonPlatformWheel: - logger.info("This does not look like a platform wheel") - return 1 + try: + wheel_abi = analyze_wheel_abi(wheel_file) + except NonPlatformWheel: + logger.info("This does not look like a platform wheel") + return 1 - policy = get_policy_by_name(args.PLAT) - reqd_tag = policy["priority"] + policy = get_policy_by_name(args.PLAT) + reqd_tag = policy["priority"] - if reqd_tag > get_priority_by_name(wheel_abi.sym_tag): - msg = ( - 'cannot repair "%s" to "%s" ABI because of the presence ' - "of too-recent versioned symbols. You'll need to compile " - "the wheel on an older toolchain." % (args.WHEEL_FILE, args.PLAT) - ) - p.error(msg) - - if reqd_tag > get_priority_by_name(wheel_abi.ucs_tag): - msg = ( - 'cannot repair "%s" to "%s" ABI because it was compiled ' - "against a UCS2 build of Python. You'll need to compile " - "the wheel against a wide-unicode build of Python." - % (args.WHEEL_FILE, args.PLAT) - ) - p.error(msg) + if reqd_tag > get_priority_by_name(wheel_abi.sym_tag): + msg = ( + 'cannot repair "%s" to "%s" ABI because of the presence ' + "of too-recent versioned symbols. You'll need to compile " + "the wheel on an older toolchain." % (wheel_file, args.PLAT) + ) + p.error(msg) + + if reqd_tag > get_priority_by_name(wheel_abi.ucs_tag): + msg = ( + 'cannot repair "%s" to "%s" ABI because it was compiled ' + "against a UCS2 build of Python. You'll need to compile " + "the wheel against a wide-unicode build of Python." + % (wheel_file, args.PLAT) + ) + p.error(msg) - if reqd_tag > get_priority_by_name(wheel_abi.blacklist_tag): - msg = ( - 'cannot repair "%s" to "%s" ABI because it depends on ' - "black-listed symbols." % (args.WHEEL_FILE, args.PLAT) - ) - p.error(msg) - - abis = [policy["name"]] + policy["aliases"] - if not args.ONLY_PLAT: - if reqd_tag < get_priority_by_name(wheel_abi.overall_tag): - logger.info( - ( - "Wheel is eligible for a higher priority tag. " - "You requested %s but I have found this wheel is " - "eligible for %s." - ), - args.PLAT, - wheel_abi.overall_tag, + if reqd_tag > get_priority_by_name(wheel_abi.blacklist_tag): + msg = ( + 'cannot repair "%s" to "%s" ABI because it depends on ' + "black-listed symbols." % (wheel_file, args.PLAT) ) - higher_policy = get_policy_by_name(wheel_abi.overall_tag) - abis = [higher_policy["name"]] + higher_policy["aliases"] + abis - - patcher = Patchelf() - out_wheel = repair_wheel( - args.WHEEL_FILE, - abis=abis, - lib_sdir=args.LIB_SDIR, - out_dir=args.WHEEL_DIR, - update_tags=args.UPDATE_TAGS, - patcher=patcher, - strip=args.STRIP, - ) + p.error(msg) + + abis = [policy["name"]] + policy["aliases"] + if not args.ONLY_PLAT: + if reqd_tag < get_priority_by_name(wheel_abi.overall_tag): + logger.info( + ( + "Wheel is eligible for a higher priority tag. " + "You requested %s but I have found this wheel is " + "eligible for %s." + ), + args.PLAT, + wheel_abi.overall_tag, + ) + higher_policy = get_policy_by_name(wheel_abi.overall_tag) + abis = [higher_policy["name"]] + higher_policy["aliases"] + abis + + patcher = Patchelf() + out_wheel = repair_wheel( + wheel_file, + abis=abis, + lib_sdir=args.LIB_SDIR, + out_dir=args.WHEEL_DIR, + update_tags=args.UPDATE_TAGS, + patcher=patcher, + strip=args.STRIP, + ) - if out_wheel is not None: - logger.info("\nFixed-up wheel written to %s", out_wheel) + if out_wheel is not None: + logger.info("\nFixed-up wheel written to %s", out_wheel)
pypa/auditwheel
f3c7691f258de76c11f679ab85826b730c658c14
diff --git a/tests/integration/test_bundled_wheels.py b/tests/integration/test_bundled_wheels.py index fa51f63..f3f5bc8 100644 --- a/tests/integration/test_bundled_wheels.py +++ b/tests/integration/test_bundled_wheels.py @@ -66,7 +66,7 @@ def test_wheel_source_date_epoch(tmp_path, monkeypatch): STRIP=False, UPDATE_TAGS=True, WHEEL_DIR=str(wheel_output_path), - WHEEL_FILE=str(wheel_path), + WHEEL_FILE=[str(wheel_path)], cmd="repair", func=Mock(), prog="auditwheel",
Support multiple wheel files in repair command Currently ``auditwheel repair`` command supports only one ``WHEEL_FILE`` argument, I thought it would be nice if it will be possible to give multiple wheels to repair, what do you think? It will be useful in my use case when I build a set of wheels some of which should be repaired. And if you consider it to be useful addition, I'll submit a patch.
0.0
f3c7691f258de76c11f679ab85826b730c658c14
[ "[100%]", "tests/integration/test_bundled_wheels.py::test_wheel_source_date_epoch" ]
[ "tests/integration/test_bundled_wheels.py::test_analyze_wheel_abi[cffi-1.5.0-cp27-none-linux_x86_64.whl-external_libs0]", "tests/integration/test_bundled_wheels.py::test_analyze_wheel_abi[python_snappy-0.5.2-pp260-pypy_41-linux_x86_64.whl-external_libs1]", "tests/integration/test_bundled_wheels.py::test_analyze_wheel_abi_pyfpe" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-10-21 19:09:20+00:00
mit
4,960
pypa__auditwheel-367
diff --git a/src/auditwheel/tools.py b/src/auditwheel/tools.py index ed8b514..bce72f2 100644 --- a/src/auditwheel/tools.py +++ b/src/auditwheel/tools.py @@ -70,19 +70,21 @@ def dir2zip(in_dir: str, zip_fname: str, date_time: Optional[datetime] = None) - st = os.stat(in_dir) date_time = datetime.fromtimestamp(st.st_mtime, tz=timezone.utc) date_time_args = date_time.timetuple()[:6] - with zipfile.ZipFile(zip_fname, "w", compression=zipfile.ZIP_DEFLATED) as z: + compression = zipfile.ZIP_DEFLATED + with zipfile.ZipFile(zip_fname, "w", compression=compression) as z: for root, dirs, files in os.walk(in_dir): for dir in dirs: dname = os.path.join(root, dir) out_dname = os.path.relpath(dname, in_dir) + "/" - zinfo = zipfile.ZipInfo(out_dname, date_time=date_time_args) - zinfo.external_attr = os.stat(dname).st_mode << 16 - z.writestr(zinfo, "") + zinfo = zipfile.ZipInfo.from_file(dname, out_dname) + zinfo.date_time = date_time_args + z.writestr(zinfo, b"") for file in files: fname = os.path.join(root, file) out_fname = os.path.relpath(fname, in_dir) - zinfo = zipfile.ZipInfo(out_fname, date_time=date_time_args) - zinfo.external_attr = os.stat(fname).st_mode << 16 + zinfo = zipfile.ZipInfo.from_file(fname, out_fname) + zinfo.date_time = date_time_args + zinfo.compress_type = compression with open(fname, "rb") as fp: z.writestr(zinfo, fp.read())
pypa/auditwheel
68aad23937225a629d70cb4b3e224abd07f16f44
diff --git a/tests/unit/test_tools.py b/tests/unit/test_tools.py index dd2a086..ee79467 100644 --- a/tests/unit/test_tools.py +++ b/tests/unit/test_tools.py @@ -87,3 +87,14 @@ def test_zip2dir_round_trip_permissions(tmp_path): dir2zip(str(tmp_path / "unzip1"), str(tmp_path / "tmp.zip")) zip2dir(str(tmp_path / "tmp.zip"), str(extract_path)) _check_permissions(extract_path) + + +def test_dir2zip_deflate(tmp_path): + buffer = b"\0" * 1024 * 1024 + input_dir = tmp_path / "input_dir" + input_dir.mkdir() + input_file = input_dir / "zeros.bin" + input_file.write_bytes(buffer) + output_file = tmp_path / "ouput.zip" + dir2zip(str(input_dir), str(output_file)) + assert output_file.stat().st_size < len(buffer) / 4
auditwheel repair: whls not getting compressed for auditwheel 5.1.0 and above? After upgrading to 5.1.0, we noticed that our wheels are not getting compressed, resulting in very large whls after running `auditwheel repair foo.whl`: ``` -rw-r--r-- 1 root root 104093514 Jan 7 01:54 accera-1.2.1.dev17-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.5.1.0.whl ``` auditwheel 5.0.0 was able to compress the whls by roughly 70%: ``` -rw-r--r-- 1 root root 35413658 Jan 7 01:44 accera-1.2.1.dev17-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.5.0.0.whl ``` The contents of both files are the same after unzipping, so the binaries themselves are unchanged but the whl does not seem to be compressed when using auditwheel 5.1.0 and above. ```shell [root@9a0260dd545d wheelhouse]# ls -al accera-5.0.0/ total 101324 drwxr-xr-x 8 root root 4096 Jan 7 01:44 . drwxr-xr-x 6 root root 4096 Jan 7 01:55 .. -rw-r--r-- 1 root root 476 Jan 7 01:44 Constants.py -rw-r--r-- 1 root root 3219 Jan 7 01:44 Debug.py drwxr-xr-x 2 root root 4096 Jan 7 01:44 hat -rw-r--r-- 1 root root 1035 Jan 7 01:44 __init__.py drwxr-xr-x 2 root root 4096 Jan 7 01:44 lang -rwxr-xr-x 1 root root 103664768 Jan 7 01:44 _lang_python.cpython-38-x86_64-linux-gnu.so -rw-r--r-- 1 root root 20883 Jan 7 01:44 Package.py -rw-r--r-- 1 root root 1563 Jan 7 01:44 Parameter.py drwxr-xr-x 2 root root 4096 Jan 7 01:44 samples -rw-r--r-- 1 root root 9045 Jan 7 01:44 Targets.py drwxr-xr-x 2 root root 4096 Jan 7 01:44 test drwxr-xr-x 3 root root 4096 Jan 7 01:44 tools drwxr-xr-x 2 root root 4096 Jan 7 01:44 tuning -rw-r--r-- 1 root root 36 Jan 7 01:44 _version.py [root@9a0260dd545d wheelhouse]# ls -al accera-5.1.0/ total 101324 drwxr-xr-x 8 root root 4096 Jan 7 01:54 . drwxr-xr-x 6 root root 4096 Jan 7 01:55 .. -rw-r--r-- 1 root root 476 Jan 7 01:54 Constants.py -rw-r--r-- 1 root root 3219 Jan 7 01:54 Debug.py drwxr-xr-x 2 root root 4096 Jan 7 01:54 hat -rw-r--r-- 1 root root 1035 Jan 7 01:54 __init__.py drwxr-xr-x 2 root root 4096 Jan 7 01:54 lang -rwxr-xr-x 1 root root 103664768 Jan 7 01:54 _lang_python.cpython-38-x86_64-linux-gnu.so -rw-r--r-- 1 root root 20883 Jan 7 01:54 Package.py -rw-r--r-- 1 root root 1563 Jan 7 01:54 Parameter.py drwxr-xr-x 2 root root 4096 Jan 7 01:54 samples -rw-r--r-- 1 root root 9045 Jan 7 01:54 Targets.py drwxr-xr-x 2 root root 4096 Jan 7 01:54 test drwxr-xr-x 3 root root 4096 Jan 7 01:54 tools drwxr-xr-x 2 root root 4096 Jan 7 01:54 tuning -rw-r--r-- 1 root root 36 Jan 7 01:54 _version.py ```
0.0
68aad23937225a629d70cb4b3e224abd07f16f44
[ "tests/unit/test_tools.py::test_dir2zip_deflate" ]
[ "tests/unit/test_tools.py::test_environment_action[None-None-manylinux1]", "tests/unit/test_tools.py::test_environment_action[None-manylinux2010-manylinux2010]", "tests/unit/test_tools.py::test_environment_action[manylinux2010-None-manylinux2010]", "tests/unit/test_tools.py::test_environment_action[manylinux2010-linux-linux]", "tests/unit/test_tools.py::test_environment_action_invalid_env", "tests/unit/test_tools.py::test_zip2dir_permissions", "tests/unit/test_tools.py::test_zip2dir_round_trip_permissions" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-01-07 22:20:14+00:00
mit
4,961
pypa__auditwheel-424
diff --git a/src/auditwheel/policy/external_references.py b/src/auditwheel/policy/external_references.py index 1c05b10..23afde8 100644 --- a/src/auditwheel/policy/external_references.py +++ b/src/auditwheel/policy/external_references.py @@ -8,7 +8,7 @@ from ..elfutils import filter_undefined_symbols, is_subdir from . import load_policies log = logging.getLogger(__name__) -LIBPYTHON_RE = re.compile(r"^libpython\d\.\dm?.so(.\d)*$") +LIBPYTHON_RE = re.compile(r"^libpython\d+\.\d+m?.so(.\d)*$") def lddtree_external_references(lddtree: dict, wheel_path: str) -> dict:
pypa/auditwheel
d270db8188386891fd1a653a6737ce5553de568c
diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py index 9fa21c9..adbdad8 100644 --- a/tests/unit/test_policy.py +++ b/tests/unit/test_policy.py @@ -10,6 +10,7 @@ from auditwheel.policy import ( get_policy_name, get_priority_by_name, get_replace_platforms, + lddtree_external_references, ) @@ -202,3 +203,32 @@ class TestPolicyAccess: def test_get_by_name_duplicate(self): with pytest.raises(RuntimeError): get_priority_by_name("duplicate") + + +class TestLddTreeExternalReferences: + """Tests for lddtree_external_references.""" + + def test_filter_libs(self): + """Test the nested filter_libs function.""" + filtered_libs = [ + "ld-linux-x86_64.so.1", + "ld64.so.1", + "ld64.so.2", + "libpython3.7m.so.1.0", + "libpython3.9.so.1.0", + "libpython3.10.so.1.0", + "libpython999.999.so.1.0", + ] + unfiltered_libs = ["libfoo.so.1.0", "libbar.so.999.999.999"] + libs = filtered_libs + unfiltered_libs + + lddtree = { + "realpath": "/path/to/lib", + "needed": libs, + "libs": {lib: {"needed": [], "realpath": "/path/to/lib"} for lib in libs}, + } + full_external_refs = lddtree_external_references(lddtree, "/path/to/wheel") + + # Assert that each policy only has the unfiltered libs. + for policy in full_external_refs: + assert set(full_external_refs[policy]["libs"]) == set(unfiltered_libs)
libpython3.x is skipped but libpython3.xx is included howdy, i noticed when running auditwheel repair on a wheel with dependency on libpython3.8.so or libpython3.9.so, they are not added to the wheel libs directory, but libpython3.10.so and libpython3.11.so are added. I'm not very familiar with the project, but i suspect [the regex detecting libpython](https://github.com/pypa/auditwheel/blob/63c30761e6857491af50fbb1922ecfd4c034ef76/src/auditwheel/policy/external_references.py#L11) could be the culprit
0.0
d270db8188386891fd1a653a6737ce5553de568c
[ "tests/unit/test_policy.py::TestLddTreeExternalReferences::test_filter_libs" ]
[ "tests/unit/test_policy.py::test_32bits_arch_name[armv6l-armv6l]", "tests/unit/test_policy.py::test_32bits_arch_name[armv7l-armv7l]", "tests/unit/test_policy.py::test_32bits_arch_name[armv8l-armv7l]", "tests/unit/test_policy.py::test_32bits_arch_name[aarch64-armv7l]", "tests/unit/test_policy.py::test_32bits_arch_name[i686-i686]", "tests/unit/test_policy.py::test_32bits_arch_name[x86_64-i686]", "tests/unit/test_policy.py::test_64bits_arch_name[armv8l-aarch64]", "tests/unit/test_policy.py::test_64bits_arch_name[aarch64-aarch64]", "tests/unit/test_policy.py::test_64bits_arch_name[ppc64le-ppc64le]", "tests/unit/test_policy.py::test_64bits_arch_name[i686-x86_64]", "tests/unit/test_policy.py::test_64bits_arch_name[x86_64-x86_64]", "tests/unit/test_policy.py::test_replacement_platform[linux_aarch64-expected0]", "tests/unit/test_policy.py::test_replacement_platform[manylinux1_ppc64le-expected1]", "tests/unit/test_policy.py::test_replacement_platform[manylinux2014_x86_64-expected2]", "tests/unit/test_policy.py::test_replacement_platform[manylinux_2_24_x86_64-expected3]", "tests/unit/test_policy.py::test_pep600_compliance", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority_missing", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_priority_duplicate", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name_missing", "tests/unit/test_policy.py::TestPolicyAccess::test_get_by_name_duplicate" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-04-25 17:30:15+00:00
mit
4,962
pypa__build-177
diff --git a/src/build/__init__.py b/src/build/__init__.py index 6a0a32f..fcdb925 100644 --- a/src/build/__init__.py +++ b/src/build/__init__.py @@ -133,26 +133,31 @@ class ProjectBuilder(object): try: with open(spec_file) as f: - self._spec = toml.load(f) + spec = toml.load(f) except FileNotFoundError: - self._spec = {} + spec = {} except PermissionError as e: raise BuildException("{}: '{}' ".format(e.strerror, e.filename)) except toml.decoder.TomlDecodeError as e: - raise BuildException('Failed to parse pyproject.toml: {} '.format(e)) - - _find_typo(self._spec, 'build-system') - self._build_system = self._spec.get('build-system', _DEFAULT_BACKEND) - - if 'build-backend' not in self._build_system: - _find_typo(self._build_system, 'build-backend') - _find_typo(self._build_system, 'requires') - self._build_system['build-backend'] = _DEFAULT_BACKEND['build-backend'] - self._build_system['requires'] = self._build_system.get('requires', []) + _DEFAULT_BACKEND['requires'] - - if 'requires' not in self._build_system: - raise BuildException("Missing 'build-system.requires' in pyproject.toml") - + raise BuildException('Failed to parse {}: {} '.format(spec_file, e)) + + build_system = spec.get('build-system') + # if pyproject.toml is missing (per PEP 517) or [build-system] is missing (pep PEP 518), + # use default values. + if build_system is None: + _find_typo(spec, 'build-system') + build_system = _DEFAULT_BACKEND + # if [build-system] is present, it must have a ``requires`` field (per PEP 518). + elif 'requires' not in build_system: + _find_typo(build_system, 'requires') + raise BuildException("Missing 'build-system.requires' in {}".format(spec_file)) + # if ``build-backend`` is missing, inject the legacy setuptools backend + # but leave ``requires`` alone to emulate pip. + elif 'build-backend' not in build_system: + _find_typo(build_system, 'build-backend') + build_system['build-backend'] = _DEFAULT_BACKEND['build-backend'] + + self._build_system = build_system self._backend = self._build_system['build-backend'] self._hook = pep517.wrappers.Pep517HookCaller(
pypa/build
a1ef3b82ab8db4d889bf4e52c451a3308bb1eb6f
diff --git a/tests/conftest.py b/tests/conftest.py index c06d26a..fe76ba6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -118,6 +118,11 @@ def test_no_requires_path(packages_path): return os.path.join(packages_path, 'test-no-requires') [email protected] +def test_optional_hooks_path(packages_path): + return os.path.join(packages_path, 'test-optional-hooks') + + @pytest.fixture def test_typo(packages_path): return os.path.join(packages_path, 'test-typo') diff --git a/tests/packages/test-optional-hooks/hookless_backend.py b/tests/packages/test-optional-hooks/hookless_backend.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/packages/test-optional-hooks/pyproject.toml b/tests/packages/test-optional-hooks/pyproject.toml new file mode 100644 index 0000000..2796891 --- /dev/null +++ b/tests/packages/test-optional-hooks/pyproject.toml @@ -0,0 +1,4 @@ +[build-system] +requires = [] +build-backend = 'hookless_backend' +backend-path = ['.'] diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index 1d38efa..7cbd19f 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -148,6 +148,13 @@ def test_get_dependencies_missing_backend(packages_path, distribution): builder.get_dependencies(distribution) [email protected]('distribution', ['wheel', 'sdist']) +def test_get_dependencies_missing_optional_hooks(test_optional_hooks_path, distribution): + builder = build.ProjectBuilder(test_optional_hooks_path) + + assert builder.get_dependencies(distribution) == set() + + @pytest.mark.parametrize('distribution', ['wheel', 'sdist']) def test_build_missing_backend(packages_path, distribution, tmpdir): bad_backend_path = os.path.join(packages_path, 'test-bad-backend') @@ -238,7 +245,7 @@ def test_missing_backend(mocker, test_no_backend_path): builder = build.ProjectBuilder(test_no_backend_path) - assert builder._build_system == DEFAULT_BACKEND + assert builder._build_system == {'requires': [], 'build-backend': DEFAULT_BACKEND['build-backend']} def test_missing_requires(mocker, test_no_requires_path):
Double requirement error if build-backend missing I have the following pyproject.toml: ```toml [build-system] requires = ["wheel", "setuptools>=42", "setuptools_scm[toml]>=3.4"] ``` Build fails with: ``` Looking in links: /tmp/tmpu9cyr1oc Processing /tmp/tmpu9cyr1oc/setuptools-47.1.0-py3-none-any.whl Processing /tmp/tmpu9cyr1oc/pip-20.1.1-py2.py3-none-any.whl Installing collected packages: setuptools, pip Successfully installed pip setuptools ERROR: Double requirement given: setuptools>=42 (from -r /tmp/build-reqs-akrau6fv.txt (line 2)) (already in setuptools>=40.8.0 (from -r /tmp/build-reqs-akrau6fv.txt (line 1)), name='setuptools') WARNING: You are using pip version 20.1.1; however, version 20.2.3 is available. You should consider upgrading via the '/opt/hostedtoolcache/Python/3.8.5/x64/bin/python -m pip install --upgrade pip' command. Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/build/__main__.py", line 176, in <module> main(sys.argv[1:], 'python -m build') File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/build/__main__.py", line 168, in main build(args.srcdir, args.outdir, distributions, config_settings, not args.no_isolation, args.skip_dependencies) File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/build/__main__.py", line 80, in build _build_in_isolated_env(builder, outdir, distributions) File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/build/__main__.py", line 45, in _build_in_isolated_env env.install(builder.build_dependencies) File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/build/env.py", line 176, in install subprocess.check_call(cmd) File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/opt/hostedtoolcache/Python/3.8.5/x64/bin/python', '-m', 'pip', 'install', '--prefix', '/tmp/build-env-6o04yjl_', '-r', '/tmp/build-reqs-akrau6fv.txt']' returned non-zero exit status 1. ``` However, there is a missing line - and adding it fixed the problem: ```toml build-backend = "setuptools.build_meta" ``` a) Is it possible to improve the error message and b) should this error be happening anyway? It seems to be trying to recursively produce all the requirements manually and put then into a requirements.txt-like file, which then collide?
0.0
a1ef3b82ab8db4d889bf4e52c451a3308bb1eb6f
[ "tests/test_projectbuilder.py::test_missing_backend" ]
[ "tests/test_projectbuilder.py::test_check_version[something-True-False]", "tests/test_projectbuilder.py::test_check_version[something_else-False-False]", "tests/test_projectbuilder.py::test_check_version[something[extra]-False-False]", "tests/test_projectbuilder.py::test_check_version[something[some_extra]-True-True]", "tests/test_projectbuilder.py::test_check_version[something_else;", "tests/test_projectbuilder.py::test_check_version[something", "tests/test_projectbuilder.py::test_check_version[something[some_extra]", "tests/test_projectbuilder.py::test_python_executable[something]", "tests/test_projectbuilder.py::test_python_executable[something_else]", "tests/test_projectbuilder.py::test_get_dependencies_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_dependencies_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_dependencies_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_dependencies_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_working_directory", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_relative_outdir", "tests/test_projectbuilder.py::test_not_dir_outdir" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-11-01 02:33:30+00:00
mit
4,963
pypa__build-218
diff --git a/src/build/__init__.py b/src/build/__init__.py index 1abf0eb..f6513c4 100644 --- a/src/build/__init__.py +++ b/src/build/__init__.py @@ -116,17 +116,15 @@ def _working_directory(path): # type: (str) -> Iterator[None] class ProjectBuilder(object): - def __init__(self, srcdir, config_settings=None, python_executable=sys.executable): - # type: (str, Optional[ConfigSettings], Union[bytes, Text]) -> None + def __init__(self, srcdir, python_executable=sys.executable): + # type: (str, Union[bytes, Text]) -> None """ Create a project builder. :param srcdir: the source directory - :param config_settings: config settings for the build backend :param python_executable: the python executable where the backend lives """ self.srcdir = os.path.abspath(srcdir) # type: str - self.config_settings = config_settings if config_settings else {} # type: ConfigSettings spec_file = os.path.join(srcdir, 'pyproject.toml') @@ -188,42 +186,46 @@ class ProjectBuilder(object): """ return set(self._build_system['requires']) - def get_dependencies(self, distribution): # type: (str) -> Set[str] + def get_dependencies(self, distribution, config_settings=None): # type: (str, Optional[ConfigSettings]) -> Set[str] """ Return the dependencies defined by the backend in addition to :attr:`build_dependencies` for a given distribution. :param distribution: Distribution to get the dependencies of (``sdist`` or ``wheel``) + :param config_settings: Config settings for the build backend """ get_requires = getattr(self._hook, 'get_requires_for_build_{}'.format(distribution)) try: with _working_directory(self.srcdir): - return set(get_requires(self.config_settings)) + return set(get_requires(config_settings)) except pep517.wrappers.BackendUnavailable: raise BuildException("Backend '{}' is not available.".format(self._backend)) except Exception as e: # noqa: E722 raise BuildBackendException('Backend operation failed: {}'.format(e)) - def check_dependencies(self, distribution): # type: (str) -> Set[Tuple[str, ...]] + def check_dependencies(self, distribution, config_settings=None): + # type: (str, Optional[ConfigSettings]) -> Set[Tuple[str, ...]] """ Return the dependencies which are not satisfied from the combined set of :attr:`build_dependencies` and :meth:`get_dependencies` for a given distribution. :param distribution: Distribution to check (``sdist`` or ``wheel``) + :param config_settings: Config settings for the build backend :returns: Set of variable-length unmet dependency tuples """ - dependencies = self.get_dependencies(distribution).union(self.build_dependencies) + dependencies = self.get_dependencies(distribution, config_settings).union(self.build_dependencies) return {u for d in dependencies for u in check_dependency(d)} - def build(self, distribution, outdir): # type: (str, str) -> str + def build(self, distribution, outdir, config_settings=None): # type: (str, str, Optional[ConfigSettings]) -> str """ Build a distribution. :param distribution: Distribution to build (``sdist`` or ``wheel``) :param outdir: Output directory + :param config_settings: Config settings for the build backend :returns: The full path to the built distribution """ build = getattr(self._hook, 'build_{}'.format(distribution)) @@ -237,7 +239,7 @@ class ProjectBuilder(object): try: with _working_directory(self.srcdir): - basename = build(outdir, self.config_settings) # type: str + basename = build(outdir, config_settings) # type: str return os.path.join(outdir, basename) except pep517.wrappers.BackendUnavailable: raise BuildException("Backend '{}' is not available.".format(self._backend)) diff --git a/src/build/__main__.py b/src/build/__main__.py index 4f6ef61..b08d84e 100644 --- a/src/build/__main__.py +++ b/src/build/__main__.py @@ -46,8 +46,8 @@ def _format_dep_chain(dep_chain): # type: (Sequence[str]) -> str return ' -> '.join(dep.partition(';')[0].strip() for dep in dep_chain) -def _build_in_isolated_env(builder, outdir, distributions): - # type: (ProjectBuilder, str, List[str]) -> None +def _build_in_isolated_env(builder, outdir, distributions, config_settings): + # type: (ProjectBuilder, str, List[str], ConfigSettings) -> None for distribution in distributions: with IsolatedEnvBuilder() as env: builder.python_executable = env.executable @@ -55,11 +55,11 @@ def _build_in_isolated_env(builder, outdir, distributions): env.install(builder.build_dependencies) # then get the extra required dependencies from the backend (which was installed in the call above :P) env.install(builder.get_dependencies(distribution)) - builder.build(distribution, outdir) + builder.build(distribution, outdir, config_settings) -def _build_in_current_env(builder, outdir, distributions, skip_dependencies=False): - # type: (ProjectBuilder, str, List[str], bool) -> None +def _build_in_current_env(builder, outdir, distributions, config_settings, skip_dependencies=False): + # type: (ProjectBuilder, str, List[str], ConfigSettings, bool) -> None for dist in distributions: if not skip_dependencies: missing = builder.check_dependencies(dist) @@ -69,7 +69,7 @@ def _build_in_current_env(builder, outdir, distributions, skip_dependencies=Fals + ''.join('\n\t' + dep for deps in missing for dep in (deps[0], _format_dep_chain(deps[1:])) if dep) ) - builder.build(dist, outdir) + builder.build(dist, outdir, config_settings) def build_package(srcdir, outdir, distributions, config_settings=None, isolation=True, skip_dependencies=False): @@ -88,11 +88,11 @@ def build_package(srcdir, outdir, distributions, config_settings=None, isolation config_settings = {} try: - builder = ProjectBuilder(srcdir, config_settings) + builder = ProjectBuilder(srcdir) if isolation: - _build_in_isolated_env(builder, outdir, distributions) + _build_in_isolated_env(builder, outdir, distributions, config_settings) else: - _build_in_current_env(builder, outdir, distributions, skip_dependencies) + _build_in_current_env(builder, outdir, distributions, config_settings, skip_dependencies) except BuildException as e: _error(str(e)) except BuildBackendException as e:
pypa/build
d8a30a316e5c66cd418d7789bfca7c4aa04de687
diff --git a/tests/test_main.py b/tests/test_main.py index 445a2aa..840ec30 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -118,7 +118,7 @@ def test_build_isolated(mocker, test_flit_path): required_cmd.assert_called_with('sdist') install.assert_any_call(['dep1', 'dep2']) - build_cmd.assert_called_with('sdist', '.') + build_cmd.assert_called_with('sdist', '.', {}) def test_build_no_isolation_check_deps_empty(mocker, test_flit_path): @@ -128,7 +128,7 @@ def test_build_no_isolation_check_deps_empty(mocker, test_flit_path): build.__main__.build_package(test_flit_path, '.', ['sdist'], isolation=False) - build_cmd.assert_called_with('sdist', '.') + build_cmd.assert_called_with('sdist', '.', {}) @pytest.mark.parametrize( @@ -145,7 +145,7 @@ def test_build_no_isolation_with_check_deps(mocker, test_flit_path, missing_deps build.__main__.build_package(test_flit_path, '.', ['sdist'], isolation=False) - build_cmd.assert_called_with('sdist', '.') + build_cmd.assert_called_with('sdist', '.', {}) error.assert_called_with('Missing dependencies:' + output) diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index f6c6bf4..43c6349 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -256,11 +256,11 @@ def test_build(mocker, test_flit_path, tmp_dir): builder._hook.build_wheel.side_effect = ['dist.whl', Exception] assert builder.build('sdist', tmp_dir) == os.path.join(tmp_dir, 'dist.tar.gz') - builder._hook.build_sdist.assert_called_with(tmp_dir, {}) + builder._hook.build_sdist.assert_called_with(tmp_dir, None) build._working_directory.assert_called_with(test_flit_path) assert builder.build('wheel', tmp_dir) == os.path.join(tmp_dir, 'dist.whl') - builder._hook.build_wheel.assert_called_with(tmp_dir, {}) + builder._hook.build_wheel.assert_called_with(tmp_dir, None) build._working_directory.assert_called_with(test_flit_path) with pytest.raises(build.BuildBackendException): @@ -322,7 +322,7 @@ def test_relative_outdir(mocker, tmp_dir, test_flit_path): builder.build('sdist', '.') - builder._hook.build_sdist.assert_called_with(os.path.abspath('.'), {}) + builder._hook.build_sdist.assert_called_with(os.path.abspath('.'), None) def test_not_dir_outdir(mocker, tmp_dir, test_flit_path):
Varying `config_settings` between hook calls Configuration settings should be allowed to vary between distributions, hooks and hook calls, e.g. an option which is valid for a wheel might not be valid for an sdist or a different hook. The `config_settings` parameter can either be removed from the constructor or hook wrappers can have their own `config_settings` parameter to overwrite the init value.
0.0
d8a30a316e5c66cd418d7789bfca7c4aa04de687
[ "tests/test_main.py::test_build_isolated", "tests/test_main.py::test_build_no_isolation_check_deps_empty", "tests/test_main.py::test_build_no_isolation_with_check_deps[missing_deps0-\\n\\tfoo]", "tests/test_main.py::test_build_no_isolation_with_check_deps[missing_deps1-\\n\\tfoo\\n\\tbar\\n\\tbaz", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_relative_outdir" ]
[ "tests/test_main.py::test_parse_args[cli_args0-build_args0]", "tests/test_main.py::test_parse_args[cli_args1-build_args1]", "tests/test_main.py::test_parse_args[cli_args2-build_args2]", "tests/test_main.py::test_parse_args[cli_args3-build_args3]", "tests/test_main.py::test_parse_args[cli_args4-build_args4]", "tests/test_main.py::test_parse_args[cli_args5-build_args5]", "tests/test_main.py::test_parse_args[cli_args6-build_args6]", "tests/test_main.py::test_parse_args[cli_args7-build_args7]", "tests/test_main.py::test_parse_args[cli_args8-build_args8]", "tests/test_main.py::test_parse_args[cli_args9-build_args9]", "tests/test_main.py::test_parse_args[cli_args10-build_args10]", "tests/test_main.py::test_prog", "tests/test_main.py::test_version", "tests/test_main.py::test_build_raises_build_exception", "tests/test_main.py::test_build_raises_build_backend_exception", "tests/test_projectbuilder.py::test_check_dependency[extras_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep-expected1]", "tests/test_projectbuilder.py::test_check_dependency[requireless_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[undefined_extra]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_unmet_deps]-expected5]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[recursive_extra_with_unmet_deps]-expected6]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_met_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep;", "tests/test_projectbuilder.py::test_check_dependency[extras_dep", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]", "tests/test_projectbuilder.py::test_check_dependency[prerelease_dep", "tests/test_projectbuilder.py::test_python_executable[something]", "tests/test_projectbuilder.py::test_python_executable[something_else]", "tests/test_projectbuilder.py::test_get_dependencies_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_dependencies_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_dependencies_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_dependencies_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_working_directory", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_not_dir_outdir" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-29 15:52:26+00:00
mit
4,964
pypa__build-229
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 1c83b16..c6a2b67 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,16 @@ Changelog +++++++++ +Unreleased +========== + +- Upgrade pip based on venv pip version, avoids error from unrecognised pip flag on Debian Python 3.6.5-3.8 (`PR #229`_, Fixes `#228`_) + +.. _PR #229: https://github.com/pypa/build/pull/229 +.. _#228: https://github.com/pypa/build/issues/228 + + + 0.2.1 (09-02-2021) ================== diff --git a/src/build/env.py b/src/build/env.py index c0bdc2c..8d79527 100644 --- a/src/build/env.py +++ b/src/build/env.py @@ -13,9 +13,16 @@ import tempfile from types import TracebackType from typing import Iterable, Optional, Tuple, Type +import packaging.version + from ._compat import abstractproperty, add_metaclass +if sys.version_info < (3, 8): + import importlib_metadata as metadata +else: + from importlib import metadata + try: import virtualenv except ImportError: # pragma: no cover @@ -169,20 +176,28 @@ def _create_isolated_env_venv(path): # type: (str) -> Tuple[str, str] import venv venv.EnvBuilder(with_pip=True).create(path) - executable, script_dir = _find_executable_and_scripts(path) - # avoid the setuptools from ensurepip to break the isolation - if sys.version_info < (3, 6, 6): # python 3.5 up to 3.6.5 come with pip 9 that's too old, for new standards + executable, script_dir, purelib = _find_executable_and_scripts(path) + + # Get the version of pip in the environment + pip_distribution = next(iter(metadata.distributions(name='pip', path=[purelib]))) + pip_version = packaging.version.Version(pip_distribution.version) + + # Currently upgrade if Pip 19.1+ not available, since Pip 19 is the first + # one to officially support PEP 517, and 19.1 supports manylinux1. + if pip_version < packaging.version.Version('19.1'): subprocess.check_call([executable, '-m', 'pip', 'install', '-U', 'pip']) + + # Avoid the setuptools from ensurepip to break the isolation subprocess.check_call([executable, '-m', 'pip', 'uninstall', 'setuptools', '-y']) return executable, script_dir -def _find_executable_and_scripts(path): # type: (str) -> Tuple[str, str] +def _find_executable_and_scripts(path): # type: (str) -> Tuple[str, str, str] """ Detect the Python executable and script folder of a virtual environment. :param path: The location of the virtual environment - :return: The Python executable and script folder + :return: The Python executable, script folder, and purelib folder """ config_vars = sysconfig.get_config_vars().copy() # globally cached, copy before altering it config_vars['base'] = path @@ -195,7 +210,11 @@ def _find_executable_and_scripts(path): # type: (str) -> Tuple[str, str] executable = os.path.join(env_scripts, exe) if not os.path.exists(executable): raise RuntimeError('Virtual environment creation failed, executable {} missing'.format(executable)) - return executable, env_scripts + + purelib = sysconfig.get_path('purelib', vars=config_vars) + if not purelib: + raise RuntimeError("Couldn't get environment purelib folder") + return executable, env_scripts, purelib __all__ = (
pypa/build
7d8f9150ae56c6bc43dc34bcefa30b0c6d03246a
diff --git a/tests/test_env.py b/tests/test_env.py index f677659..04f18ab 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -8,6 +8,8 @@ import sysconfig import pytest +from packaging.version import Version + import build.env @@ -58,6 +60,25 @@ def test_fail_to_get_script_path(mocker): assert get_path.call_count == 1 [email protected](sys.version_info[0] == 2, reason='venv module used on Python 3 only') [email protected](IS_PYPY3, reason='PyPy3 uses get path to create and provision venv') +def test_fail_to_get_purepath(mocker): + sysconfig_get_path = sysconfig.get_path + + def mock_sysconfig_get_path(path, *args, **kwargs): + if path == 'purelib': + return '' + else: + return sysconfig_get_path(path, *args, **kwargs) + + mocker.patch('sysconfig.get_path', side_effect=mock_sysconfig_get_path) + + with pytest.raises(RuntimeError, match="Couldn't get environment purelib folder"): + env = build.env.IsolatedEnvBuilder() + with env: + pass + + @pytest.mark.skipif(sys.version_info[0] == 2, reason='venv module used on Python 3 only') @pytest.mark.skipif(IS_PYPY3, reason='PyPy3 uses get path to create and provision venv') def test_executable_missing_post_creation(mocker): @@ -100,7 +121,9 @@ def test_isolated_env_has_install_still_abstract(): @pytest.mark.isolated [email protected](sys.version_info > (3, 6, 5), reason='inapplicable') -def test_default_pip_is_upgraded_on_python_3_6_5_and_below(): +def test_default_pip_is_never_too_old(): with build.env.IsolatedEnvBuilder() as env: - assert not subprocess.check_output([env.executable, '-m', 'pip', '-V']).startswith(b'pip 9.0') + version = subprocess.check_output( + [env.executable, '-c', 'import pip; print(pip.__version__)'], universal_newlines=True + ).strip() + assert Version(version) >= Version('19.1')
pipx run --spec build still broken I'm still getting the same error as in #226: ``` Run pipx run --spec build==0.2.1 pyproject-build --sdist Uninstalling setuptools-39.0.1: Successfully uninstalled setuptools-39.0.1 25l25h Usage: /tmp/build-env-5zipwlv4/bin/python -m pip install [options] <requirement specifier> [package-index-options] ... /tmp/build-env-5zipwlv4/bin/python -m pip install [options] -r <requirements file> [package-index-options] ... /tmp/build-env-5zipwlv4/bin/python -m pip install [options] [-e] <vcs project url> ... /tmp/build-env-5zipwlv4/bin/python -m pip install [options] [-e] <local project path> ... /tmp/build-env-5zipwlv4/bin/python -m pip install [options] <archive url/path> ... no such option: --no-warn-script-location Traceback (most recent call last): File "/opt/pipx/.cache/14c4e297c8a7e45/bin/pyproject-build", line 8, in <module> sys.exit(entrypoint()) File "/opt/pipx/.cache/14c4e297c8a7e45/lib/python3.6/site-packages/build/__main__.py", line 210, in entrypoint main(sys.argv[1:]) File "/opt/pipx/.cache/14c4e297c8a7e45/lib/python3.6/site-packages/build/__main__.py", line 206, in main build_package(args.srcdir, outdir, distributions, config_settings, not args.no_isolation, args.skip_dependencies) File "/opt/pipx/.cache/14c4e297c8a7e45/lib/python3.6/site-packages/build/__main__.py", line 94, in build_package _build_in_isolated_env(builder, outdir, distributions, config_settings) File "/opt/pipx/.cache/14c4e297c8a7e45/lib/python3.6/site-packages/build/__main__.py", line 56, in _build_in_isolated_env env.install(builder.build_dependencies) File "/opt/pipx/.cache/14c4e297c8a7e45/lib/python3.6/site-packages/build/env.py", line 143, in install subprocess.check_call(cmd) File "/usr/lib/python3.6/subprocess.py", line 311, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/tmp/build-env-5zipwlv4/bin/python', '-Im', 'pip', 'install', '--no-warn-script-location', '-r', '/tmp/build-reqs-pgst_mml.txt']' returned non-zero exit status 2. ``` See here: https://github.com/scikit-hep/boost-histogram/runs/1868826515?check_suite_focus=true I can reproduce it locally with these four lines: ```bash docker run --rm -it ubuntu:18.04 apt-get update && apt-get install -y python3-pip python3-venv python3 -m pip install pipx pipx run --spec build pyproject-build ```
0.0
7d8f9150ae56c6bc43dc34bcefa30b0c6d03246a
[ "tests/test_env.py::test_fail_to_get_purepath" ]
[ "tests/test_env.py::test_isolation", "tests/test_env.py::test_isolated_environment_install", "tests/test_env.py::test_fail_to_get_script_path", "tests/test_env.py::test_executable_missing_post_creation", "tests/test_env.py::test_isolated_env_abstract", "tests/test_env.py::test_isolated_env_has_executable_still_abstract", "tests/test_env.py::test_isolated_env_has_install_still_abstract", "tests/test_env.py::test_default_pip_is_never_too_old" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-10 05:35:29+00:00
mit
4,965
pypa__build-290
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 585e8d4..2f9858e 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,15 +10,18 @@ Unreleased - Set and test minimum versions of build's runtime dependencies (`PR #267`_, Fixes `#263`_) - Use symlinks on creating venv's when available (`PR #274`_, Fixes `#271`_) - Error sooner if pip upgrade is required and fails (`PR #288`_, Fixes `#256`_) +- Add a ``runner`` argument to ``ProjectBuilder`` (`PR #290`_, Fixes `#289`_) .. _PR #260: https://github.com/pypa/build/pull/260 .. _PR #267: https://github.com/pypa/build/pull/267 .. _PR #274: https://github.com/pypa/build/pull/274 .. _PR #288: https://github.com/pypa/build/pull/288 +.. _PR #290: https://github.com/pypa/build/pull/290 .. _#256: https://github.com/pypa/build/issues/256 .. _#259: https://github.com/pypa/build/issues/259 .. _#263: https://github.com/pypa/build/issues/263 .. _#271: https://github.com/pypa/build/issues/271 +.. _#289: https://github.com/pypa/build/issues/289 Breaking Changes ---------------- diff --git a/src/build/__init__.py b/src/build/__init__.py index 10e5c9d..4345623 100644 --- a/src/build/__init__.py +++ b/src/build/__init__.py @@ -20,6 +20,8 @@ import toml import toml.decoder +RUNNER_TYPE = Callable[[Sequence[str], Optional[Union[bytes, Text]], Optional[Dict[str, str]]], None] + if sys.version_info < (3,): FileNotFoundError = IOError PermissionError = OSError @@ -139,12 +141,31 @@ class ProjectBuilder(object): The PEP 517 consumer API. """ - def __init__(self, srcdir, python_executable=sys.executable, scripts_dir=None): - # type: (str, Union[bytes, Text], Optional[Union[bytes, Text]]) -> None + def __init__( + self, + srcdir, # type: str + python_executable=sys.executable, # type: Union[bytes, Text] + scripts_dir=None, # type: Optional[Union[bytes, Text]] + runner=pep517.wrappers.default_subprocess_runner, # type: RUNNER_TYPE + ): + # type: (...) -> None """ :param srcdir: The source directory :param scripts_dir: The location of the scripts dir (defaults to the folder where the python executable lives) :param python_executable: The python executable where the backend lives + :param runner: An alternative runner for backend subprocesses + + The 'runner', if provided, must accept the following arguments: + + - cmd: a list of strings representing the command and arguments to + execute, as would be passed to e.g. 'subprocess.check_call'. + - cwd: a string representing the working directory that must be + used for the subprocess. Corresponds to the provided srcdir. + - extra_environ: a dict mapping environment variable names to values + which must be set for the subprocess execution. + + The default runner simply calls the backend hooks in a subprocess, writing backend output + to stdout/stderr. """ self.srcdir = os.path.abspath(srcdir) # type: str _validate_source_directory(srcdir) @@ -180,6 +201,7 @@ class ProjectBuilder(object): self._build_system = build_system self._backend = self._build_system['build-backend'] self._scripts_dir = scripts_dir + self._hook_runner = runner self._hook = pep517.wrappers.Pep517HookCaller( self.srcdir, self._backend, @@ -198,7 +220,7 @@ class ProjectBuilder(object): paths.update((i, None) for i in os.environ['PATH'].split(os.pathsep)) extra_environ = {} if extra_environ is None else extra_environ extra_environ['PATH'] = os.pathsep.join(paths) - pep517.default_subprocess_runner(cmd, cwd, extra_environ) + self._hook_runner(cmd, cwd, extra_environ) @property def python_executable(self): # type: () -> Union[bytes, Text]
pypa/build
8d93fc48c68236b37621353a5800eeb7cd078f54
diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index 1485b74..9c1f8d8 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -460,3 +460,12 @@ def test_prepare_not_dir_outdir(mocker, tmp_dir, test_flit_path): f.write('Not a directory') with pytest.raises(build.BuildException, match='Build path .* exists and is not a directory'): builder.prepare('wheel', out) + + +def test_runner_user_specified(tmp_dir, test_flit_path): + def dummy_runner(cmd, cwd=None, env=None): + raise RuntimeError('Runner was called') + + builder = build.ProjectBuilder(test_flit_path, runner=dummy_runner) + with pytest.raises(build.BuildBackendException, match='Runner was called'): + builder.build('wheel', tmp_dir)
API: Add a method to customise handling of build output When calling the API (`builder.build()`) the backend output is sent directly to the terminal. There's no clear way to capture that output, either to redirect it to a log, or to save it for manual processing. This makes it very difficult to use the API without the caller's output being extremely cluttered. Related: #188 For now, in my code, I am using ```python build.pep517.default_subprocess_runner = build.pep517.quiet_subprocess_runner ``` to suppress output. Yes, I *know* this is an immense hack. Would a PR to allow use of a pep517 custom runner object at https://github.com/pypa/build/blob/main/src/build/__init__.py#L201 be accepted?
0.0
8d93fc48c68236b37621353a5800eeb7cd078f54
[ "tests/test_projectbuilder.py::test_runner_user_specified" ]
[ "tests/test_projectbuilder.py::test_check_dependency[extras_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep-expected1]", "tests/test_projectbuilder.py::test_check_dependency[requireless_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[undefined_extra]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_unmet_deps]-expected5]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[recursive_extra_with_unmet_deps]-expected6]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_met_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep;", "tests/test_projectbuilder.py::test_check_dependency[extras_dep", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]", "tests/test_projectbuilder.py::test_check_dependency[prerelease_dep", "tests/test_projectbuilder.py::test_bad_project", "tests/test_projectbuilder.py::test_python_executable[something]", "tests/test_projectbuilder.py::test_python_executable[something_else]", "tests/test_projectbuilder.py::test_get_dependencies_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_dependencies_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_dependencies_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_dependencies_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_working_directory", "tests/test_projectbuilder.py::test_working_directory_exc_is_not_transformed", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_relative_outdir", "tests/test_projectbuilder.py::test_build_not_dir_outdir", "tests/test_projectbuilder.py::test_build_with_dep_on_console_script", "tests/test_projectbuilder.py::test_prepare", "tests/test_projectbuilder.py::test_prepare_no_hook", "tests/test_projectbuilder.py::test_prepare_error", "tests/test_projectbuilder.py::test_prepare_not_dir_outdir" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-05-01 11:57:30+00:00
mit
4,966
pypa__build-318
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index dd43f31..9790e90 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,17 @@ Changelog +++++++++ + +Unreleased +========== + +- Fix invoking the backend on an inexistent output directory with multiple levels (`PR #318`_, Fixes `#316`_) + +.. _PR #318: https://github.com/pypa/build/pull/318 +.. _#316: https://github.com/pypa/build/issues/316 + + + 0.5.0 (19-06-2021) ================== diff --git a/src/build/__init__.py b/src/build/__init__.py index 11a045d..75ee7da 100644 --- a/src/build/__init__.py +++ b/src/build/__init__.py @@ -383,7 +383,7 @@ class ProjectBuilder(object): if not os.path.isdir(outdir): raise BuildException("Build path '{}' exists and is not a directory".format(outdir)) else: - os.mkdir(outdir) + os.makedirs(outdir) with self._handle_backend(hook_name): basename = callback(outdir, config_settings, **kwargs) # type: str
pypa/build
4492dec726cdfd159f0850d68c98f82496b28d79
diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index e910765..a825410 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -467,6 +467,28 @@ def test_prepare_not_dir_outdir(mocker, tmp_dir, test_flit_path): builder.prepare('wheel', out) +def test_no_outdir_single(mocker, tmp_dir, test_flit_path): + mocker.patch('pep517.wrappers.Pep517HookCaller.prepare_metadata_for_build_wheel', return_value='') + + builder = build.ProjectBuilder(test_flit_path) + + out = os.path.join(tmp_dir, 'out') + builder.prepare('wheel', out) + + assert os.path.isdir(out) + + +def test_no_outdir_multiple(mocker, tmp_dir, test_flit_path): + mocker.patch('pep517.wrappers.Pep517HookCaller.prepare_metadata_for_build_wheel', return_value='') + + builder = build.ProjectBuilder(test_flit_path) + + out = os.path.join(tmp_dir, 'does', 'not', 'exist') + builder.prepare('wheel', out) + + assert os.path.isdir(out) + + def test_runner_user_specified(tmp_dir, test_flit_path): def dummy_runner(cmd, cwd=None, env=None): raise RuntimeError('Runner was called')
0.4.0: --outdir fails when parent directory does not exist ```console + cd rich-10.4.0 + /usr/bin/python3 -m build --no-isolation --outdir build/lib Traceback (most recent call last): File "/usr/lib64/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib64/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/usr/lib/python3.8/site-packages/build/__main__.py", line 236, in <module> main(sys.argv[1:], 'python -m build') File "/usr/lib/python3.8/site-packages/build/__main__.py", line 228, in main build_package(args.srcdir, outdir, distributions, config_settings, not args.no_isolation, args.skip_dependency_check) File "/usr/lib/python3.8/site-packages/build/__main__.py", line 107, in build_package _build_in_current_env(builder, outdir, distributions, config_settings, skip_dependency_check) File "/usr/lib/python3.8/site-packages/build/__main__.py", line 84, in _build_in_current_env builder.build(dist, outdir, config_settings) File "/usr/lib/python3.8/site-packages/build/__init__.py", line 330, in build return self._call_backend(build, output_directory, config_settings, **kwargs) File "/usr/lib/python3.8/site-packages/build/__init__.py", line 340, in _call_backend os.mkdir(outdir) FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/rich-10.4.0/build/lib' ```
0.0
4492dec726cdfd159f0850d68c98f82496b28d79
[ "tests/test_projectbuilder.py::test_no_outdir_multiple" ]
[ "tests/test_projectbuilder.py::test_check_dependency[extras_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep-expected1]", "tests/test_projectbuilder.py::test_check_dependency[requireless_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[undefined_extra]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_unmet_deps]-expected5]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[recursive_extra_with_unmet_deps]-expected6]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_met_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep;", "tests/test_projectbuilder.py::test_check_dependency[extras_dep", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]", "tests/test_projectbuilder.py::test_check_dependency[prerelease_dep", "tests/test_projectbuilder.py::test_bad_project", "tests/test_projectbuilder.py::test_python_executable[something]", "tests/test_projectbuilder.py::test_python_executable[something_else]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_working_directory", "tests/test_projectbuilder.py::test_working_directory_exc_is_not_transformed", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_relative_outdir", "tests/test_projectbuilder.py::test_build_not_dir_outdir", "tests/test_projectbuilder.py::test_build_with_dep_on_console_script", "tests/test_projectbuilder.py::test_prepare", "tests/test_projectbuilder.py::test_prepare_no_hook", "tests/test_projectbuilder.py::test_prepare_error", "tests/test_projectbuilder.py::test_prepare_not_dir_outdir", "tests/test_projectbuilder.py::test_no_outdir_single", "tests/test_projectbuilder.py::test_runner_user_specified", "tests/test_projectbuilder.py::test_metadata_path_legacy", "tests/test_projectbuilder.py::test_metadata_invalid_wheel" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-06-19 17:28:48+00:00
mit
4,967
pypa__build-339
diff --git a/src/build/__init__.py b/src/build/__init__.py index 4b0b0e7..beb3469 100644 --- a/src/build/__init__.py +++ b/src/build/__init__.py @@ -441,7 +441,10 @@ class ProjectBuilder: :param msg: Message to output """ - _logger.log(logging.INFO, message, stacklevel=2) + if sys.version_info >= (3, 8): + _logger.log(logging.INFO, message, stacklevel=2) + else: + _logger.log(logging.INFO, message) __all__ = ( diff --git a/src/build/env.py b/src/build/env.py index c37ff8e..d9d8077 100644 --- a/src/build/env.py +++ b/src/build/env.py @@ -135,7 +135,10 @@ class IsolatedEnvBuilder: :param msg: Message to output """ - _logger.log(logging.INFO, message, stacklevel=2) + if sys.version_info >= (3, 8): + _logger.log(logging.INFO, message, stacklevel=2) + else: + _logger.log(logging.INFO, message) class _IsolatedEnvVenvPip(IsolatedEnv):
pypa/build
720d69dadc1641769be89e3630b12b207e157ca3
diff --git a/tests/test_env.py b/tests/test_env.py index 37acbca..f7be8aa 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: MIT import collections +import logging import os import platform import shutil @@ -98,6 +99,24 @@ def test_isolated_env_has_install_still_abstract(): Env() +def test_isolated_env_log(mocker, caplog, test_flit_path): + mocker.patch('build.env._subprocess') + caplog.set_level(logging.DEBUG) + + builder = build.env.IsolatedEnvBuilder() + builder.log('something') + with builder as env: + env.install(['something']) + + assert [(record.levelname, record.message) for record in caplog.records] == [ + ('INFO', 'something'), + ('INFO', 'Creating venv isolated environment...'), + ('INFO', 'Installing packages in isolated environment... (something)'), + ] + if sys.version_info >= (3, 8): # stacklevel + assert [(record.lineno) for record in caplog.records] == [107, 103, 194] + + @pytest.mark.isolated def test_default_pip_is_never_too_old(): with build.env.IsolatedEnvBuilder() as env: diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index 4d58f33..c61871e 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -3,6 +3,7 @@ import copy import importlib +import logging import os import sys import textwrap @@ -545,3 +546,28 @@ def test_toml_instead_of_tomli(mocker, mock_tomli_not_available, tmp_dir, test_f builder.build('sdist', '.') builder._hook.build_sdist.assert_called_with(os.path.abspath('.'), None) + + +def test_log(mocker, caplog, test_flit_path): + mocker.patch('pep517.wrappers.Pep517HookCaller', autospec=True) + mocker.patch('build.ProjectBuilder._call_backend', return_value='some_path') + caplog.set_level(logging.DEBUG) + + builder = build.ProjectBuilder(test_flit_path) + builder.get_requires_for_build('sdist') + builder.get_requires_for_build('wheel') + builder.prepare('wheel', '.') + builder.build('sdist', '.') + builder.build('wheel', '.') + builder.log('something') + + assert [(record.levelname, record.message) for record in caplog.records] == [ + ('INFO', 'Getting dependencies for sdist...'), + ('INFO', 'Getting dependencies for wheel...'), + ('INFO', 'Getting metadata for wheel...'), + ('INFO', 'Building sdist...'), + ('INFO', 'Building wheel...'), + ('INFO', 'something'), + ] + if sys.version_info >= (3, 8): # stacklevel + assert [(record.lineno) for record in caplog.records] == [305, 305, 338, 368, 368, 562]
v0.6 is not compatible with python 3.6 due to use of `stacklevel` in log calls # Problem V0.6 fails on python 3.6 with <details> <summary> TypeError: _log() got an unexpected keyword argument 'stacklevel' </summary> ``` python /home/jenkins/workspace/_core_dependabot_pip_build-0.6.0/project/inmanta-core/.tox/py36/lib/python3.6/site-packages/build/env.py:100: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ message = 'Creating virtualenv isolated environment...' @staticmethod def log(message: str) -> None: """ Prints message The default implementation uses the logging module but this function can be overwritten by users to have a different implementation. :param msg: Message to output """ > _logger.log(logging.INFO, message, stacklevel=2) /home/jenkins/workspace/_core_dependabot_pip_build-0.6.0/project/inmanta-core/.tox/py36/lib/python3.6/site-packages/build/env.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <Logger build.env (DEBUG)>, level = 20 msg = 'Creating virtualenv isolated environment...', args = () kwargs = {'stacklevel': 2} def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ if not isinstance(level, int): if raiseExceptions: raise TypeError("level must be an integer") else: return if self.isEnabledFor(level): > self._log(level, msg, args, **kwargs) E TypeError: _log() got an unexpected keyword argument 'stacklevel' ``` </details> # Cause this change https://github.com/pypa/build/commit/32398749d06b19bd2cf21be278e8ceb871411dbb#diff-4f1bb46d65de7fbb1573dfc2a2bca9f63c7b03d55e74c53339f0c8ee4fa054d8R129 makes use of the stacklevel argument, which is only supported from python 3.8 [ref](https://docs.python.org/3/library/logging.html#logging.Logger.debug)
0.0
720d69dadc1641769be89e3630b12b207e157ca3
[ "tests/test_env.py::test_isolated_env_log" ]
[ "tests/test_env.py::test_isolation", "tests/test_env.py::test_isolated_environment_install", "tests/test_env.py::test_executable_missing_post_creation", "tests/test_env.py::test_isolated_env_abstract", "tests/test_env.py::test_isolated_env_has_executable_still_abstract", "tests/test_env.py::test_isolated_env_has_install_still_abstract", "tests/test_env.py::test_default_pip_is_never_too_old", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-20.2.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-20.3.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-21.0.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-21.0.1]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-20.2.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-20.3.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-21.0.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-21.0.1]", "tests/test_env.py::test_venv_symlink[True]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep-expected1]", "tests/test_projectbuilder.py::test_check_dependency[requireless_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[undefined_extra]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_unmet_deps]-expected5]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[recursive_extra_with_unmet_deps]-expected6]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_met_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep;", "tests/test_projectbuilder.py::test_check_dependency[extras_dep", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]", "tests/test_projectbuilder.py::test_check_dependency[prerelease_dep", "tests/test_projectbuilder.py::test_bad_project", "tests/test_projectbuilder.py::test_python_executable[something]", "tests/test_projectbuilder.py::test_python_executable[something_else]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_working_directory", "tests/test_projectbuilder.py::test_working_directory_exc_is_not_transformed", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_relative_outdir", "tests/test_projectbuilder.py::test_build_not_dir_outdir", "tests/test_projectbuilder.py::test_build_with_dep_on_console_script", "tests/test_projectbuilder.py::test_prepare", "tests/test_projectbuilder.py::test_prepare_no_hook", "tests/test_projectbuilder.py::test_prepare_error", "tests/test_projectbuilder.py::test_prepare_not_dir_outdir", "tests/test_projectbuilder.py::test_no_outdir_single", "tests/test_projectbuilder.py::test_no_outdir_multiple", "tests/test_projectbuilder.py::test_runner_user_specified", "tests/test_projectbuilder.py::test_metadata_path_legacy", "tests/test_projectbuilder.py::test_metadata_invalid_wheel", "tests/test_projectbuilder.py::test_toml_instead_of_tomli", "tests/test_projectbuilder.py::test_log" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-08-04 09:54:47+00:00
mit
4,968
pypa__build-365
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 78652a1..41be321 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,16 @@ Changelog +++++++++ +Unreleased +========== + +- Add schema validation for ``build-system`` table to check conformity + with PEP 517 and PEP 518 (`PR #365`_, Fixes `#364`_) + +.. _PR #365: https://github.com/pypa/build/pull/365 +.. _#364: https://github.com/pypa/build/issues/364 + + 0.7.0 (16-09-2021) ================== diff --git a/src/build/__init__.py b/src/build/__init__.py index 9b43981..853a122 100644 --- a/src/build/__init__.py +++ b/src/build/__init__.py @@ -94,12 +94,33 @@ class BuildBackendException(Exception): return f'Backend operation failed: {self.exception!r}' +class BuildSystemTableValidationError(BuildException): + """ + Exception raised when the ``[build-system]`` table in pyproject.toml is invalid. + """ + + def __str__(self) -> str: + return f'Failed to validate `build-system` in pyproject.toml: {self.args[0]}' + + class TypoWarning(Warning): """ Warning raised when a potential typo is found """ [email protected] +def _working_directory(path: str) -> Iterator[None]: + current = os.getcwd() + + os.chdir(path) + + try: + yield + finally: + os.chdir(current) + + def _validate_source_directory(srcdir: str) -> None: if not os.path.isdir(srcdir): raise BuildException(f'Source {srcdir} is not a directory') @@ -153,25 +174,51 @@ def check_dependency( def _find_typo(dictionary: Mapping[str, str], expected: str) -> None: - if expected not in dictionary: - for obj in dictionary: - if difflib.SequenceMatcher(None, expected, obj).ratio() >= 0.8: - warnings.warn( - f"Found '{obj}' in pyproject.toml, did you mean '{expected}'?", - TypoWarning, - ) + for obj in dictionary: + if difflib.SequenceMatcher(None, expected, obj).ratio() >= 0.8: + warnings.warn( + f"Found '{obj}' in pyproject.toml, did you mean '{expected}'?", + TypoWarning, + ) [email protected] -def _working_directory(path: str) -> Iterator[None]: - current = os.getcwd() +def _parse_build_system_table(pyproject_toml: Mapping[str, Any]) -> Dict[str, Any]: + # If pyproject.toml is missing (per PEP 517) or [build-system] is missing + # (per PEP 518), use default values + if 'build-system' not in pyproject_toml: + _find_typo(pyproject_toml, 'build-system') + return _DEFAULT_BACKEND - os.chdir(path) + build_system_table = dict(pyproject_toml['build-system']) - try: - yield - finally: - os.chdir(current) + # If [build-system] is present, it must have a ``requires`` field (per PEP 518) + if 'requires' not in build_system_table: + _find_typo(build_system_table, 'requires') + raise BuildSystemTableValidationError('`requires` is a required property') + elif not isinstance(build_system_table['requires'], list) or not all( + isinstance(i, str) for i in build_system_table['requires'] + ): + raise BuildSystemTableValidationError('`requires` must be an array of strings') + + if 'build-backend' not in build_system_table: + _find_typo(build_system_table, 'build-backend') + # If ``build-backend`` is missing, inject the legacy setuptools backend + # but leave ``requires`` intact to emulate pip + build_system_table['build-backend'] = _DEFAULT_BACKEND['build-backend'] + elif not isinstance(build_system_table['build-backend'], str): + raise BuildSystemTableValidationError('`build-backend` must be a string') + + if 'backend-path' in build_system_table and ( + not isinstance(build_system_table['backend-path'], list) + or not all(isinstance(i, str) for i in build_system_table['backend-path']) + ): + raise BuildSystemTableValidationError('`backend-path` must be an array of strings') + + unknown_props = build_system_table.keys() - {'requires', 'build-backend', 'backend-path'} + if unknown_props: + raise BuildSystemTableValidationError(f'Unknown properties: {", ".join(unknown_props)}') + + return build_system_table class ProjectBuilder: @@ -219,23 +266,7 @@ class ProjectBuilder: except TOMLDecodeError as e: raise BuildException(f'Failed to parse {spec_file}: {e} ') - build_system = spec.get('build-system') - # if pyproject.toml is missing (per PEP 517) or [build-system] is missing (per PEP 518), - # use default values. - if build_system is None: - _find_typo(spec, 'build-system') - build_system = _DEFAULT_BACKEND - # if [build-system] is present, it must have a ``requires`` field (per PEP 518). - elif 'requires' not in build_system: - _find_typo(build_system, 'requires') - raise BuildException(f"Missing 'build-system.requires' in {spec_file}") - # if ``build-backend`` is missing, inject the legacy setuptools backend - # but leave ``requires`` alone to emulate pip. - elif 'build-backend' not in build_system: - _find_typo(build_system, 'build-backend') - build_system['build-backend'] = _DEFAULT_BACKEND['build-backend'] - - self._build_system = build_system + self._build_system = _parse_build_system_table(spec) self._backend = self._build_system['build-backend'] self._scripts_dir = scripts_dir self._hook_runner = runner
pypa/build
cccaf931f88dff9e21ce89570e017278e7364dc6
diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index c61871e..221897d 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -570,4 +570,63 @@ def test_log(mocker, caplog, test_flit_path): ('INFO', 'something'), ] if sys.version_info >= (3, 8): # stacklevel - assert [(record.lineno) for record in caplog.records] == [305, 305, 338, 368, 368, 562] + assert caplog.records[-1].lineno == 562 + + [email protected]( + ('pyproject_toml', 'parse_output'), + [ + ( + {'build-system': {'requires': ['foo']}}, + {'requires': ['foo'], 'build-backend': 'setuptools.build_meta:__legacy__'}, + ), + ( + {'build-system': {'requires': ['foo'], 'build-backend': 'bar'}}, + {'requires': ['foo'], 'build-backend': 'bar'}, + ), + ( + {'build-system': {'requires': ['foo'], 'build-backend': 'bar', 'backend-path': ['baz']}}, + {'requires': ['foo'], 'build-backend': 'bar', 'backend-path': ['baz']}, + ), + ], +) +def test_parse_valid_build_system_table_type(pyproject_toml, parse_output): + assert build._parse_build_system_table(pyproject_toml) == parse_output + + [email protected]( + ('pyproject_toml', 'error_message'), + [ + ( + {'build-system': {}}, + '`requires` is a required property', + ), + ( + {'build-system': {'requires': 'not an array'}}, + '`requires` must be an array of strings', + ), + ( + {'build-system': {'requires': [1]}}, + '`requires` must be an array of strings', + ), + ( + {'build-system': {'requires': ['foo'], 'build-backend': ['not a string']}}, + '`build-backend` must be a string', + ), + ( + {'build-system': {'requires': ['foo'], 'backend-path': 'not an array'}}, + '`backend-path` must be an array of strings', + ), + ( + {'build-system': {'requires': ['foo'], 'backend-path': [1]}}, + '`backend-path` must be an array of strings', + ), + ( + {'build-system': {'requires': ['foo'], 'unknown-prop': False}}, + 'Unknown properties: unknown-prop', + ), + ], +) +def test_parse_invalid_build_system_table_type(pyproject_toml, error_message): + with pytest.raises(build.BuildSystemTableValidationError, match=error_message): + build._parse_build_system_table(pyproject_toml)
Validate build-system table schema I just spend a bunch of time debugging an error due to me mistakenly setting `build-backend = ['something']` in the `build-system` table. We should verify the schema (types) and provide a helpful error message if something is wrong. https://www.python.org/dev/peps/pep-0518/#build-system-table https://www.python.org/dev/peps/pep-0518/#json-schema
0.0
cccaf931f88dff9e21ce89570e017278e7364dc6
[ "tests/test_projectbuilder.py::test_parse_valid_build_system_table_type[pyproject_toml0-parse_output0]", "tests/test_projectbuilder.py::test_parse_valid_build_system_table_type[pyproject_toml1-parse_output1]", "tests/test_projectbuilder.py::test_parse_valid_build_system_table_type[pyproject_toml2-parse_output2]", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml0-`requires`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml1-`requires`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml2-`requires`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml3-`build-backend`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml4-`backend-path`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml5-`backend-path`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml6-Unknown" ]
[ "tests/test_projectbuilder.py::test_check_dependency[extras_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep-expected1]", "tests/test_projectbuilder.py::test_check_dependency[requireless_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[undefined_extra]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_unmet_deps]-expected5]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[recursive_extra_with_unmet_deps]-expected6]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_with_met_deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep;", "tests/test_projectbuilder.py::test_check_dependency[extras_dep", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra_without_associated_deps]", "tests/test_projectbuilder.py::test_check_dependency[prerelease_dep", "tests/test_projectbuilder.py::test_bad_project", "tests/test_projectbuilder.py::test_python_executable[something]", "tests/test_projectbuilder.py::test_python_executable[something_else]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_working_directory", "tests/test_projectbuilder.py::test_working_directory_exc_is_not_transformed", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_relative_outdir", "tests/test_projectbuilder.py::test_build_not_dir_outdir", "tests/test_projectbuilder.py::test_build_with_dep_on_console_script", "tests/test_projectbuilder.py::test_prepare", "tests/test_projectbuilder.py::test_prepare_no_hook", "tests/test_projectbuilder.py::test_prepare_error", "tests/test_projectbuilder.py::test_prepare_not_dir_outdir", "tests/test_projectbuilder.py::test_no_outdir_single", "tests/test_projectbuilder.py::test_no_outdir_multiple", "tests/test_projectbuilder.py::test_runner_user_specified", "tests/test_projectbuilder.py::test_metadata_path_legacy", "tests/test_projectbuilder.py::test_metadata_invalid_wheel", "tests/test_projectbuilder.py::test_toml_instead_of_tomli", "tests/test_projectbuilder.py::test_log" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-09-29 17:15:27+00:00
mit
4,969
pypa__build-420
diff --git a/src/build/env.py b/src/build/env.py index e6d22b5..80c42d8 100644 --- a/src/build/env.py +++ b/src/build/env.py @@ -92,7 +92,12 @@ class IsolatedEnvBuilder: :return: The isolated build environment """ - self._path = tempfile.mkdtemp(prefix='build-env-') + # Call ``realpath`` to prevent spurious warning from being emitted + # that the venv location has changed on Windows. The username is + # DOS-encoded in the output of tempfile - the location is the same + # but the representation of it is different, which confuses venv. + # Ref: https://bugs.python.org/issue46171 + self._path = os.path.realpath(tempfile.mkdtemp(prefix='build-env-')) try: # use virtualenv when available (as it's faster than venv) if _should_use_virtualenv():
pypa/build
cb912931995c90d3319832ff59650aae47d71e83
diff --git a/tests/test_env.py b/tests/test_env.py index 9b5506f..831d725 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -112,7 +112,7 @@ def test_isolated_env_log(mocker, caplog, package_test_flit): ('INFO', 'Installing packages in isolated environment... (something)'), ] if sys.version_info >= (3, 8): # stacklevel - assert [(record.lineno) for record in caplog.records] == [105, 102, 193] + assert [(record.lineno) for record in caplog.records] == [105, 107, 198] @pytest.mark.isolated
Failing Windows 3.9.9 tests Can someone with Windows experience take a look at why the Windows 3.9.9 tests are failing? Some context might be found at https://github.com/actions/setup-python/issues/267.
0.0
cb912931995c90d3319832ff59650aae47d71e83
[ "tests/test_env.py::test_isolated_env_log" ]
[ "tests/test_env.py::test_isolation", "tests/test_env.py::test_isolated_environment_install", "tests/test_env.py::test_executable_missing_post_creation", "tests/test_env.py::test_isolated_env_abstract", "tests/test_env.py::test_isolated_env_has_executable_still_abstract", "tests/test_env.py::test_isolated_env_has_install_still_abstract", "tests/test_env.py::test_default_pip_is_never_too_old", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-20.2.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-20.3.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-21.0.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[x86_64-21.0.1]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-20.2.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-20.3.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-21.0.0]", "tests/test_env.py::test_pip_needs_upgrade_mac_os_11[arm64-21.0.1]", "tests/test_env.py::test_venv_symlink[True]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-12-24 09:26:00+00:00
mit
4,970
pypa__build-631
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index acd8eb8..074282d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -35,7 +35,7 @@ repos: hooks: - id: prettier - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.0.275 + rev: v0.0.276 hooks: - id: ruff args: [--fix, --format, grouped, --show-fixes] diff --git a/pyproject.toml b/pyproject.toml index dfeb60a..0457578 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ dependencies = [ "pyproject_hooks", # not actually a runtime dependency, only supplied as there is not "recommended dependency" support 'colorama; os_name == "nt"', - 'importlib-metadata >= 0.22; python_version < "3.8"', + 'importlib-metadata >= 4.6; python_version < "3.10"', # Not required for 3.8+, but fixes a stdlib bug 'tomli >= 1.1.0; python_version < "3.11"', ] diff --git a/src/build/_importlib.py b/src/build/_importlib.py new file mode 100644 index 0000000..f95b2a6 --- /dev/null +++ b/src/build/_importlib.py @@ -0,0 +1,14 @@ +import sys + + +if sys.version_info < (3, 8): + import importlib_metadata as metadata +elif sys.version_info < (3, 9, 10) or (3, 10, 0) <= sys.version_info < (3, 10, 2): + try: + import importlib_metadata as metadata + except ModuleNotFoundError: + from importlib import metadata +else: + from importlib import metadata + +__all__ = ['metadata'] diff --git a/src/build/_util.py b/src/build/_util.py index 234297f..0582a28 100644 --- a/src/build/_util.py +++ b/src/build/_util.py @@ -27,10 +27,7 @@ def check_dependency( """ import packaging.requirements - if sys.version_info >= (3, 8): - import importlib.metadata as importlib_metadata - else: - import importlib_metadata + from ._importlib import metadata req = packaging.requirements.Requirement(req_string) normalised_req_string = str(req) @@ -51,8 +48,8 @@ def check_dependency( return try: - dist = importlib_metadata.distribution(req.name) - except importlib_metadata.PackageNotFoundError: + dist = metadata.distribution(req.name) + except metadata.PackageNotFoundError: # dependency is not installed in the environment. yield (*ancestral_req_strings, normalised_req_string) else: diff --git a/src/build/util.py b/src/build/util.py index 9f0570e..9f204b8 100644 --- a/src/build/util.py +++ b/src/build/util.py @@ -3,25 +3,19 @@ from __future__ import annotations import pathlib -import sys import tempfile import pyproject_hooks from . import PathType, ProjectBuilder, RunnerType +from ._importlib import metadata from .env import DefaultIsolatedEnv -if sys.version_info >= (3, 8): - import importlib.metadata as importlib_metadata -else: - import importlib_metadata - - -def _project_wheel_metadata(builder: ProjectBuilder) -> importlib_metadata.PackageMetadata: +def _project_wheel_metadata(builder: ProjectBuilder) -> metadata.PackageMetadata: with tempfile.TemporaryDirectory() as tmpdir: path = pathlib.Path(builder.metadata_path(tmpdir)) - return importlib_metadata.PathDistribution(path).metadata + return metadata.PathDistribution(path).metadata def project_wheel_metadata( @@ -29,7 +23,7 @@ def project_wheel_metadata( isolated: bool = True, *, runner: RunnerType = pyproject_hooks.quiet_subprocess_runner, -) -> importlib_metadata.PackageMetadata: +) -> metadata.PackageMetadata: """ Return the wheel metadata for a project.
pypa/build
7a4b1bfd556bcdf3d04b755d1d3f70afeb8679d3
diff --git a/tests/constraints.txt b/tests/constraints.txt index ee7ad5f..36446db 100644 --- a/tests/constraints.txt +++ b/tests/constraints.txt @@ -1,4 +1,4 @@ -importlib-metadata==0.22 +importlib-metadata==4.6 packaging==19.0 pyproject_hooks==1.0 setuptools==42.0.0; python_version < "3.10" diff --git a/tests/test_projectbuilder.py b/tests/test_projectbuilder.py index f03839d..98a96ee 100644 --- a/tests/test_projectbuilder.py +++ b/tests/test_projectbuilder.py @@ -4,6 +4,7 @@ import copy import logging import os +import pathlib import sys import textwrap @@ -12,13 +13,7 @@ import pytest import build - -if sys.version_info >= (3, 8): # pragma: no cover - from importlib import metadata as importlib_metadata -else: # pragma: no cover - import importlib_metadata - -import pathlib +from build import _importlib build_open_owner = 'builtins' @@ -30,7 +25,7 @@ DEFAULT_BACKEND = { } -class MockDistribution(importlib_metadata.Distribution): +class MockDistribution(_importlib.metadata.Distribution): def locate_file(self, path): # pragma: no cover return '' @@ -48,7 +43,7 @@ class MockDistribution(importlib_metadata.Distribution): return CircularMockDistribution() elif name == 'nested_circular_dep': return NestedCircularMockDistribution() - raise importlib_metadata.PackageNotFoundError + raise _importlib.metadata.PackageNotFoundError class ExtraMockDistribution(MockDistribution): @@ -167,7 +162,7 @@ class NestedCircularMockDistribution(MockDistribution): ], ) def test_check_dependency(monkeypatch, requirement_string, expected): - monkeypatch.setattr(importlib_metadata, 'Distribution', MockDistribution) + monkeypatch.setattr(_importlib.metadata, 'Distribution', MockDistribution) assert next(build.check_dependency(requirement_string), None) == expected @@ -502,7 +497,7 @@ def test_runner_user_specified(tmp_dir, package_test_flit): def test_metadata_path_no_prepare(tmp_dir, package_test_no_prepare): builder = build.ProjectBuilder(package_test_no_prepare) - metadata = importlib_metadata.PathDistribution( + metadata = _importlib.metadata.PathDistribution( pathlib.Path(builder.metadata_path(tmp_dir)), ).metadata @@ -513,7 +508,7 @@ def test_metadata_path_no_prepare(tmp_dir, package_test_no_prepare): def test_metadata_path_with_prepare(tmp_dir, package_test_setuptools): builder = build.ProjectBuilder(package_test_setuptools) - metadata = importlib_metadata.PathDistribution( + metadata = _importlib.metadata.PathDistribution( pathlib.Path(builder.metadata_path(tmp_dir)), ).metadata @@ -524,7 +519,7 @@ def test_metadata_path_with_prepare(tmp_dir, package_test_setuptools): def test_metadata_path_legacy(tmp_dir, package_legacy): builder = build.ProjectBuilder(package_legacy) - metadata = importlib_metadata.PathDistribution( + metadata = _importlib.metadata.PathDistribution( pathlib.Path(builder.metadata_path(tmp_dir)), ).metadata diff --git a/tests/test_self_packaging.py b/tests/test_self_packaging.py index 00870fd..b134f53 100644 --- a/tests/test_self_packaging.py +++ b/tests/test_self_packaging.py @@ -21,6 +21,7 @@ sdist_files = { 'src/build/__init__.py', 'src/build/__main__.py', 'src/build/_exceptions.py', + 'src/build/_importlib.py', 'src/build/_util.py', 'src/build/env.py', 'src/build/py.typed', @@ -31,6 +32,7 @@ wheel_files = { 'build/__init__.py', 'build/__main__.py', 'build/_exceptions.py', + 'build/_importlib.py', 'build/_util.py', 'build/env.py', 'build/py.typed',
InvalidRequirement on Python 3.8 In pypa/setuptools#3965, I discovered that `build` fails to build a dependency with a url req that's part of extras because it stumbles on python/importlib_metadata#357, which was only backported to Python 3.9, but [build uses stdlib importlib.metadata for Python 3.8](https://github.com/pypa/build/blob/cd06da25481b9a610f846fa60cb67b5a5fa9a051/src/build/__init__.py#L150-L153). Build should probably use `importlib_metadata` for Python 3.8 and maybe for Python 3.9 ([quite a few improvements and fixes](https://importlib-metadata.readthedocs.io/en/latest/history.html#v4-3-0) landed in CPython 3.10).
0.0
7a4b1bfd556bcdf3d04b755d1d3f70afeb8679d3
[ "tests/test_projectbuilder.py::test_check_dependency[extras_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep-expected1]", "tests/test_projectbuilder.py::test_check_dependency[requireless_dep-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[undefined_extra]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra-without-associated-deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra-with-unmet-deps]-expected5]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[recursive-extra-with-unmet-deps]-expected6]", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra-with-met-deps]-None]", "tests/test_projectbuilder.py::test_check_dependency[missing_dep;", "tests/test_projectbuilder.py::test_check_dependency[extras_dep", "tests/test_projectbuilder.py::test_check_dependency[extras_dep[extra-without-associated-deps]", "tests/test_projectbuilder.py::test_check_dependency[prerelease_dep", "tests/test_projectbuilder.py::test_check_dependency[circular_dep-None]", "tests/test_projectbuilder.py::test_bad_project", "tests/test_projectbuilder.py::test_init_makes_source_dir_absolute", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[wheel]", "tests/test_projectbuilder.py::test_get_requires_for_build_missing_optional_hooks[sdist]", "tests/test_projectbuilder.py::test_build_missing_backend[wheel]", "tests/test_projectbuilder.py::test_build_missing_backend[sdist]", "tests/test_projectbuilder.py::test_check_dependencies", "tests/test_projectbuilder.py::test_build", "tests/test_projectbuilder.py::test_default_backend", "tests/test_projectbuilder.py::test_missing_backend", "tests/test_projectbuilder.py::test_missing_requires", "tests/test_projectbuilder.py::test_build_system_typo", "tests/test_projectbuilder.py::test_missing_outdir", "tests/test_projectbuilder.py::test_relative_outdir", "tests/test_projectbuilder.py::test_build_not_dir_outdir", "tests/test_projectbuilder.py::test_build_with_dep_on_console_script", "tests/test_projectbuilder.py::test_prepare", "tests/test_projectbuilder.py::test_prepare_no_hook", "tests/test_projectbuilder.py::test_prepare_error", "tests/test_projectbuilder.py::test_prepare_not_dir_outdir", "tests/test_projectbuilder.py::test_no_outdir_single", "tests/test_projectbuilder.py::test_no_outdir_multiple", "tests/test_projectbuilder.py::test_runner_user_specified", "tests/test_projectbuilder.py::test_metadata_path_legacy", "tests/test_projectbuilder.py::test_metadata_invalid_wheel", "tests/test_projectbuilder.py::test_log", "tests/test_projectbuilder.py::test_parse_valid_build_system_table_type[pyproject_toml0-parse_output0]", "tests/test_projectbuilder.py::test_parse_valid_build_system_table_type[pyproject_toml1-parse_output1]", "tests/test_projectbuilder.py::test_parse_valid_build_system_table_type[pyproject_toml2-parse_output2]", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml0-`requires`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml1-`requires`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml2-`requires`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml3-`build-backend`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml4-`backend-path`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml5-`backend-path`", "tests/test_projectbuilder.py::test_parse_invalid_build_system_table_type[pyproject_toml6-Unknown", "tests/test_self_packaging.py::test_build_sdist", "tests/test_self_packaging.py::test_build_wheel[from_sdist]", "tests/test_self_packaging.py::test_build_wheel[direct]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-27 08:30:40+00:00
mit
4,971
pypa__cibuildwheel-1031
diff --git a/README.md b/README.md index 41cb6203..702b9baa 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ | CPython 3.10 | ✅ | ✅ | ✅ | ✅ | ✅² | ✅ | ✅ | ✅ | ✅ | ✅ | | PyPy 3.7 v7.3 | ✅ | N/A | ✅ | N/A | N/A | ✅¹ | ✅¹ | ✅¹ | N/A | N/A | | PyPy 3.8 v7.3 | ✅ | N/A | ✅ | N/A | N/A | ✅¹ | ✅¹ | ✅¹ | N/A | N/A | +| PyPy 3.9 v7.3 | ✅ | N/A | ✅ | N/A | N/A | ✅¹ | ✅¹ | ✅¹ | N/A | N/A | <sup>¹ PyPy is only supported for manylinux wheels.</sup><br> <sup>² Windows arm64 support is experimental.</sup><br> diff --git a/bin/update_pythons.py b/bin/update_pythons.py index 30859259..e4939f79 100755 --- a/bin/update_pythons.py +++ b/bin/update_pythons.py @@ -109,7 +109,12 @@ def __init__(self, arch_str: ArchStr): response = requests.get("https://downloads.python.org/pypy/versions.json") response.raise_for_status() - releases = [r for r in response.json() if r["pypy_version"] != "nightly"] + releases = [ + r + for r in response.json() + if r["pypy_version"] != "nightly" + and f'{r["python_version"]}-{r["pypy_version"]}' != "3.7.12-7.3.8" + ] for release in releases: release["pypy_version"] = Version(release["pypy_version"]) release["python_version"] = Version(release["python_version"]) diff --git a/cibuildwheel/resources/build-platforms.toml b/cibuildwheel/resources/build-platforms.toml index 13625461..5bb0350e 100644 --- a/cibuildwheel/resources/build-platforms.toml +++ b/cibuildwheel/resources/build-platforms.toml @@ -12,6 +12,7 @@ python_configurations = [ { identifier = "cp310-manylinux_i686", version = "3.10", path_str = "/opt/python/cp310-cp310" }, { identifier = "pp37-manylinux_x86_64", version = "3.7", path_str = "/opt/python/pp37-pypy37_pp73" }, { identifier = "pp38-manylinux_x86_64", version = "3.8", path_str = "/opt/python/pp38-pypy38_pp73" }, + { identifier = "pp39-manylinux_x86_64", version = "3.9", path_str = "/opt/python/pp39-pypy39_pp73" }, { identifier = "cp36-manylinux_aarch64", version = "3.6", path_str = "/opt/python/cp36-cp36m" }, { identifier = "cp37-manylinux_aarch64", version = "3.7", path_str = "/opt/python/cp37-cp37m" }, { identifier = "cp38-manylinux_aarch64", version = "3.8", path_str = "/opt/python/cp38-cp38" }, @@ -29,8 +30,10 @@ python_configurations = [ { identifier = "cp310-manylinux_s390x", version = "3.10", path_str = "/opt/python/cp310-cp310" }, { identifier = "pp37-manylinux_aarch64", version = "3.7", path_str = "/opt/python/pp37-pypy37_pp73" }, { identifier = "pp38-manylinux_aarch64", version = "3.8", path_str = "/opt/python/pp38-pypy38_pp73" }, + { identifier = "pp39-manylinux_aarch64", version = "3.9", path_str = "/opt/python/pp39-pypy39_pp73" }, { identifier = "pp37-manylinux_i686", version = "3.7", path_str = "/opt/python/pp37-pypy37_pp73" }, { identifier = "pp38-manylinux_i686", version = "3.8", path_str = "/opt/python/pp38-pypy38_pp73" }, + { identifier = "pp39-manylinux_i686", version = "3.9", path_str = "/opt/python/pp39-pypy39_pp73" }, { identifier = "cp36-musllinux_x86_64", version = "3.6", path_str = "/opt/python/cp36-cp36m" }, { identifier = "cp37-musllinux_x86_64", version = "3.7", path_str = "/opt/python/cp37-cp37m" }, { identifier = "cp38-musllinux_x86_64", version = "3.8", path_str = "/opt/python/cp38-cp38" }, @@ -71,8 +74,9 @@ python_configurations = [ { identifier = "cp310-macosx_x86_64", version = "3.10", url = "https://www.python.org/ftp/python/3.10.2/python-3.10.2-macos11.pkg" }, { identifier = "cp310-macosx_arm64", version = "3.10", url = "https://www.python.org/ftp/python/3.10.2/python-3.10.2-macos11.pkg" }, { identifier = "cp310-macosx_universal2", version = "3.10", url = "https://www.python.org/ftp/python/3.10.2/python-3.10.2-macos11.pkg" }, - { identifier = "pp37-macosx_x86_64", version = "3.7", url = "https://downloads.python.org/pypy/pypy3.7-v7.3.8-osx64.tar.bz2" }, + { identifier = "pp37-macosx_x86_64", version = "3.7", url = "https://downloads.python.org/pypy/pypy3.7-v7.3.7-osx64.tar.bz2" }, { identifier = "pp38-macosx_x86_64", version = "3.8", url = "https://downloads.python.org/pypy/pypy3.8-v7.3.8-osx64.tar.bz2" }, + { identifier = "pp39-macosx_x86_64", version = "3.9", url = "https://downloads.python.org/pypy/pypy3.9-v7.3.8-osx64.tar.bz2" }, ] [windows] @@ -89,6 +93,7 @@ python_configurations = [ { identifier = "cp310-win_amd64", version = "3.10.2", arch = "64" }, { identifier = "cp39-win_arm64", version = "3.9.10", arch = "ARM64" }, { identifier = "cp310-win_arm64", version = "3.10.2", arch = "ARM64" }, - { identifier = "pp37-win_amd64", version = "3.7", arch = "64", url = "https://downloads.python.org/pypy/pypy3.7-v7.3.8-win64.zip" }, + { identifier = "pp37-win_amd64", version = "3.7", arch = "64", url = "https://downloads.python.org/pypy/pypy3.7-v7.3.7-win64.zip" }, { identifier = "pp38-win_amd64", version = "3.8", arch = "64", url = "https://downloads.python.org/pypy/pypy3.8-v7.3.8-win64.zip" }, + { identifier = "pp39-win_amd64", version = "3.9", arch = "64", url = "https://downloads.python.org/pypy/pypy3.9-v7.3.8-win64.zip" }, ] diff --git a/cibuildwheel/resources/pinned_docker_images.cfg b/cibuildwheel/resources/pinned_docker_images.cfg index 3b946830..ffcb0f03 100644 --- a/cibuildwheel/resources/pinned_docker_images.cfg +++ b/cibuildwheel/resources/pinned_docker_images.cfg @@ -1,43 +1,43 @@ [x86_64] manylinux1 = quay.io/pypa/manylinux1_x86_64:2022-02-20-044a1ea -manylinux2010 = quay.io/pypa/manylinux2010_x86_64:2022-02-20-e7cad68 -manylinux2014 = quay.io/pypa/manylinux2014_x86_64:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_x86_64:2022-02-20-e7cad68 -musllinux_1_1 = quay.io/pypa/musllinux_1_1_x86_64:2022-02-20-e7cad68 +manylinux2010 = quay.io/pypa/manylinux2010_x86_64:2022-02-24-3876535 +manylinux2014 = quay.io/pypa/manylinux2014_x86_64:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_x86_64:2022-02-24-3876535 +musllinux_1_1 = quay.io/pypa/musllinux_1_1_x86_64:2022-02-24-3876535 [i686] manylinux1 = quay.io/pypa/manylinux1_i686:2022-02-20-044a1ea -manylinux2010 = quay.io/pypa/manylinux2010_i686:2022-02-20-e7cad68 -manylinux2014 = quay.io/pypa/manylinux2014_i686:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_i686:2022-02-20-e7cad68 -musllinux_1_1 = quay.io/pypa/musllinux_1_1_i686:2022-02-20-e7cad68 +manylinux2010 = quay.io/pypa/manylinux2010_i686:2022-02-24-3876535 +manylinux2014 = quay.io/pypa/manylinux2014_i686:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_i686:2022-02-24-3876535 +musllinux_1_1 = quay.io/pypa/musllinux_1_1_i686:2022-02-24-3876535 [pypy_x86_64] -manylinux2010 = quay.io/pypa/manylinux2010_x86_64:2022-02-20-e7cad68 -manylinux2014 = quay.io/pypa/manylinux2014_x86_64:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_x86_64:2022-02-20-e7cad68 +manylinux2010 = quay.io/pypa/manylinux2010_x86_64:2022-02-24-3876535 +manylinux2014 = quay.io/pypa/manylinux2014_x86_64:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_x86_64:2022-02-24-3876535 [pypy_i686] -manylinux2010 = quay.io/pypa/manylinux2010_i686:2022-02-20-e7cad68 -manylinux2014 = quay.io/pypa/manylinux2014_i686:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_i686:2022-02-20-e7cad68 +manylinux2010 = quay.io/pypa/manylinux2010_i686:2022-02-24-3876535 +manylinux2014 = quay.io/pypa/manylinux2014_i686:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_i686:2022-02-24-3876535 [aarch64] -manylinux2014 = quay.io/pypa/manylinux2014_aarch64:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_aarch64:2022-02-20-e7cad68 -musllinux_1_1 = quay.io/pypa/musllinux_1_1_aarch64:2022-02-20-e7cad68 +manylinux2014 = quay.io/pypa/manylinux2014_aarch64:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_aarch64:2022-02-24-3876535 +musllinux_1_1 = quay.io/pypa/musllinux_1_1_aarch64:2022-02-24-3876535 [ppc64le] -manylinux2014 = quay.io/pypa/manylinux2014_ppc64le:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_ppc64le:2022-02-20-e7cad68 -musllinux_1_1 = quay.io/pypa/musllinux_1_1_ppc64le:2022-02-20-e7cad68 +manylinux2014 = quay.io/pypa/manylinux2014_ppc64le:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_ppc64le:2022-02-24-3876535 +musllinux_1_1 = quay.io/pypa/musllinux_1_1_ppc64le:2022-02-24-3876535 [s390x] -manylinux2014 = quay.io/pypa/manylinux2014_s390x:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_s390x:2022-02-20-e7cad68 -musllinux_1_1 = quay.io/pypa/musllinux_1_1_s390x:2022-02-20-e7cad68 +manylinux2014 = quay.io/pypa/manylinux2014_s390x:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_s390x:2022-02-24-3876535 +musllinux_1_1 = quay.io/pypa/musllinux_1_1_s390x:2022-02-24-3876535 [pypy_aarch64] -manylinux2014 = quay.io/pypa/manylinux2014_aarch64:2022-02-20-e7cad68 -manylinux_2_24 = quay.io/pypa/manylinux_2_24_aarch64:2022-02-20-e7cad68 +manylinux2014 = quay.io/pypa/manylinux2014_aarch64:2022-02-24-3876535 +manylinux_2_24 = quay.io/pypa/manylinux_2_24_aarch64:2022-02-24-3876535 diff --git a/docs/options.md b/docs/options.md index 46f2d24e..45f67873 100644 --- a/docs/options.md +++ b/docs/options.md @@ -211,6 +211,7 @@ ### `CIBW_BUILD`, `CIBW_SKIP` {: #build-skip} | Python 3.10 | cp310-macosx_x86_64<br/>cp310-macosx_universal2<br/>cp310-macosx_arm64 | cp310-win_amd64<br/>cp310-win32<br/>cp310-win_arm64 | cp310-manylinux_x86_64<br/>cp310-manylinux_i686<br/>cp310-musllinux_x86_64<br/>cp310-musllinux_i686 | cp310-manylinux_aarch64<br/>cp310-manylinux_ppc64le<br/>cp310-manylinux_s390x<br/>cp310-musllinux_aarch64<br/>cp310-musllinux_ppc64le<br/>cp310-musllinux_s390x | | PyPy3.7 v7.3 | pp37-macosx_x86_64 | pp37-win_amd64 | pp37-manylinux_x86_64<br/>pp37-manylinux_i686 | pp37-manylinux_aarch64 | | PyPy3.8 v7.3 | pp38-macosx_x86_64 | pp38-win_amd64 | pp38-manylinux_x86_64<br/>pp38-manylinux_i686 | pp38-manylinux_aarch64 | +| PyPy3.9 v7.3 | pp39-macosx_x86_64 | pp39-win_amd64 | pp39-manylinux_x86_64<br/>pp39-manylinux_i686 | pp39-manylinux_aarch64 | The list of supported and currently selected build identifiers can also be retrieved by passing the `--print-build-identifiers` flag to cibuildwheel. The format is `python_tag-platform_tag`, with tags similar to those in [PEP 425](https://www.python.org/dev/peps/pep-0425/#details).
pypa/cibuildwheel
4465ec193f1508ee4b9b2866eae68f3a2a198d88
diff --git a/test/test_manylinuxXXXX_only.py b/test/test_manylinuxXXXX_only.py index f7c533d4..7ae5ebb1 100644 --- a/test/test_manylinuxXXXX_only.py +++ b/test/test_manylinuxXXXX_only.py @@ -71,6 +71,9 @@ def test(manylinux_image, tmp_path): if manylinux_image in {"manylinux1"}: # We don't have a manylinux1 image for PyPy & CPython 3.10 and above add_env["CIBW_SKIP"] = "pp* cp31*" + if manylinux_image in {"manylinux2010"}: + # We don't have a manylinux2010 image for PyPy 3.9 + add_env["CIBW_SKIP"] = "pp39*" actual_wheels = utils.cibuildwheel_run(project_dir, add_env=add_env) @@ -88,4 +91,7 @@ def test(manylinux_image, tmp_path): if manylinux_image in {"manylinux1"}: # remove PyPy & CPython 3.10 and above expected_wheels = [w for w in expected_wheels if "-pp" not in w and "-cp31" not in w] + if manylinux_image in {"manylinux2010"}: + # remove PyPy 3.9 + expected_wheels = [w for w in expected_wheels if "-pp39" not in w] assert set(actual_wheels) == set(expected_wheels) diff --git a/test/utils.py b/test/utils.py index 98715954..0248a7c1 100644 --- a/test/utils.py +++ b/test/utils.py @@ -135,7 +135,7 @@ def expected_wheels( python_abi_tags = ["cp36-cp36m", "cp37-cp37m", "cp38-cp38", "cp39-cp39", "cp310-cp310"] if machine_arch in ["x86_64", "AMD64", "x86", "aarch64"]: - python_abi_tags += ["pp37-pypy37_pp73", "pp38-pypy38_pp73"] + python_abi_tags += ["pp37-pypy37_pp73", "pp38-pypy38_pp73", "pp39-pypy39_pp73"] if platform == "macos" and machine_arch == "arm64": # currently, arm64 macs are only supported by cp39 & cp310 diff --git a/unit_test/option_prepare_test.py b/unit_test/option_prepare_test.py index d21ba65d..354cda4a 100644 --- a/unit_test/option_prepare_test.py +++ b/unit_test/option_prepare_test.py @@ -11,7 +11,7 @@ from cibuildwheel import linux, util from cibuildwheel.__main__ import main -ALL_IDS = {"cp36", "cp37", "cp38", "cp39", "cp310", "pp37", "pp38"} +ALL_IDS = {"cp36", "cp37", "cp38", "cp39", "cp310", "pp37", "pp38", "pp39"} @pytest.fixture @@ -133,7 +133,7 @@ def test_build_with_override_launches(mock_build_docker, monkeypatch, tmp_path): identifiers = {x.identifier for x in kwargs["platform_configs"]} assert identifiers == { - f"{x}-manylinux_x86_64" for x in ALL_IDS - {"cp36", "cp310", "pp37", "pp38"} + f"{x}-manylinux_x86_64" for x in ALL_IDS - {"cp36", "cp310", "pp37", "pp38", "pp39"} } assert kwargs["options"].build_options("cp37-manylinux_x86_64").before_all == "" @@ -146,6 +146,7 @@ def test_build_with_override_launches(mock_build_docker, monkeypatch, tmp_path): "cp310-manylinux_x86_64", "pp37-manylinux_x86_64", "pp38-manylinux_x86_64", + "pp39-manylinux_x86_64", } kwargs = build_on_docker.call_args_list[3][1]
PyPy has released bug fixes and a python3.9 ### Description PyPy released version v7.3.8. It would be nice to be able to use it in cibuildwheel, including the newly released python3.9 ### Build log _No response_ ### CI config _No response_
0.0
4465ec193f1508ee4b9b2866eae68f3a2a198d88
[ "unit_test/option_prepare_test.py::test_build_default_launches", "unit_test/option_prepare_test.py::test_build_with_override_launches" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-02-20 21:43:26+00:00
bsd-2-clause
4,972
pypa__cibuildwheel-1098
diff --git a/action.yml b/action.yml index a27269dd..111acc93 100644 --- a/action.yml +++ b/action.yml @@ -13,6 +13,10 @@ inputs: description: 'File containing the config, defaults to {package}/pyproject.toml' required: false default: '' + only: + description: 'Build a specific wheel only. No need for arch/platform if this is set' + required: false + default: '' branding: icon: package color: yellow @@ -36,5 +40,6 @@ runs: ${{ inputs.package-dir }} --output-dir ${{ inputs.output-dir }} --config-file "${{ inputs.config-file }}" + --only "${{ inputs.only }}" 2>&1 shell: bash diff --git a/cibuildwheel/__main__.py b/cibuildwheel/__main__.py index f3b44261..4d1402d8 100644 --- a/cibuildwheel/__main__.py +++ b/cibuildwheel/__main__.py @@ -6,6 +6,7 @@ import sys import tarfile import textwrap +import typing from pathlib import Path from tempfile import mkdtemp @@ -40,7 +41,7 @@ def main() -> None: parser.add_argument( "--platform", choices=["auto", "linux", "macos", "windows"], - default=os.environ.get("CIBW_PLATFORM", "auto"), + default=None, help=""" Platform to build for. Use this option to override the auto-detected platform or to run cibuildwheel on your development @@ -64,6 +65,16 @@ def main() -> None: """, ) + parser.add_argument( + "--only", + default=None, + help=""" + Force a single wheel build when given an identifier. Overrides + CIBW_BUILD/CIBW_SKIP. --platform and --arch cannot be specified + if this is given. + """, + ) + parser.add_argument( "--output-dir", type=Path, @@ -154,10 +165,40 @@ def main() -> None: def build_in_directory(args: CommandLineArguments) -> None: + platform_option_value = args.platform or os.environ.get("CIBW_PLATFORM", "auto") platform: PlatformName - if args.platform != "auto": - platform = args.platform + if args.only: + if "linux_" in args.only: + platform = "linux" + elif "macosx_" in args.only: + platform = "macos" + elif "win_" in args.only: + platform = "windows" + else: + print( + f"Invalid --only='{args.only}', must be a build selector with a known platform", + file=sys.stderr, + ) + sys.exit(2) + if args.platform is not None: + print( + "--platform cannot be specified with --only, it is computed from --only", + file=sys.stderr, + ) + sys.exit(2) + if args.archs is not None: + print( + "--arch cannot be specified with --only, it is computed from --only", + file=sys.stderr, + ) + sys.exit(2) + elif platform_option_value != "auto": + if platform_option_value not in PLATFORMS: + print(f"cibuildwheel: Unsupported platform: {platform_option_value}", file=sys.stderr) + sys.exit(2) + + platform = typing.cast(PlatformName, platform_option_value) else: ci_provider = detect_ci_provider() if ci_provider is None: @@ -187,10 +228,6 @@ def build_in_directory(args: CommandLineArguments) -> None: ) sys.exit(2) - if platform not in PLATFORMS: - print(f"cibuildwheel: Unsupported platform: {platform}", file=sys.stderr) - sys.exit(2) - options = compute_options(platform=platform, command_line_arguments=args) package_dir = options.globals.package_dir diff --git a/cibuildwheel/options.py b/cibuildwheel/options.py index 241f0e0e..75e367c6 100644 --- a/cibuildwheel/options.py +++ b/cibuildwheel/options.py @@ -42,9 +42,10 @@ @dataclass class CommandLineArguments: - platform: Literal["auto", "linux", "macos", "windows"] + platform: Literal["auto", "linux", "macos", "windows"] | None archs: str | None output_dir: Path + only: str | None config_file: str package_dir: Path print_build_identifiers: bool @@ -403,6 +404,15 @@ def globals(self) -> GlobalOptions: ) requires_python = None if requires_python_str is None else SpecifierSet(requires_python_str) + archs_config_str = args.archs or self.reader.get("archs", sep=" ") + architectures = Architecture.parse_config(archs_config_str, platform=self.platform) + + # Process `--only` + if args.only: + build_config = args.only + skip_config = "" + architectures = Architecture.all_archs(self.platform) + build_selector = BuildSelector( build_config=build_config, skip_config=skip_config, @@ -411,9 +421,6 @@ def globals(self) -> GlobalOptions: ) test_selector = TestSelector(skip_config=test_skip) - archs_config_str = args.archs or self.reader.get("archs", sep=" ") - architectures = Architecture.parse_config(archs_config_str, platform=self.platform) - container_engine_str = self.reader.get("container-engine") if container_engine_str not in ["docker", "podman"]: @@ -588,6 +595,9 @@ def summary(self, identifiers: list[str]) -> str: ] build_option_defaults = self.build_options(identifier=None) + build_options_for_identifier = { + identifier: self.build_options(identifier) for identifier in identifiers + } for option_name, default_value in sorted(asdict(build_option_defaults).items()): if option_name == "globals": @@ -597,7 +607,7 @@ def summary(self, identifiers: list[str]) -> str: # if any identifiers have an overridden value, print that too for identifier in identifiers: - option_value = getattr(self.build_options(identifier=identifier), option_name) + option_value = getattr(build_options_for_identifier[identifier], option_name) if option_value != default_value: lines.append(f" {identifier}: {option_value!r}") diff --git a/cibuildwheel/util.py b/cibuildwheel/util.py index 4b3d4fb9..e494929d 100644 --- a/cibuildwheel/util.py +++ b/cibuildwheel/util.py @@ -145,7 +145,7 @@ def shell(*commands: str, env: dict[str, str] | None = None, cwd: PathOrStr | No subprocess.run(command, env=env, cwd=cwd, shell=True, check=True) -def format_safe(template: str, **kwargs: Any) -> str: +def format_safe(template: str, **kwargs: str | os.PathLike[str]) -> str: """ Works similarly to `template.format(**kwargs)`, except that unmatched fields in `template` are passed through untouched. @@ -173,11 +173,9 @@ def format_safe(template: str, **kwargs: Any) -> str: re.VERBOSE, ) - # we use a function for repl to prevent re.sub interpreting backslashes - # in repl as escape sequences. result = re.sub( pattern=find_pattern, - repl=lambda _: str(value), # pylint: disable=cell-var-from-loop + repl=str(value).replace("\\", r"\\"), string=result, ) diff --git a/docs/options.md b/docs/options.md index cc093079..498b15d0 100644 --- a/docs/options.md +++ b/docs/options.md @@ -113,7 +113,7 @@ ### Configuration file {: #configuration-file} !!! tip Static configuration works across all CI systems, and can be used locally if - you run `cibuildwheel --plat linux`. This is preferred, but environment + you run `cibuildwheel --platform linux`. This is preferred, but environment variables are better if you need to change per-matrix element (`CIBW_BUILD` is often in this category, for example), or if you cannot or do not want to change a `pyproject.toml` file. You can specify a different file to @@ -202,6 +202,10 @@ ### `CIBW_PLATFORM` {: #platform} This is even more convenient if you store your cibuildwheel config in [`pyproject.toml`](#configuration-file). + You can also run a single identifier with `--only <identifier>`. This will + not require `--platform` or `--arch`, and will override any build/skip + configuration. + ### `CIBW_BUILD`, `CIBW_SKIP` {: #build-skip} > Choose the Python versions to build
pypa/cibuildwheel
3a46bde3fbcdffa4b61a4cc0b7f8a4b403408fd0
diff --git a/unit_test/main_tests/conftest.py b/unit_test/main_tests/conftest.py index 25732187..c90fb555 100644 --- a/unit_test/main_tests/conftest.py +++ b/unit_test/main_tests/conftest.py @@ -12,7 +12,13 @@ class ArgsInterceptor: + def __init__(self): + self.call_count = 0 + self.args = None + self.kwargs = None + def __call__(self, *args, **kwargs): + self.call_count += 1 self.args = args self.kwargs = kwargs @@ -75,16 +81,14 @@ def platform(request, monkeypatch): @pytest.fixture -def intercepted_build_args(platform, monkeypatch): +def intercepted_build_args(monkeypatch): intercepted = ArgsInterceptor() - if platform == "linux": - monkeypatch.setattr(linux, "build", intercepted) - elif platform == "macos": - monkeypatch.setattr(macos, "build", intercepted) - elif platform == "windows": - monkeypatch.setattr(windows, "build", intercepted) - else: - raise ValueError(f"unknown platform value: {platform}") + monkeypatch.setattr(linux, "build", intercepted) + monkeypatch.setattr(macos, "build", intercepted) + monkeypatch.setattr(windows, "build", intercepted) + + yield intercepted - return intercepted + # check that intercepted_build_args only ever had one set of args + assert intercepted.call_count <= 1 diff --git a/unit_test/main_tests/main_platform_test.py b/unit_test/main_tests/main_platform_test.py index 96fd4412..9136802c 100644 --- a/unit_test/main_tests/main_platform_test.py +++ b/unit_test/main_tests/main_platform_test.py @@ -192,3 +192,73 @@ def test_archs_platform_all(platform, intercepted_build_args, monkeypatch): Architecture.arm64, Architecture.universal2, } + + [email protected]( + "only,plat", + ( + ("cp311-manylinux_x86_64", "linux"), + ("cp310-win_amd64", "windows"), + ("cp311-macosx_x86_64", "macos"), + ), +) +def test_only_argument(intercepted_build_args, monkeypatch, only, plat): + monkeypatch.setenv("CIBW_BUILD", "unused") + monkeypatch.setenv("CIBW_SKIP", "unused") + monkeypatch.setattr(sys, "argv", sys.argv + ["--only", only]) + + main() + + options = intercepted_build_args.args[0] + assert options.globals.build_selector.build_config == only + assert options.globals.build_selector.skip_config == "" + assert options.platform == plat + assert options.globals.architectures == Architecture.all_archs(plat) + + [email protected]("only", ("cp311-manylxinux_x86_64", "some_linux_thing")) +def test_only_failed(monkeypatch, only): + monkeypatch.setattr(sys, "argv", sys.argv + ["--only", only]) + + with pytest.raises(SystemExit): + main() + + +def test_only_no_platform(monkeypatch): + monkeypatch.setattr( + sys, "argv", sys.argv + ["--only", "cp311-manylinux_x86_64", "--platform", "macos"] + ) + + with pytest.raises(SystemExit): + main() + + +def test_only_no_archs(monkeypatch): + monkeypatch.setattr( + sys, "argv", sys.argv + ["--only", "cp311-manylinux_x86_64", "--archs", "x86_64"] + ) + + with pytest.raises(SystemExit): + main() + + [email protected]( + "envvar_name,envvar_value", + ( + ("CIBW_BUILD", "cp310-*"), + ("CIBW_SKIP", "cp311-*"), + ("CIBW_ARCHS", "auto32"), + ("CIBW_PLATFORM", "macos"), + ), +) +def test_only_overrides_env_vars(monkeypatch, intercepted_build_args, envvar_name, envvar_value): + monkeypatch.setattr(sys, "argv", sys.argv + ["--only", "cp311-manylinux_x86_64"]) + monkeypatch.setenv(envvar_name, envvar_value) + + main() + + options = intercepted_build_args.args[0] + assert options.globals.build_selector.build_config == "cp311-manylinux_x86_64" + assert options.globals.build_selector.skip_config == "" + assert options.platform == "linux" + assert options.globals.architectures == Architecture.all_archs("linux") diff --git a/unit_test/utils.py b/unit_test/utils.py index 0cd2fefb..bf44382a 100644 --- a/unit_test/utils.py +++ b/unit_test/utils.py @@ -10,6 +10,7 @@ def get_default_command_line_arguments() -> CommandLineArguments: platform="auto", allow_empty=False, archs=None, + only=None, config_file="", output_dir=Path("wheelhouse"), package_dir=Path("."),
How do I build one specific wheel from the command line? I'm running cibuildwheel from the command line on my local machine. I want to debug a build failure for the `cp39-musllinux_i686` wheel. But I can't figure out how to say "only build `cp39-musllinux_i686` not anything else; I don't have all day here". I was expecting this to work: `cibuildwheel --build-identifiers cp39-musllinux_i686` but there is no such flag.
0.0
3a46bde3fbcdffa4b61a4cc0b7f8a4b403408fd0
[ "unit_test/main_tests/main_platform_test.py::test_only_argument[cp311-manylinux_x86_64-linux]", "unit_test/main_tests/main_platform_test.py::test_only_argument[cp310-win_amd64-windows]", "unit_test/main_tests/main_platform_test.py::test_only_argument[cp311-macosx_x86_64-macos]", "unit_test/main_tests/main_platform_test.py::test_only_overrides_env_vars[CIBW_BUILD-cp310-*]", "unit_test/main_tests/main_platform_test.py::test_only_overrides_env_vars[CIBW_SKIP-cp311-*]", "unit_test/main_tests/main_platform_test.py::test_only_overrides_env_vars[CIBW_ARCHS-auto32]", "unit_test/main_tests/main_platform_test.py::test_only_overrides_env_vars[CIBW_PLATFORM-macos]" ]
[ "unit_test/main_tests/main_platform_test.py::test_unknown_platform_non_ci", "unit_test/main_tests/main_platform_test.py::test_unknown_platform_on_ci", "unit_test/main_tests/main_platform_test.py::test_unknown_platform", "unit_test/main_tests/main_platform_test.py::test_platform_argument[linux]", "unit_test/main_tests/main_platform_test.py::test_platform_argument[macos]", "unit_test/main_tests/main_platform_test.py::test_platform_argument[windows]", "unit_test/main_tests/main_platform_test.py::test_platform_environment[linux]", "unit_test/main_tests/main_platform_test.py::test_platform_environment[macos]", "unit_test/main_tests/main_platform_test.py::test_platform_environment[windows]", "unit_test/main_tests/main_platform_test.py::test_archs_default[linux]", "unit_test/main_tests/main_platform_test.py::test_archs_default[macos]", "unit_test/main_tests/main_platform_test.py::test_archs_default[windows]", "unit_test/main_tests/main_platform_test.py::test_archs_argument[linux-False]", "unit_test/main_tests/main_platform_test.py::test_archs_argument[linux-True]", "unit_test/main_tests/main_platform_test.py::test_archs_argument[macos-False]", "unit_test/main_tests/main_platform_test.py::test_archs_argument[macos-True]", "unit_test/main_tests/main_platform_test.py::test_archs_argument[windows-False]", "unit_test/main_tests/main_platform_test.py::test_archs_argument[windows-True]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_specific[linux]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_specific[macos]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_specific[windows]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_native[linux]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_native[macos]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_native[windows]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_auto64[linux]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_auto64[macos]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_auto64[windows]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_auto32[linux]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_auto32[macos]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_auto32[windows]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_all[linux]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_all[macos]", "unit_test/main_tests/main_platform_test.py::test_archs_platform_all[windows]", "unit_test/main_tests/main_platform_test.py::test_only_failed[cp311-manylxinux_x86_64]", "unit_test/main_tests/main_platform_test.py::test_only_failed[some_linux_thing]", "unit_test/main_tests/main_platform_test.py::test_only_no_platform", "unit_test/main_tests/main_platform_test.py::test_only_no_archs" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-28 04:22:39+00:00
mit
4,973
pypa__cibuildwheel-1138
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a80717e6..679254fd 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,7 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 + rev: v4.3.0 hooks: - id: check-case-conflict - id: check-merge-conflict @@ -14,7 +14,7 @@ repos: - id: trailing-whitespace - repo: https://github.com/asottile/pyupgrade - rev: v2.32.1 + rev: v2.34.0 hooks: - id: pyupgrade name: PyUpgrade 3.6+ @@ -49,7 +49,7 @@ repos: - id: setup-cfg-fmt - repo: https://github.com/pre-commit/mirrors-mypy - rev: v0.960 + rev: v0.961 hooks: - id: mypy name: mypy 3.6 on cibuildwheel/ diff --git a/cibuildwheel/util.py b/cibuildwheel/util.py index 064f3fca..db0cc687 100644 --- a/cibuildwheel/util.py +++ b/cibuildwheel/util.py @@ -234,21 +234,20 @@ def selector_matches(patterns: str, string: str) -> bool: # Once we require Python 3.10+, we can add kw_only=True @dataclasses.dataclass -class IdentifierSelector: +class BuildSelector: """ This class holds a set of build/skip patterns. You call an instance with a build identifier, and it returns True if that identifier should be included. Only call this on valid identifiers, ones that have at least 2 - numeric digits before the first dash. If a pre-release version X.Y is present, - you can filter it with prerelease="XY". + numeric digits before the first dash. """ - # a pattern that skips prerelease versions, when include_prereleases is False. - PRERELEASE_SKIP: ClassVar[str] = "cp311-*" - - skip_config: str build_config: str + skip_config: str requires_python: Optional[SpecifierSet] = None + + # a pattern that skips prerelease versions, when include_prereleases is False. + PRERELEASE_SKIP: ClassVar[str] = "cp311-*" prerelease_pythons: bool = False def __call__(self, build_id: str) -> bool: @@ -272,15 +271,16 @@ def __call__(self, build_id: str) -> bool: @dataclasses.dataclass -class BuildSelector(IdentifierSelector): - pass +class TestSelector: + """ + A build selector that can only skip tests according to a skip pattern. + """ + skip_config: str -# Note that requires-python is not needed for TestSelector, as you can't test -# what you can't build. [email protected] -class TestSelector(IdentifierSelector): - build_config: str = "*" + def __call__(self, build_id: str) -> bool: + should_skip = selector_matches(self.skip_config, build_id) + return not should_skip # Taken from https://stackoverflow.com/a/107717
pypa/cibuildwheel
aa753429b2fdc380e9665c4f031c7d9998718d7c
diff --git a/unit_test/build_selector_test.py b/unit_test/build_selector_test.py index 6b31d1c0..b71cb05f 100644 --- a/unit_test/build_selector_test.py +++ b/unit_test/build_selector_test.py @@ -136,3 +136,14 @@ def test_build_limited_python_patch(): assert build_selector("cp36-manylinux_x86_64") assert build_selector("cp37-manylinux_x86_64") + + +def test_testing_selector(): + # local import to avoid pytest trying to collect this as a test class! + from cibuildwheel.util import TestSelector + + test_selector = TestSelector(skip_config="cp36-*") + + assert not test_selector("cp36-win_amd64") + assert test_selector("cp37-manylinux_x86_64") + assert test_selector("cp311-manylinux_x86_64")
Tests are skipped on pre-release Pythons ### Description On cibuildwheel==2.6.1, when running with `CIBW_PRERELEASE_PYTHONS=1`, any configured test command is always skipped when targeting a pre-release Python version. A quick glance at the code makes me think it's an unintended consequence of having `TestSelector` inherit the prerelease exclusion behavior from `IdentifierSelector`. ### Build log https://github.com/rolpdog/cffi-mirror/runs/6867587654?check_suite_focus=true ### CI config https://github.com/rolpdog/cffi-mirror/commit/b7a01156bafba52bd2bfedc1222c9eb8d36491c7#diff-944291df2c9c06359d37cc8833d182d705c9e8c3108e7cfe132d61a06e9133dd
0.0
aa753429b2fdc380e9665c4f031c7d9998718d7c
[ "unit_test/build_selector_test.py::test_testing_selector" ]
[ "unit_test/build_selector_test.py::test_build", "unit_test/build_selector_test.py::test_build_filter_pre", "unit_test/build_selector_test.py::test_skip", "unit_test/build_selector_test.py::test_build_and_skip", "unit_test/build_selector_test.py::test_build_braces", "unit_test/build_selector_test.py::test_build_limited_python", "unit_test/build_selector_test.py::test_build_limited_python_partial", "unit_test/build_selector_test.py::test_build_limited_python_patch" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-13 21:44:24+00:00
mit
4,974
pypa__cibuildwheel-1205
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 30772612..325eaac5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,7 @@ jobs: name: artifact path: dist - - uses: pypa/[email protected] + - uses: pypa/[email protected] with: user: __token__ password: ${{ secrets.pypi_password }} diff --git a/cibuildwheel/options.py b/cibuildwheel/options.py index 30803604..c8d050fa 100644 --- a/cibuildwheel/options.py +++ b/cibuildwheel/options.py @@ -1,5 +1,6 @@ from __future__ import annotations +import difflib import functools import os import sys @@ -188,14 +189,10 @@ def __init__( # Validate project config for option_name in config_options: - if not self._is_valid_global_option(option_name): - raise ConfigOptionError(f'Option "{option_name}" not supported in a config file') + self._validate_global_option(option_name) for option_name in config_platform_options: - if not self._is_valid_platform_option(option_name): - raise ConfigOptionError( - f'Option "{option_name}" not supported in the "{self.platform}" section' - ) + self._validate_platform_option(option_name) self.config_options = config_options self.config_platform_options = config_platform_options @@ -207,40 +204,51 @@ def __init__( if config_overrides is not None: if not isinstance(config_overrides, list): - raise ConfigOptionError('"tool.cibuildwheel.overrides" must be a list') + raise ConfigOptionError("'tool.cibuildwheel.overrides' must be a list") for config_override in config_overrides: select = config_override.pop("select", None) if not select: - raise ConfigOptionError('"select" must be set in an override') + raise ConfigOptionError("'select' must be set in an override") if isinstance(select, list): select = " ".join(select) self.overrides.append(Override(select, config_override)) - def _is_valid_global_option(self, name: str) -> bool: + def _validate_global_option(self, name: str) -> None: """ - Returns True if an option with this name is allowed in the + Raises an error if an option with this name is not allowed in the [tool.cibuildwheel] section of a config file. """ allowed_option_names = self.default_options.keys() | PLATFORMS | {"overrides"} - return name in allowed_option_names + if name not in allowed_option_names: + msg = f"Option {name!r} not supported in a config file." + matches = difflib.get_close_matches(name, allowed_option_names, 1, 0.7) + if matches: + msg += f" Perhaps you meant {matches[0]!r}?" + raise ConfigOptionError(msg) - def _is_valid_platform_option(self, name: str) -> bool: + def _validate_platform_option(self, name: str) -> None: """ - Returns True if an option with this name is allowed in the + Raises an error if an option with this name is not allowed in the [tool.cibuildwheel.<current-platform>] section of a config file. """ disallowed_platform_options = self.disallow.get(self.platform, set()) if name in disallowed_platform_options: - return False + msg = f"{name!r} is not allowed in {disallowed_platform_options}" + raise ConfigOptionError(msg) allowed_option_names = self.default_options.keys() | self.default_platform_options.keys() - return name in allowed_option_names + if name not in allowed_option_names: + msg = f"Option {name!r} not supported in the {self.platform!r} section" + matches = difflib.get_close_matches(name, allowed_option_names, 1, 0.7) + if matches: + msg += f" Perhaps you meant {matches[0]!r}?" + raise ConfigOptionError(msg) def _load_file(self, filename: Path) -> tuple[dict[str, Any], dict[str, Any]]: """ @@ -290,7 +298,8 @@ def get( """ if name not in self.default_options and name not in self.default_platform_options: - raise ConfigOptionError(f"{name} must be in cibuildwheel/resources/defaults.toml file") + msg = f"{name!r} must be in cibuildwheel/resources/defaults.toml file to be accessed." + raise ConfigOptionError(msg) # Environment variable form envvar = f"CIBW_{name.upper().replace('-', '_')}" @@ -314,12 +323,12 @@ def get( if isinstance(result, dict): if table is None: - raise ConfigOptionError(f"{name} does not accept a table") + raise ConfigOptionError(f"{name!r} does not accept a table") return table["sep"].join(table["item"].format(k=k, v=v) for k, v in result.items()) if isinstance(result, list): if sep is None: - raise ConfigOptionError(f"{name} does not accept a list") + raise ConfigOptionError(f"{name!r} does not accept a list") return sep.join(result) if isinstance(result, int): @@ -393,7 +402,7 @@ def globals(self) -> GlobalOptions: container_engine_str = self.reader.get("container-engine") if container_engine_str not in ["docker", "podman"]: - msg = f"cibuildwheel: Unrecognised container_engine '{container_engine_str}', only 'docker' and 'podman' are supported" + msg = f"cibuildwheel: Unrecognised container_engine {container_engine_str!r}, only 'docker' and 'podman' are supported" print(msg, file=sys.stderr) sys.exit(2) @@ -437,7 +446,7 @@ def build_options(self, identifier: str | None) -> BuildOptions: elif build_frontend_str == "pip": build_frontend = "pip" else: - msg = f"cibuildwheel: Unrecognised build frontend '{build_frontend_str}', only 'pip' and 'build' are supported" + msg = f"cibuildwheel: Unrecognised build frontend {build_frontend_str!r}, only 'pip' and 'build' are supported" print(msg, file=sys.stderr) sys.exit(2) @@ -445,7 +454,7 @@ def build_options(self, identifier: str | None) -> BuildOptions: environment = parse_environment(environment_config) except (EnvironmentParseError, ValueError): print( - f'cibuildwheel: Malformed environment option "{environment_config}"', + f"cibuildwheel: Malformed environment option {environment_config!r}", file=sys.stderr, ) traceback.print_exc(None, sys.stderr)
pypa/cibuildwheel
c73152918723802fb39c9e9544e6dbf840845591
diff --git a/unit_test/options_toml_test.py b/unit_test/options_toml_test.py index a3fab2cc..a0a1705d 100644 --- a/unit_test/options_toml_test.py +++ b/unit_test/options_toml_test.py @@ -160,9 +160,28 @@ def test_unexpected_key(tmp_path): """ ) - with pytest.raises(ConfigOptionError): + with pytest.raises(ConfigOptionError) as excinfo: OptionsReader(pyproject_toml, platform="linux") + assert "repair-wheel-command" in str(excinfo.value) + + +def test_underscores_in_key(tmp_path): + # Note that platform contents are only checked when running + # for that platform. + pyproject_toml = tmp_path / "pyproject.toml" + pyproject_toml.write_text( + """ +[tool.cibuildwheel] +repair_wheel_command = "repair-project-linux" +""" + ) + + with pytest.raises(ConfigOptionError) as excinfo: + OptionsReader(pyproject_toml, platform="linux") + + assert "repair-wheel-command" in str(excinfo.value) + def test_unexpected_table(tmp_path): pyproject_toml = tmp_path / "pyproject.toml"
Consider auto-correcting underscores to dashes in TOML options From https://github.com/pypa/cibuildwheel/pull/759#discussion_r670922746 While TOML prefers dashes, as a Python programmer, it's easy to accidentally write underscores for option names. I wonder if it would be nice to do autofix this a la `option_name.replace("_","-")`, after we read these. pip does something similar - if you do e.g. `pip install python_dateutil`, it will still find `python-dateutil`, because underscores are invalid.
0.0
c73152918723802fb39c9e9544e6dbf840845591
[ "unit_test/options_toml_test.py::test_unexpected_key", "unit_test/options_toml_test.py::test_underscores_in_key" ]
[ "unit_test/options_toml_test.py::test_simple_settings[linux-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[linux-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_simple_settings[macos-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[macos-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_simple_settings[windows-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[windows-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_envvar_override[linux]", "unit_test/options_toml_test.py::test_envvar_override[macos]", "unit_test/options_toml_test.py::test_envvar_override[windows]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[linux]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[macos]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[windows]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[linux]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[macos]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[windows]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[linux]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[macos]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[windows]", "unit_test/options_toml_test.py::test_global_platform_order[linux]", "unit_test/options_toml_test.py::test_global_platform_order[macos]", "unit_test/options_toml_test.py::test_global_platform_order[windows]", "unit_test/options_toml_test.py::test_unexpected_table", "unit_test/options_toml_test.py::test_unsupported_join", "unit_test/options_toml_test.py::test_disallowed_a", "unit_test/options_toml_test.py::test_environment_override_empty", "unit_test/options_toml_test.py::test_dig_first[True]", "unit_test/options_toml_test.py::test_dig_first[False]", "unit_test/options_toml_test.py::test_pyproject_2[linux]", "unit_test/options_toml_test.py::test_pyproject_2[macos]", "unit_test/options_toml_test.py::test_pyproject_2[windows]", "unit_test/options_toml_test.py::test_overrides_not_a_list[linux]", "unit_test/options_toml_test.py::test_overrides_not_a_list[macos]", "unit_test/options_toml_test.py::test_overrides_not_a_list[windows]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-01 06:08:19+00:00
mit
4,975
pypa__cibuildwheel-1206
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 30772612..325eaac5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,7 @@ jobs: name: artifact path: dist - - uses: pypa/[email protected] + - uses: pypa/[email protected] with: user: __token__ password: ${{ secrets.pypi_password }} diff --git a/cibuildwheel/options.py b/cibuildwheel/options.py index 30803604..c8d050fa 100644 --- a/cibuildwheel/options.py +++ b/cibuildwheel/options.py @@ -1,5 +1,6 @@ from __future__ import annotations +import difflib import functools import os import sys @@ -188,14 +189,10 @@ def __init__( # Validate project config for option_name in config_options: - if not self._is_valid_global_option(option_name): - raise ConfigOptionError(f'Option "{option_name}" not supported in a config file') + self._validate_global_option(option_name) for option_name in config_platform_options: - if not self._is_valid_platform_option(option_name): - raise ConfigOptionError( - f'Option "{option_name}" not supported in the "{self.platform}" section' - ) + self._validate_platform_option(option_name) self.config_options = config_options self.config_platform_options = config_platform_options @@ -207,40 +204,51 @@ def __init__( if config_overrides is not None: if not isinstance(config_overrides, list): - raise ConfigOptionError('"tool.cibuildwheel.overrides" must be a list') + raise ConfigOptionError("'tool.cibuildwheel.overrides' must be a list") for config_override in config_overrides: select = config_override.pop("select", None) if not select: - raise ConfigOptionError('"select" must be set in an override') + raise ConfigOptionError("'select' must be set in an override") if isinstance(select, list): select = " ".join(select) self.overrides.append(Override(select, config_override)) - def _is_valid_global_option(self, name: str) -> bool: + def _validate_global_option(self, name: str) -> None: """ - Returns True if an option with this name is allowed in the + Raises an error if an option with this name is not allowed in the [tool.cibuildwheel] section of a config file. """ allowed_option_names = self.default_options.keys() | PLATFORMS | {"overrides"} - return name in allowed_option_names + if name not in allowed_option_names: + msg = f"Option {name!r} not supported in a config file." + matches = difflib.get_close_matches(name, allowed_option_names, 1, 0.7) + if matches: + msg += f" Perhaps you meant {matches[0]!r}?" + raise ConfigOptionError(msg) - def _is_valid_platform_option(self, name: str) -> bool: + def _validate_platform_option(self, name: str) -> None: """ - Returns True if an option with this name is allowed in the + Raises an error if an option with this name is not allowed in the [tool.cibuildwheel.<current-platform>] section of a config file. """ disallowed_platform_options = self.disallow.get(self.platform, set()) if name in disallowed_platform_options: - return False + msg = f"{name!r} is not allowed in {disallowed_platform_options}" + raise ConfigOptionError(msg) allowed_option_names = self.default_options.keys() | self.default_platform_options.keys() - return name in allowed_option_names + if name not in allowed_option_names: + msg = f"Option {name!r} not supported in the {self.platform!r} section" + matches = difflib.get_close_matches(name, allowed_option_names, 1, 0.7) + if matches: + msg += f" Perhaps you meant {matches[0]!r}?" + raise ConfigOptionError(msg) def _load_file(self, filename: Path) -> tuple[dict[str, Any], dict[str, Any]]: """ @@ -290,7 +298,8 @@ def get( """ if name not in self.default_options and name not in self.default_platform_options: - raise ConfigOptionError(f"{name} must be in cibuildwheel/resources/defaults.toml file") + msg = f"{name!r} must be in cibuildwheel/resources/defaults.toml file to be accessed." + raise ConfigOptionError(msg) # Environment variable form envvar = f"CIBW_{name.upper().replace('-', '_')}" @@ -314,12 +323,12 @@ def get( if isinstance(result, dict): if table is None: - raise ConfigOptionError(f"{name} does not accept a table") + raise ConfigOptionError(f"{name!r} does not accept a table") return table["sep"].join(table["item"].format(k=k, v=v) for k, v in result.items()) if isinstance(result, list): if sep is None: - raise ConfigOptionError(f"{name} does not accept a list") + raise ConfigOptionError(f"{name!r} does not accept a list") return sep.join(result) if isinstance(result, int): @@ -393,7 +402,7 @@ def globals(self) -> GlobalOptions: container_engine_str = self.reader.get("container-engine") if container_engine_str not in ["docker", "podman"]: - msg = f"cibuildwheel: Unrecognised container_engine '{container_engine_str}', only 'docker' and 'podman' are supported" + msg = f"cibuildwheel: Unrecognised container_engine {container_engine_str!r}, only 'docker' and 'podman' are supported" print(msg, file=sys.stderr) sys.exit(2) @@ -437,7 +446,7 @@ def build_options(self, identifier: str | None) -> BuildOptions: elif build_frontend_str == "pip": build_frontend = "pip" else: - msg = f"cibuildwheel: Unrecognised build frontend '{build_frontend_str}', only 'pip' and 'build' are supported" + msg = f"cibuildwheel: Unrecognised build frontend {build_frontend_str!r}, only 'pip' and 'build' are supported" print(msg, file=sys.stderr) sys.exit(2) @@ -445,7 +454,7 @@ def build_options(self, identifier: str | None) -> BuildOptions: environment = parse_environment(environment_config) except (EnvironmentParseError, ValueError): print( - f'cibuildwheel: Malformed environment option "{environment_config}"', + f"cibuildwheel: Malformed environment option {environment_config!r}", file=sys.stderr, ) traceback.print_exc(None, sys.stderr) diff --git a/examples/github-with-qemu.yml b/examples/github-with-qemu.yml index 1ba744d2..2911f98c 100644 --- a/examples/github-with-qemu.yml +++ b/examples/github-with-qemu.yml @@ -13,14 +13,9 @@ jobs: steps: - uses: actions/checkout@v3 - - uses: actions/setup-python@v3 - name: Install Python - with: - python-version: '3.7' - - name: Set up QEMU if: runner.os == 'Linux' - uses: docker/setup-qemu-action@v1 + uses: docker/setup-qemu-action@v2 with: platforms: all
pypa/cibuildwheel
c73152918723802fb39c9e9544e6dbf840845591
diff --git a/unit_test/options_toml_test.py b/unit_test/options_toml_test.py index a3fab2cc..a0a1705d 100644 --- a/unit_test/options_toml_test.py +++ b/unit_test/options_toml_test.py @@ -160,9 +160,28 @@ def test_unexpected_key(tmp_path): """ ) - with pytest.raises(ConfigOptionError): + with pytest.raises(ConfigOptionError) as excinfo: OptionsReader(pyproject_toml, platform="linux") + assert "repair-wheel-command" in str(excinfo.value) + + +def test_underscores_in_key(tmp_path): + # Note that platform contents are only checked when running + # for that platform. + pyproject_toml = tmp_path / "pyproject.toml" + pyproject_toml.write_text( + """ +[tool.cibuildwheel] +repair_wheel_command = "repair-project-linux" +""" + ) + + with pytest.raises(ConfigOptionError) as excinfo: + OptionsReader(pyproject_toml, platform="linux") + + assert "repair-wheel-command" in str(excinfo.value) + def test_unexpected_table(tmp_path): pyproject_toml = tmp_path / "pyproject.toml"
Question: Why `uses: actions/setup-python@v3` exists in github-with-qemu.yml while it is not in github-minimal.yml? ### Description Hello, In github-with-qemu.yml, is https://github.com/pypa/cibuildwheel/blob/7c7dda72084bd9203b4fffd3af856560f8e48c64/examples/github-with-qemu.yml#L16-L19 useful while it is not in github-minimal.yml or github-apple-silicon.yml? If it is not necessary, maybe those lines should be removed to simplify and for consistency... ### CI config GitHub Actions
0.0
c73152918723802fb39c9e9544e6dbf840845591
[ "unit_test/options_toml_test.py::test_unexpected_key", "unit_test/options_toml_test.py::test_underscores_in_key" ]
[ "unit_test/options_toml_test.py::test_simple_settings[linux-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[linux-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_simple_settings[macos-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[macos-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_simple_settings[windows-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[windows-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_envvar_override[linux]", "unit_test/options_toml_test.py::test_envvar_override[macos]", "unit_test/options_toml_test.py::test_envvar_override[windows]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[linux]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[macos]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[windows]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[linux]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[macos]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[windows]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[linux]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[macos]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[windows]", "unit_test/options_toml_test.py::test_global_platform_order[linux]", "unit_test/options_toml_test.py::test_global_platform_order[macos]", "unit_test/options_toml_test.py::test_global_platform_order[windows]", "unit_test/options_toml_test.py::test_unexpected_table", "unit_test/options_toml_test.py::test_unsupported_join", "unit_test/options_toml_test.py::test_disallowed_a", "unit_test/options_toml_test.py::test_environment_override_empty", "unit_test/options_toml_test.py::test_dig_first[True]", "unit_test/options_toml_test.py::test_dig_first[False]", "unit_test/options_toml_test.py::test_pyproject_2[linux]", "unit_test/options_toml_test.py::test_pyproject_2[macos]", "unit_test/options_toml_test.py::test_pyproject_2[windows]", "unit_test/options_toml_test.py::test_overrides_not_a_list[linux]", "unit_test/options_toml_test.py::test_overrides_not_a_list[macos]", "unit_test/options_toml_test.py::test_overrides_not_a_list[windows]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-01 11:09:21+00:00
mit
4,976
pypa__cibuildwheel-1273
diff --git a/cibuildwheel/environment.py b/cibuildwheel/environment.py index a544852a..23ea9877 100644 --- a/cibuildwheel/environment.py +++ b/cibuildwheel/environment.py @@ -4,6 +4,7 @@ from typing import Any, Mapping, Sequence import bashlex +import bashlex.errors from cibuildwheel.typing import Protocol @@ -33,7 +34,11 @@ def split_env_items(env_string: str) -> list[str]: if not env_string: return [] - command_node = bashlex.parsesingle(env_string) + try: + command_node = bashlex.parsesingle(env_string) + except bashlex.errors.ParsingError as e: + raise EnvironmentParseError(env_string) from e + result = [] for word_node in command_node.parts: diff --git a/cibuildwheel/options.py b/cibuildwheel/options.py index 75e367c6..5a03c6b8 100644 --- a/cibuildwheel/options.py +++ b/cibuildwheel/options.py @@ -10,7 +10,7 @@ from contextlib import contextmanager from dataclasses import asdict, dataclass from pathlib import Path -from typing import Any, Dict, Generator, Iterator, List, Mapping, Union, cast +from typing import Any, Callable, Dict, Generator, Iterator, List, Mapping, Union, cast if sys.version_info >= (3, 11): import tomllib @@ -23,7 +23,7 @@ from .environment import EnvironmentParseError, ParsedEnvironment, parse_environment from .oci_container import ContainerEngine from .projectfiles import get_requires_python_str -from .typing import PLATFORMS, Literal, PlatformName, TypedDict +from .typing import PLATFORMS, Literal, NotRequired, PlatformName, TypedDict from .util import ( MANYLINUX_ARCHS, MUSLLINUX_ARCHS, @@ -123,6 +123,7 @@ class Override: class TableFmt(TypedDict): item: str sep: str + quote: NotRequired[Callable[[str], str]] class ConfigOptionError(KeyError): @@ -329,7 +330,7 @@ def get( if table is None: raise ConfigOptionError(f"{name!r} does not accept a table") return table["sep"].join( - item for k, v in result.items() for item in _inner_fmt(k, v, table["item"]) + item for k, v in result.items() for item in _inner_fmt(k, v, table) ) if isinstance(result, list): @@ -343,14 +344,16 @@ def get( return result -def _inner_fmt(k: str, v: Any, table_item: str) -> Iterator[str]: +def _inner_fmt(k: str, v: Any, table: TableFmt) -> Iterator[str]: + quote_function = table.get("quote", lambda a: a) + if isinstance(v, list): for inner_v in v: - qv = shlex.quote(inner_v) - yield table_item.format(k=k, v=qv) + qv = quote_function(inner_v) + yield table["item"].format(k=k, v=qv) else: - qv = shlex.quote(v) - yield table_item.format(k=k, v=qv) + qv = quote_function(v) + yield table["item"].format(k=k, v=qv) class Options: @@ -449,13 +452,13 @@ def build_options(self, identifier: str | None) -> BuildOptions: build_frontend_str = self.reader.get("build-frontend", env_plat=False) environment_config = self.reader.get( - "environment", table={"item": "{k}={v}", "sep": " "} + "environment", table={"item": '{k}="{v}"', "sep": " "} ) environment_pass = self.reader.get("environment-pass", sep=" ").split() before_build = self.reader.get("before-build", sep=" && ") repair_command = self.reader.get("repair-wheel-command", sep=" && ") config_settings = self.reader.get( - "config-settings", table={"item": "{k}={v}", "sep": " "} + "config-settings", table={"item": "{k}={v}", "sep": " ", "quote": shlex.quote} ) dependency_versions = self.reader.get("dependency-versions") diff --git a/cibuildwheel/typing.py b/cibuildwheel/typing.py index a546d7bf..3ffa5476 100644 --- a/cibuildwheel/typing.py +++ b/cibuildwheel/typing.py @@ -10,6 +10,10 @@ else: from typing import Final, Literal, OrderedDict, Protocol, TypedDict +if sys.version_info < (3, 11): + from typing_extensions import NotRequired +else: + from typing import NotRequired __all__ = ( "Final", @@ -26,6 +30,7 @@ "OrderedDict", "Union", "assert_never", + "NotRequired", ) diff --git a/pyproject.toml b/pyproject.toml index 6c78cdb0..92c086e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,6 +66,7 @@ module = [ "setuptools", "pytest", # ignored in pre-commit to speed up check "bashlex", + "bashlex.*", "importlib_resources", "ghapi.*", ] diff --git a/setup.cfg b/setup.cfg index 4d9e9656..8a9f4ef9 100644 --- a/setup.cfg +++ b/setup.cfg @@ -37,7 +37,7 @@ install_requires = packaging>=20.9 platformdirs tomli;python_version < '3.11' - typing-extensions>=3.10.0.0;python_version < '3.8' + typing-extensions>=4.1.0;python_version < '3.11' python_requires = >=3.7 include_package_data = True zip_safe = False
pypa/cibuildwheel
00b2600cca381be796f3755f9c38065dfbf8c3b1
diff --git a/unit_test/options_test.py b/unit_test/options_test.py index f0fb5f63..73d558f4 100644 --- a/unit_test/options_test.py +++ b/unit_test/options_test.py @@ -1,11 +1,14 @@ from __future__ import annotations +import os import platform as platform_module import textwrap +from pathlib import Path import pytest from cibuildwheel.__main__ import get_build_identifiers +from cibuildwheel.bashlex_eval import local_environment_executor from cibuildwheel.environment import parse_environment from cibuildwheel.options import Options, _get_pinned_container_images @@ -59,7 +62,7 @@ def test_options_1(tmp_path, monkeypatch): default_build_options = options.build_options(identifier=None) - assert default_build_options.environment == parse_environment("FOO=BAR") + assert default_build_options.environment == parse_environment('FOO="BAR"') all_pinned_container_images = _get_pinned_container_images() pinned_x86_64_container_image = all_pinned_container_images["x86_64"] @@ -119,30 +122,75 @@ def test_passthrough_evil(tmp_path, monkeypatch, env_var_value): assert parsed_environment.as_dictionary(prev_environment={}) == {"ENV_VAR": env_var_value} +xfail_env_parse = pytest.mark.xfail( + raises=SystemExit, reason="until we can figure out the right way to quote these values" +) + + @pytest.mark.parametrize( "env_var_value", [ "normal value", - '"value wrapped in quotes"', - 'an unclosed double-quote: "', + pytest.param('"value wrapped in quotes"', marks=[xfail_env_parse]), + pytest.param('an unclosed double-quote: "', marks=[xfail_env_parse]), "string\nwith\ncarriage\nreturns\n", - "a trailing backslash \\", + pytest.param("a trailing backslash \\", marks=[xfail_env_parse]), ], ) def test_toml_environment_evil(tmp_path, monkeypatch, env_var_value): args = get_default_command_line_arguments() args.package_dir = tmp_path - with tmp_path.joinpath("pyproject.toml").open("w") as f: - f.write( - textwrap.dedent( - f"""\ - [tool.cibuildwheel.environment] - EXAMPLE='''{env_var_value}''' - """ - ) + tmp_path.joinpath("pyproject.toml").write_text( + textwrap.dedent( + f"""\ + [tool.cibuildwheel.environment] + EXAMPLE='''{env_var_value}''' + """ ) + ) options = Options(platform="linux", command_line_arguments=args) parsed_environment = options.build_options(identifier=None).environment assert parsed_environment.as_dictionary(prev_environment={}) == {"EXAMPLE": env_var_value} + + [email protected]( + "toml_assignment,result_value", + [ + ('TEST_VAR="simple_value"', "simple_value"), + # spaces + ('TEST_VAR="simple value"', "simple value"), + # env var + ('TEST_VAR="$PARAM"', "spam"), + ('TEST_VAR="$PARAM $PARAM"', "spam spam"), + # env var extension + ('TEST_VAR="before:$PARAM:after"', "before:spam:after"), + # env var extension with spaces + ('TEST_VAR="before $PARAM after"', "before spam after"), + # literal $ - this test is just for reference, I'm not sure if this + # syntax will work if we change the TOML quoting behaviour + (r'TEST_VAR="before\\$after"', "before$after"), + ], +) +def test_toml_environment_quoting(tmp_path: Path, toml_assignment, result_value): + args = get_default_command_line_arguments() + args.package_dir = tmp_path + + tmp_path.joinpath("pyproject.toml").write_text( + textwrap.dedent( + f"""\ + [tool.cibuildwheel.environment] + {toml_assignment} + """ + ) + ) + + options = Options(platform="linux", command_line_arguments=args) + parsed_environment = options.build_options(identifier=None).environment + environment_values = parsed_environment.as_dictionary( + prev_environment={**os.environ, "PARAM": "spam"}, + executor=local_environment_executor, + ) + + assert environment_values["TEST_VAR"] == result_value
`sh: No such file or directory` in `before_all` for linux builds with cibuildwheel v2.10.0 ### Description After updating from `2.9.0` to `v2.10.0`, I get the following error for linux builds using a simple `before-all` command like `before-all = "ls"`: ``` Running before_all... + /opt/python/cp38-cp38/bin/python -c 'import sys, json, os; json.dump(os.environ.copy(), sys.stdout)' + sh -c ls env: sh: No such file or directory ``` This seems to be related to the fact that we're updating the `PATH` environment variable: ``` [tool.cibuildwheel] before-all = "ls" environment = { PATH="$PATH:/usr/local/bin" } ```
0.0
00b2600cca381be796f3755f9c38065dfbf8c3b1
[ "unit_test/options_test.py::test_options_1", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"$PARAM\"-spam]", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"$PARAM", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"before:$PARAM:after\"-before:spam:after]", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"before", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"before\\\\\\\\$after\"-before$after]" ]
[ "unit_test/options_test.py::test_passthrough", "unit_test/options_test.py::test_passthrough_evil[normal", "unit_test/options_test.py::test_passthrough_evil[\"value", "unit_test/options_test.py::test_passthrough_evil[an", "unit_test/options_test.py::test_passthrough_evil[string\\nwith\\ncarriage\\nreturns\\n]", "unit_test/options_test.py::test_passthrough_evil[a", "unit_test/options_test.py::test_toml_environment_evil[normal", "unit_test/options_test.py::test_toml_environment_evil[string\\nwith\\ncarriage\\nreturns\\n]", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"simple_value\"-simple_value]", "unit_test/options_test.py::test_toml_environment_quoting[TEST_VAR=\"simple" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-09-17 10:22:40+00:00
mit
4,977
pypa__cibuildwheel-829
diff --git a/cibuildwheel/__main__.py b/cibuildwheel/__main__.py index a1cb85cd..9d1421ed 100644 --- a/cibuildwheel/__main__.py +++ b/cibuildwheel/__main__.py @@ -291,9 +291,9 @@ def main() -> None: for build_platform in MANYLINUX_ARCHS: pinned_images = all_pinned_docker_images[build_platform] - config_value = options(f"manylinux-{build_platform}-image") + config_value = options(f"manylinux-{build_platform}-image", ignore_empty=True) - if config_value is None: + if not config_value: # default to manylinux2010 if it's available, otherwise manylinux2014 image = pinned_images.get("manylinux2010") or pinned_images.get("manylinux2014") elif config_value in pinned_images: diff --git a/cibuildwheel/options.py b/cibuildwheel/options.py index 6631d762..5ee9c475 100644 --- a/cibuildwheel/options.py +++ b/cibuildwheel/options.py @@ -19,15 +19,26 @@ class ConfigOptionError(KeyError): pass -def _dig_first(*pairs: Tuple[Mapping[str, Any], str]) -> Setting: +def _dig_first(*pairs: Tuple[Mapping[str, Setting], str], ignore_empty: bool = False) -> Setting: """ Return the first dict item that matches from pairs of dicts and keys. - Final result is will throw a KeyError if missing. + Will throw a KeyError if missing. _dig_first((dict1, "key1"), (dict2, "key2"), ...) """ - (dict_like, key), *others = pairs - return dict_like.get(key, _dig_first(*others)) if others else dict_like[key] + if not pairs: + raise ValueError("pairs cannot be empty") + + for dict_like, key in pairs: + if key in dict_like: + value = dict_like[key] + + if ignore_empty and value == "": + continue + + return value + + raise KeyError(key) class ConfigOptions: @@ -62,7 +73,7 @@ def __init__( defaults_path = resources_dir / "defaults.toml" self.default_options, self.default_platform_options = self._load_file(defaults_path) - # load the project config file + # Load the project config file config_options: Dict[str, Any] = {} config_platform_options: Dict[str, Any] = {} @@ -75,7 +86,7 @@ def __init__( if pyproject_toml_path.exists(): config_options, config_platform_options = self._load_file(pyproject_toml_path) - # validate project config + # Validate project config for option_name in config_options: if not self._is_valid_global_option(option_name): raise ConfigOptionError(f'Option "{option_name}" not supported in a config file') @@ -129,6 +140,7 @@ def __call__( env_plat: bool = True, sep: Optional[str] = None, table: Optional[TableFmt] = None, + ignore_empty: bool = False, ) -> str: """ Get and return the value for the named option from environment, @@ -136,7 +148,8 @@ def __call__( accept platform versions of the environment variable. If this is an array it will be merged with "sep" before returning. If it is a table, it will be formatted with "table['item']" using {k} and {v} and merged - with "table['sep']". + with "table['sep']". Empty variables will not override if ignore_empty + is True. """ if name not in self.default_options and name not in self.default_platform_options: @@ -155,6 +168,7 @@ def __call__( (self.config_options, name), (self.default_platform_options, name), (self.default_options, name), + ignore_empty=ignore_empty, ) if isinstance(result, dict): diff --git a/docs/options.md b/docs/options.md index 53637f1d..6fe44c4c 100644 --- a/docs/options.md +++ b/docs/options.md @@ -797,8 +797,7 @@ ### CIBW_MANYLINUX_*_IMAGE {: #manylinux-image} Set an alternative Docker image to be used for building [manylinux](https://github.com/pypa/manylinux) wheels. cibuildwheel will then pull these instead of the default images, [`quay.io/pypa/manylinux2010_x86_64`](https://quay.io/pypa/manylinux2010_x86_64), [`quay.io/pypa/manylinux2010_i686`](https://quay.io/pypa/manylinux2010_i686), [`quay.io/pypa/manylinux2010_x86_64`](https://quay.io/pypa/manylinux2010_x86_64), [`quay.io/pypa/manylinux2014_aarch64`](https://quay.io/pypa/manylinux2014_aarch64), [`quay.io/pypa/manylinux2014_ppc64le`](https://quay.io/pypa/manylinux2014_ppc64le), and [`quay.io/pypa/manylinux2014_s390x`](https://quay.io/pypa/manylinux2010_s390x). The value of this option can either be set to `manylinux1`, `manylinux2010`, `manylinux2014` or `manylinux_2_24` to use a pinned version of the [official manylinux images](https://github.com/pypa/manylinux). Alternatively, set these options to any other valid Docker image name. For PyPy, the `manylinux1` image is not available. For architectures other -than x86 (x86\_64 and i686) `manylinux2014` or `manylinux_2_24` must be used, because the first version of the manylinux specification that supports additional architectures is `manylinux2014`. - +than x86 (x86\_64 and i686) `manylinux2014` or `manylinux_2_24` must be used, because the first version of the manylinux specification that supports additional architectures is `manylinux2014`. If this option is blank, it will fall though to the next available definition (environment variable -> pyproject.toml -> default). If setting a custom Docker image, you'll need to make sure it can be used in the same way as the official, default Docker images: all necessary Python and pip versions need to be present in `/opt/python/`, and the auditwheel tool needs to be present for cibuildwheel to work. Apart from that, the architecture and relevant shared system libraries need to be compatible to the relevant standard to produce valid manylinux1/manylinux2010/manylinux2014/manylinux_2_24 wheels (see [pypa/manylinux on GitHub](https://github.com/pypa/manylinux), [PEP 513](https://www.python.org/dev/peps/pep-0513/), [PEP 571](https://www.python.org/dev/peps/pep-0571/), [PEP 599](https://www.python.org/dev/peps/pep-0599/) and [PEP 600](https://www.python.org/dev/peps/pep-0600/) for more details).
pypa/cibuildwheel
fded547220d97f03121dbb50a9104d7341bea802
diff --git a/unit_test/options_toml_test.py b/unit_test/options_toml_test.py index dce9f8f5..d002d209 100644 --- a/unit_test/options_toml_test.py +++ b/unit_test/options_toml_test.py @@ -1,6 +1,6 @@ import pytest -from cibuildwheel.options import ConfigOptionError, ConfigOptions +from cibuildwheel.options import ConfigOptionError, ConfigOptions, _dig_first PYPROJECT_1 = """ [tool.cibuildwheel] @@ -181,10 +181,68 @@ def test_disallowed_a(tmp_path): tmp_path.joinpath("pyproject.toml").write_text( """ [tool.cibuildwheel.windows] -manylinux-x64_86-image = "manylinux1" +manylinux-x86_64-image = "manylinux1" """ ) - disallow = {"windows": {"manylinux-x64_86-image"}} + disallow = {"windows": {"manylinux-x86_64-image"}} ConfigOptions(tmp_path, platform="linux", disallow=disallow) with pytest.raises(ConfigOptionError): ConfigOptions(tmp_path, platform="windows", disallow=disallow) + + +def test_environment_override_empty(tmp_path, monkeypatch): + tmp_path.joinpath("pyproject.toml").write_text( + """ +[tool.cibuildwheel] +manylinux-i686-image = "manylinux1" +manylinux-x86_64-image = "" +""" + ) + + monkeypatch.setenv("CIBW_MANYLINUX_I686_IMAGE", "") + monkeypatch.setenv("CIBW_MANYLINUX_AARCH64_IMAGE", "manylinux1") + + options = ConfigOptions(tmp_path, platform="linux") + + assert options("manylinux-x86_64-image") == "" + assert options("manylinux-i686-image") == "" + assert options("manylinux-aarch64-image") == "manylinux1" + + assert options("manylinux-x86_64-image", ignore_empty=True) == "manylinux2010" + assert options("manylinux-i686-image", ignore_empty=True) == "manylinux1" + assert options("manylinux-aarch64-image", ignore_empty=True) == "manylinux1" + + [email protected]("ignore_empty", (True, False)) +def test_dig_first(ignore_empty): + d1 = {"random": "thing"} + d2 = {"this": "that", "empty": ""} + d3 = {"other": "hi"} + d4 = {"this": "d4", "empty": "not"} + + answer = _dig_first( + (d1, "empty"), + (d2, "empty"), + (d3, "empty"), + (d4, "empty"), + ignore_empty=ignore_empty, + ) + assert answer == ("not" if ignore_empty else "") + + answer = _dig_first( + (d1, "this"), + (d2, "this"), + (d3, "this"), + (d4, "this"), + ignore_empty=ignore_empty, + ) + assert answer == "that" + + with pytest.raises(KeyError): + _dig_first( + (d1, "this"), + (d2, "other"), + (d3, "this"), + (d4, "other"), + ignore_empty=ignore_empty, + )
Empty MANYLINUX env variable produces invalid result If the MANYLINUX environment variables are empty, then cibuildwheel fails, rather than falling back to either the value in the config or the default value. This means code like this is broken: ```yaml build_wheels: strategy: fail-fast: false matrix: os: [windows-latest, macos-latest, ubuntu-latest] arch: [auto64] build: ["*"] include: - os: ubuntu-latest arch: auto32 build: "*" - os: ubuntu-latest type: ManyLinux1 arch: auto build: "cp{36,37,38}-*" CIBW_MANYLINUX_X86_64_IMAGE: skhep/manylinuxgcc-x86_64 CIBW_MANYLINUX_I686_IMAGE: skhep/manylinuxgcc-i686 steps: - uses: actions/checkout@v2 - uses: pypa/[email protected] env: CIBW_BUILD: ${{ matrix.build }} CIBW_MANYLINUX_I686_IMAGE: ${{ matrix.CIBW_MANYLINUX_I686_IMAGE }} CIBW_MANYLINUX_X86_64_IMAGE: ${{ matrix.CIBW_MANYLINUX_X86_64_IMAGE }} CIBW_ARCHS: ${{ matrix.arch }} ``` This sets `CIBW_MANYLINUX_I686_IMAGE` to an empty string on most jobs, which is then an invalid docker container. This should either be the default, or better yet, the pyproject.toml file value or the default. I don't think this generalizes to all parameters, though; setting things like the repair command to an empty string is valid.
0.0
fded547220d97f03121dbb50a9104d7341bea802
[ "unit_test/options_toml_test.py::test_environment_override_empty", "unit_test/options_toml_test.py::test_dig_first[True]", "unit_test/options_toml_test.py::test_dig_first[False]" ]
[ "unit_test/options_toml_test.py::test_simple_settings[linux-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[linux-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_simple_settings[macos-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[macos-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_simple_settings[windows-pyproject.toml]", "unit_test/options_toml_test.py::test_simple_settings[windows-cibuildwheel.toml]", "unit_test/options_toml_test.py::test_envvar_override[linux]", "unit_test/options_toml_test.py::test_envvar_override[macos]", "unit_test/options_toml_test.py::test_envvar_override[windows]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[linux]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[macos]", "unit_test/options_toml_test.py::test_project_global_override_default_platform[windows]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[linux]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[macos]", "unit_test/options_toml_test.py::test_env_global_override_default_platform[windows]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[linux]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[macos]", "unit_test/options_toml_test.py::test_env_global_override_project_platform[windows]", "unit_test/options_toml_test.py::test_global_platform_order[linux]", "unit_test/options_toml_test.py::test_global_platform_order[macos]", "unit_test/options_toml_test.py::test_global_platform_order[windows]", "unit_test/options_toml_test.py::test_unexpected_key", "unit_test/options_toml_test.py::test_unexpected_table", "unit_test/options_toml_test.py::test_unsupported_join", "unit_test/options_toml_test.py::test_disallowed_a" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-09-17 02:35:22+00:00
mit
4,978
pypa__hatch-234
diff --git a/docs/config/environment.md b/docs/config/environment.md index 1727977a..c9b1115d 100644 --- a/docs/config/environment.md +++ b/docs/config/environment.md @@ -361,12 +361,36 @@ Scripts can also be defined as an array of strings. ] ``` +You can ignore the exit code of commands that start with `-` (a hyphen). For example, the script `error` defined by the following configuration would halt after the second command with `3` as the exit code: + +=== ":octicons-file-code-16: pyproject.toml" + + ```toml + [tool.hatch.envs.test.scripts] + error = [ + "- exit 1", + "exit 3", + "exit 0", + ] + ``` + +=== ":octicons-file-code-16: hatch.toml" + + ```toml + [envs.test.scripts] + error = [ + "- exit 1", + "exit 3", + "exit 0", + ] + ``` + !!! tip - Scripts [inherit](#inheritance) from parent environments just like options. + Individual scripts [inherit](#inheritance) from parent environments just like options. ## Commands -All commands are able to use any defined [scripts](#scripts). +All commands are able to use any defined [scripts](#scripts). Also like scripts, the exit code of commands that start with a hyphen will be ignored. ### Pre-install diff --git a/docs/history.md b/docs/history.md index 427320ec..accdadb2 100644 --- a/docs/history.md +++ b/docs/history.md @@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Add context formatting functionality i.e. the ability to insert values into configuration like environment variables and command line arguments - Add `--show-headers` option to the `env run` command to always display headers, even for single environments +- Similar to `make`, ignore the exit code of executed commands that start with `-` (a hyphen) - Update project metadata to reflect the adoption by PyPA ### [1.0.0](https://github.com/pypa/hatch/releases/tag/hatch-v1.0.0) - 2022-04-28 ### {: #hatch-v1.0.0 } diff --git a/src/hatch/cli/application.py b/src/hatch/cli/application.py index ac4e8dda..6601608b 100644 --- a/src/hatch/cli/application.py +++ b/src/hatch/cli/application.py @@ -93,6 +93,10 @@ class Application(Terminal): def run_shell_commands(self, environment, commands: list[str], show_code_on_error=True): with environment.command_context(): for command in environment.resolve_commands(commands): + if command.startswith('-'): + environment.run_shell_command(command[1:].strip()) + continue + process = environment.run_shell_command(command) if process.returncode: if show_code_on_error:
pypa/hatch
85cc5bf67155e778f6fabbb4022e919bb96fb499
diff --git a/tests/cli/run/test_run.py b/tests/cli/run/test_run.py index 3a18db1f..2738117c 100644 --- a/tests/cli/run/test_run.py +++ b/tests/cli/run/test_run.py @@ -399,6 +399,73 @@ def test_error(hatch, helpers, temp_dir, config_file): assert not output_file.is_file() +def test_ignore_error(hatch, helpers, temp_dir, config_file): + config_file.model.template.plugins['default']['tests'] = False + config_file.save() + + project_name = 'My App' + + with temp_dir.as_cwd(): + result = hatch('new', project_name) + + assert result.exit_code == 0, result.output + + project_path = temp_dir / 'my-app' + data_path = temp_dir / 'data' + data_path.mkdir() + + project = Project(project_path) + helpers.update_project_environment( + project, + 'default', + { + 'skip-install': True, + 'scripts': { + 'error': [ + '- python -c "import sys;sys.exit(3)"', + 'python -c "import pathlib,sys;pathlib.Path(\'test.txt\').write_text(sys.executable)"', + ], + }, + **project.config.envs['default'], + }, + ) + + with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): + result = hatch('run', 'error') + + assert result.exit_code == 0 + assert result.output == helpers.dedent( + """ + Creating environment: default + """ + ) + output_file = project_path / 'test.txt' + assert output_file.is_file() + + env_data_path = data_path / 'env' / 'virtual' + assert env_data_path.is_dir() + + storage_dirs = list(env_data_path.iterdir()) + assert len(storage_dirs) == 1 + + storage_path = storage_dirs[0] + + project_part = f'{project_path.name}-' + assert storage_path.name.startswith(project_part) + + hash_part = storage_path.name[len(project_part) :] + assert len(hash_part) == 8 + + env_dirs = list(storage_path.iterdir()) + assert len(env_dirs) == 1 + + env_path = env_dirs[0] + + assert env_path.name == project_path.name + + assert str(env_path) in str(output_file.read_text()) + + def test_matrix_no_environments(hatch, helpers, temp_dir, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save()
Option to run all commands in script array even if one fails [poethepoet](https://github.com/nat-n/poethepoet), for example, allows running all scripts even if any fail. The result code will be 0 only if all succeeded. This is nice so that you can always see all errors when running multiple linting commands, for example. It might be nice if hatch eventually had some more advanced functionality like poethepoet for running scripts, but right now this is the only feature I actually care about.
0.0
85cc5bf67155e778f6fabbb4022e919bb96fb499
[ "tests/cli/run/test_run.py::test_ignore_error" ]
[ "tests/cli/run/test_run.py::test_automatic_creation", "tests/cli/run/test_run.py::test_enter_project_directory", "tests/cli/run/test_run.py::test_sync_dependencies", "tests/cli/run/test_run.py::test_scripts", "tests/cli/run/test_run.py::test_scripts_specific_environment", "tests/cli/run/test_run.py::test_scripts_no_environment", "tests/cli/run/test_run.py::test_error", "tests/cli/run/test_run.py::test_matrix_no_environments", "tests/cli/run/test_run.py::test_matrix", "tests/cli/run/test_run.py::test_incompatible_single", "tests/cli/run/test_run.py::test_incompatible_matrix_full", "tests/cli/run/test_run.py::test_incompatible_matrix_partial", "tests/cli/run/test_run.py::test_incompatible_missing_python", "tests/cli/run/test_run.py::test_env_detection", "tests/cli/run/test_run.py::test_env_detection_override", "tests/cli/run/test_run.py::test_matrix_variable_selection_no_command", "tests/cli/run/test_run.py::test_matrix_variable_selection_duplicate_inclusion", "tests/cli/run/test_run.py::test_matrix_variable_selection_duplicate_exclusion", "tests/cli/run/test_run.py::test_matrix_variable_selection_python_alias", "tests/cli/run/test_run.py::test_matrix_variable_selection_not_matrix", "tests/cli/run/test_run.py::test_matrix_variable_selection_inclusion", "tests/cli/run/test_run.py::test_matrix_variable_selection_exclusion", "tests/cli/run/test_run.py::test_matrix_variable_selection_exclude_all", "tests/cli/run/test_run.py::test_matrix_variable_selection_include_none", "tests/cli/run/test_run.py::test_context_formatting_recursion" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-05-11 22:02:14+00:00
mit
4,979
pypa__hatch-340
diff --git a/docs/history.md b/docs/history.md index 513cf80f..20891b80 100644 --- a/docs/history.md +++ b/docs/history.md @@ -15,6 +15,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Support the absence of `pyproject.toml` files, as is the case for apps and non-Python projects - Hide scripts that start with an underscore for the `env show` command by default - Ignoring the exit codes of commands by prefixing with hyphens now works with entire named scripts +- Add a way to require confirmation for publishing - Add `--force-continue` flag to the `env run` command - Make tracebacks colorful and less verbose - When shell configuration has not been defined, attempt to use the current shell based on parent processes before resorting to the defaults diff --git a/docs/plugins/publisher/reference.md b/docs/plugins/publisher/reference.md index 1b29b336..ae2ce280 100644 --- a/docs/plugins/publisher/reference.md +++ b/docs/plugins/publisher/reference.md @@ -11,4 +11,5 @@ - cache_dir - project_config - plugin_config + - disable - publish diff --git a/docs/publish.md b/docs/publish.md index c568e8a2..5ed3569b 100644 --- a/docs/publish.md +++ b/docs/publish.md @@ -52,8 +52,33 @@ The `main` repository is used by default. ## Authentication -The first time you publish to a repository you need to authenticate using the `-u`/`--user` (environment variable `HATCH_PYPI_USER`) and `-a`/`--auth` (environment variable `HATCH_PYPI_AUTH`) options. You will be prompted if either option is not provided. +The first time you publish to a repository you need to authenticate using the `-u`/`--user` (environment variable `HATCH_PYPI_USER`) and `-a`/`--auth` (environment variable `HATCH_PYPI_AUTH`) options. You will be prompted if either option is not provided. The user that most recently published to the chosen repository is [cached](config/hatch.md#cache), with their credentials saved to the system [keyring](https://github.com/jaraco/keyring), so that they will no longer need to provide authentication information. For automated releases, it is recommended that you use per-project [API tokens](https://pypi.org/help/#apitoken). + +## Confirmation + +You can require a confirmation prompt or use of the `-y`/`--yes` flag by setting publishers' `disable` option to `true` in either Hatch's [config file](config/hatch.md) or project-specific configuration (which takes precedence): + +=== ":octicons-file-code-16: config.toml" + + ```toml + [publish.pypi] + disable = true + ``` + +=== ":octicons-file-code-16: pyproject.toml" + + ```toml + [tool.hatch.publish.pypi] + disable = true + ``` + +=== ":octicons-file-code-16: hatch.toml" + + ```toml + [publish.pypi] + disable = true + ``` diff --git a/src/hatch/cli/application.py b/src/hatch/cli/application.py index a54f897e..1c50d791 100644 --- a/src/hatch/cli/application.py +++ b/src/hatch/cli/application.py @@ -156,4 +156,5 @@ class SafeApplication: self.display_mini_header = app.display_mini_header # Divergence from what the backend provides self.prompt = app.prompt + self.confirm = app.confirm self.status_waiting = app.status_waiting diff --git a/src/hatch/cli/publish/__init__.py b/src/hatch/cli/publish/__init__.py index 1a2d5dcd..0596d07c 100644 --- a/src/hatch/cli/publish/__init__.py +++ b/src/hatch/cli/publish/__init__.py @@ -20,7 +20,7 @@ from hatch.config.constants import PublishEnvVars envvar=PublishEnvVars.REPO, help='The repository with which to publish artifacts [env var: `HATCH_PYPI_REPO`]', ) [email protected]('--no-prompt', '-n', is_flag=True, help='Do not prompt for missing required fields') [email protected]('--no-prompt', '-n', is_flag=True, help='Disable prompts, such as for missing required fields') @click.option( '--publisher', '-p', @@ -40,8 +40,9 @@ from hatch.config.constants import PublishEnvVars 'times e.g. `-o foo=bar -o baz=23` [env var: `HATCH_PUBLISHER_OPTIONS`]' ), ) [email protected]('--yes', '-y', is_flag=True, help='Confirm without prompting when the plugin is disabled') @click.pass_obj -def publish(app, artifacts, user, auth, repo, no_prompt, publisher_name, options): +def publish(app, artifacts, user, auth, repo, no_prompt, publisher_name, options, yes): """Publish build artifacts.""" option_map = {'no_prompt': no_prompt} if publisher_name == 'pypi': @@ -70,4 +71,7 @@ def publish(app, artifacts, user, auth, repo, no_prompt, publisher_name, options app.project.config.publish.get(publisher_name, {}), app.config.publish.get(publisher_name, {}), ) + if publisher.disable and not (yes or (not no_prompt and app.confirm(f'Confirm `{publisher_name}` publishing'))): + app.abort(f'Publisher is disabled: {publisher_name}') + publisher.publish(list(artifacts), option_map) diff --git a/src/hatch/cli/terminal.py b/src/hatch/cli/terminal.py index 0652a6d3..445d5942 100644 --- a/src/hatch/cli/terminal.py +++ b/src/hatch/cli/terminal.py @@ -192,6 +192,10 @@ class Terminal: def prompt(text, **kwargs): return click.prompt(text, **kwargs) + @staticmethod + def confirm(text, **kwargs): + return click.confirm(text, **kwargs) + class MockStatus: def stop(self): diff --git a/src/hatch/publish/plugin/interface.py b/src/hatch/publish/plugin/interface.py index 3134ddf7..b79406e1 100644 --- a/src/hatch/publish/plugin/interface.py +++ b/src/hatch/publish/plugin/interface.py @@ -42,6 +42,8 @@ class PublisherInterface(ABC): self.__project_config = project_config self.__plugin_config = plugin_config + self.__disable = None + @property def app(self): """ @@ -93,6 +95,30 @@ class PublisherInterface(ABC): """ return self.__plugin_config + @property + def disable(self): + """ + Whether this plugin is disabled, thus requiring confirmation when publishing. Local + [project configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.project_config) + takes precedence over global + [plugin configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.plugin_config). + """ + if self.__disable is None: + if 'disable' in self.project_config: + disable = self.project_config['disable'] + if not isinstance(disable, bool): + raise TypeError(f'Field `tool.hatch.publish.{self.PLUGIN_NAME}.disable` must be a boolean') + else: + disable = self.plugin_config.get('disable', False) + if not isinstance(disable, bool): + raise TypeError( + f'Global plugin configuration `publish.{self.PLUGIN_NAME}.disable` must be a boolean' + ) + + self.__disable = disable + + return self.__disable + @abstractmethod def publish(self, artifacts: list[str], options: dict): """
pypa/hatch
cd1956a80f04cc4304b5985098d21e0a0190aec4
diff --git a/tests/cli/publish/test_publish.py b/tests/cli/publish/test_publish.py index 619f2c59..81084f2e 100644 --- a/tests/cli/publish/test_publish.py +++ b/tests/cli/publish/test_publish.py @@ -130,6 +130,25 @@ def test_unknown_publisher(hatch, temp_dir): assert result.output == 'Unknown publisher: foo\n' +def test_disabled(hatch, temp_dir, config_file): + config_file.model.publish['pypi']['disable'] = True + config_file.save() + + project_name = 'My App' + + with temp_dir.as_cwd(): + result = hatch('new', project_name) + assert result.exit_code == 0, result.output + + path = temp_dir / 'my-app' + + with path.as_cwd(): + result = hatch('publish', '-n') + + assert result.exit_code == 1, result.output + assert result.output == 'Publisher is disabled: pypi\n' + + def test_missing_user(hatch, temp_dir): project_name = 'My App' @@ -406,6 +425,87 @@ def test_no_artifacts(hatch, temp_dir_cache, helpers, published_project_name): ) +def test_enable_with_flag(hatch, temp_dir_cache, helpers, published_project_name, config_file): + config_file.model.publish['pypi']['user'] = '__token__' + config_file.model.publish['pypi']['auth'] = PUBLISHER_TOKEN + config_file.model.publish['pypi']['repo'] = 'test' + config_file.model.publish['pypi']['disable'] = True + config_file.save() + + with temp_dir_cache.as_cwd(): + result = hatch('new', published_project_name) + assert result.exit_code == 0, result.output + + path = temp_dir_cache / published_project_name + + with path.as_cwd(): + del os.environ[PublishEnvVars.REPO] + + current_version = timestamp_to_version(helpers.get_current_timestamp()) + result = hatch('version', current_version) + assert result.exit_code == 0, result.output + + result = hatch('build') + assert result.exit_code == 0, result.output + + build_directory = path / 'dist' + artifacts = list(build_directory.iterdir()) + + result = hatch('publish', '-y') + + assert result.exit_code == 0, result.output + assert result.output == helpers.dedent( + f""" + {artifacts[0].relative_to(path)} ... success + {artifacts[1].relative_to(path)} ... success + + [{published_project_name}] + https://test.pypi.org/project/{published_project_name}/{current_version}/ + """ + ) + + +def test_enable_with_prompt(hatch, temp_dir_cache, helpers, published_project_name, config_file): + config_file.model.publish['pypi']['user'] = '__token__' + config_file.model.publish['pypi']['auth'] = PUBLISHER_TOKEN + config_file.model.publish['pypi']['repo'] = 'test' + config_file.model.publish['pypi']['disable'] = True + config_file.save() + + with temp_dir_cache.as_cwd(): + result = hatch('new', published_project_name) + assert result.exit_code == 0, result.output + + path = temp_dir_cache / published_project_name + + with path.as_cwd(): + del os.environ[PublishEnvVars.REPO] + + current_version = timestamp_to_version(helpers.get_current_timestamp()) + result = hatch('version', current_version) + assert result.exit_code == 0, result.output + + result = hatch('build') + assert result.exit_code == 0, result.output + + build_directory = path / 'dist' + artifacts = list(build_directory.iterdir()) + + result = hatch('publish', input='y\n') + + assert result.exit_code == 0, result.output + assert result.output == helpers.dedent( + f""" + Confirm `pypi` publishing [y/N]: y + {artifacts[0].relative_to(path)} ... success + {artifacts[1].relative_to(path)} ... success + + [{published_project_name}] + https://test.pypi.org/project/{published_project_name}/{current_version}/ + """ + ) + + class TestWheel: @pytest.mark.parametrize('field', ['name', 'version']) def test_missing_required_metadata_field(self, hatch, temp_dir_cache, helpers, published_project_name, field): diff --git a/tests/publish/__init__.py b/tests/publish/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/publish/plugin/__init__.py b/tests/publish/plugin/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/publish/plugin/test_interface.py b/tests/publish/plugin/test_interface.py new file mode 100644 index 00000000..c93ed9bd --- /dev/null +++ b/tests/publish/plugin/test_interface.py @@ -0,0 +1,56 @@ +import pytest + +from hatch.publish.plugin.interface import PublisherInterface + + +class MockPublisher(PublisherInterface): + PLUGIN_NAME = 'mock' + + def publish(self, artifacts, options): + pass + + +class TestDisable: + def test_default(self, isolation): + project_config = {} + plugin_config = {} + publisher = MockPublisher(None, isolation, None, project_config, plugin_config) + + assert publisher.disable is publisher.disable is False + + def test_project_config(self, isolation): + project_config = {'disable': True} + plugin_config = {} + publisher = MockPublisher(None, isolation, None, project_config, plugin_config) + + assert publisher.disable is True + + def test_project_config_not_boolean(self, isolation): + project_config = {'disable': 9000} + plugin_config = {} + publisher = MockPublisher(None, isolation, None, project_config, plugin_config) + + with pytest.raises(TypeError, match='Field `tool.hatch.publish.mock.disable` must be a boolean'): + _ = publisher.disable + + def test_plugin_config(self, isolation): + project_config = {} + plugin_config = {'disable': True} + publisher = MockPublisher(None, isolation, None, project_config, plugin_config) + + assert publisher.disable is True + + def test_plugin_config_not_boolean(self, isolation): + project_config = {} + plugin_config = {'disable': 9000} + publisher = MockPublisher(None, isolation, None, project_config, plugin_config) + + with pytest.raises(TypeError, match='Global plugin configuration `publish.mock.disable` must be a boolean'): + _ = publisher.disable + + def test_project_config_overrides_plugin_config(self, isolation): + project_config = {'disable': False} + plugin_config = {'disable': True} + publisher = MockPublisher(None, isolation, None, project_config, plugin_config) + + assert publisher.disable is False
Disabling `upload` per-project For private package development, I've always been afraid of `twine` and similar tools' "by-default" behavior when it comes to publishing packages. I love the `hatch version ...` syntax, and the easy and fast builds and plugins, so I'd to have it as an option for in-house standard builds. Is there any way to remove the default repository URL for `hatch` on a per-project basis? Something in `pyproject.toml` to specify the repository URL, so it isn't the public PyPi? I know I can do so via the user `config` file, as described [here](https://hatch.pypa.io/latest/publish/), but I'd ideally like to specify this for every project, so someone would have to edit the config file or supply a command-line argument to upload to PyPi. Is this supported?
0.0
cd1956a80f04cc4304b5985098d21e0a0190aec4
[ "tests/publish/plugin/test_interface.py::TestDisable::test_default", "tests/publish/plugin/test_interface.py::TestDisable::test_project_config", "tests/publish/plugin/test_interface.py::TestDisable::test_project_config_not_boolean", "tests/publish/plugin/test_interface.py::TestDisable::test_plugin_config", "tests/publish/plugin/test_interface.py::TestDisable::test_plugin_config_not_boolean", "tests/publish/plugin/test_interface.py::TestDisable::test_project_config_overrides_plugin_config" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-07-10 16:06:50+00:00
mit
4,980
pypa__hatch-377
diff --git a/docs/history.md b/docs/history.md index b429887a..8c6874b5 100644 --- a/docs/history.md +++ b/docs/history.md @@ -16,6 +16,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Add `name` override for environments to allow for regular expression matching - Add support for Almquist (`ash`) shells +***Fixed:*** + +- Acknowledge `extra-dependencies` for the `env show` command + ### [1.3.1](https://github.com/pypa/hatch/releases/tag/hatch-v1.3.1) - 2022-07-11 ### {: #hatch-v1.3.1 } ***Fixed:*** diff --git a/src/hatch/cli/env/show.py b/src/hatch/cli/env/show.py index 546e13e9..4c146b5a 100644 --- a/src/hatch/cli/env/show.py +++ b/src/hatch/cli/env/show.py @@ -23,8 +23,13 @@ def show(app, envs, force_ascii, as_json): if config.get('features'): columns['Features'][i] = '\n'.join(sorted({normalize_project_name(f) for f in config['features']})) + dependencies = [] if config.get('dependencies'): - columns['Dependencies'][i] = '\n'.join(get_normalized_dependencies(config['dependencies'])) + dependencies.extend(config['dependencies']) + if config.get('extra-dependencies'): + dependencies.extend(config['extra-dependencies']) + if dependencies: + columns['Dependencies'][i] = '\n'.join(get_normalized_dependencies(dependencies)) if config.get('env-vars'): columns['Environment variables'][i] = '\n'.join(
pypa/hatch
3f45eb3a7a1c9dbb32a0a405574d1eab052813b4
diff --git a/tests/cli/env/test_show.py b/tests/cli/env/test_show.py index 3d13e066..82172615 100644 --- a/tests/cli/env/test_show.py +++ b/tests/cli/env/test_show.py @@ -318,7 +318,8 @@ def test_optional_columns(hatch, helpers, temp_dir, config_file): data_path = temp_dir / 'data' data_path.mkdir() - dependencies = ['python___dateutil', 'bAr.Baz[TLS] >=1.2RC5', 'Foo;python_version<"3.8"'] + dependencies = ['python___dateutil', 'bAr.Baz[TLS] >=1.2RC5'] + extra_dependencies = ['Foo;python_version<"3.8"'] env_vars = {'FOO': '1', 'BAR': '2'} description = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna \ @@ -334,13 +335,21 @@ occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim 'matrix': [{'version': ['9000', '3.14'], 'py': ['39', '310']}], 'description': description, 'dependencies': dependencies, + 'extra-dependencies': extra_dependencies, 'env-vars': env_vars, 'features': ['Foo...Bar', 'Baz', 'baZ'], 'scripts': {'test': 'pytest', 'build': 'python -m build', '_foo': 'test'}, }, ) helpers.update_project_environment( - project, 'foo', {'description': description, 'dependencies': dependencies, 'env-vars': env_vars} + project, + 'foo', + { + 'description': description, + 'dependencies': dependencies, + 'extra-dependencies': extra_dependencies, + 'env-vars': env_vars, + }, ) with project_path.as_cwd():
'hatch env show' does not list dependencies from extra-dependencies I've got this in pyproject.toml: ```toml [tool.hatch.envs.lint] detached = true dependencies = [ "black", "flake8", ] [tool.hatch.envs.lint.scripts] lint = [ "flake8 --ignore=E501,E402,E231", "black --check .", "bash -c 'shellcheck workflow-support/*.sh'", ] [tool.hatch.envs.lint-action] template = "lint" extra-dependencies = [ "lintly23", "markupsafe==2.0.1", ] [tool.hatch.envs.lint-action.scripts] lint = [ "bash -c 'flake8 --ignore=E501,E402,E231 | lintly --format=flake8 --no-request-changes'", "bash -c 'black --check . 2>&1 >/dev/null | lintly --format=black --no-request-changes'", "bash -c 'shellcheck workflow-support/*.sh'", ] ``` But `hatch env show` reports this: ``` Standalone ┏━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━┓ ┃ Name ┃ Type ┃ Dependencies ┃ Scripts ┃ ┡━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━┩ │ default │ virtual │ │ │ ├─────────────┼─────────┼──────────────┼─────────┤ │ lint │ virtual │ black │ lint │ │ │ │ flake8 │ │ ├─────────────┼─────────┼──────────────┼─────────┤ │ lint-action │ virtual │ black │ lint │ │ │ │ flake8 │ │ └─────────────┴─────────┴──────────────┴─────────┘ ``` The inherited dependencies from `lint` to `lint-action` are correctly displayed, but the additional dependencies in `lint-action` are not. They *are* correctly installed into the lint-action enviroment.
0.0
3f45eb3a7a1c9dbb32a0a405574d1eab052813b4
[ "tests/cli/env/test_show.py::test_optional_columns" ]
[ "tests/cli/env/test_show.py::test_default", "tests/cli/env/test_show.py::test_default_as_json", "tests/cli/env/test_show.py::test_single_only", "tests/cli/env/test_show.py::test_single_and_matrix", "tests/cli/env/test_show.py::test_default_matrix_only", "tests/cli/env/test_show.py::test_all_matrix_types_with_single", "tests/cli/env/test_show.py::test_specific", "tests/cli/env/test_show.py::test_specific_unknown" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-07-28 00:26:24+00:00
mit
4,981
pypa__hatch-415
diff --git a/docs/history.md b/docs/history.md index 8dde7476..f02541f2 100644 --- a/docs/history.md +++ b/docs/history.md @@ -10,6 +10,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Unreleased +***Fixed:*** + +- Fix non-detached inheritance disabling for environments + ### [1.4.0](https://github.com/pypa/hatch/releases/tag/hatch-v1.4.0) - 2022-08-06 ### {: #hatch-v1.4.0 } ***Added:*** diff --git a/src/hatch/project/config.py b/src/hatch/project/config.py index a5db13b8..a821723b 100644 --- a/src/hatch/project/config.py +++ b/src/hatch/project/config.py @@ -426,8 +426,7 @@ def expand_script_commands(script_name, commands, config, seen, active): def _populate_default_env_values(env_name, data, config, seen, active): if env_name in seen: return - elif data.get('detached', False): - ensure_valid_environment(data) + elif data.pop('detached', False): data['template'] = env_name data['skip-install'] = True @@ -440,6 +439,7 @@ def _populate_default_env_values(env_name, data, config, seen, active): active.append(env_name) raise ValueError(f'Circular inheritance detected for field `tool.hatch.envs.*.template`: {" -> ".join(active)}') elif template_name == env_name: + ensure_valid_environment(data) seen.add(env_name) return
pypa/hatch
b14f6ffbf7f549dc45a9fc07277edd15bcff3ad1
diff --git a/tests/project/test_config.py b/tests/project/test_config.py index 3f68823d..ee64e86f 100644 --- a/tests/project/test_config.py +++ b/tests/project/test_config.py @@ -174,13 +174,22 @@ class TestEnvs: 'baz': {'type': 'virtual', 'scripts': {'cmd1': 'bar', 'cmd2': 'baz'}}, } + def test_self_referential(self, isolation): + env_config = {'default': {'option1': 'foo'}, 'bar': {'template': 'bar'}} + project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) + + assert project_config.envs == { + 'default': {'type': 'virtual', 'option1': 'foo'}, + 'bar': {'type': 'virtual'}, + } + def test_detached(self, isolation): env_config = {'default': {'option1': 'foo'}, 'bar': {'detached': True}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == { 'default': {'type': 'virtual', 'option1': 'foo'}, - 'bar': {'type': 'virtual', 'detached': True, 'skip-install': True}, + 'bar': {'type': 'virtual', 'skip-install': True}, } def test_matrices_not_array(self, isolation):
"Self-referential environments" raises error Hi Thank you for a very nice tool :) Reference to documentation: [Self-referential environments](https://hatch.pypa.io/latest/config/environment/overview/#self-referential-environments) Using config: ```toml [tool.hatch.envs.lock] template = "lock" ``` ```bash $ hatch --version Hatch, version 1.4.0 $ hatch run lock:pip list KeyError: 'type' ```
0.0
b14f6ffbf7f549dc45a9fc07277edd15bcff3ad1
[ "tests/project/test_config.py::TestEnvs::test_self_referential", "tests/project/test_config.py::TestEnvs::test_detached" ]
[ "tests/project/test_config.py::TestEnv::test_not_table", "tests/project/test_config.py::TestEnv::test_default", "tests/project/test_config.py::TestEnvCollectors::test_not_table", "tests/project/test_config.py::TestEnvCollectors::test_collector_not_table", "tests/project/test_config.py::TestEnvCollectors::test_default", "tests/project/test_config.py::TestEnvCollectors::test_defined", "tests/project/test_config.py::TestEnvs::test_not_table", "tests/project/test_config.py::TestEnvs::test_config_not_table", "tests/project/test_config.py::TestEnvs::test_unknown_collector", "tests/project/test_config.py::TestEnvs::test_unknown_template", "tests/project/test_config.py::TestEnvs::test_default_undefined", "tests/project/test_config.py::TestEnvs::test_default_partially_defined", "tests/project/test_config.py::TestEnvs::test_default_defined", "tests/project/test_config.py::TestEnvs::test_basic", "tests/project/test_config.py::TestEnvs::test_basic_override", "tests/project/test_config.py::TestEnvs::test_multiple_inheritance", "tests/project/test_config.py::TestEnvs::test_circular_inheritance", "tests/project/test_config.py::TestEnvs::test_scripts_inheritance", "tests/project/test_config.py::TestEnvs::test_matrices_not_array", "tests/project/test_config.py::TestEnvs::test_matrix_not_table", "tests/project/test_config.py::TestEnvs::test_matrix_empty", "tests/project/test_config.py::TestEnvs::test_matrix_variable_empty_string", "tests/project/test_config.py::TestEnvs::test_matrix_variable_not_array", "tests/project/test_config.py::TestEnvs::test_matrix_variable_array_empty", "tests/project/test_config.py::TestEnvs::test_matrix_variable_entry_not_string", "tests/project/test_config.py::TestEnvs::test_matrix_variable_entry_empty_string", "tests/project/test_config.py::TestEnvs::test_matrix_variable_entry_duplicate", "tests/project/test_config.py::TestEnvs::test_matrix_multiple_python_variables", "tests/project/test_config.py::TestEnvs::test_matrix_name_format_not_string", "tests/project/test_config.py::TestEnvs::test_matrix_name_format_invalid", "tests/project/test_config.py::TestEnvs::test_overrides_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_platform_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_env_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_name_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_platform_entry_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_env_entry_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_entry_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_name_entry_not_table", "tests/project/test_config.py::TestEnvs::test_matrix_simple_no_python", "tests/project/test_config.py::TestEnvs::test_matrix_simple_no_python_custom_name_format", "tests/project/test_config.py::TestEnvs::test_matrix_simple_only_python[py]", "tests/project/test_config.py::TestEnvs::test_matrix_simple_only_python[python]", "tests/project/test_config.py::TestEnvs::test_matrix_simple[py]", "tests/project/test_config.py::TestEnvs::test_matrix_simple[python]", "tests/project/test_config.py::TestEnvs::test_matrix_simple_custom_name_format[py]", "tests/project/test_config.py::TestEnvs::test_matrix_simple_custom_name_format[python]", "tests/project/test_config.py::TestEnvs::test_matrix_multiple_non_python", "tests/project/test_config.py::TestEnvs::test_matrix_series", "tests/project/test_config.py::TestEnvs::test_matrices_not_inherited", "tests/project/test_config.py::TestEnvs::test_matrix_default_naming", "tests/project/test_config.py::TestEnvs::test_matrix_pypy_naming", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_invalid_type[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_invalid_type[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_entry_invalid_type[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_entry_invalid_type[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_no_key[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_no_key[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_key_not_string[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_key_not_string[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_key_empty_string[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_key_empty_string[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_value_not_string[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_value_not_string[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_if_not_array[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_table_entry_if_not_array[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_invalid_type[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_no_value[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_not_string[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_value_empty_string[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_entry_if_not_array[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_entry_invalid_type[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_invalid_type[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_invalid_type[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_no_value[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_no_value[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_value_not_string[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_value_not_string[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_entry_invalid_type[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_entry_invalid_type[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_no_value[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_no_value[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_value_not_string[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_value_not_string[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_if_not_array[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_if_not_array[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_invalid_type[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_invalid_type[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_no_value[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_no_value[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_value_not_boolean[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_value_not_boolean[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_entry_invalid_type[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_entry_invalid_type[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_no_value[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_no_value[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_value_not_boolean[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_value_not_boolean[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_if_not_array[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_if_not_array[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_platform_not_array[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_platform_not_array[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_platform_item_not_string[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_platform_item_not_string[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_env_not_array[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_env_not_array[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_env_item_not_string[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_env_item_not_string[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_string_with_value[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_string_with_value[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_string_without_value[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_string_without_value[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_string_override[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_string_override[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_string_with_value[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_string_with_value[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_string_without_value[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_string_without_value[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_string_override[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_string_override[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_key_with_value[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_key_with_value[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_key_without_value[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_key_without_value[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_override[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_override[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_conditional[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_array_table_conditional[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_overwrite[env-vars]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_mapping_overwrite[scripts]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_string_existing_append[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_existing_append[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_platform[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_wrong_platform[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_match_empty_string[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_present[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_no_match[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_table_conditional_with_env_var_missing[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_set_with_no_type_information", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_set_with_no_type_information_not_table", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[dependencies]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[env-exclude]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[env-include]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[features]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[platforms]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[post-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_array_overwrite[pre-install-commands]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_string_create[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_string_create[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_string_overwrite[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_string_overwrite[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_create[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_create[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_override[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_override[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_conditional[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_table_conditional[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_create[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_create[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_override[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_override[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_conditional[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_conditional[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_conditional_eager_string[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_conditional_eager_string[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_conditional_eager_table[python]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_string_array_table_conditional_eager_table[type]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_boolean_create[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_boolean_create[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_boolean_overwrite[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_boolean_overwrite[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_create[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_create[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_override[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_override[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_conditional[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_table_conditional[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_create[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_create[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_override[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_override[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_conditional[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_conditional[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_conditional_eager_boolean[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_conditional_eager_boolean[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_conditional_eager_table[dev-mode]", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_boolean_array_table_conditional_eager_table[skip-install]", "tests/project/test_config.py::TestEnvs::test_overrides_platform_boolean_boolean_create", "tests/project/test_config.py::TestEnvs::test_overrides_platform_boolean_boolean_overwrite", "tests/project/test_config.py::TestEnvs::test_overrides_platform_boolean_table_create", "tests/project/test_config.py::TestEnvs::test_overrides_platform_boolean_table_overwrite", "tests/project/test_config.py::TestEnvs::test_overrides_env_boolean_boolean_create", "tests/project/test_config.py::TestEnvs::test_overrides_env_boolean_boolean_overwrite", "tests/project/test_config.py::TestEnvs::test_overrides_env_boolean_table_create", "tests/project/test_config.py::TestEnvs::test_overrides_env_boolean_table_overwrite", "tests/project/test_config.py::TestEnvs::test_overrides_env_boolean_conditional", "tests/project/test_config.py::TestEnvs::test_overrides_name_boolean_boolean_create", "tests/project/test_config.py::TestEnvs::test_overrides_name_boolean_boolean_overwrite", "tests/project/test_config.py::TestEnvs::test_overrides_name_boolean_table_create", "tests/project/test_config.py::TestEnvs::test_overrides_name_boolean_table_overwrite", "tests/project/test_config.py::TestEnvs::test_overrides_name_precedence_over_matrix", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_precedence_over_platform", "tests/project/test_config.py::TestEnvs::test_overrides_matrix_precedence_over_env", "tests/project/test_config.py::TestEnvs::test_overrides_env_precedence_over_platform", "tests/project/test_config.py::TestEnvs::test_overrides_for_environment_plugins", "tests/project/test_config.py::TestEnvs::test_environment_collector_finalize_config", "tests/project/test_config.py::TestEnvs::test_environment_collector_finalize_environments", "tests/project/test_config.py::TestPublish::test_not_table", "tests/project/test_config.py::TestPublish::test_config_not_table", "tests/project/test_config.py::TestPublish::test_default", "tests/project/test_config.py::TestPublish::test_defined", "tests/project/test_config.py::TestScripts::test_not_table", "tests/project/test_config.py::TestScripts::test_name_contains_spaces", "tests/project/test_config.py::TestScripts::test_default", "tests/project/test_config.py::TestScripts::test_single_commands", "tests/project/test_config.py::TestScripts::test_multiple_commands", "tests/project/test_config.py::TestScripts::test_multiple_commands_not_string", "tests/project/test_config.py::TestScripts::test_config_invalid_type", "tests/project/test_config.py::TestScripts::test_command_expansion_basic", "tests/project/test_config.py::TestScripts::test_command_expansion_multiple_nested", "tests/project/test_config.py::TestScripts::test_command_expansion_multiple_nested_ignore_exit_code", "tests/project/test_config.py::TestScripts::test_command_expansion_modification", "tests/project/test_config.py::TestScripts::test_command_expansion_circular_inheritance" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-08-13 03:38:00+00:00
mit
4,982
pypa__hatch-422
diff --git a/backend/src/hatchling/cli/version/__init__.py b/backend/src/hatchling/cli/version/__init__.py index babc7f00..a67fc430 100644 --- a/backend/src/hatchling/cli/version/__init__.py +++ b/backend/src/hatchling/cli/version/__init__.py @@ -14,7 +14,7 @@ def version_impl(called_by_app, desired_version): plugin_manager = PluginManager() metadata = ProjectMetadata(root, plugin_manager) - if metadata.core.version is not None: + if 'version' in metadata.config.get('project', {}): if desired_version: app.abort('Cannot set version when it is statically defined by the `project.version` field') else: diff --git a/docs/history.md b/docs/history.md index 8e9f170d..1d5cdd7c 100644 --- a/docs/history.md +++ b/docs/history.md @@ -10,6 +10,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Unreleased +***Fixed:*** + +- Fix check for updating static versions with the `version` command when metadata hooks are in use + ### [1.4.1](https://github.com/pypa/hatch/releases/tag/hatch-v1.4.1) - 2022-08-13 ### {: #hatch-v1.4.1 } ***Fixed:*** @@ -136,6 +140,10 @@ This is the first stable release of Hatch v1, a complete rewrite. Enjoy! ### Unreleased +***Fixed:*** + +- Fix check for updating static versions with the `version` command when metadata hooks are in use + ### [1.7.1](https://github.com/pypa/hatch/releases/tag/hatchling-v1.7.1) - 2022-08-13 ### {: #hatchling-v1.7.1 } ***Fixed:*** diff --git a/src/hatch/cli/version/__init__.py b/src/hatch/cli/version/__init__.py index 80120f2e..d87b2120 100644 --- a/src/hatch/cli/version/__init__.py +++ b/src/hatch/cli/version/__init__.py @@ -6,7 +6,7 @@ import click @click.pass_obj def version(app, desired_version): """View or set a project's version.""" - if app.project.metadata.core.version is not None: + if 'version' in app.project.metadata.config.get('project', {}): if desired_version: app.abort('Cannot set version when it is statically defined by the `project.version` field') else:
pypa/hatch
f6a06fdb675461614dc1c218a8c45fe4f35ee408
diff --git a/tests/cli/version/test_version.py b/tests/cli/version/test_version.py index a2e2ec23..5cb34a00 100644 --- a/tests/cli/version/test_version.py +++ b/tests/cli/version/test_version.py @@ -1,4 +1,5 @@ from hatch.project.core import Project +from hatchling.utils.constants import DEFAULT_BUILD_SCRIPT def test_show_dynamic(hatch, temp_dir): @@ -24,6 +25,24 @@ def test_set_dynamic(hatch, helpers, temp_dir): path = temp_dir / 'my-app' + project = Project(path) + config = dict(project.raw_config) + config['tool']['hatch']['metadata'] = {'hooks': {'custom': {}}} + project.save_config(config) + + build_script = path / DEFAULT_BUILD_SCRIPT + build_script.write_text( + helpers.dedent( + """ + from hatchling.metadata.plugin.interface import MetadataHookInterface + + class CustomMetadataHook(MetadataHookInterface): + def update(self, metadata): + pass + """ + ) + ) + with path.as_cwd(): result = hatch('version', 'minor,rc')
`hatch version <new-version>` fails when any custom metadata hook is installed ### Setup hatch 1.4.1 #### pyproject.toml ```toml [project] name = "myapp" dynamic = ["version"] [tool.hatch.version] path = "myapp/__init__.py" [tool.hatch.metadata.hooks] custom = {} ``` #### hatch_build.py ```py from hatchling.metadata.plugin.interface import MetadataHookInterface class CustomMetadataHook(MetadataHookInterface): def update(self, metadata: dict) -> None: pass ``` #### myapp/\_\_init\_\_.py ```py __version__ = '1.0.0' ``` ### Steps `hatch version patch` ### Result ``` Cannot set version when it is statically defined by the `project.version` field ``` ### Expected ``` Old: 1.0.0 New: 1.0.1 ``` ### More details Commenting out the custom metadata hook works around the error. Perhaps the test in hatch/cli/version/\_\_init\_\_.py should be more like `'version' in app.project.metadata.config['project']`?
0.0
f6a06fdb675461614dc1c218a8c45fe4f35ee408
[ "tests/cli/version/test_version.py::test_set_dynamic" ]
[ "tests/cli/version/test_version.py::test_show_dynamic", "tests/cli/version/test_version.py::test_show_static", "tests/cli/version/test_version.py::test_set_static" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-16 01:47:38+00:00
mit
4,983
pypa__hatch-434
diff --git a/docs/history.md b/docs/history.md index cb5382fa..d1ad35c7 100644 --- a/docs/history.md +++ b/docs/history.md @@ -10,6 +10,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Unreleased +***Added:*** + +- The `index` publisher now recognizes repository-specific options + ***Fixed:*** - Handle more edge cases in the `setuptools` migration script diff --git a/docs/plugins/publisher/package-index.md b/docs/plugins/publisher/package-index.md index 5f5213e5..a4021da4 100644 --- a/docs/plugins/publisher/package-index.md +++ b/docs/plugins/publisher/package-index.md @@ -24,4 +24,20 @@ The publisher plugin name is `index`. | `--ca-cert` | `ca-cert` | The path to a CA bundle | | `--client-cert` | `client-cert` | The path to a client certificate, optionally containing the private key | | `--client-key` | `client-key` | The path to the client certificate's private key | -| | `repos` | A table of named repositories to their respective URLs | +| | `repos` | A table of named [repositories](#repositories) to their respective options | + +## Repositories + +All top-level options can be overridden per repository using the `repos` table with a required `url` attribute for each repository. The following shows the default configuration: + +=== ":octicons-file-code-16: config.toml" + + ```toml + [publish.index.repos.main] + url = "https://upload.pypi.org/legacy/" + + [publish.index.repos.test] + url = "https://test.pypi.org/legacy/" + ``` + +The `repo` and `repos` options have no effect. diff --git a/docs/publish.md b/docs/publish.md index 56b3cd7e..959b0eaf 100644 --- a/docs/publish.md +++ b/docs/publish.md @@ -36,8 +36,8 @@ Rather than specifying the full URL of a repository, you can use a named reposit === ":octicons-file-code-16: config.toml" ```toml - [publish.index.repos] - repo1 = "url1" + [publish.index.repos.private] + url = "..." ... ``` diff --git a/src/hatch/config/model.py b/src/hatch/config/model.py index 886b3ad8..08a48747 100644 --- a/src/hatch/config/model.py +++ b/src/hatch/config/model.py @@ -181,7 +181,7 @@ class RootConfig(LazilyParsedConfig): self._field_publish = publish else: - self._field_publish = self.raw_data['publish'] = {'index': {'user': '', 'auth': ''}} + self._field_publish = self.raw_data['publish'] = {'index': {'repo': 'main'}} return self._field_publish diff --git a/src/hatch/publish/index.py b/src/hatch/publish/index.py index d4953f20..fc77d41d 100644 --- a/src/hatch/publish/index.py +++ b/src/hatch/publish/index.py @@ -11,12 +11,33 @@ from hatchling.metadata.utils import normalize_project_name class IndexPublisher(PublisherInterface): PLUGIN_NAME = 'index' - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - self.repos = self.plugin_config.get('repos', {}).copy() - self.repos['main'] = 'https://upload.pypi.org/legacy/' - self.repos['test'] = 'https://test.pypi.org/legacy/' + def get_repos(self): + global_plugin_config = self.plugin_config.copy() + defined_repos = self.plugin_config.pop('repos', {}) + self.plugin_config.pop('repo', None) + + # Normalize type + repos = {} + for repo, data in defined_repos.items(): + if isinstance(data, str): + data = {'url': data} + elif not isinstance(data, dict): + self.app.abort(f'Hatch config field `publish.index.repos.{repo}` must be a string or a mapping') + elif 'url' not in data: + self.app.abort(f'Hatch config field `publish.index.repos.{repo}` must define a `url` key') + + repos[repo] = data + + # Ensure PyPI correct + for repo, url in (('main', 'https://upload.pypi.org/legacy/'), ('test', 'https://test.pypi.org/legacy/')): + repos.setdefault(repo, {})['url'] = url + + # Populate defaults + for config in repos.values(): + for key, value in global_plugin_config.items(): + config.setdefault(key, value) + + return repos def publish(self, artifacts: list, options: dict): """ @@ -37,14 +58,18 @@ class IndexPublisher(PublisherInterface): else: repo = self.plugin_config.get('repo', 'main') - if repo in self.repos: - repo = self.repos[repo] + repos = self.get_repos() + + if repo in repos: + repo_config = repos[repo] + else: + repo_config = {'url': repo} index = PackageIndex( - repo, - ca_cert=options.get('ca_cert', self.plugin_config.get('ca-cert')), - client_cert=options.get('client_cert', self.plugin_config.get('client-cert')), - client_key=options.get('client_key', self.plugin_config.get('client-key')), + repo_config['url'], + ca_cert=options.get('ca_cert', repo_config.get('ca-cert')), + client_cert=options.get('client_cert', repo_config.get('client-cert')), + client_key=options.get('client_key', repo_config.get('client-key')), ) cached_user_file = CachedUserFile(self.cache_dir) @@ -52,7 +77,7 @@ class IndexPublisher(PublisherInterface): if 'user' in options: user = options['user'] else: - user = self.plugin_config.get('user', '') + user = repo_config.get('user', '') if not user: user = cached_user_file.get_user(repo) if user is None: @@ -66,7 +91,7 @@ class IndexPublisher(PublisherInterface): if 'auth' in options: auth = options['auth'] else: - auth = self.plugin_config.get('auth', '') + auth = repo_config.get('auth', '') if not auth: import keyring
pypa/hatch
0d3559c43d260cd3167063c75db0183afcdc2f6b
diff --git a/tests/cli/config/test_show.py b/tests/cli/config/test_show.py index a5edef0d..abf28ef1 100644 --- a/tests/cli/config/test_show.py +++ b/tests/cli/config/test_show.py @@ -80,7 +80,7 @@ def test_reveal(hatch, config_file, helpers, default_cache_dir, default_data_dir [projects] [publish.index] - user = "" + repo = "main" auth = "bar" [template] diff --git a/tests/cli/publish/test_publish.py b/tests/cli/publish/test_publish.py index c49a0d40..a16dcffd 100644 --- a/tests/cli/publish/test_publish.py +++ b/tests/cli/publish/test_publish.py @@ -119,6 +119,44 @@ def test_disabled(hatch, temp_dir, config_file): assert result.output == 'Publisher is disabled: index\n' +def test_repo_invalid_type(hatch, temp_dir, config_file): + config_file.model.publish['index']['repos'] = {'dev': 9000} + config_file.save() + + project_name = 'My.App' + + with temp_dir.as_cwd(): + result = hatch('new', project_name) + assert result.exit_code == 0, result.output + + path = temp_dir / 'my-app' + + with path.as_cwd(): + result = hatch('publish', '--user', 'foo', '--auth', 'bar') + + assert result.exit_code == 1, result.output + assert result.output == 'Hatch config field `publish.index.repos.dev` must be a string or a mapping\n' + + +def test_repo_missing_url(hatch, temp_dir, config_file): + config_file.model.publish['index']['repos'] = {'dev': {}} + config_file.save() + + project_name = 'My.App' + + with temp_dir.as_cwd(): + result = hatch('new', project_name) + assert result.exit_code == 0, result.output + + path = temp_dir / 'my-app' + + with path.as_cwd(): + result = hatch('publish', '--user', 'foo', '--auth', 'bar') + + assert result.exit_code == 1, result.output + assert result.output == 'Hatch config field `publish.index.repos.dev` must define a `url` key\n' + + def test_missing_user(hatch, temp_dir): project_name = 'My.App' @@ -226,6 +264,49 @@ def test_plugin_config(hatch, devpi, temp_dir_cache, helpers, published_project_ ) +def test_plugin_config_repo_override(hatch, devpi, temp_dir_cache, helpers, published_project_name, config_file): + config_file.model.publish['index']['user'] = 'foo' + config_file.model.publish['index']['auth'] = 'bar' + config_file.model.publish['index']['ca-cert'] = 'cert' + config_file.model.publish['index']['repo'] = 'dev' + config_file.model.publish['index']['repos'] = { + 'dev': {'url': devpi.repo, 'user': devpi.user, 'auth': devpi.auth, 'ca-cert': devpi.ca_cert}, + } + config_file.save() + + with temp_dir_cache.as_cwd(): + result = hatch('new', published_project_name) + assert result.exit_code == 0, result.output + + path = temp_dir_cache / published_project_name + + with path.as_cwd(): + del os.environ[PublishEnvVars.REPO] + + current_version = timestamp_to_version(helpers.get_current_timestamp()) + result = hatch('version', current_version) + assert result.exit_code == 0, result.output + + result = hatch('build') + assert result.exit_code == 0, result.output + + build_directory = path / 'dist' + artifacts = list(build_directory.iterdir()) + + result = hatch('publish') + + assert result.exit_code == 0, result.output + assert result.output == helpers.dedent( + f""" + {artifacts[0].relative_to(path)} ... success + {artifacts[1].relative_to(path)} ... success + + [{published_project_name}] + {devpi.repo}{published_project_name}/{current_version}/ + """ + ) + + def test_prompt(hatch, devpi, temp_dir_cache, helpers, published_project_name, config_file): config_file.model.publish['index']['ca-cert'] = devpi.ca_cert config_file.model.publish['index']['repo'] = 'dev' diff --git a/tests/config/test_model.py b/tests/config/test_model.py index 778724de..c0d3ea2f 100644 --- a/tests/config/test_model.py +++ b/tests/config/test_model.py @@ -21,7 +21,7 @@ def test_default(default_cache_dir, default_data_dir): 'cache': str(default_cache_dir), }, 'projects': {}, - 'publish': {'index': {'user': '', 'auth': ''}}, + 'publish': {'index': {'repo': 'main'}}, 'template': { 'name': 'Foo Bar', 'email': '[email protected]', @@ -722,8 +722,8 @@ class TestPublish: def test_default(self): config = RootConfig({}) - assert config.publish == config.publish == {'index': {'user': '', 'auth': ''}} - assert config.raw_data == {'publish': {'index': {'user': '', 'auth': ''}}} + assert config.publish == config.publish == {'index': {'repo': 'main'}} + assert config.raw_data == {'publish': {'index': {'repo': 'main'}}} def test_defined(self): config = RootConfig({'publish': {'foo': {'username': '', 'password': ''}}})
How to make `hatch publish` use my pypi API token? Having read Hatch's Publish documentation I did not figure out how to make it use my PyPI API token. For `test.pypi.org` and for `upload.pypi.org` I have these tokens defined in my `~/.pypirc` file but it seems that hatch is ignoring this: ``` hatch publish -r test Enter your username: ``` I tried to carry the tokens over from `.pypirc` to my hatch's `config.toml`, like this: ``` [publish.index] user = "" auth = "" [publish.index.repos.test] user = "__token__" auth = "pypi-<SECRET_PART>" [publish.index.repos.main] user = "__token__" auth = "pypi-<SECRET_PART>" ``` but this has no effect. I'm still getting the interactive prompt for username and credentials. What am I missing?
0.0
0d3559c43d260cd3167063c75db0183afcdc2f6b
[ "tests/cli/config/test_show.py::test_reveal", "tests/config/test_model.py::test_default", "tests/config/test_model.py::TestPublish::test_default" ]
[ "tests/cli/config/test_show.py::test_default_scrubbed", "tests/config/test_model.py::TestMode::test_default", "tests/config/test_model.py::TestMode::test_defined", "tests/config/test_model.py::TestMode::test_not_string", "tests/config/test_model.py::TestMode::test_unknown", "tests/config/test_model.py::TestMode::test_set_lazy_error", "tests/config/test_model.py::TestProject::test_default", "tests/config/test_model.py::TestProject::test_defined", "tests/config/test_model.py::TestProject::test_not_string", "tests/config/test_model.py::TestProject::test_set_lazy_error", "tests/config/test_model.py::TestShell::test_default", "tests/config/test_model.py::TestShell::test_invalid_type", "tests/config/test_model.py::TestShell::test_string", "tests/config/test_model.py::TestShell::test_table", "tests/config/test_model.py::TestShell::test_table_with_path", "tests/config/test_model.py::TestShell::test_table_with_path_and_args", "tests/config/test_model.py::TestShell::test_table_no_name", "tests/config/test_model.py::TestShell::test_table_name_not_string", "tests/config/test_model.py::TestShell::test_table_path_not_string", "tests/config/test_model.py::TestShell::test_table_args_not_array", "tests/config/test_model.py::TestShell::test_table_args_entry_not_string", "tests/config/test_model.py::TestShell::test_set_lazy_error", "tests/config/test_model.py::TestShell::test_table_name_set_lazy_error", "tests/config/test_model.py::TestShell::test_table_path_set_lazy_error", "tests/config/test_model.py::TestShell::test_table_args_set_lazy_error", "tests/config/test_model.py::TestDirs::test_default", "tests/config/test_model.py::TestDirs::test_not_table", "tests/config/test_model.py::TestDirs::test_set_lazy_error", "tests/config/test_model.py::TestDirs::test_project", "tests/config/test_model.py::TestDirs::test_project_not_array", "tests/config/test_model.py::TestDirs::test_project_entry_not_string", "tests/config/test_model.py::TestDirs::test_project_set_lazy_error", "tests/config/test_model.py::TestDirs::test_env", "tests/config/test_model.py::TestDirs::test_env_not_table", "tests/config/test_model.py::TestDirs::test_env_value_not_string", "tests/config/test_model.py::TestDirs::test_env_set_lazy_error", "tests/config/test_model.py::TestDirs::test_python", "tests/config/test_model.py::TestDirs::test_python_not_string", "tests/config/test_model.py::TestDirs::test_python_set_lazy_error", "tests/config/test_model.py::TestDirs::test_data", "tests/config/test_model.py::TestDirs::test_data_not_string", "tests/config/test_model.py::TestDirs::test_data_set_lazy_error", "tests/config/test_model.py::TestDirs::test_cache", "tests/config/test_model.py::TestDirs::test_cache_not_string", "tests/config/test_model.py::TestDirs::test_cache_set_lazy_error", "tests/config/test_model.py::TestProjects::test_default", "tests/config/test_model.py::TestProjects::test_not_table", "tests/config/test_model.py::TestProjects::test_set_lazy_error", "tests/config/test_model.py::TestProjects::test_entry_invalid_type", "tests/config/test_model.py::TestProjects::test_string", "tests/config/test_model.py::TestProjects::test_table", "tests/config/test_model.py::TestProjects::test_table_no_location", "tests/config/test_model.py::TestProjects::test_location_not_string", "tests/config/test_model.py::TestProjects::test_location_set_lazy_error", "tests/config/test_model.py::TestPublish::test_defined", "tests/config/test_model.py::TestPublish::test_not_table", "tests/config/test_model.py::TestPublish::test_data_not_table", "tests/config/test_model.py::TestPublish::test_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_not_table", "tests/config/test_model.py::TestTemplate::test_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_name", "tests/config/test_model.py::TestTemplate::test_name_default_env_var", "tests/config/test_model.py::TestTemplate::test_name_default_git", "tests/config/test_model.py::TestTemplate::test_name_default_no_git", "tests/config/test_model.py::TestTemplate::test_name_not_string", "tests/config/test_model.py::TestTemplate::test_name_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_email", "tests/config/test_model.py::TestTemplate::test_email_default_env_var", "tests/config/test_model.py::TestTemplate::test_email_default_git", "tests/config/test_model.py::TestTemplate::test_email_default_no_git", "tests/config/test_model.py::TestTemplate::test_email_not_string", "tests/config/test_model.py::TestTemplate::test_email_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_licenses_not_table", "tests/config/test_model.py::TestTemplate::test_licenses_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_licenses_headers", "tests/config/test_model.py::TestTemplate::test_licenses_headers_default", "tests/config/test_model.py::TestTemplate::test_licenses_headers_not_boolean", "tests/config/test_model.py::TestTemplate::test_licenses_headers_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_licenses_default", "tests/config/test_model.py::TestTemplate::test_licenses_default_default", "tests/config/test_model.py::TestTemplate::test_licenses_default_not_array", "tests/config/test_model.py::TestTemplate::test_licenses_default_entry_not_string", "tests/config/test_model.py::TestTemplate::test_licenses_default_set_lazy_error", "tests/config/test_model.py::TestTemplate::test_plugins", "tests/config/test_model.py::TestTemplate::test_plugins_default", "tests/config/test_model.py::TestTemplate::test_plugins_not_table", "tests/config/test_model.py::TestTemplate::test_plugins_data_not_table", "tests/config/test_model.py::TestTemplate::test_plugins_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_default", "tests/config/test_model.py::TestTerminal::test_not_table", "tests/config/test_model.py::TestTerminal::test_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_not_table", "tests/config/test_model.py::TestTerminal::test_styles_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_info", "tests/config/test_model.py::TestTerminal::test_styles_info_not_string", "tests/config/test_model.py::TestTerminal::test_styles_info_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_success", "tests/config/test_model.py::TestTerminal::test_styles_success_not_string", "tests/config/test_model.py::TestTerminal::test_styles_success_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_error", "tests/config/test_model.py::TestTerminal::test_styles_error_not_string", "tests/config/test_model.py::TestTerminal::test_styles_error_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_warning", "tests/config/test_model.py::TestTerminal::test_styles_warning_not_string", "tests/config/test_model.py::TestTerminal::test_styles_warning_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_waiting", "tests/config/test_model.py::TestTerminal::test_styles_waiting_not_string", "tests/config/test_model.py::TestTerminal::test_styles_waiting_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_debug", "tests/config/test_model.py::TestTerminal::test_styles_debug_not_string", "tests/config/test_model.py::TestTerminal::test_styles_debug_set_lazy_error", "tests/config/test_model.py::TestTerminal::test_styles_spinner", "tests/config/test_model.py::TestTerminal::test_styles_spinner_not_string", "tests/config/test_model.py::TestTerminal::test_styles_spinner_set_lazy_error" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-27 16:41:35+00:00
mit
4,984
pypa__hatch-610
diff --git a/docs/history/hatch.md b/docs/history/hatch.md index f2076ec3..3930bafa 100644 --- a/docs/history/hatch.md +++ b/docs/history/hatch.md @@ -20,6 +20,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ***Fixed:*** +- Fix displaying the version with the `version` command when the version is static and build dependencies are unmet - Fix the `support-legacy` option for the `sdist` target when using a src-layout project structure ### [1.6.3](https://github.com/pypa/hatch/releases/tag/hatch-v1.6.3) - 2022-10-24 ### {: #hatch-v1.6.3 } diff --git a/src/hatch/cli/version/__init__.py b/src/hatch/cli/version/__init__.py index 5c619527..e22466b1 100644 --- a/src/hatch/cli/version/__init__.py +++ b/src/hatch/cli/version/__init__.py @@ -10,7 +10,7 @@ def version(app, desired_version): if desired_version: app.abort('Cannot set version when it is statically defined by the `project.version` field') else: - app.display_always(app.project.metadata.core.version) + app.display_always(app.project.metadata.config['project']['version']) return from hatchling.dep.core import dependencies_in_sync
pypa/hatch
a56a77491ee2c832d7bcb1ba2aa4c0b2df8ee8e8
diff --git a/tests/cli/version/test_version.py b/tests/cli/version/test_version.py index 03d0dbf5..ea1441d7 100644 --- a/tests/cli/version/test_version.py +++ b/tests/cli/version/test_version.py @@ -130,6 +130,7 @@ def test_show_static(hatch, temp_dir): config = dict(project.raw_config) config['project']['version'] = '1.2.3' config['project']['dynamic'].remove('version') + config['tool']['hatch']['metadata'] = {'hooks': {'foo': {}}} project.save_config(config) with path.as_cwd():
`hatch version` fails for "unknown metadata hook" With [this `pyproject.toml`](https://github.com/scikit-hep/awkward/blob/agoose77/chore/split-awkward-package/pyproject.toml), running ```bash hatch version ``` gives the following traceback: ``` ╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/hatch/cli/__init__.p │ │ y:205 in main │ │ │ │ 202 │ │ 203 def main(): # no cov │ │ 204 │ try: │ │ ❱ 205 │ │ return hatch(windows_expand_args=False) │ │ 206 │ except Exception: │ │ 207 │ │ from rich.console import Console │ │ 208 │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/click/core.py:1130 │ │ in __call__ │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/click/core.py:1055 │ │ in main │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/click/core.py:1657 │ │ in invoke │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/click/core.py:1404 │ │ in invoke │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/click/core.py:760 in │ │ invoke │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/click/decorators.py: │ │ 38 in new_func │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/hatch/cli/version/__ │ │ init__.py:13 in version │ │ │ │ 10 │ │ if desired_version: │ │ 11 │ │ │ app.abort('Cannot set version when it is statically defined by the `project. │ │ 12 │ │ else: │ │ ❱ 13 │ │ │ app.display_always(app.project.metadata.core.version) │ │ 14 │ │ │ return │ │ 15 │ │ │ 16 │ from hatchling.dep.core import dependencies_in_sync │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/hatchling/metadata/c │ │ ore.py:139 in core │ │ │ │ 136 │ │ │ # Save the fields │ │ 137 │ │ │ _ = self.dynamic │ │ 138 │ │ │ │ │ ❱ 139 │ │ │ metadata_hooks = self.hatch.metadata.hooks │ │ 140 │ │ │ if metadata_hooks: │ │ 141 │ │ │ │ static_fields = set(self.core_raw_metadata) │ │ 142 │ │ │ │ if 'version' in self.hatch.config: │ │ │ │ /home/angus/.local/pipx/.cache/953f6e33b1619f9/lib/python3.10/site-packages/hatchling/metadata/c │ │ ore.py:1400 in hooks │ │ │ │ 1397 │ │ │ │ if metadata_hook is None: │ │ 1398 │ │ │ │ │ from hatchling.plugin.exceptions import UnknownPluginError │ │ 1399 │ │ │ │ │ │ │ ❱ 1400 │ │ │ │ │ raise UnknownPluginError(f'Unknown metadata hook: {hook_name}') │ │ 1401 │ │ │ │ │ │ 1402 │ │ │ │ configured_hooks[hook_name] = metadata_hook(self.root, config) │ │ 1403 │ ╰────────────────────────────────────────────────────────────── ``` My expectation is that hatch installs any plugins that it needs, but otherwise does not. We have a mechanism for this with build plugins: https://hatch.pypa.io/latest/config/build/#dependencies In this case, we probably don't need to load this plugin to begin with, though.
0.0
a56a77491ee2c832d7bcb1ba2aa4c0b2df8ee8e8
[ "tests/cli/version/test_version.py::test_show_static" ]
[ "tests/cli/version/test_version.py::test_incompatible_environment", "tests/cli/version/test_version.py::test_show_dynamic", "tests/cli/version/test_version.py::test_set_dynamic", "tests/cli/version/test_version.py::test_set_static" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-11-21 00:55:00+00:00
mit
4,985
pypa__hatch-709
diff --git a/docs/history/hatch.md b/docs/history/hatch.md index 51be6673..966196ab 100644 --- a/docs/history/hatch.md +++ b/docs/history/hatch.md @@ -27,6 +27,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Fix displaying the version with the `version` command when the version is static and build dependencies are unmet - Fix build environments for the `virtual` environment type when storing within a relative path +- Work around System Integrity Protection on macOS when running commands - Support boolean values for the `config set` command ## [1.6.3](https://github.com/pypa/hatch/releases/tag/hatch-v1.6.3) - 2022-10-24 ## {: #hatch-v1.6.3 } diff --git a/docs/plugins/environment/virtual.md b/docs/plugins/environment/virtual.md index d662645b..7fecf9dc 100644 --- a/docs/plugins/environment/virtual.md +++ b/docs/plugins/environment/virtual.md @@ -39,3 +39,16 @@ The [location](../../cli/reference.md#hatch-env-find) of environments is determi 3. Otherwise, environments are stored within the configured `virtual` [environment directory](../../config/hatch.md#environments) in a deeply nested structure in order to support multiple projects Additionally, when the `path` option is not used, the name of the directory for the `default` environment will be the normalized project name to provide a more meaningful default [shell](../../cli/reference.md#hatch-shell) prompt. + +## Troubleshooting + +### macOS SIP + +If you need to set linker environment variables like those starting with `DYLD_` or `LD_`, any executable secured by [System Integrity Protection](https://en.wikipedia.org/wiki/System_Integrity_Protection) that is invoked when [running commands](../../environment.md#command-execution) will not see those environment variable modifications as macOS strips those. + +Hatch interprets such commands as shell commands but deliberately ignores such paths to protected shells. This workaround suffices for the majority of use cases but there are 2 situations in which it may not: + +1. There are no unprotected `sh`, `bash`, `zsh`, nor `fish` executables found along PATH. +2. The desired executable is a project's [script](../../config/metadata.md#cli), and the [location](#location) of environments contains spaces or is longer than 124[^1] characters. In this case `pip` and other installers will create such an entry point with a shebang pointing to `/bin/sh` (which is protected) to avoid shebang limitations. + +[^1]: The shebang length limit is [usually](https://web.archive.org/web/20221231220856/https://www.in-ulm.de/~mascheck/various/shebang/#length) 127 but 3 characters surround the executable path: `#!<EXE_PATH>\n` diff --git a/src/hatch/utils/platform.py b/src/hatch/utils/platform.py index 1cda416a..83dc5f76 100644 --- a/src/hatch/utils/platform.py +++ b/src/hatch/utils/platform.py @@ -95,6 +95,7 @@ class Platform: if self.displaying_status and not kwargs.get('capture_output'): return self._run_command_integrated(command, shell=shell, **kwargs) + self.populate_default_popen_kwargs(kwargs, shell=shell) return self.modules.subprocess.run(self.format_for_subprocess(command, shell=shell), shell=shell, **kwargs) def check_command(self, command: str | list[str], *, shell: bool = False, **kwargs: Any) -> CompletedProcess: @@ -130,6 +131,7 @@ class Platform: with all output captured by `stdout` and the command first being [properly formatted](utilities.md#hatch.utils.platform.Platform.format_for_subprocess). """ + self.populate_default_popen_kwargs(kwargs, shell=shell) return self.modules.subprocess.Popen( self.format_for_subprocess(command, shell=shell), shell=shell, @@ -138,6 +140,31 @@ class Platform: **kwargs, ) + def populate_default_popen_kwargs(self, kwargs: dict[str, Any], *, shell: bool) -> None: + # https://support.apple.com/en-us/HT204899 + # https://en.wikipedia.org/wiki/System_Integrity_Protection + if ( + 'executable' not in kwargs + and self.macos + and shell + and any(env_var.startswith(('DYLD_', 'LD_')) for env_var in os.environ) + ): + default_paths = os.environ.get('PATH', os.defpath).split(os.pathsep) + unprotected_paths = [] + for path in default_paths: + normalized_path = os.path.normpath(path) + if not normalized_path.startswith(('/System', '/usr', '/bin', '/sbin', '/var')): + unprotected_paths.append(path) + elif normalized_path.startswith('/usr/local'): + unprotected_paths.append(path) + + search_path = os.pathsep.join(unprotected_paths) + for exe_name in ('sh', 'bash', 'zsh', 'fish'): + executable = self.modules.shutil.which(exe_name, path=search_path) + if executable: + kwargs['executable'] = executable + break + @staticmethod def stream_process_output(process: Popen) -> Iterable[str]: # To avoid blocking never use a pipe's file descriptor iterator. See https://bugs.python.org/issue3907
pypa/hatch
5e5af51cef5bccdd6e7f68b8438560894cafb448
diff --git a/tests/utils/test_platform.py b/tests/utils/test_platform.py index e365ea7b..86389f18 100644 --- a/tests/utils/test_platform.py +++ b/tests/utils/test_platform.py @@ -1,9 +1,11 @@ import os +import stat import pytest from hatch.utils.fs import Path from hatch.utils.platform import Platform +from hatch.utils.structures import EnvVars @pytest.mark.requires_windows @@ -31,6 +33,17 @@ class TestWindows: assert platform.home == platform.home == Path(os.path.expanduser('~')) + def test_populate_default_popen_kwargs_executable(self): + platform = Platform() + + kwargs = {} + platform.populate_default_popen_kwargs(kwargs, shell=True) + assert not kwargs + + kwargs['executable'] = 'foo' + platform.populate_default_popen_kwargs(kwargs, shell=True) + assert kwargs['executable'] == 'foo' + @pytest.mark.requires_macos class TestMacOS: @@ -57,6 +70,20 @@ class TestMacOS: assert platform.home == platform.home == Path(os.path.expanduser('~')) + def test_populate_default_popen_kwargs_executable(self, temp_dir): + new_path = f'{os.environ.get("PATH", "")}{os.pathsep}{temp_dir}'.strip(os.pathsep) + executable = temp_dir / 'sh' + executable.touch() + executable.chmod(executable.stat().st_mode | stat.S_IEXEC) + + kwargs = {} + + platform = Platform() + with EnvVars({'DYLD_FOO': 'bar', 'PATH': new_path}): + platform.populate_default_popen_kwargs(kwargs, shell=True) + + assert kwargs['executable'] == str(executable) + @pytest.mark.requires_linux class TestLinux: @@ -82,3 +109,14 @@ class TestLinux: platform = Platform() assert platform.home == platform.home == Path(os.path.expanduser('~')) + + def test_populate_default_popen_kwargs_executable(self): + platform = Platform() + + kwargs = {} + platform.populate_default_popen_kwargs(kwargs, shell=True) + assert not kwargs + + kwargs['executable'] = 'foo' + platform.populate_default_popen_kwargs(kwargs, shell=True) + assert kwargs['executable'] == 'foo'
Impossible to passthru / set DYLD_LIBRARY_PATH on macOS macOS treats `DYLD_LIBRARY_PATH` special, but I need to be able to pass it to the process to use drivers for an obscure database I'm forced to use. It's a bit icky to test, because just running `env` doesn't work. Here's the best test case I can give you: ```console $ env DYLD_LIBRARY_PATH="XXX" python -c 'import os; print(os.environ["DYLD_LIBRARY_PATH"])' XXX ``` vs ```toml [tool.hatch.envs.default.scripts] p = "python -c 'import os; print(os.environ[\"DYLD_LIBRARY_PATH\"])'" ``` → ```console $ env DYLD_LIBRARY_PATH="XXX" hatch run p Traceback (most recent call last): File "<string>", line 1, in <module> File "<frozen os>", line 679, in __getitem__ KeyError: 'DYLD_LIBRARY_PATH' ``` To be clear, this is not a problem specific to hatch; it's a security feature and Make and Just are also being difficult where I have to run my tests by setting the var using `env`. tox works fine if passed `passenv = DYLD_LIBRARY_PATH` and I'm not sure why. But adding the variable manually doesn't work either: ```toml [tool.hatch.envs.default.env-vars] DYLD_LIBRARY_PATH = "XXX" ``` ```console $ hatch run p Traceback (most recent call last): File "<string>", line 1, in <module> File "<frozen os>", line 679, in __getitem__ KeyError: 'DYLD_LIBRARY_PATH' ```
0.0
5e5af51cef5bccdd6e7f68b8438560894cafb448
[ "tests/utils/test_platform.py::TestLinux::test_populate_default_popen_kwargs_executable" ]
[ "tests/utils/test_platform.py::TestLinux::test_tag", "tests/utils/test_platform.py::TestLinux::test_default_shell", "tests/utils/test_platform.py::TestLinux::test_format_for_subprocess_list", "tests/utils/test_platform.py::TestLinux::test_format_for_subprocess_list_shell", "tests/utils/test_platform.py::TestLinux::test_format_for_subprocess_string", "tests/utils/test_platform.py::TestLinux::test_format_for_subprocess_string_shell", "tests/utils/test_platform.py::TestLinux::test_home" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-07 18:51:12+00:00
mit
4,986
pypa__setuptools_scm-1020
diff --git a/changelog.d/20240305_102047_allow_non_normalized_semver.md b/changelog.d/20240305_102047_allow_non_normalized_semver.md new file mode 100644 index 0000000..f5d8567 --- /dev/null +++ b/changelog.d/20240305_102047_allow_non_normalized_semver.md @@ -0,0 +1,4 @@ + +### Fixed + +- fix #1018: allow non-normalized versions for semver diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index 742abe6..0a36742 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -244,10 +244,13 @@ def guess_next_dev_version(version: ScmVersion) -> str: def guess_next_simple_semver( version: ScmVersion, retain: int, increment: bool = True ) -> str: - try: - parts = [int(i) for i in str(version.tag).split(".")[:retain]] - except ValueError: - raise ValueError(f"{version} can't be parsed as numeric version") from None + if isinstance(version.tag, _v.Version): + parts = list(version.tag.release[:retain]) + else: + try: + parts = [int(i) for i in str(version.tag).split(".")[:retain]] + except ValueError: + raise ValueError(f"{version} can't be parsed as numeric version") from None while len(parts) < retain: parts.append(0) if increment:
pypa/setuptools_scm
fee09f4cb57de4a50becc4eba0639bbb68d86725
diff --git a/testing/test_version.py b/testing/test_version.py index 8a823d8..371c754 100644 --- a/testing/test_version.py +++ b/testing/test_version.py @@ -54,6 +54,11 @@ c_non_normalize = Configuration(version_cls=NonNormalizedVersion) "1.1.0.dev2", id="feature_in_branch", ), + pytest.param( + meta(NonNormalizedVersion("v1.0"), distance=2, branch="default", config=c), + "1.0.1.dev2", + id="non-normalized-allowed", + ), ], ) def test_next_semver(version: ScmVersion, expected_next: str) -> None:
get_version(): normalize=False incompatible with several version schemes running anything that calls this function with -release-branch-semver -python-simplified-semver an error is thrown: e.g. `ValueError: <ScmVersion v2.0.0 dist=0 node=g17520db dirty=True branch=branch-name> can't be parsed as numeric version`
0.0
fee09f4cb57de4a50becc4eba0639bbb68d86725
[ "testing/test_version.py::test_next_semver[non-normalized-allowed]" ]
[ "testing/test_version.py::test_next_semver[exact]", "testing/test_version.py::test_next_semver[short_tag]", "testing/test_version.py::test_next_semver[normal_branch]", "testing/test_version.py::test_next_semver[normal_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_branch]", "testing/test_version.py::test_next_semver[feature_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_in_branch]", "testing/test_version.py::test_next_semver_bad_tag", "testing/test_version.py::test_next_release_branch_semver[exact]", "testing/test_version.py::test_next_release_branch_semver[development_branch]", "testing/test_version.py::test_next_release_branch_semver[development_branch_release_candidate]", "testing/test_version.py::test_next_release_branch_semver[release_branch_legacy_version]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_v_prefix]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_prefix]", "testing/test_version.py::test_next_release_branch_semver[false_positive_release_branch]", "testing/test_version.py::test_no_guess_version[dev_distance]", "testing/test_version.py::test_no_guess_version[dev_distance_after_dev_tag]", "testing/test_version.py::test_no_guess_version[dev_distance_short_tag]", "testing/test_version.py::test_no_guess_version[no_dev_distance]", "testing/test_version.py::test_no_guess_version_bad[1.0.dev1-choosing", "testing/test_version.py::test_no_guess_version_bad[1.0.post1-already", "testing/test_version.py::test_bump_dev_version_zero", "testing/test_version.py::test_bump_dev_version_nonzero_raises", "testing/test_version.py::test_only_version[1.dev0]", "testing/test_version.py::test_only_version[1.0.dev456]", "testing/test_version.py::test_only_version[1.0a1]", "testing/test_version.py::test_only_version[1.0a2.dev456]", "testing/test_version.py::test_only_version[1.0a12.dev456]", "testing/test_version.py::test_only_version[1.0a12]", "testing/test_version.py::test_only_version[1.0b1.dev456]", "testing/test_version.py::test_only_version[1.0b2]", "testing/test_version.py::test_only_version[1.0b2.post345.dev456]", "testing/test_version.py::test_only_version[1.0b2.post345]", "testing/test_version.py::test_only_version[1.0rc1.dev456]", "testing/test_version.py::test_only_version[1.0rc1]", "testing/test_version.py::test_only_version[1.0]", "testing/test_version.py::test_only_version[1.0.post456.dev34]", "testing/test_version.py::test_only_version[1.0.post456]", "testing/test_version.py::test_only_version[1.0.15]", "testing/test_version.py::test_only_version[1.1.dev1]", "testing/test_version.py::test_tag_regex1[v1.0.0-1.0.0]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1-1.0.0rc1]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1+-25259o4382757gjurh54-1.0.0rc1]", "testing/test_version.py::test_version_bump_bad", "testing/test_version.py::test_format_version_schemes", "testing/test_version.py::test_custom_version_schemes", "testing/test_version.py::test_calver_by_date[exact]", "testing/test_version.py::test_calver_by_date[exact", "testing/test_version.py::test_calver_by_date[leading", "testing/test_version.py::test_calver_by_date[dirty", "testing/test_version.py::test_calver_by_date[normal", "testing/test_version.py::test_calver_by_date[4", "testing/test_version.py::test_calver_by_date[release", "testing/test_version.py::test_calver_by_date[node", "testing/test_version.py::test_calver_by_date[using", "testing/test_version.py::test_calver_by_date_semver[SemVer", "testing/test_version.py::test_calver_by_date_future_warning", "testing/test_version.py::test_calver_guess_next_data[next", "testing/test_version.py::test_calver_guess_next_data[same", "testing/test_version.py::test_custom_version_cls" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2024-03-05 09:31:28+00:00
mit
4,987
pypa__setuptools_scm-168
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 50f0cde..054bfe5 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,9 @@ +v1.15.5 +======= + +* fix #167 by correctly respecting preformatted version metadata + from PKG-INFO/EGG-INFO + v1.15.4 ======= diff --git a/setuptools_scm/hacks.py b/setuptools_scm/hacks.py index 2d298be..add89a8 100644 --- a/setuptools_scm/hacks.py +++ b/setuptools_scm/hacks.py @@ -10,7 +10,7 @@ def parse_pkginfo(root): data = data_from_mime(pkginfo) version = data.get('Version') if version != 'UNKNOWN': - return meta(version) + return meta(version, preformatted=True) def parse_pip_egg_info(root): diff --git a/setuptools_scm/version.py b/setuptools_scm/version.py index 15c4495..dce8c75 100644 --- a/setuptools_scm/version.py +++ b/setuptools_scm/version.py @@ -55,7 +55,10 @@ def tags_to_versions(tags): class ScmVersion(object): def __init__(self, tag_version, distance=None, node=None, dirty=False, + preformatted=False, **kw): + if kw: + trace("unknown args", kw) self.tag = tag_version if dirty and distance is None: distance = 0 @@ -64,6 +67,7 @@ class ScmVersion(object): self.time = datetime.datetime.now() self.extra = kw self.dirty = dirty + self.preformatted = preformatted @property def exact(self): @@ -84,13 +88,19 @@ class ScmVersion(object): return self.format_with(dirty_format if self.dirty else clean_format) -def meta(tag, distance=None, dirty=False, node=None, **kw): +def _parse_tag(tag, preformatted): + if preformatted: + return tag if SetuptoolsVersion is None or not isinstance(tag, SetuptoolsVersion): tag = tag_to_version(tag) - trace('version', tag) + return tag + +def meta(tag, distance=None, dirty=False, node=None, preformatted=False, **kw): + tag = _parse_tag(tag, preformatted) + trace('version', tag) assert tag is not None, 'cant parse version %s' % tag - return ScmVersion(tag, distance, node, dirty, **kw) + return ScmVersion(tag, distance, node, dirty, preformatted, **kw) def guess_next_version(tag_version, distance): @@ -147,6 +157,8 @@ def postrelease_version(version): def format_version(version, **config): trace('scm version', version) trace('config', config) + if version.preformatted: + return version.tag version_scheme = callable_or_entrypoint( 'setuptools_scm.version_scheme', config['version_scheme']) local_scheme = callable_or_entrypoint(
pypa/setuptools_scm
00f3fbe0dfd3ae396abdd4b33cd69cca7d4459c3
diff --git a/testing/conftest.py b/testing/conftest.py index 49a9d14..29e129c 100644 --- a/testing/conftest.py +++ b/testing/conftest.py @@ -52,14 +52,18 @@ class Wd(object): self(self.add_command) self.commit(reason=reason) - @property - def version(self): + def get_version(self, **kw): __tracebackhide__ = True from setuptools_scm import get_version - version = get_version(root=str(self.cwd)) + version = get_version(root=str(self.cwd), **kw) print(version) return version + @property + def version(self): + __tracebackhide__ = True + return self.get_version() + @pytest.yield_fixture(autouse=True) def debug_mode(): diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index 5f9e1d6..4192f71 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -30,6 +30,9 @@ def test_version_from_pkginfo(wd): wd.write('PKG-INFO', 'Version: 0.1') assert wd.version == '0.1' + # replicate issue 167 + assert wd.get_version(version_scheme="1.{0.distance}.0".format) == '0.1' + def assert_root(monkeypatch, expected_root): """
setuptools_scm unable to compute distance? I have a tarball that was built with a previous version of setuptools_scm. The other day it started failing because the version number it was producing was ``1.None.0``. Nothing in the code base had changed, so I believe it to be a setuptools_scm regression. This tarball is private, but the ``setup.py`` looks like: ```python #!/usr/bin/env python import setuptools setuptools.setup( name="pypi-theme", version="15.0", packages=[ "pypi_theme", ], include_package_data=True, use_scm_version={ "local_scheme": "dirty-tag", "version_scheme": lambda v: "1.{.distance}.0".format(v), }, install_requires=[ "Pyramid", ], setup_requires=["setuptools_scm"], ) ``` I'm guessing that ``v.distance`` is returning ``None`` now when it previously didn't, but I don't know why.
0.0
00f3fbe0dfd3ae396abdd4b33cd69cca7d4459c3
[ "testing/test_basic_api.py::test_version_from_pkginfo" ]
[ "testing/test_basic_api.py::test_do[ls]", "testing/test_basic_api.py::test_do[dir]", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_pretended", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_dump_version", "testing/test_basic_api.py::test_parse_plain" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-04-08 16:14:53+00:00
mit
4,988
pypa__setuptools_scm-186
diff --git a/.gitignore b/.gitignore index 7bdd112..19ae6c2 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,9 @@ ## Directory-based project format: .idea/ +### Other editors +.*.swp + ### Python template # Byte-compiled / optimized diff --git a/setuptools_scm/git.py b/setuptools_scm/git.py index 7fa1b32..6ec9962 100644 --- a/setuptools_scm/git.py +++ b/setuptools_scm/git.py @@ -1,15 +1,20 @@ from .utils import do_ex, trace, has_command from .version import meta + from os.path import isfile, join +import subprocess +import sys +import tarfile import warnings + try: from os.path import samefile except ImportError: from .win_py31_compat import samefile -FILES_COMMAND = 'git ls-files' +FILES_COMMAND = sys.executable + ' -m setuptools_scm.git' DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*' @@ -116,3 +121,17 @@ def parse(root, describe_command=DEFAULT_DESCRIBE, pre_parse=warn_on_shallow): return meta(tag, distance=number, node=node, dirty=dirty) else: return meta(tag, node=node, dirty=dirty) + + +def _list_files_in_archive(): + """List the files that 'git archive' generates. + """ + cmd = ['git', 'archive', 'HEAD'] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) + tf = tarfile.open(fileobj=proc.stdout, mode='r|*') + for name in tf.getnames(): + print(name) + + +if __name__ == "__main__": + _list_files_in_archive() diff --git a/setuptools_scm/utils.py b/setuptools_scm/utils.py index f744337..0e8a555 100644 --- a/setuptools_scm/utils.py +++ b/setuptools_scm/utils.py @@ -61,7 +61,7 @@ def _popen_pipes(cmd, cwd): def do_ex(cmd, cwd='.'): trace('cmd', repr(cmd)) - if not isinstance(cmd, (list, tuple)): + if os.name == "posix" and not isinstance(cmd, (list, tuple)): cmd = shlex.split(cmd) p = _popen_pipes(cmd, cwd)
pypa/setuptools_scm
fc824aaaa952ded5f6ee54bcddafb0d96f4b44c4
diff --git a/testing/test_git.py b/testing/test_git.py index ddae5d4..4f4ad53 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -112,3 +112,15 @@ def test_alphanumeric_tags_match(wd): wd.commit_testfile() wd('git tag newstyle-development-started') assert wd.version.startswith('0.1.dev1+g') + + +def test_git_archive_export_ignore(wd): + wd.write('test1.txt', 'test') + wd.write('test2.txt', 'test') + wd.write('.git/info/attributes', + # Explicitly include test1.txt so that the test is not affected by + # a potentially global gitattributes file on the test machine. + '/test1.txt -export-ignore\n/test2.txt export-ignore') + wd('git add test1.txt test2.txt') + wd.commit() + assert integration.find_files(str(wd.cwd)) == ['test1.txt']
support git's export-ignore `git archive` reads the `export-ignore` gitattribute (https://git-scm.com/docs/gitattributes#_creating_an_archive) which allows marking some files as NOT packaged into the archive. It would be nice if setuptools_scm did the same for the sdist. Typical use cases would be to remove CI scripts. Unfortunately AFAICT there is no way to ask git for the files it would archive short of actually running git archive and examining the resulting tarball. OTOH it appears that such a step is much faster than the sdist build itself, so perhaps that remains an acceptable approach?
0.0
fc824aaaa952ded5f6ee54bcddafb0d96f4b44c4
[ "testing/test_git.py::test_git_archive_export_ignore" ]
[ "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-11-14 05:31:23+00:00
mit
4,989
pypa__setuptools_scm-247
diff --git a/setup.py b/setup.py index 7fc33f3..2b93690 100644 --- a/setup.py +++ b/setup.py @@ -82,7 +82,7 @@ arguments = dict( [setuptools_scm.files_command] .hg = setuptools_scm.hg:FILES_COMMAND - .git = setuptools_scm.git:list_files_in_archive + .git = setuptools_scm.git_file_finder:find_files [setuptools_scm.version_scheme] guess-next-dev = setuptools_scm.version:guess_next_dev_version diff --git a/setuptools_scm/git.py b/setuptools_scm/git.py index 6f35e78..df31358 100644 --- a/setuptools_scm/git.py +++ b/setuptools_scm/git.py @@ -2,8 +2,6 @@ from .utils import do_ex, trace, has_command from .version import meta from os.path import isfile, join -import subprocess -import tarfile import warnings @@ -128,13 +126,3 @@ def parse(root, describe_command=DEFAULT_DESCRIBE, pre_parse=warn_on_shallow): return meta(tag, distance=number, node=node, dirty=dirty, branch=branch) else: return meta(tag, node=node, dirty=dirty, branch=branch) - - -def list_files_in_archive(path): - """List the files that 'git archive' generates. - """ - cmd = ['git', 'archive', 'HEAD'] - proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=path) - tf = tarfile.open(fileobj=proc.stdout, mode='r|*') - return [member.name for member in tf.getmembers() - if member.type != tarfile.DIRTYPE] diff --git a/setuptools_scm/git_file_finder.py b/setuptools_scm/git_file_finder.py new file mode 100644 index 0000000..2c978d3 --- /dev/null +++ b/setuptools_scm/git_file_finder.py @@ -0,0 +1,65 @@ +import os +import subprocess +import tarfile + + +def _git_toplevel(path): + try: + out = subprocess.check_output([ + 'git', 'rev-parse', '--show-toplevel', + ], cwd=(path or '.'), universal_newlines=True) + return os.path.normcase(os.path.realpath(out.strip())) + except subprocess.CalledProcessError: + # git returned error, we are not in a git repo + return None + except OSError: + # git command not found, probably + return None + + +def _git_ls_files_and_dirs(toplevel): + # use git archive instead of git ls-file to honor + # export-ignore git attribute + cmd = ['git', 'archive', '--prefix', toplevel + os.path.sep, 'HEAD'] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=toplevel) + tf = tarfile.open(fileobj=proc.stdout, mode='r|*') + git_files = set() + git_dirs = set([toplevel]) + for member in tf.getmembers(): + name = os.path.normcase(member.name).replace('/', os.path.sep) + if member.type == tarfile.DIRTYPE: + git_dirs.add(name) + else: + git_files.add(name) + return git_files, git_dirs + + +def find_files(path=''): + """ setuptools compatible git file finder that follows symlinks + + Spec here: http://setuptools.readthedocs.io/en/latest/setuptools.html#\ + adding-support-for-revision-control-systems + """ + toplevel = _git_toplevel(path) + if not toplevel: + return [] + git_files, git_dirs = _git_ls_files_and_dirs(toplevel) + realpath = os.path.normcase(os.path.realpath(path)) + assert realpath.startswith(toplevel) + assert realpath in git_dirs + seen = set() + res = [] + for dirpath, dirnames, filenames in os.walk(realpath, followlinks=True): + # dirpath with symlinks resolved + realdirpath = os.path.normcase(os.path.realpath(dirpath)) + if realdirpath not in git_dirs or realdirpath in seen: + dirnames[:] = [] + continue + for filename in filenames: + # dirpath + filename with symlinks preserved + fullfilename = os.path.join(dirpath, filename) + if os.path.normcase(os.path.realpath(fullfilename)) in git_files: + res.append( + os.path.join(path, os.path.relpath(fullfilename, path))) + seen.add(realdirpath) + return res
pypa/setuptools_scm
e4f80b9f248aea2cfea92a9fc2e2ace5d4584b9c
diff --git a/testing/conftest.py b/testing/conftest.py index 29e129c..6a155cd 100644 --- a/testing/conftest.py +++ b/testing/conftest.py @@ -42,6 +42,10 @@ class Wd(object): else: return given_reason + def add_and_commit(self, reason=None): + self(self.add_command) + self.commit(reason) + def commit(self, reason=None): reason = self._reason(reason) self(self.commit_command, reason=reason) diff --git a/testing/test_git.py b/testing/test_git.py index 5762452..6b165e2 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -3,6 +3,7 @@ from setuptools_scm.utils import do from setuptools_scm import git import pytest from datetime import date +from os.path import join as opj @pytest.fixture @@ -123,7 +124,8 @@ def test_git_archive_export_ignore(wd): '/test1.txt -export-ignore\n/test2.txt export-ignore') wd('git add test1.txt test2.txt') wd.commit() - assert integration.find_files(str(wd.cwd)) == ['test1.txt'] + with wd.cwd.as_cwd(): + assert integration.find_files('.') == [opj('.', 'test1.txt')] @pytest.mark.issue(228) @@ -132,7 +134,8 @@ def test_git_archive_subdirectory(wd): wd.write('foobar/test1.txt', 'test') wd('git add foobar') wd.commit() - assert integration.find_files(str(wd.cwd)) == ['foobar/test1.txt'] + with wd.cwd.as_cwd(): + assert integration.find_files('.') == [opj('.', 'foobar', 'test1.txt')] def test_git_feature_branch_increments_major(wd): diff --git a/testing/test_git_file_finder.py b/testing/test_git_file_finder.py new file mode 100644 index 0000000..fb7d6f1 --- /dev/null +++ b/testing/test_git_file_finder.py @@ -0,0 +1,133 @@ +import os +import sys + +import pytest + +from setuptools_scm.git_file_finder import find_files + + [email protected] +def inwd(wd): + wd('git init') + wd('git config user.email [email protected]') + wd('git config user.name "a test"') + wd.add_command = 'git add .' + wd.commit_command = 'git commit -m test-{reason}' + (wd.cwd / 'file1').ensure(file=True) + adir = (wd.cwd / 'adir').ensure(dir=True) + (adir / 'filea').ensure(file=True) + bdir = (wd.cwd / 'bdir').ensure(dir=True) + (bdir / 'fileb').ensure(file=True) + wd.add_and_commit() + with wd.cwd.as_cwd(): + yield wd + + +def _sep(paths): + return { + path.replace('/', os.path.sep) + for path in paths + } + + +def test_basic(inwd): + assert set(find_files()) == _sep({ + 'file1', + 'adir/filea', + 'bdir/fileb', + }) + assert set(find_files('.')) == _sep({ + './file1', + './adir/filea', + './bdir/fileb', + }) + assert set(find_files('adir')) == _sep({ + 'adir/filea', + }) + + +def test_case(inwd): + (inwd.cwd / 'CamelFile').ensure(file=True) + (inwd.cwd / 'file2').ensure(file=True) + inwd.add_and_commit() + assert set(find_files()) == _sep({ + 'CamelFile', + 'file2', + 'file1', + 'adir/filea', + 'bdir/fileb', + }) + + [email protected](sys.platform == 'win32', + reason="symlinks to dir not supported") +def test_symlink_dir(inwd): + (inwd.cwd / 'adir' / 'bdirlink').mksymlinkto('../bdir') + inwd.add_and_commit() + assert set(find_files('adir')) == _sep({ + 'adir/filea', + 'adir/bdirlink/fileb', + }) + + [email protected](sys.platform == 'win32', + reason="symlinks to files not supported on windows") +def test_symlink_file(inwd): + (inwd.cwd / 'adir' / 'file1link').mksymlinkto('../file1') + inwd.add_and_commit() + assert set(find_files('adir')) == _sep({ + 'adir/filea', + 'adir/file1link', + }) + + [email protected](sys.platform == 'win32', + reason="symlinks to dir not supported") +def test_symlink_loop(inwd): + (inwd.cwd / 'adir' / 'loop').mksymlinkto('../adir') + inwd.add_and_commit() + assert set(find_files('adir')) == _sep({ + 'adir/filea', + }) + + [email protected](sys.platform == 'win32', + reason="symlinks to dir not supported") +def test_symlink_dir_out_of_git(inwd): + (inwd.cwd / 'adir' / 'outsidedirlink').\ + mksymlinkto(os.path.join(__file__, '..')) + inwd.add_and_commit() + assert set(find_files('adir')) == _sep({ + 'adir/filea', + }) + + [email protected](sys.platform == 'win32', + reason="symlinks to files not supported on windows") +def test_symlink_file_out_of_git(inwd): + (inwd.cwd / 'adir' / 'outsidefilelink').mksymlinkto(__file__) + inwd.add_and_commit() + assert set(find_files('adir')) == _sep({ + 'adir/filea', + }) + + +def test_empty_root(inwd): + subdir = inwd.cwd / 'cdir' / 'subdir' + subdir.ensure(dir=True) + (subdir / 'filec').ensure(file=True) + inwd.add_and_commit() + assert set(find_files('cdir')) == _sep({ + 'cdir/subdir/filec', + }) + + +def test_empty_subdir(inwd): + subdir = inwd.cwd / 'adir' / 'emptysubdir' / 'subdir' + subdir.ensure(dir=True) + (subdir / 'xfile').ensure(file=True) + inwd.add_and_commit() + assert set(find_files('adir')) == _sep({ + 'adir/filea', + 'adir/emptysubdir/subdir/xfile', + }) diff --git a/testing/test_regressions.py b/testing/test_regressions.py index 7abd659..8e4f396 100644 --- a/testing/test_regressions.py +++ b/testing/test_regressions.py @@ -53,8 +53,8 @@ def test_pip_egg_info(tmpdir, monkeypatch): def test_pip_download(tmpdir, monkeypatch): monkeypatch.chdir(tmpdir) subprocess.check_call([ - sys.executable, '-c', - 'import pip;pip.main()', 'download', 'lz4==0.9.0', + sys.executable, '-m', + 'pip', 'download', 'lz4==0.9.0', ])
git file finder: follow symlinks Imagine the following directory structure where setup.py is in a subdirectory in the git repo, and contains a symlink to a parent directory. ``` package/module.py setup/setup.py setup/package -> ../package ``` Currently, the git file finder will ignore the symlinked directory as it does a `git ls-files <setup root>`. Such a directory structure is useful in situations where one does not have freedom to arrange a canonical directory structure in the repo. Would you review a PR that makes the git file finder follow symlinks (of course restricting links to files/directories that are themselves part of the same git repo).
0.0
e4f80b9f248aea2cfea92a9fc2e2ace5d4584b9c
[ "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git_file_finder.py::test_basic", "testing/test_git_file_finder.py::test_case", "testing/test_git_file_finder.py::test_symlink_dir", "testing/test_git_file_finder.py::test_symlink_file", "testing/test_git_file_finder.py::test_symlink_loop", "testing/test_git_file_finder.py::test_symlink_dir_out_of_git", "testing/test_git_file_finder.py::test_symlink_file_out_of_git", "testing/test_git_file_finder.py::test_empty_root", "testing/test_git_file_finder.py::test_empty_subdir", "testing/test_regressions.py::test_pkginfo_noscmroot", "testing/test_regressions.py::test_pip_egg_info", "testing/test_regressions.py::test_pip_download", "testing/test_regressions.py::test_use_scm_version_callable" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-04-25 15:19:55+00:00
mit
4,990
pypa__setuptools_scm-269
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index adc33c1..1548d32 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,6 +6,8 @@ v3.0.0 * switch to src layout (breaking change) * no longer alias tag and parsed_version in order to support understanding a version parse failure * require parse results to be ScmVersion or None (breaking change) +* fix #266 by requirin the prefix word to be a word again + (breaking change as the bug allowed arbitrary prefixes while the original feature only allowed words") v2.1.0 ====== diff --git a/src/setuptools_scm/git.py b/src/setuptools_scm/git.py index 6ff2c0d..7c45a84 100644 --- a/src/setuptools_scm/git.py +++ b/src/setuptools_scm/git.py @@ -111,19 +111,26 @@ def parse(root, describe_command=DEFAULT_DESCRIBE, pre_parse=warn_on_shallow): dirty=dirty, branch=wd.get_branch(), ) + else: + tag, number, node, dirty = _git_parse_describe(out) + + branch = wd.get_branch() + if number: + return meta(tag, distance=number, node=node, dirty=dirty, branch=branch) + else: + return meta(tag, node=node, dirty=dirty, branch=branch) + - # 'out' looks e.g. like 'v1.5.0-0-g4060507' or +def _git_parse_describe(describe_output): + # 'describe_output' looks e.g. like 'v1.5.0-0-g4060507' or # 'v1.15.1rc1-37-g9bd1298-dirty'. - if out.endswith("-dirty"): + + if describe_output.endswith("-dirty"): dirty = True - out = out[:-6] + describe_output = describe_output[:-6] else: dirty = False - tag, number, node = out.rsplit("-", 2) + tag, number, node = describe_output.rsplit("-", 2) number = int(number) - branch = wd.get_branch() - if number: - return meta(tag, distance=number, node=node, dirty=dirty, branch=branch) - else: - return meta(tag, node=node, dirty=dirty, branch=branch) + return tag, number, node, dirty diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index aba231d..5799f1a 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -13,6 +13,7 @@ from pkg_resources import parse_version as pkg_parse_version SEMVER_MINOR = 2 SEMVER_PATCH = 3 SEMVER_LEN = 3 +TAG_PREFIX = re.compile(r"^\w+-(.*)") def _pad(iterable, size, padding=None): @@ -56,14 +57,21 @@ def callable_or_entrypoint(group, callable_or_name): def tag_to_version(tag): + """ + take a tag that might be prefixed with a keyword and return only the version part + """ trace("tag", tag) if "+" in tag: warnings.warn("tag %r will be stripped of the local component" % tag) tag = tag.split("+")[0] # lstrip the v because of py2/py3 differences in setuptools # also required for old versions of setuptools - - version = tag.rsplit("-", 1)[-1].lstrip("v") + prefix_match = TAG_PREFIX.match(tag) + if prefix_match is not None: + version = prefix_match.group(1) + else: + version = tag + trace("version pre parse", version) if VERSION_CLASS is None: return version version = pkg_parse_version(version)
pypa/setuptools_scm
7cd319baaa1635a46d7325a8f8c7a42235bd0634
diff --git a/testing/test_functions.py b/testing/test_functions.py index 0c817b8..db573ac 100644 --- a/testing/test_functions.py +++ b/testing/test_functions.py @@ -2,7 +2,12 @@ import pytest import sys import pkg_resources from setuptools_scm import dump_version, get_version, PRETEND_KEY -from setuptools_scm.version import guess_next_version, meta, format_version +from setuptools_scm.version import ( + guess_next_version, + meta, + format_version, + tag_to_version, +) from setuptools_scm.utils import has_command PY3 = sys.version_info > (2,) @@ -77,3 +82,16 @@ def test_has_command(recwarn): assert not has_command("yadayada_setuptools_aint_ne") msg = recwarn.pop() assert "yadayada" in str(msg.message) + + [email protected]( + "tag, expected_version", + [ + ("1.1", "1.1"), + ("release-1.1", "1.1"), + pytest.param("3.3.1-rc26", "3.3.1rc26", marks=pytest.mark.issue(266)), + ], +) +def test_tag_to_version(tag, expected_version): + version = str(tag_to_version(tag)) + assert version == expected_version diff --git a/testing/test_git.py b/testing/test_git.py index be7e0a4..9530400 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -16,6 +16,15 @@ def wd(wd): return wd [email protected]( + "given, tag, number, node, dirty", + [("3.3.1-rc26-0-g9df187b", "3.3.1-rc26", 0, "g9df187b", False)], +) +def test_parse_describe_output(given, tag, number, node, dirty): + parsed = git._git_parse_describe(given) + assert parsed == (tag, number, node, dirty) + + def test_version_from_git(wd): assert wd.version == "0.1.dev0"
tags with dashes get mangled I want to be able to tag my git repo with "1.0.0-rc1". That version should be acceptable to setuptools_scm independently of "distance", "hash", and "dirty" suffixes. Doing so results in an error (sample tag is "3.3.1-rc26"): ``` looking for ep setuptools_scm.parse_scm_fallback . root '/Users/twall/plex/rd' looking for ep setuptools_scm.parse_scm /Users/twall/plex/rd found ep .git = setuptools_scm.git:parse cmd 'git rev-parse --show-toplevel' out b'/Users/twall/plex/rd\n' real root /Users/twall/plex/rd cmd 'git describe --dirty --tags --long --match *.*' out b'3.3.1-rc26-0-g9df187b\n' cmd 'git rev-parse --abbrev-ref HEAD' out b'pyplex\n' tag 3.3.1-rc26 version <LegacyVersion('rc26')> version None Traceback (most recent call last): File "setup.py", line 46, in <module> entry_points = { File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools/__init__.py", line 129, in setup return distutils.core.setup(**attrs) File "/anaconda3/lib/python3.6/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools/dist.py", line 370, in __init__ k: v for k, v in attrs.items() File "/anaconda3/lib/python3.6/distutils/dist.py", line 281, in __init__ self.finalize_options() File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools/dist.py", line 529, in finalize_options ep.load()(self, ep.name, value) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/integration.py", line 22, in version_keyword dist.metadata.version = get_version(**value) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 119, in get_version parsed_version = _do_parse(root, parse) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 83, in _do_parse version = version_from_scm(root) or _version_from_entrypoint( File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 31, in version_from_scm return _version_from_entrypoint(root, 'setuptools_scm.parse_scm') File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 36, in _version_from_entrypoint version = ep.load()(root) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/git.py", line 128, in parse return meta(tag, node=node, dirty=dirty, branch=branch) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/version.py", line 135, in meta assert tag is not None, 'cant parse version %s' % tag AssertionError: cant parse version None ``` The `SemVer` description seems to allow nearly arbitrary strings for `www` in `x.y.z-www`, so I would expect such tags to work. Note that "3.3.1.rc26" sort of works, resulting in a modified version of "3.3.1rc26".
0.0
7cd319baaa1635a46d7325a8f8c7a42235bd0634
[ "testing/test_functions.py::test_tag_to_version[3.3.1-rc26-3.3.1rc26]", "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]" ]
[ "testing/test_functions.py::test_next_tag[1.1-1.2]", "testing/test_functions.py::test_next_tag[1.2.dev-1.2]", "testing/test_functions.py::test_next_tag[1.1a2-1.1a3]", "testing/test_functions.py::test_next_tag[23.24.post2+deadbeef-23.24.post3]", "testing/test_functions.py::test_format_version[exact-guess-next-dev", "testing/test_functions.py::test_format_version[zerodistance-guess-next-dev", "testing/test_functions.py::test_format_version[dirty-guess-next-dev", "testing/test_functions.py::test_format_version[distance-guess-next-dev", "testing/test_functions.py::test_format_version[distancedirty-guess-next-dev", "testing/test_functions.py::test_format_version[exact-post-release", "testing/test_functions.py::test_format_version[zerodistance-post-release", "testing/test_functions.py::test_format_version[dirty-post-release", "testing/test_functions.py::test_format_version[distance-post-release", "testing/test_functions.py::test_format_version[distancedirty-post-release", "testing/test_functions.py::test_dump_version_doesnt_bail_on_value_error", "testing/test_functions.py::test_dump_version_works_with_pretend", "testing/test_functions.py::test_has_command", "testing/test_functions.py::test_tag_to_version[1.1-1.1]", "testing/test_functions.py::test_tag_to_version[release-1.1-1.1]", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-22 04:42:12+00:00
mit
4,991
pypa__setuptools_scm-277
diff --git a/src/setuptools_scm/__init__.py b/src/setuptools_scm/__init__.py index b256289..8ea3136 100644 --- a/src/setuptools_scm/__init__.py +++ b/src/setuptools_scm/__init__.py @@ -60,7 +60,7 @@ def _do_parse(root, parse): if pretended: # we use meta here since the pretended version # must adhere to the pep to begin with - return meta(pretended) + return meta(tag=pretended, preformatted=True) if parse: parse_result = parse(root) diff --git a/tox.ini b/tox.ini index 1281b87..c5edb78 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist=py{27,34,35,36,37}-test,flake8,check_readme,py{27,36}-selftest +envlist=py{27,34,35,36,37}-test,flake8,check_readme,py{27,36}-selfcheck [flake8] max-complexity = 10 @@ -39,7 +39,7 @@ deps= readme check-manifest commands= - python setup.py check -r -s + python setup.py check -r rst2html.py README.rst {envlogdir}/README.html --strict [] check-manifest
pypa/setuptools_scm
e377112e996ed0adf65f6378475ea360103d947b
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index b26688b..6d7f112 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -51,10 +51,12 @@ def test_root_parameter_pass_by(monkeypatch, tmpdir): setuptools_scm.get_version(root=tmpdir.strpath) -def test_pretended(monkeypatch): - pretense = "2345" - monkeypatch.setenv(setuptools_scm.PRETEND_KEY, pretense) - assert setuptools_scm.get_version() == pretense [email protected]( + "version", ["1.0", "1.2.3.dev1+ge871260", "1.2.3.dev15+ge871260.d20180625", "2345"] +) +def test_pretended(version, monkeypatch): + monkeypatch.setenv(setuptools_scm.PRETEND_KEY, version) + assert setuptools_scm.get_version() == version def test_root_relative_to(monkeypatch, tmpdir): diff --git a/testing/test_functions.py b/testing/test_functions.py index db573ac..6c82b32 100644 --- a/testing/test_functions.py +++ b/testing/test_functions.py @@ -72,10 +72,13 @@ def test_dump_version_doesnt_bail_on_value_error(tmpdir): assert str(exc_info.value).startswith("bad file format:") -def test_dump_version_works_with_pretend(tmpdir, monkeypatch): - monkeypatch.setenv(PRETEND_KEY, "1.0") [email protected]( + "version", ["1.0", "1.2.3.dev1+ge871260", "1.2.3.dev15+ge871260.d20180625"] +) +def test_dump_version_works_with_pretend(version, tmpdir, monkeypatch): + monkeypatch.setenv(PRETEND_KEY, version) get_version(write_to=str(tmpdir.join("VERSION.txt"))) - assert tmpdir.join("VERSION.txt").read() == "1.0" + assert tmpdir.join("VERSION.txt").read() == version def test_has_command(recwarn):
PRETEND behaviour Hi, I am not sure I understand the `SETUPTOOLS_SCM_PRETEND_VERSION` usage. I use it in a container context where I don't wan't the scm repository to be included in the container image. Thus I use something like: ```shell SETUPTOOLS_SCM_PRETEND_VERSION=$(python ${PWD}/setup.py --version) ``` prior to create the container image so that `setuptools_scm` can retrieve the version without the scm repository. However, I don't get the same result as with the scm repository. With a version like `1.0.1.dev1+ge871260.d20180625` and the scm repository, the generated artifact (here a wheel) will be `my_python_project-1.0.1.dev1+ge871260.d20180625-py3-none-any.whl`, while without the scm repository and with `SETUPTOOLS_SCM_PRETEND_VERSION` set to `1.0.1.dev1+ge871260.d20180625` the generated artifact is `my_python_project-1.0.1.dev1-py3-none-any.whl`. Looking at the `_do_parse` function code: ```python if pretended: # we use meta here since the pretended version # must adhere to the pep to begin with return meta(pretended) ``` I understand this is done on purpose, but I don't get why. I would expect the result to be the same, unless I don't get the `SETUPTOOLS_SCM_PRETEND_VERSION` usage properly.
0.0
e377112e996ed0adf65f6378475ea360103d947b
[ "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_functions.py::test_dump_version_works_with_pretend[1.2.3.dev1+ge871260]", "testing/test_functions.py::test_dump_version_works_with_pretend[1.2.3.dev15+ge871260.d20180625]" ]
[ "testing/test_basic_api.py::test_do[ls]", "testing/test_basic_api.py::test_do[dir]", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_dump_version", "testing/test_basic_api.py::test_parse_plain_fails", "testing/test_functions.py::test_next_tag[1.1-1.2]", "testing/test_functions.py::test_next_tag[1.2.dev-1.2]", "testing/test_functions.py::test_next_tag[1.1a2-1.1a3]", "testing/test_functions.py::test_next_tag[23.24.post2+deadbeef-23.24.post3]", "testing/test_functions.py::test_format_version[exact-guess-next-dev", "testing/test_functions.py::test_format_version[zerodistance-guess-next-dev", "testing/test_functions.py::test_format_version[dirty-guess-next-dev", "testing/test_functions.py::test_format_version[distance-guess-next-dev", "testing/test_functions.py::test_format_version[distancedirty-guess-next-dev", "testing/test_functions.py::test_format_version[exact-post-release", "testing/test_functions.py::test_format_version[zerodistance-post-release", "testing/test_functions.py::test_format_version[dirty-post-release", "testing/test_functions.py::test_format_version[distance-post-release", "testing/test_functions.py::test_format_version[distancedirty-post-release", "testing/test_functions.py::test_dump_version_doesnt_bail_on_value_error", "testing/test_functions.py::test_dump_version_works_with_pretend[1.0]", "testing/test_functions.py::test_has_command", "testing/test_functions.py::test_tag_to_version[1.1-1.1]", "testing/test_functions.py::test_tag_to_version[release-1.1-1.1]", "testing/test_functions.py::test_tag_to_version[3.3.1-rc26-3.3.1rc26]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-07-01 16:15:43+00:00
mit
4,992
pypa__setuptools_scm-287
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ea83b4e..ad7ca4f 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,9 @@ +v3.0.3 +====== + +* fix #286 - duo an oversight a helper functio nwas returning a generator instead of a list + + v3.0.2 ====== diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index 47ad6d3..b2ad2f7 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -30,12 +30,12 @@ def _parse_version_tag(tag, config): if len(match.groups()) == 1: key = 1 else: - key = 'version' - + key = "version" + result = { - 'version': match.group(key), - 'prefix': match.group(0)[:match.start(key)], - 'suffix': match.group(0)[match.end(key):], + "version": match.group(key), + "prefix": match.group(0)[:match.start(key)], + "suffix": match.group(0)[match.end(key):], } trace("tag '%s' parsed to %s" % (tag, result)) @@ -88,20 +88,21 @@ def tag_to_version(tag, config=None): config = Configuration() tagdict = _parse_version_tag(tag, config) - if not isinstance(tagdict, dict) or not tagdict.get('version', None): + if not isinstance(tagdict, dict) or not tagdict.get("version", None): warnings.warn("tag %r no version found" % (tag,)) return None - version = tagdict['version'] + version = tagdict["version"] trace("version pre parse", version) - if tagdict.get('suffix', ''): - warnings.warn("tag %r will be stripped of its suffix '%s'" % (tag, tagdict['suffix'])) + if tagdict.get("suffix", ""): + warnings.warn( + "tag %r will be stripped of its suffix '%s'" % (tag, tagdict["suffix"]) + ) if VERSION_CLASS is not None: version = pkg_parse_version(version) trace("version", repr(version)) - return version @@ -111,7 +112,12 @@ def tags_to_versions(tags, config=None): :param tags: an iterable of tags :param config: optional configuration object """ - return filter(None, map(lambda tag: tag_to_version(tag, config=config), tags)) + result = [] + for tag in tags: + tag = tag_to_version(tag, config=config) + if tag: + result.append(tag) + return result class ScmVersion(object): @@ -176,9 +182,14 @@ def _parse_tag(tag, preformatted, config): return tag -def meta(tag, distance=None, dirty=False, node=None, preformatted=False, config=None, **kw): +def meta( + tag, distance=None, dirty=False, node=None, preformatted=False, config=None, **kw +): if not config: - warnings.warn("meta invoked without explicit configuration, will use defaults where required.") + warnings.warn( + "meta invoked without explicit configuration," + " will use defaults where required." + ) parsed_version = _parse_tag(tag, preformatted, config) trace("version", tag, "->", parsed_version) assert parsed_version is not None, "cant parse version %s" % tag
pypa/setuptools_scm
6f2703342a7060c4673117e54d9a0c133a07211e
diff --git a/testing/test_version.py b/testing/test_version.py index 4de545c..31f33f7 100644 --- a/testing/test_version.py +++ b/testing/test_version.py @@ -1,6 +1,6 @@ import pytest from setuptools_scm.config import Configuration -from setuptools_scm.version import meta, simplified_semver_version +from setuptools_scm.version import meta, simplified_semver_version, tags_to_versions @pytest.mark.parametrize( @@ -49,6 +49,13 @@ def test_next_semver(version, expected_next): ], ) def test_tag_regex1(tag, expected): - Configuration().tag_regex = r'^(?P<prefix>v)?(?P<version>[^\+]+)(?P<suffix>.*)?$' + Configuration().tag_regex = r"^(?P<prefix>v)?(?P<version>[^\+]+)(?P<suffix>.*)?$" result = meta(tag) assert result.tag.public == expected + + [email protected]("https://github.com/pypa/setuptools_scm/issues/286") +def test_tags_to_versions(): + config = Configuration() + versions = tags_to_versions(["1", "2", "3"], config=config) + assert isinstance(versions, list) # enable subscription
in version 3 tags_to_versions returns a iterator instead of a list I get this issue when using `setuptools>=3` and `<=3.0.2` ``` (venv) macbeth $ pip install --no-binary :all: cheroot Looking in indexes: http://artifactory.factset.com/artifactory/api/pypi/python/simple/ Collecting cheroot Downloading http://artifactory.factset.com/artifactory/api/pypi/python/packages/a3/fe/60797128186577348abc612fdd1011e737d7f01137c0c927dba489360fc3/cheroot-6.3.3.tar.gz (73kB) 100% |████████████████████████████████| 81kB 65.5MB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-otm5evwb/cheroot/setup.py", line 113, in <module> setuptools.setup(**params) File "/REDACTED_DIR/venv/lib/python3.6/site-packages/setuptools/__init__.py", line 131, in setup return distutils.core.setup(**attrs) File "/home/user/macbeth/.local/share/pyenv/versions/3.6.4/lib/python3.6/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/REDACTED_DIR/venv/lib/python3.6/site-packages/setuptools/dist.py", line 370, in __init__ k: v for k, v in attrs.items() File "/home/user/macbeth/.local/share/pyenv/versions/3.6.4/lib/python3.6/distutils/dist.py", line 281, in __init__ self.finalize_options() File "/REDACTED_DIR/venv/lib/python3.6/site-packages/setuptools/dist.py", line 529, in finalize_options ep.load()(self, ep.name, value) File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm-3.0.2-py3.6.egg/setuptools_scm/integration.py", line 23, in version_keyword dist.metadata.version = get_version(**value) File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm-3.0.2-py3.6.egg/setuptools_scm/__init__.py", line 135, in get_version parsed_version = _do_parse(config) File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm-3.0.2-py3.6.egg/setuptools_scm/__init__.py", line 88, in _do_parse config, "setuptools_scm.parse_scm" File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm-3.0.2-py3.6.egg/setuptools_scm/__init__.py", line 45, in _version_from_entrypoint version = _call_entrypoint_fn(config, ep.load()) File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm-3.0.2-py3.6.egg/setuptools_scm/__init__.py", line 40, in _call_entrypoint_fn return fn(config.absolute_root) File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm_git_archive-1.0-py3.6.egg/setuptools_scm_git_archive/__init__.py", line 21, in parse return archival_to_version(data) File "/tmp/pip-install-otm5evwb/cheroot/.eggs/setuptools_scm_git_archive-1.0-py3.6.egg/setuptools_scm_git_archive/__init__.py", line 15, in archival_to_version return meta(versions[0]) TypeError: 'filter' object is not subscriptable ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-otm5evwb/cheroot/ (venv) macbeth $ pip freeze --all pip==18.0 setuptools==40.0.0 (venv) macbeth $ python --version Python 3.6.4 ```
0.0
6f2703342a7060c4673117e54d9a0c133a07211e
[ "testing/test_version.py::test_tags_to_versions" ]
[ "testing/test_version.py::test_next_semver[exact]", "testing/test_version.py::test_next_semver[short_tag]", "testing/test_version.py::test_next_semver[normal_branch]", "testing/test_version.py::test_next_semver[normal_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_branch]", "testing/test_version.py::test_next_semver[feature_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_in_branch]", "testing/test_version.py::test_tag_regex1[v1.0.0-1.0.0]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1-1.0.0rc1]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1+-25259o4382757gjurh54-1.0.0rc1]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-07-24 07:11:27+00:00
mit
4,993
pypa__setuptools_scm-299
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 506e985..861d321 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,8 @@ +v3.1.0 +======= + +* fix #297 - correct the invocation in version_from_scm and deprecate it as its exposed by accident + v3.0.6 ====== * fix #295 - correctly handle selfinstall from tarballs diff --git a/src/setuptools_scm/__init__.py b/src/setuptools_scm/__init__.py index 49c0c4b..72b7b22 100644 --- a/src/setuptools_scm/__init__.py +++ b/src/setuptools_scm/__init__.py @@ -24,8 +24,14 @@ version = {version!r} def version_from_scm(root): + warnings.warn( + "version_from_scm is deprecated please use get_version", + category=DeprecationWarning, + ) + config = Configuration() + config.root = root # TODO: Is it API? - return _version_from_entrypoint(root, "setuptools_scm.parse_scm") + return _version_from_entrypoint(config, "setuptools_scm.parse_scm") def _call_entrypoint_fn(config, fn): diff --git a/src/setuptools_scm/file_finder_git.py b/src/setuptools_scm/file_finder_git.py index d886d06..b7b55ed 100644 --- a/src/setuptools_scm/file_finder_git.py +++ b/src/setuptools_scm/file_finder_git.py @@ -1,8 +1,11 @@ import os import subprocess import tarfile - +import logging from .file_finder import scm_find_files +from .utils import trace + +log = logging.getLogger(__name__) def _git_toplevel(path): @@ -14,6 +17,7 @@ def _git_toplevel(path): universal_newlines=True, stderr=devnull, ) + trace("find files toplevel", out) return os.path.normcase(os.path.realpath(out.strip())) except subprocess.CalledProcessError: # git returned error, we are not in a git repo @@ -23,12 +27,8 @@ def _git_toplevel(path): return None -def _git_ls_files_and_dirs(toplevel): - # use git archive instead of git ls-file to honor - # export-ignore git attribute - cmd = ["git", "archive", "--prefix", toplevel + os.path.sep, "HEAD"] - proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=toplevel) - tf = tarfile.open(fileobj=proc.stdout, mode="r|*") +def _git_interpret_archive(fd, toplevel): + tf = tarfile.open(fileobj=fd, mode="r|*") git_files = set() git_dirs = {toplevel} for member in tf.getmembers(): @@ -40,6 +40,19 @@ def _git_ls_files_and_dirs(toplevel): return git_files, git_dirs +def _git_ls_files_and_dirs(toplevel): + # use git archive instead of git ls-file to honor + # export-ignore git attribute + cmd = ["git", "archive", "--prefix", toplevel + os.path.sep, "HEAD"] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=toplevel) + try: + return _git_interpret_archive(proc.stdout, toplevel) + except Exception: + if proc.wait() != 0: + log.exception("listing git files failed - pretending there aren't any") + return (), () + + def git_find_files(path=""): toplevel = _git_toplevel(path) if not toplevel:
pypa/setuptools_scm
3ae1cad231545abfeedea9aaa7405e15fb28d95c
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index 1a0fa78..c032d23 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -46,6 +46,11 @@ def test_root_parameter_creation(monkeypatch): setuptools_scm.get_version() +def test_version_from_scm(wd): + with pytest.warns(DeprecationWarning, match=".*version_from_scm.*"): + setuptools_scm.version_from_scm(str(wd)) + + def test_root_parameter_pass_by(monkeypatch, tmpdir): assert_root(monkeypatch, tmpdir) setuptools_scm.get_version(root=tmpdir.strpath) diff --git a/testing/test_git.py b/testing/test_git.py index d854a7c..f498db0 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -4,6 +4,7 @@ from setuptools_scm import git import pytest from datetime import date from os.path import join as opj +from setuptools_scm.file_finder_git import git_find_files @pytest.fixture @@ -28,6 +29,14 @@ def test_parse_describe_output(given, tag, number, node, dirty): assert parsed == (tag, number, node, dirty) [email protected]("https://github.com/pypa/setuptools_scm/issues/298") +def test_file_finder_no_history(wd, caplog): + file_list = git_find_files(str(wd.cwd)) + assert file_list == [] + + assert "listing git files failed - pretending there aren't any" in caplog.text + + @pytest.mark.issue("https://github.com/pypa/setuptools_scm/issues/281") def test_parse_call_order(wd): git.parse(str(wd.cwd), git.DEFAULT_DESCRIBE)
tarfile.ReadError: empty file - in filefinder on no commits ``` /usr/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'test_requires' warnings.warn(msg) /home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/version.py:191: UserWarning: meta invoked without explicit configuration, will use defaults where required. "meta invoked without explicit configuration," running egg_info writing rio_redis.egg-info/PKG-INFO writing dependency_links to rio_redis.egg-info/dependency_links.txt writing requirements to rio_redis.egg-info/requires.txt writing top-level names to rio_redis.egg-info/top_level.txt fatal: Not a valid object name Traceback (most recent call last): File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 2287, in next tarinfo = self.tarinfo.fromtarfile(self) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1093, in fromtarfile obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1029, in frombuf raise EmptyHeaderError("empty header") tarfile.EmptyHeaderError: empty header During handling of the above exception, another exception occurred: Traceback (most recent call last): File "setup.py", line 39, in <module> python_requires=">=3.6.0", File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/__init__.py", line 131, in setup return distutils.core.setup(**attrs) File "/usr/lib64/python3.7/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib64/python3.7/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/usr/lib64/python3.7/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 278, in run self.find_sources() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 293, in find_sources mm.run() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 524, in run self.add_defaults() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 563, in add_defaults rcfiles = list(walk_revctrl()) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/sdist.py", line 20, in walk_revctrl for item in ep.load()(dirname): File "/home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/integration.py", line 33, in find_files res = command(path) File "/home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/file_finder_git.py", line 47, in git_find_files git_files, git_dirs = _git_ls_files_and_dirs(toplevel) File "/home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/file_finder_git.py", line 31, in _git_ls_files_and_dirs tf = tarfile.open(fileobj=proc.stdout, mode="r|*") File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1601, in open t = cls(name, filemode, stream, **kwargs) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1482, in __init__ self.firstmember = self.next() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 2302, in next raise ReadError("empty file") tarfile.ReadError: empty file ```
0.0
3ae1cad231545abfeedea9aaa7405e15fb28d95c
[ "testing/test_basic_api.py::test_version_from_scm", "testing/test_git.py::test_file_finder_no_history" ]
[ "testing/test_basic_api.py::test_do[ls]", "testing/test_basic_api.py::test_do[dir]", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_dump_version", "testing/test_basic_api.py::test_parse_plain_fails", "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-08-08 09:26:04+00:00
mit
4,994
pypa__setuptools_scm-300
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 506e985..861d321 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,8 @@ +v3.1.0 +======= + +* fix #297 - correct the invocation in version_from_scm and deprecate it as its exposed by accident + v3.0.6 ====== * fix #295 - correctly handle selfinstall from tarballs diff --git a/src/setuptools_scm/__init__.py b/src/setuptools_scm/__init__.py index 49c0c4b..72b7b22 100644 --- a/src/setuptools_scm/__init__.py +++ b/src/setuptools_scm/__init__.py @@ -24,8 +24,14 @@ version = {version!r} def version_from_scm(root): + warnings.warn( + "version_from_scm is deprecated please use get_version", + category=DeprecationWarning, + ) + config = Configuration() + config.root = root # TODO: Is it API? - return _version_from_entrypoint(root, "setuptools_scm.parse_scm") + return _version_from_entrypoint(config, "setuptools_scm.parse_scm") def _call_entrypoint_fn(config, fn):
pypa/setuptools_scm
3ae1cad231545abfeedea9aaa7405e15fb28d95c
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index 1a0fa78..c032d23 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -46,6 +46,11 @@ def test_root_parameter_creation(monkeypatch): setuptools_scm.get_version() +def test_version_from_scm(wd): + with pytest.warns(DeprecationWarning, match=".*version_from_scm.*"): + setuptools_scm.version_from_scm(str(wd)) + + def test_root_parameter_pass_by(monkeypatch, tmpdir): assert_root(monkeypatch, tmpdir) setuptools_scm.get_version(root=tmpdir.strpath)
setuptools_scm 3.0.6: `version_from_scm()` fails under Python2 When I invoke `setuptools_scm.version_from_scm()` within my Python 2 program, I get a stacktrace: ``` Traceback (most recent call last): ... File "/usr/local/lib/python2.7/dist-packages/setuptools_scm/__init__.py", line 28, in version_from_scm return _version_from_entrypoint(root, "setuptools_scm.parse_scm") File "/usr/local/lib/python2.7/dist-packages/setuptools_scm/__init__.py", line 44, in _version_from_entrypoint for ep in iter_matching_entrypoints(config.absolute_root, entrypoint): AttributeError: 'str' object has no attribute 'absolute_root' ``` This error occurs with version 3.0.6. Everything worked fine under 2.1.0. Appears to have been introduced in PR #276, looks similar to #281. Python 2 is still intended to be supported, right? Thanks for your work on `setuptools_scm`! Sorry some of us are still stuck on Python 2 :-/
0.0
3ae1cad231545abfeedea9aaa7405e15fb28d95c
[ "testing/test_basic_api.py::test_version_from_scm" ]
[ "testing/test_basic_api.py::test_do[ls]", "testing/test_basic_api.py::test_do[dir]", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_dump_version", "testing/test_basic_api.py::test_parse_plain_fails" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-08-08 10:16:31+00:00
mit
4,995
pypa__setuptools_scm-398
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 8545f4f..5267e2b 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,8 @@ +v3.4.2 +====== + +* fix #395: correctly transfer tag regex in the Configuration constructor + v3.4.1 ====== diff --git a/src/setuptools_scm/config.py b/src/setuptools_scm/config.py index 7dee1e4..139512d 100644 --- a/src/setuptools_scm/config.py +++ b/src/setuptools_scm/config.py @@ -66,7 +66,7 @@ class Configuration(object): self.fallback_version = fallback_version self.fallback_root = fallback_root self.parse = parse - self.tag_regex = DEFAULT_TAG_REGEX + self.tag_regex = tag_regex self.git_describe_command = git_describe_command @property
pypa/setuptools_scm
823c3acac310aab86a57e4a26405db2a7296164a
diff --git a/testing/test_config.py b/testing/test_config.py index 38bc8f4..b8ea265 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -1,7 +1,7 @@ from __future__ import unicode_literals from setuptools_scm.config import Configuration - +import re import pytest @@ -26,3 +26,9 @@ def test_config_from_pyproject(tmpdir): fn = tmpdir / "pyproject.toml" fn.write_text("[tool.setuptools_scm]\n", encoding="utf-8") assert Configuration.from_file(str(fn)) + + +def test_config_regex_init(): + tag_regex = re.compile(r"v(\d+)") + conf = Configuration(tag_regex=tag_regex) + assert conf.tag_regex is tag_regex
tag_regex not working with setuptools_scm 3.4.1 With setuptools_scm 3.4.1, custom tag_regex expressions are not working correctly. My setup.py contains: ... setup_args["use_scm_version"] = { "tag_regex": r"^(?P<prefix>.*/)?(?P<version>\d+(?:\.\d+){1,2})$" } setup_args["setup_requires"] = ['setuptools_scm'] setuptools.setup(**setup_args) setuptools_scm 3.4.0 works: $ python3 setup.py --version 0.4.1.dev7+gc2397c5' With 3.4.1: $ python3 setup.py --version /home/kolbus/.local/lib/python3.6/site-packages/setuptools_scm/version.py:92: UserWarning: tag 'development/0.4.0' no version found warnings.warn("tag {!r} no version found".format(tag)) Traceback (most recent call last): ... File "/home/kolbus/.local/lib/python3.6/site-packages/setuptools_scm/git.py", line 135, in parse branch=branch, File "/home/kolbus/.local/lib/python3.6/site-packages/setuptools_scm/version.py", line 205, in meta assert parsed_version is not None, "cant parse version %s" % tag AssertionError: cant parse version development/0.4.0
0.0
823c3acac310aab86a57e4a26405db2a7296164a
[ "testing/test_config.py::test_config_regex_init" ]
[ "testing/test_config.py::test_tag_regex[apache-arrow-0.9.0-0.9.0]", "testing/test_config.py::test_tag_regex[arrow-0.9.0-0.9.0]", "testing/test_config.py::test_tag_regex[arrow-0.9.0-rc-0.9.0-rc]", "testing/test_config.py::test_tag_regex[v1.1-v1.1]", "testing/test_config.py::test_tag_regex[V1.1-V1.1]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-01-19 12:02:33+00:00
mit
4,996
pypa__setuptools_scm-475
diff --git a/src/setuptools_scm/__init__.py b/src/setuptools_scm/__init__.py index 6b22b28..beb7168 100644 --- a/src/setuptools_scm/__init__.py +++ b/src/setuptools_scm/__init__.py @@ -23,6 +23,7 @@ TEMPLATES = { # file generated by setuptools_scm # don't change, don't track in version control version = {version!r} +version_tuple = {version_tuple!r} """, ".txt": "{version}", } @@ -80,8 +81,19 @@ def dump_version(root, version, write_to, template=None): os.path.splitext(target)[1], target ) ) + + # version_tuple: each field is converted to an int if possible or kept as string + fields = tuple(version.split(".")) + version_fields = [] + for field in fields: + try: + v = int(field) + except ValueError: + v = field + version_fields.append(v) + with open(target, "w") as fp: - fp.write(template.format(version=version)) + fp.write(template.format(version=version, version_tuple=tuple(version_fields))) def _do_parse(config):
pypa/setuptools_scm
1c8bb50e90520a39279f213706ad69b4f180fea1
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index c5104f5..5111542 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -101,9 +101,13 @@ def test_dump_version(tmpdir): dump_version(sp, "1.0", "first.txt") assert tmpdir.join("first.txt").read() == "1.0" - dump_version(sp, "1.0", "first.py") + + dump_version(sp, "1.0.dev42", "first.py") content = tmpdir.join("first.py").read() - assert repr("1.0") in content + lines = content.splitlines() + assert "version = '1.0.dev42'" in lines + assert "version_tuple = (1, 0, 'dev42')" in lines + import ast ast.parse(content)
enable version-tuples/lazy parsed versions in write_to contents follow up to https://github.com/pytest-dev/pytest/pull/7605 a way to have easy static version tuples or a available layz parsed version to do version comparisation correctly is nice to have, if only the string is there, users of a library are tempted into potentially hazardous solutions to compare versions too quick and too error prone
0.0
1c8bb50e90520a39279f213706ad69b4f180fea1
[ "testing/test_basic_api.py::test_dump_version" ]
[ "testing/test_basic_api.py::test_do[ls]", "testing/test_basic_api.py::test_do[dir]", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_version_from_scm", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_parentdir_prefix", "testing/test_basic_api.py::test_fallback", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_parse_plain_fails" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-08-22 11:58:23+00:00
mit
4,997
pypa__setuptools_scm-497
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index c376a55..34f923e 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,7 @@ v4.2.0 ====== +* fix #352: add support for generally ignoring specific vcs roots * fix #471: better error for version bump failing on complex but accepted tag * fix #479: raise indicative error when tags carry non-parsable information * Add `no-guess-dev` which does no next version guessing, just adds `.post1.devN` in diff --git a/README.rst b/README.rst index a318332..d4b2453 100644 --- a/README.rst +++ b/README.rst @@ -446,6 +446,11 @@ Environment variables derived, otherwise the current time is used (https://reproducible-builds.org/docs/source-date-epoch/) + +:SETUPTOOLS_SCM_IGNORE_VCS_ROOTS: + when defined, a ``os.pathsep`` separated list + of directory names to ignore for root finding + Extending setuptools_scm ------------------------ diff --git a/src/setuptools_scm/file_finder.py b/src/setuptools_scm/file_finder.py index 77ec146..5b85117 100644 --- a/src/setuptools_scm/file_finder.py +++ b/src/setuptools_scm/file_finder.py @@ -1,4 +1,5 @@ import os +from .utils import trace def scm_find_files(path, scm_files, scm_dirs): @@ -53,3 +54,16 @@ def scm_find_files(path, scm_files, scm_dirs): res.append(os.path.join(path, os.path.relpath(fullfilename, realpath))) seen.add(realdirpath) return res + + +def is_toplevel_acceptable(toplevel): + "" + if toplevel is None: + return False + + ignored = os.environ.get("SETUPTOOLS_SCM_IGNORE_VCS_ROOTS", "").split(os.pathsep) + ignored = [os.path.normcase(p) for p in ignored] + + trace(toplevel, ignored) + + return toplevel not in ignored diff --git a/src/setuptools_scm/file_finder_git.py b/src/setuptools_scm/file_finder_git.py index 9aa6245..1d3e69b 100644 --- a/src/setuptools_scm/file_finder_git.py +++ b/src/setuptools_scm/file_finder_git.py @@ -3,6 +3,7 @@ import subprocess import tarfile import logging from .file_finder import scm_find_files +from .file_finder import is_toplevel_acceptable from .utils import trace log = logging.getLogger(__name__) @@ -60,7 +61,7 @@ def _git_ls_files_and_dirs(toplevel): def git_find_files(path=""): toplevel = _git_toplevel(path) - if not toplevel: + if not is_toplevel_acceptable(toplevel): return [] fullpath = os.path.abspath(os.path.normpath(path)) if not fullpath.startswith(toplevel): diff --git a/src/setuptools_scm/file_finder_hg.py b/src/setuptools_scm/file_finder_hg.py index 2aa1e16..816560d 100644 --- a/src/setuptools_scm/file_finder_hg.py +++ b/src/setuptools_scm/file_finder_hg.py @@ -2,6 +2,7 @@ import os import subprocess from .file_finder import scm_find_files +from .file_finder import is_toplevel_acceptable def _hg_toplevel(path): @@ -41,7 +42,7 @@ def _hg_ls_files_and_dirs(toplevel): def hg_find_files(path=""): toplevel = _hg_toplevel(path) - if not toplevel: + if not is_toplevel_acceptable(toplevel): return [] hg_files, hg_dirs = _hg_ls_files_and_dirs(toplevel) return scm_find_files(path, hg_files, hg_dirs)
pypa/setuptools_scm
1cb4c5a43fc39a5098491d03dd5520121250e56d
diff --git a/testing/test_file_finder.py b/testing/test_file_finder.py index 463d3d4..55b9cea 100644 --- a/testing/test_file_finder.py +++ b/testing/test_file_finder.py @@ -126,6 +126,12 @@ def test_symlink_file_out_of_git(inwd): assert set(find_files("adir")) == _sep({"adir/filea"}) [email protected]("path_add", ["{cwd}", "{cwd}" + os.pathsep + "broken"]) +def test_ignore_root(inwd, monkeypatch, path_add): + monkeypatch.setenv("SETUPTOOLS_SCM_IGNORE_VCS_ROOTS", path_add.format(cwd=inwd.cwd)) + assert find_files() == [] + + def test_empty_root(inwd): subdir = inwd.cwd / "cdir" / "subdir" subdir.mkdir(parents=True)
hg failing if external repo is broken I have /.hg in my root fs of Gentoo Linux, tracking almost /etc and other files. And if something is broken with that external repo, all Python installations by the package manager inside of it's building sandbox in /var/tmp/portage are failing like this: ``` writing dependency_links to python_mimeparse.egg-info/dependency_links.txt abort: No such file or directory: '/boot/config' Traceback (most recent call last): File "setup.py", line 50, in <module> long_description=read('README.rst') File "/usr/lib64/python2.7/site-packages/setuptools/__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "/usr/lib64/python2.7/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib64/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/usr/lib64/python2.7/site-packages/setuptools/command/install.py", line 61, in run return orig.install.run(self) File "/usr/lib64/python2.7/distutils/command/install.py", line 575, in run self.run_command(cmd_name) File "/usr/lib64/python2.7/distutils/cmd.py", line 326, in run_command self.distribution.run_command(command) File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/usr/lib64/python2.7/site-packages/setuptools/command/install_egg_info.py", line 34, in run self.run_command('egg_info') File "/usr/lib64/python2.7/distutils/cmd.py", line 326, in run_command self.distribution.run_command(command) File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/usr/lib64/python2.7/site-packages/setuptools/command/egg_info.py", line 296, in run self.find_sources() File "/usr/lib64/python2.7/site-packages/setuptools/command/egg_info.py", line 303, in find_sources mm.run() File "/usr/lib64/python2.7/site-packages/setuptools/command/egg_info.py", line 534, in run self.add_defaults() File "/usr/lib64/python2.7/site-packages/setuptools/command/egg_info.py", line 574, in add_defaults rcfiles = list(walk_revctrl()) File "/usr/lib64/python2.7/site-packages/setuptools/command/sdist.py", line 20, in walk_revctrl for item in ep.load()(dirname): File "/usr/lib64/python2.7/site-packages/setuptools_scm/integration.py", line 27, in find_files res = command(path) File "/usr/lib64/python2.7/site-packages/setuptools_scm/file_finder_hg.py", line 46, in hg_find_files hg_files, hg_dirs = _hg_ls_files_and_dirs(toplevel) File "/usr/lib64/python2.7/site-packages/setuptools_scm/file_finder_hg.py", line 29, in _hg_ls_files_and_dirs ["hg", "files"], cwd=toplevel, universal_newlines=True File "/usr/lib64/python2.7/subprocess.py", line 223, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['hg', 'files']' returned non-zero exit status 255 ``` setuptools should be completely independent from outside Mercurial repos or maybe have an option to ignore that like this: ```patch --- a/src/setuptools_scm/file_finder_hg.py 2019-08-01 08:24:15.060553831 +0200 +++ b/src/setuptools_scm/file_finder_hg.py 2019-08-01 08:26:11.334617120 +0200 @@ -41,7 +41,11 @@ def hg_find_files(path=""): toplevel = _hg_toplevel(path) if not toplevel: return [] + # SETUPTOOLS_SCM_IGNORE_VCS_ROOTS is a ':'-separated list of VCS roots to ignore. + # Example: SETUPTOOLS_SCM_IGNORE_VCS_ROOTS=/var:/etc:/home/me + if toplevel in os.environ.get('SETUPTOOLS_SCM_IGNORE_VCS_ROOTS', '').split(':'): + return [] hg_files, hg_dirs = _hg_ls_files_and_dirs(toplevel) return scm_find_files(path, hg_files, hg_dirs) ```
0.0
1cb4c5a43fc39a5098491d03dd5520121250e56d
[ "testing/test_file_finder.py::test_ignore_root[git-{cwd}]", "testing/test_file_finder.py::test_ignore_root[git-{cwd}:broken]", "testing/test_file_finder.py::test_ignore_root[hg-{cwd}]", "testing/test_file_finder.py::test_ignore_root[hg-{cwd}:broken]" ]
[ "testing/test_file_finder.py::test_basic[git]", "testing/test_file_finder.py::test_basic[hg]", "testing/test_file_finder.py::test_whitespace[git]", "testing/test_file_finder.py::test_whitespace[hg]", "testing/test_file_finder.py::test_case[git]", "testing/test_file_finder.py::test_case[hg]", "testing/test_file_finder.py::test_symlink_dir[git]", "testing/test_file_finder.py::test_symlink_dir[hg]", "testing/test_file_finder.py::test_symlink_dir_source_not_in_scm[git]", "testing/test_file_finder.py::test_symlink_dir_source_not_in_scm[hg]", "testing/test_file_finder.py::test_symlink_file[git]", "testing/test_file_finder.py::test_symlink_file[hg]", "testing/test_file_finder.py::test_symlink_file_source_not_in_scm[git]", "testing/test_file_finder.py::test_symlink_file_source_not_in_scm[hg]", "testing/test_file_finder.py::test_symlink_loop[git]", "testing/test_file_finder.py::test_symlink_loop[hg]", "testing/test_file_finder.py::test_symlink_loop_outside_path[git]", "testing/test_file_finder.py::test_symlink_loop_outside_path[hg]", "testing/test_file_finder.py::test_symlink_dir_out_of_git[git]", "testing/test_file_finder.py::test_symlink_dir_out_of_git[hg]", "testing/test_file_finder.py::test_symlink_file_out_of_git[git]", "testing/test_file_finder.py::test_symlink_file_out_of_git[hg]", "testing/test_file_finder.py::test_empty_root[git]", "testing/test_file_finder.py::test_empty_root[hg]", "testing/test_file_finder.py::test_empty_subdir[git]", "testing/test_file_finder.py::test_empty_subdir[hg]", "testing/test_file_finder.py::test_double_include_through_symlink[git]", "testing/test_file_finder.py::test_double_include_through_symlink[hg]", "testing/test_file_finder.py::test_symlink_not_in_scm_while_target_is[git]", "testing/test_file_finder.py::test_symlink_not_in_scm_while_target_is[hg]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-29 21:33:01+00:00
mit
4,998
pypa__setuptools_scm-500
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5f58599..dbce446 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,7 @@ v4.2.0 * enhance documentation * consider SOURCE_DATE_EPOCH for versioning * add a version_tuple to write_to templates +* fix #321: add suppport for the ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_${DISTRIBUTION_NAME}`` env var to target the pretend key * fix #142: clearly list supported scm diff --git a/README.rst b/README.rst index d402b7e..a826b1f 100644 --- a/README.rst +++ b/README.rst @@ -442,6 +442,15 @@ Environment variables its used as the primary source for the version number in which case it will be a unparsed string + +:SETUPTOOLS_SCM_PRETEND_VERSION_FOR_${UPPERCASED_DIST_NAME}: + when defined and not empty, + its used as the primary source for the version number + in which case it will be a unparsed string + + it takes precedence over ``SETUPTOOLS_SCM_PRETEND_VERSION`` + + :SETUPTOOLS_SCM_DEBUG: when defined and not empty, a lot of debug information will be printed as part of ``setuptools_scm`` diff --git a/src/setuptools_scm/__init__.py b/src/setuptools_scm/__init__.py index beb7168..47b9e44 100644 --- a/src/setuptools_scm/__init__.py +++ b/src/setuptools_scm/__init__.py @@ -11,11 +11,12 @@ from .config import ( DEFAULT_LOCAL_SCHEME, DEFAULT_TAG_REGEX, ) -from .utils import function_has_arg, string_types +from .utils import function_has_arg, string_types, trace from .version import format_version, meta from .discover import iter_matching_entrypoints PRETEND_KEY = "SETUPTOOLS_SCM_PRETEND_VERSION" +PRETEND_KEY_NAMED = PRETEND_KEY + "_FOR_{name}" TEMPLATES = { ".py": """\ @@ -97,7 +98,18 @@ def dump_version(root, version, write_to, template=None): def _do_parse(config): - pretended = os.environ.get(PRETEND_KEY) + + trace("dist name:", config.dist_name) + if config.dist_name is not None: + pretended = os.environ.get( + PRETEND_KEY_NAMED.format(name=config.dist_name.upper()) + ) + else: + pretended = None + + if pretended is None: + pretended = os.environ.get(PRETEND_KEY) + if pretended: # we use meta here since the pretended version # must adhere to the pep to begin with @@ -144,6 +156,7 @@ def get_version( fallback_root=".", parse=None, git_describe_command=None, + dist_name=None, ): """ If supplied, relative_to should be a file from which root may diff --git a/src/setuptools_scm/config.py b/src/setuptools_scm/config.py index e7f4d72..f0d9243 100644 --- a/src/setuptools_scm/config.py +++ b/src/setuptools_scm/config.py @@ -54,6 +54,7 @@ class Configuration(object): fallback_root=".", parse=None, git_describe_command=None, + dist_name=None, ): # TODO: self._relative_to = relative_to @@ -70,6 +71,7 @@ class Configuration(object): self.parse = parse self.tag_regex = tag_regex self.git_describe_command = git_describe_command + self.dist_name = dist_name @property def fallback_root(self): diff --git a/src/setuptools_scm/integration.py b/src/setuptools_scm/integration.py index c623db7..ffd4521 100644 --- a/src/setuptools_scm/integration.py +++ b/src/setuptools_scm/integration.py @@ -1,7 +1,7 @@ from pkg_resources import iter_entry_points from .version import _warn_if_setuptools_outdated -from .utils import do, trace_exception +from .utils import do, trace_exception, trace from . import _get_version, Configuration @@ -13,7 +13,12 @@ def version_keyword(dist, keyword, value): value = {} if getattr(value, "__call__", None): value = value() - config = Configuration(**value) + assert ( + "dist_name" not in value + ), "dist_name may not be specified in the setup keyword " + trace("dist name", dist, dist.name) + dist_name = dist.name if dist.name != 0 else None + config = Configuration(dist_name=dist_name, **value) dist.metadata.version = _get_version(config) @@ -32,7 +37,7 @@ def find_files(path=""): def _args_from_toml(name="pyproject.toml"): # todo: more sensible config initialization - # move this elper back to config and unify it with the code from get_config + # move this helper back to config and unify it with the code from get_config with open(name) as strm: defn = __import__("toml").load(strm)
pypa/setuptools_scm
d0d2973413ddd3da2896aa8805f42d11201b6ff1
diff --git a/testing/test_integration.py b/testing/test_integration.py index 68c3bfe..4564897 100644 --- a/testing/test_integration.py +++ b/testing/test_integration.py @@ -3,6 +3,7 @@ import sys import pytest from setuptools_scm.utils import do +from setuptools_scm import PRETEND_KEY, PRETEND_KEY_NAMED @pytest.fixture @@ -40,3 +41,23 @@ def test_pyproject_support_with_git(tmpdir, monkeypatch, wd): pkg.join("setup.py").write("__import__('setuptools').setup()") res = do((sys.executable, "setup.py", "--version"), pkg) assert res == "0.1.dev0" + + +def test_pretend_version(tmpdir, monkeypatch, wd): + monkeypatch.setenv(PRETEND_KEY, "1.0.0") + + assert wd.get_version() == "1.0.0" + assert wd.get_version(dist_name="ignored") == "1.0.0" + + +def test_pretend_version_named(tmpdir, monkeypatch, wd): + monkeypatch.setenv(PRETEND_KEY_NAMED.format(name="test".upper()), "1.0.0") + monkeypatch.setenv(PRETEND_KEY_NAMED.format(name="test2".upper()), "2.0.0") + assert wd.get_version(dist_name="test") == "1.0.0" + assert wd.get_version(dist_name="test2") == "2.0.0" + + +def test_pretend_version_name_takes_precedence(tmpdir, monkeypatch, wd): + monkeypatch.setenv(PRETEND_KEY_NAMED.format(name="test".upper()), "1.0.0") + monkeypatch.setenv(PRETEND_KEY, "2.0.0") + assert wd.get_version(dist_name="test") == "1.0.0"
setuptools_scm should support custom per-project SETUPTOOLS_SCM_PRETEND_VERSION var When there's two project (one is dependency of another), both use `setuptools_scm` and `SETUPTOOLS_SCM_PRETEND_VERSION` env var is set, both of them use it for their version if installed from source. I think maybe providing some prefixing/suffixing mechanism would improve this.
0.0
d0d2973413ddd3da2896aa8805f42d11201b6ff1
[ "testing/test_integration.py::test_pretend_version", "testing/test_integration.py::test_pretend_version_named", "testing/test_integration.py::test_pretend_version_name_takes_precedence" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-05 07:52:48+00:00
mit
4,999
pypa__setuptools_scm-502
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index dbce446..c570357 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -12,6 +12,7 @@ v4.2.0 * add a version_tuple to write_to templates * fix #321: add suppport for the ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_${DISTRIBUTION_NAME}`` env var to target the pretend key * fix #142: clearly list supported scm +* fix #213: better error message for non-zero dev numbers in tags v4.1.2 diff --git a/README.rst b/README.rst index a826b1f..f9193c1 100644 --- a/README.rst +++ b/README.rst @@ -277,6 +277,7 @@ distance and not clean: The next version is calculated by adding ``1`` to the last numeric component of the tag. + For Git projects, the version relies on `git describe <https://git-scm.com/docs/git-describe>`_, so you will see an additional ``g`` prepended to the ``{revision hash}``. @@ -507,6 +508,8 @@ Version number construction :guess-next-dev: Automatically guesses the next development version (default). Guesses the upcoming release by incrementing the pre-release segment if present, otherwise by incrementing the micro segment. Then appends :code:`.devN`. + In case the tag ends with ``.dev0`` the version is not bumped + and custom ``.devN`` versions will trigger a error. :post-release: generates post release versions (adds :code:`.postN`) :python-simplified-semver: Basic semantic versioning. Guesses the upcoming release by incrementing the minor segment and setting the micro segment to zero if the diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index 40eadc8..f97dca5 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -230,7 +230,13 @@ def _bump_dev(version): return prefix, tail = version.rsplit(".dev", 1) - assert tail == "0", "own dev numbers are unsupported" + if tail != "0": + raise ValueError( + "choosing custom numbers for the `.devX` distance " + "is not supported.\n " + "The {version} can't be bumped\n" + "Please drop the tag or create a new supported one".format(version=version) + ) return prefix diff --git a/tox.ini b/tox.ini index 5f1143e..030dbd4 100644 --- a/tox.ini +++ b/tox.ini @@ -48,6 +48,7 @@ setenv = SETUPTOOLS_SCM_PRETEND_VERSION=2.0 deps= check-manifest docutils + pygments commands= rst2html.py README.rst {envlogdir}/README.html --strict [] check-manifest
pypa/setuptools_scm
6b444b930e95d8487c30534d9dab083739e497f8
diff --git a/testing/test_version.py b/testing/test_version.py index 722b8e8..ee13801 100644 --- a/testing/test_version.py +++ b/testing/test_version.py @@ -120,6 +120,22 @@ def test_no_guess_version(version, expected_next): assert computed == expected_next +def test_bump_dev_version_zero(): + guess_next_version("1.0.dev0") + + +def test_bump_dev_version_nonzero_raises(): + with pytest.raises(ValueError) as excinfo: + guess_next_version("1.0.dev1") + + assert str(excinfo.value) == ( + "choosing custom numbers for the `.devX` distance " + "is not supported.\n " + "The 1.0.dev1 can't be bumped\n" + "Please drop the tag or create a new supported one" + ) + + @pytest.mark.parametrize( "tag, expected", [
document/gracefully handle when users create own dev versions in tags I had already created the tag "0.15.0.dev0" of my package, before uploading that development version to PyPI. I made some further progress and wanted to release a new development version, and so I created the tag "0.15.0.dev1". It seems I've found out the hard way though (doesn't seem to be documented?) that dev versions greater than 0 are currently unsupported – I'm now hitting this AssertionError: https://github.com/pypa/setuptools_scm/blob/46df188a54e3eb2b0dfb93dbae59fb23249fbcce/setuptools_scm/version.py#L124 (``assert tail == '0', 'own dev numbers are unsupported'``) If I comment out that assertion, `guess_next_dev_version` works like a charm. Could you please explain why that assertion is there, whether there are any plans to add support for "own dev numbers" (seems like totally valid usage, no?), and what you recommend doing in the meantime? Thanks 😊
0.0
6b444b930e95d8487c30534d9dab083739e497f8
[ "testing/test_version.py::test_bump_dev_version_nonzero_raises" ]
[ "testing/test_version.py::test_next_semver[exact]", "testing/test_version.py::test_next_semver[short_tag]", "testing/test_version.py::test_next_semver[normal_branch]", "testing/test_version.py::test_next_semver[normal_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_branch]", "testing/test_version.py::test_next_semver[feature_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_in_branch]", "testing/test_version.py::test_next_release_branch_semver[exact]", "testing/test_version.py::test_next_release_branch_semver[development_branch]", "testing/test_version.py::test_next_release_branch_semver[development_branch_release_candidate]", "testing/test_version.py::test_next_release_branch_semver[release_branch_legacy_version]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_prefix]", "testing/test_version.py::test_next_release_branch_semver[false_positive_release_branch]", "testing/test_version.py::test_no_guess_version[dev_distance]", "testing/test_version.py::test_no_guess_version[dev_distance_short_tag]", "testing/test_version.py::test_no_guess_version[no_dev_distance]", "testing/test_version.py::test_bump_dev_version_zero", "testing/test_version.py::test_tag_regex1[v1.0.0-1.0.0]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1-1.0.0rc1]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1+-25259o4382757gjurh54-1.0.0rc1]", "testing/test_version.py::test_tags_to_versions", "testing/test_version.py::test_version_bump_bad" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-06 16:12:47+00:00
mit
5,000
pypa__setuptools_scm-503
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index c570357..83666ae 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,12 @@ -v4.2.0 +v5.0.0 ====== + +Breaking changes: +* fix #339: strict errors on missing scms when parsing a scm dir to avoid false version lookups + +Bugfixes: + * fix #352: add support for generally ignoring specific vcs roots * fix #471: better error for version bump failing on complex but accepted tag * fix #479: raise indicative error when tags carry non-parsable information diff --git a/src/setuptools_scm/git.py b/src/setuptools_scm/git.py index 76be436..4fd5d49 100644 --- a/src/setuptools_scm/git.py +++ b/src/setuptools_scm/git.py @@ -1,5 +1,5 @@ from .config import Configuration -from .utils import do_ex, trace, has_command +from .utils import do_ex, trace, require_command from .version import meta from os.path import isfile, join @@ -92,8 +92,7 @@ def parse( if not config: config = Configuration(root=root) - if not has_command("git"): - return + require_command("git") wd = GitWorkdir.from_potential_worktree(config.absolute_root) if wd is None: diff --git a/src/setuptools_scm/hg.py b/src/setuptools_scm/hg.py index d699d45..2ac9141 100644 --- a/src/setuptools_scm/hg.py +++ b/src/setuptools_scm/hg.py @@ -1,6 +1,6 @@ import os from .config import Configuration -from .utils import do, trace, data_from_mime, has_command +from .utils import do, trace, data_from_mime, require_command from .version import meta, tags_to_versions @@ -36,8 +36,7 @@ def parse(root, config=None): if not config: config = Configuration(root=root) - if not has_command("hg"): - return + require_command("hg") identity_data = do("hg id -i -b -t", config.absolute_root).split() if not identity_data: return diff --git a/src/setuptools_scm/utils.py b/src/setuptools_scm/utils.py index 15ca83e..413e98a 100644 --- a/src/setuptools_scm/utils.py +++ b/src/setuptools_scm/utils.py @@ -132,7 +132,7 @@ def function_has_arg(fn, argname): return argname in argspec -def has_command(name): +def has_command(name, warn=True): try: p = _popen_pipes([name, "help"], ".") except OSError: @@ -141,6 +141,11 @@ def has_command(name): else: p.communicate() res = not p.returncode - if not res: - warnings.warn("%r was not found" % name) + if not res and warn: + warnings.warn("%r was not found" % name, category=RuntimeWarning) return res + + +def require_command(name): + if not has_command(name, warn=False): + raise EnvironmentError("%r was not found" % name)
pypa/setuptools_scm
c4523c65a3e8ce3d3481cea42ade9b657bb6546f
diff --git a/testing/test_git.py b/testing/test_git.py index 6f5246c..1b57fed 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -7,7 +7,6 @@ import pytest from datetime import datetime from os.path import join as opj from setuptools_scm.file_finder_git import git_find_files -import warnings skip_if_win_27 = pytest.mark.skipif( @@ -16,10 +15,9 @@ skip_if_win_27 = pytest.mark.skipif( ) -with warnings.catch_warnings(): - warnings.filterwarnings("ignore") - if not has_command("git"): - pytestmark = pytest.mark.skip(reason="git executable not found") +pytestmark = pytest.mark.skipif( + not has_command("git", warn=False), reason="git executable not found" +) @pytest.fixture @@ -59,6 +57,12 @@ setup(use_scm_version={"root": "../..", assert res == "0.1.dev0" +def test_git_gone(wd, monkeypatch): + monkeypatch.setenv("PATH", str(wd.cwd / "not-existing")) + with pytest.raises(EnvironmentError, match="'git' was not found"): + git.parse(str(wd.cwd), git.DEFAULT_DESCRIBE) + + @pytest.mark.issue("https://github.com/pypa/setuptools_scm/issues/298") @pytest.mark.issue(403) def test_file_finder_no_history(wd, caplog): diff --git a/testing/test_integration.py b/testing/test_integration.py index 4564897..446aac0 100644 --- a/testing/test_integration.py +++ b/testing/test_integration.py @@ -8,11 +8,7 @@ from setuptools_scm import PRETEND_KEY, PRETEND_KEY_NAMED @pytest.fixture def wd(wd): - try: - wd("git init") - except OSError: - pytest.skip("git executable not found") - + wd("git init") wd("git config user.email [email protected]") wd('git config user.name "a test"') wd.add_command = "git add ." diff --git a/testing/test_mercurial.py b/testing/test_mercurial.py index 815ca00..265e207 100644 --- a/testing/test_mercurial.py +++ b/testing/test_mercurial.py @@ -4,13 +4,11 @@ from setuptools_scm import integration from setuptools_scm.config import Configuration from setuptools_scm.utils import has_command import pytest -import warnings -with warnings.catch_warnings(): - warnings.filterwarnings("ignore") - if not has_command("hg"): - pytestmark = pytest.mark.skip(reason="hg executable not found") +pytestmark = pytest.mark.skipif( + not has_command("hg", warn=False), reason="hg executable not found" +) @pytest.fixture @@ -46,6 +44,12 @@ def test_archival_to_version(expected, data): ) +def test_hg_gone(wd, monkeypatch): + monkeypatch.setenv("PATH", str(wd.cwd / "not-existing")) + with pytest.raises(EnvironmentError, match="'hg' was not found"): + parse(str(wd.cwd)) + + def test_find_files_stop_at_root_hg(wd, monkeypatch): wd.commit_testfile() project = wd.cwd / "project"
lookup failed because git is not installed https://github.com/pypa/setuptools_scm/blob/7f6c9cfa52a47f4df81e753965bc37ca430e8e21/src/setuptools_scm/__init__.py#L105-L114 While git is not installed, it will also show the follow message. ``` "setuptools-scm was unable to detect version for %r.\n\n" "Make sure you're either building from a fully intact git repository " "or PyPI tarballs. Most other sources (such as GitHub's tarballs, a " "git checkout without the .git folder) don't contain the necessary " "metadata and will not work.\n\n" "For example, if you're using pip, instead of " "https://github.com/user/proj/archive/master.zip " "use git+https://github.com/user/proj.git#egg=proj" % config.absolute_root ``` It will be great if the message also indicate the fact that not only .git folder, git is also required. While using tool like docker multi-stage build or cloudbuild to minimize the image, it is common to work in an env without git pre-installed.
0.0
c4523c65a3e8ce3d3481cea42ade9b657bb6546f
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_worktree_support", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_integration.py::test_pretend_version", "testing/test_integration.py::test_pretend_version_named", "testing/test_integration.py::test_pretend_version_name_takes_precedence", "testing/test_mercurial.py::test_archival_to_version[0.0-data0]", "testing/test_mercurial.py::test_archival_to_version[1.0-data1]", "testing/test_mercurial.py::test_archival_to_version[1.1.dev3+h000000000000-data2]", "testing/test_mercurial.py::test_archival_to_version[1.2.2-data3]", "testing/test_mercurial.py::test_archival_to_version[1.2.2.dev0-data4]", "testing/test_mercurial.py::test_hg_gone", "testing/test_mercurial.py::test_find_files_stop_at_root_hg", "testing/test_mercurial.py::test_version_from_hg_id", "testing/test_mercurial.py::test_version_from_archival", "testing/test_mercurial.py::test_version_in_merge", "testing/test_mercurial.py::test_parse_no_worktree", "testing/test_mercurial.py::test_version_bump_before_merge_commit", "testing/test_mercurial.py::test_version_bump_from_merge_commit", "testing/test_mercurial.py::test_version_bump_from_commit_including_hgtag_mods", "testing/test_mercurial.py::test_latest_tag_detection", "testing/test_mercurial.py::test_feature_branch_increments_major" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-12-06 17:25:31+00:00
mit
5,001
pypa__setuptools_scm-538
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2bfe2d9..ecbcf81 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,8 @@ +v6.0.1 +======= + +* fix #537: drop node_date on old git to avoid errors on missing %cI + v6.0.0 ====== diff --git a/src/setuptools_scm/git.py b/src/setuptools_scm/git.py index b1a85ab..c7f301b 100644 --- a/src/setuptools_scm/git.py +++ b/src/setuptools_scm/git.py @@ -61,6 +61,9 @@ class GitWorkdir: return # TODO, when dropping python3.6 use fromiso date_part = timestamp.split("T")[0] + if "%c" in date_part: + trace("git too old -> timestamp is ", timestamp) + return None return datetime.strptime(date_part, r"%Y-%m-%d").date() def is_shallow(self):
pypa/setuptools_scm
53c16ce378cae61adb970c731f95fcdcd5fdf12b
diff --git a/testing/test_git.py b/testing/test_git.py index d934c02..8080574 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -8,7 +8,7 @@ from datetime import datetime from os.path import join as opj from setuptools_scm.file_finder_git import git_find_files from datetime import date - +from unittest.mock import patch, Mock pytestmark = pytest.mark.skipif( not has_command("git", warn=False), reason="git executable not found" @@ -307,3 +307,12 @@ def test_git_getdate(wd): assert git_wd.get_head_date() == today meta = git.parse(os.fspath(wd.cwd)) assert meta.node_date == today + + +def test_git_getdate_badgit( + wd, +): + wd.commit_testfile() + git_wd = git.GitWorkdir(os.fspath(wd.cwd)) + with patch.object(git_wd, "do_ex", Mock(return_value=("%cI", "", 0))): + assert git_wd.get_head_date() is None
v6 breaks on Centos7 due to older git Hi, Changes between v5 and v6 results in downstream packages failing to build/install on Centos7, e.g. black Centos7 seems to come with git 1.8.3.1 which doesn't support the `%cI` format as used by `get_head_date()` resulting in the following error when using pre-commit+black: ``` File "/tmp/pip-build-env-y421rvu8/overlay/lib/python3.7/site-packages/setuptools_scm/git.py", line 124, in parse node_date = wd.get_head_date() or date.today() File "/tmp/pip-build-env-y421rvu8/overlay/lib/python3.7/site-packages/setuptools_scm/git.py", line 64, in get_head_date return datetime.strptime(date_part, r"%Y-%m-%d").date() File "/opt/checksec/canopy/lib/python3.7/_strptime.py", line 577, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File "/opt/checksec/canopy/lib/python3.7/_strptime.py", line 359, in _strptime (data_string, format)) ValueError: time data '%cI' does not match format '%Y-%m-%d' ``` Installing either a newer git or `setuptools_scm~=5.0` works around the issue.
0.0
53c16ce378cae61adb970c731f95fcdcd5fdf12b
[ "testing/test_git.py::test_git_getdate_badgit" ]
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_worktree_support", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_git.py::test_git_getdate" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-03-17 14:03:47+00:00
mit
5,002
pypa__setuptools_scm-573
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1952960..d0fd57e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/psf/black - rev: 21.5b2 + rev: 21.6b0 hooks: - id: black args: [--safe, --quiet] @@ -16,7 +16,7 @@ repos: hooks: - id: flake8 - repo: https://github.com/asottile/pyupgrade - rev: v2.19.0 + rev: v2.19.4 hooks: - id: pyupgrade args: [--py36-plus] diff --git a/README.rst b/README.rst index 62ad85c..205dc99 100644 --- a/README.rst +++ b/README.rst @@ -70,7 +70,7 @@ to be supplied to ``get_version()``. For example: # pyproject.toml [tool.setuptools_scm] - write_to = "pkg/version.py" + write_to = "pkg/_version.py" ``setup.py`` usage (deprecated) @@ -316,7 +316,7 @@ The currently supported configuration keys are: :write_to: A path to a file that gets replaced with a file containing the current - version. It is ideal for creating a ``version.py`` file within the + version. It is ideal for creating a ``_version.py`` file within the package, typically used to avoid using `pkg_resources.get_distribution` (which adds some overhead). @@ -395,7 +395,7 @@ Example configuration in ``setup.py`` format: setup( use_scm_version={ - 'write_to': 'version.py', + 'write_to': '_version.py', 'write_to_template': '__version__ = "{version}"', 'tag_regex': r'^(?P<prefix>v)?(?P<version>[^\+]+)(?P<suffix>.*)?$', } diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index c560418..befa0dd 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -275,11 +275,15 @@ def release_branch_semver_version(version): # Does the branch name (stripped of namespace) parse as a version? branch_ver = _parse_version_tag(version.branch.split("/")[-1], version.config) if branch_ver is not None: + branch_ver = branch_ver["version"] + if branch_ver[0] == "v": + # Allow branches that start with 'v', similar to Version. + branch_ver = branch_ver[1:] # Does the branch version up to the minor part match the tag? If not it # might be like, an issue number or something and not a version number, so # we only want to use it if it matches. tag_ver_up_to_minor = str(version.tag).split(".")[:SEMVER_MINOR] - branch_ver_up_to_minor = branch_ver["version"].split(".")[:SEMVER_MINOR] + branch_ver_up_to_minor = branch_ver.split(".")[:SEMVER_MINOR] if branch_ver_up_to_minor == tag_ver_up_to_minor: # We're in a release/maintenance branch, next is a patch/rc/beta bump: return version.format_next_version(guess_next_version)
pypa/setuptools_scm
bedd4f5c27e7e34669a3bc4753cc833c8eb229cb
diff --git a/testing/test_version.py b/testing/test_version.py index e90e7bf..9984a5d 100644 --- a/testing/test_version.py +++ b/testing/test_version.py @@ -82,6 +82,11 @@ def test_next_semver_bad_tag(): "1.0.1.dev2", id="release_branch_legacy_version", ), + pytest.param( + meta("1.0.0", distance=2, branch="v1.0.x", config=c), + "1.0.1.dev2", + id="release_branch_with_v_prefix", + ), pytest.param( meta("1.0.0", distance=2, branch="release-1.0", config=c), "1.0.1.dev2",
Treat v-prefixed branch as release for release-branch-semver? The `release-branch-semver` scheme appears to match what we do in Matplotlib pretty closely. Since we make tags like `v1,2,3`, our branches are named like `v1.2.x`. This unfortunately is not treated as a release branch because of the `v` prefix in the branch name, even though the `v` prefix is dropped from the tag. Now, we've never made a release branch with `setuptools-scm`, so this is something we could change, but it'd require updating a bunch like docs, CI, etc. Does this make sense to handle this prefixing in the `release-branch-semver`?
0.0
bedd4f5c27e7e34669a3bc4753cc833c8eb229cb
[ "testing/test_version.py::test_next_release_branch_semver[release_branch_with_v_prefix]" ]
[ "testing/test_version.py::test_next_semver[exact]", "testing/test_version.py::test_next_semver[short_tag]", "testing/test_version.py::test_next_semver[normal_branch]", "testing/test_version.py::test_next_semver[normal_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_branch]", "testing/test_version.py::test_next_semver[feature_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_in_branch]", "testing/test_version.py::test_next_semver_bad_tag", "testing/test_version.py::test_next_release_branch_semver[exact]", "testing/test_version.py::test_next_release_branch_semver[development_branch]", "testing/test_version.py::test_next_release_branch_semver[development_branch_release_candidate]", "testing/test_version.py::test_next_release_branch_semver[release_branch_legacy_version]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_prefix]", "testing/test_version.py::test_next_release_branch_semver[false_positive_release_branch]", "testing/test_version.py::test_no_guess_version[dev_distance]", "testing/test_version.py::test_no_guess_version[dev_distance_short_tag]", "testing/test_version.py::test_no_guess_version[no_dev_distance]", "testing/test_version.py::test_bump_dev_version_zero", "testing/test_version.py::test_bump_dev_version_nonzero_raises", "testing/test_version.py::test_tag_regex1[v1.0.0-1.0.0]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1-1.0.0rc1]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1+-25259o4382757gjurh54-1.0.0rc1]", "testing/test_version.py::test_tags_to_versions", "testing/test_version.py::test_version_bump_bad", "testing/test_version.py::test_format_version_schemes", "testing/test_version.py::test_calver_by_date[exact]", "testing/test_version.py::test_calver_by_date[exact", "testing/test_version.py::test_calver_by_date[leading", "testing/test_version.py::test_calver_by_date[dirty", "testing/test_version.py::test_calver_by_date[normal", "testing/test_version.py::test_calver_by_date[4", "testing/test_version.py::test_calver_by_date[release", "testing/test_version.py::test_calver_by_date[node", "testing/test_version.py::test_calver_by_date_semver[SemVer", "testing/test_version.py::test_calver_by_date_future_warning" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-06-01 06:12:39+00:00
mit
5,003
pypa__setuptools_scm-584
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ecbcf81..581e3a9 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,8 @@ +In progress +=========== + +* fix #524: new parameters ``normalize`` and ``version_cls`` to customize the version normalization class. + v6.0.1 ======= diff --git a/README.rst b/README.rst index 205dc99..ee9625b 100644 --- a/README.rst +++ b/README.rst @@ -376,6 +376,30 @@ The currently supported configuration keys are: Defaults to the value set by ``setuptools_scm.git.DEFAULT_DESCRIBE`` (see `git.py <src/setuptools_scm/git.py>`_). +:normalize: + A boolean flag indicating if the version string should be normalized. + Defaults to ``True``. Setting this to ``False`` is equivalent to setting + ``version_cls`` to ``setuptools_scm.version.NonNormalizedVersion`` + +:version_cls: + An optional class used to parse, verify and possibly normalize the version + string. Its constructor should receive a single string argument, and its + ``str`` should return the normalized version string to use. + This option can also receive a class qualified name as a string. + + This defaults to ``packaging.version.Version`` if available. If + ``packaging`` is not installed, ``pkg_resources.packaging.version.Version`` + is used. Note that it is known to modify git release candidate schemes. + + The ``setuptools_scm.NonNormalizedVersion`` convenience class is + provided to disable the normalization step done by + ``packaging.version.Version``. If this is used while ``setuptools_scm`` + is integrated in a setuptools packaging process, the non-normalized + version number will appear in all files (see ``write_to``) BUT note + that setuptools will still normalize it to create the final distribution, + so as to stay compliant with the python packaging standards. + + To use ``setuptools_scm`` in other Python code you can use the ``get_version`` function: diff --git a/src/setuptools_scm/__init__.py b/src/setuptools_scm/__init__.py index 97061f2..e874aaa 100644 --- a/src/setuptools_scm/__init__.py +++ b/src/setuptools_scm/__init__.py @@ -15,6 +15,7 @@ from .config import ( DEFAULT_VERSION_SCHEME, DEFAULT_LOCAL_SCHEME, DEFAULT_TAG_REGEX, + NonNormalizedVersion, ) from .utils import function_has_arg, trace from .version import format_version, meta @@ -159,6 +160,8 @@ def get_version( parse=None, git_describe_command=None, dist_name=None, + version_cls=None, + normalize=True, ): """ If supplied, relative_to should be a file from which root may @@ -188,3 +191,22 @@ def _get_version(config): ) return version_string + + +# Public API +__all__ = [ + "get_version", + "dump_version", + "version_from_scm", + "Configuration", + "NonNormalizedVersion", + "DEFAULT_VERSION_SCHEME", + "DEFAULT_LOCAL_SCHEME", + "DEFAULT_TAG_REGEX", + # TODO: are the symbols below part of public API ? + "function_has_arg", + "trace", + "format_version", + "meta", + "iter_matching_entrypoints", +] diff --git a/src/setuptools_scm/config.py b/src/setuptools_scm/config.py index 78c7fc2..443f1f4 100644 --- a/src/setuptools_scm/config.py +++ b/src/setuptools_scm/config.py @@ -3,6 +3,14 @@ import os import re import warnings +try: + from packaging.version import Version +except ImportError: + import pkg_resources + + Version = pkg_resources.packaging.version.Version + + from .utils import trace DEFAULT_TAG_REGEX = r"^(?:[\w-]+-)?(?P<version>[vV]?\d+(?:\.\d+){0,2}[^\+]*)(?:\+.*)?$" @@ -65,6 +73,8 @@ class Configuration: parse=None, git_describe_command=None, dist_name=None, + version_cls=None, + normalize=True, ): # TODO: self._relative_to = relative_to @@ -83,6 +93,30 @@ class Configuration: self.git_describe_command = git_describe_command self.dist_name = dist_name + if not normalize: + # `normalize = False` means `version_cls = NonNormalizedVersion` + if version_cls is not None: + raise ValueError( + "Providing a custom `version_cls` is not permitted when " + "`normalize=False`" + ) + self.version_cls = NonNormalizedVersion + else: + # Use `version_cls` if provided, default to packaging or pkg_resources + if version_cls is None: + version_cls = Version + elif isinstance(version_cls, str): + try: + # Not sure this will work in old python + import importlib + + pkg, cls_name = version_cls.rsplit(".", 1) + version_cls_host = importlib.import_module(pkg) + version_cls = getattr(version_cls_host, cls_name) + except: # noqa + raise ValueError(f"Unable to import version_cls='{version_cls}'") + self.version_cls = version_cls + @property def fallback_root(self): return self._fallback_root @@ -137,3 +171,28 @@ class Configuration: defn = __import__("toml").load(strm) section = defn.get("tool", {})["setuptools_scm"] return cls(dist_name=dist_name, **section) + + +class NonNormalizedVersion(Version): + """A non-normalizing version handler. + + You can use this class to preserve version verification but skip normalization. + For example you can use this to avoid git release candidate version tags + ("1.0.0-rc1") to be normalized to "1.0.0rc1". Only use this if you fully + trust the version tags. + """ + + def __init__(self, version): + # parse and validate using parent + super().__init__(version) + + # store raw for str + self._raw_version = version + + def __str__(self): + # return the non-normalized version (parent returns the normalized) + return self._raw_version + + def __repr__(self): + # same pattern as parent + return f"<NonNormalizedVersion({self._raw_version!r})>" diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index befa0dd..3ed5ac1 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -4,16 +4,9 @@ import re import time import os -from .config import Configuration +from .config import Configuration, Version as PkgVersion from .utils import trace, iter_entry_points -try: - from packaging.version import Version -except ImportError: - import pkg_resources - - Version = pkg_resources.packaging.version.Version - SEMVER_MINOR = 2 SEMVER_PATCH = 3 @@ -77,7 +70,7 @@ def tag_to_version(tag, config=None): ) ) - version = Version(version) + version = config.version_cls(version) trace("version", repr(version)) return version @@ -168,7 +161,7 @@ class ScmVersion: def _parse_tag(tag, preformatted, config): if preformatted: return tag - if not isinstance(tag, Version): + if not isinstance(tag, config.version_cls): tag = tag_to_version(tag, config) return tag @@ -319,7 +312,7 @@ def date_ver_match(ver): return match -def guess_next_date_ver(version, node_date=None, date_fmt=None): +def guess_next_date_ver(version, node_date=None, date_fmt=None, version_cls=None): """ same-day -> patch +1 other-day -> today @@ -354,8 +347,9 @@ def guess_next_date_ver(version, node_date=None, date_fmt=None): node_date=head_date, date_fmt=date_fmt, patch=patch ) # rely on the Version object to ensure consistency (e.g. remove leading 0s) - # TODO: support for intentionally non-normalized date versions - next_version = str(Version(next_version)) + if version_cls is None: + version_cls = PkgVersion + next_version = str(version_cls(next_version)) return next_version @@ -370,7 +364,11 @@ def calver_by_date(version): match = date_ver_match(ver) if match: return ver - return version.format_next_version(guess_next_date_ver, node_date=version.node_date) + return version.format_next_version( + guess_next_date_ver, + node_date=version.node_date, + version_cls=version.config.version_cls, + ) def _format_local_with_time(version, time_format):
pypa/setuptools_scm
b680e377f1c56437aa8b35aab87fdd452586e5c4
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index 5aaf8fa..3e56ea5 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -135,3 +135,24 @@ def test_parse_plain_fails(recwarn): with pytest.raises(TypeError): setuptools_scm.get_version(parse=parse) + + +def test_custom_version_cls(): + """Test that `normalize` and `version_cls` work as expected""" + + class MyVersion: + def __init__(self, tag_str: str): + self.version = tag_str + + def __repr__(self): + return f"hello,{self.version}" + + # you can not use normalize=False and version_cls at the same time + with pytest.raises(ValueError): + setuptools_scm.get_version(normalize=False, version_cls=MyVersion) + + # TODO unfortunately with PRETEND_KEY the preformatted flag becomes True + # which bypasses our class. which other mechanism would be ok to use here + # to create a test? + # monkeypatch.setenv(setuptools_scm.PRETEND_KEY, "1.0.1") + # assert setuptools_scm.get_version(version_cls=MyVersion) == "1" diff --git a/testing/test_git.py b/testing/test_git.py index cc5ef53..40c5e99 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -1,15 +1,15 @@ import sys import os -from setuptools_scm import integration -from setuptools_scm.utils import do, has_command -from setuptools_scm import git -import pytest -from datetime import datetime from os.path import join as opj -from setuptools_scm.file_finder_git import git_find_files -from datetime import date +import pytest +from datetime import datetime, date from unittest.mock import patch, Mock +from setuptools_scm import integration, git, NonNormalizedVersion +from setuptools_scm.utils import do, has_command +from setuptools_scm.file_finder_git import git_find_files + + pytestmark = pytest.mark.skipif( not has_command("git", warn=False), reason="git executable not found" ) @@ -104,6 +104,70 @@ def test_version_from_git(wd): wd("git tag 17.33.0-rc") assert wd.version == "17.33.0rc0" + # custom normalization + assert wd.get_version(normalize=False) == "17.33.0-rc" + assert wd.get_version(version_cls=NonNormalizedVersion) == "17.33.0-rc" + assert ( + wd.get_version(version_cls="setuptools_scm.NonNormalizedVersion") + == "17.33.0-rc" + ) + + [email protected]("with_class", [False, type, str]) +def test_git_version_unnormalized_setuptools(with_class, tmpdir, wd, monkeypatch): + """ + Test that when integrating with setuptools without normalization, + the version is not normalized in write_to files, + but still normalized by setuptools for the final dist metadata. + """ + monkeypatch.delenv("SETUPTOOLS_SCM_DEBUG") + p = wd.cwd + + # create a setup.py + dest_file = str(tmpdir.join("VERSION.txt")).replace("\\", "/") + if with_class is False: + # try normalize = False + setup_py = """ +from setuptools import setup +setup(use_scm_version={'normalize': False, 'write_to': '%s'}) +""" + elif with_class is type: + # custom non-normalizing class + setup_py = """ +from setuptools import setup + +class MyVersion: + def __init__(self, tag_str: str): + self.version = tag_str + + def __repr__(self): + return self.version + +setup(use_scm_version={'version_cls': MyVersion, 'write_to': '%s'}) +""" + elif with_class is str: + # non-normalizing class referenced by name + setup_py = """from setuptools import setup +setup(use_scm_version={ + 'version_cls': 'setuptools_scm.NonNormalizedVersion', + 'write_to': '%s' +}) +""" + + # finally write the setup.py file + p.joinpath("setup.py").write_text(setup_py % dest_file) + + # do git operations and tag + wd.commit_testfile() + wd("git tag 17.33.0-rc1") + + # setuptools still normalizes using packaging.Version (removing the dash) + res = do((sys.executable, "setup.py", "--version"), p) + assert res == "17.33.0rc1" + + # but the version tag in the file is non-normalized (with the dash) + assert tmpdir.join("VERSION.txt").read() == "17.33.0-rc1" + @pytest.mark.issue(179) def test_unicode_version_scheme(wd): diff --git a/testing/test_version.py b/testing/test_version.py index 9984a5d..eda22c8 100644 --- a/testing/test_version.py +++ b/testing/test_version.py @@ -283,3 +283,19 @@ def test_calver_by_date_semver(version, expected_next): def test_calver_by_date_future_warning(): with pytest.warns(UserWarning, match="your previous tag*"): calver_by_date(meta(date_to_str(days_offset=-2), config=c, distance=2)) + + +def test_custom_version_cls(): + """Test that we can pass our own version class instead of pkg_resources""" + + class MyVersion: + def __init__(self, tag_str: str): + self.tag = tag_str + + def __repr__(self): + return "Custom %s" % self.tag + + scm_version = meta("1.0.0-foo", config=Configuration(version_cls=MyVersion)) + + assert isinstance(scm_version.tag, MyVersion) + assert repr(scm_version.tag) == "Custom 1.0.0-foo"
Incorrect removal of dash in case of pre-release tag string ? I found this today: `1.0.0-rc1` becomes `1.0.0rc1`, see details here https://github.com/smarie/python-getversion/issues/10 The underlying error is due to `pkg_resources` that removes the pre-release dash automatically in its string representation since version [0.6a9](https://setuptools.readthedocs.io/en/latest/pkg_resources.html#0.6a9). However as suggested in [my conclusions](https://github.com/smarie/python-getversion/issues/10#issuecomment-784987499) I think that the issue should probably better be fixed in the default scheme of setuptools_scm because faithfulness to git tags and compliance with `semver` for example, is probably a higher concern for you than for `pkg_resources`. Thanks again for this great package !
0.0
b680e377f1c56437aa8b35aab87fdd452586e5c4
[ "testing/test_basic_api.py::test_do[ls]", "testing/test_basic_api.py::test_do[dir]", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_version_from_scm", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_parentdir_prefix", "testing/test_basic_api.py::test_fallback", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_dump_version", "testing/test_basic_api.py::test_parse_plain_fails", "testing/test_basic_api.py::test_custom_version_cls", "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_git_version_unnormalized_setuptools[False]", "testing/test_git.py::test_git_version_unnormalized_setuptools[type]", "testing/test_git.py::test_git_version_unnormalized_setuptools[str]", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_worktree_support", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_git.py::test_git_getdate", "testing/test_git.py::test_git_getdate_badgit", "testing/test_version.py::test_next_semver[exact]", "testing/test_version.py::test_next_semver[short_tag]", "testing/test_version.py::test_next_semver[normal_branch]", "testing/test_version.py::test_next_semver[normal_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_branch]", "testing/test_version.py::test_next_semver[feature_branch_short_tag]", "testing/test_version.py::test_next_semver[feature_in_branch]", "testing/test_version.py::test_next_semver_bad_tag", "testing/test_version.py::test_next_release_branch_semver[exact]", "testing/test_version.py::test_next_release_branch_semver[development_branch]", "testing/test_version.py::test_next_release_branch_semver[development_branch_release_candidate]", "testing/test_version.py::test_next_release_branch_semver[release_branch_legacy_version]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_v_prefix]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_prefix]", "testing/test_version.py::test_next_release_branch_semver[false_positive_release_branch]", "testing/test_version.py::test_no_guess_version[dev_distance]", "testing/test_version.py::test_no_guess_version[dev_distance_short_tag]", "testing/test_version.py::test_no_guess_version[no_dev_distance]", "testing/test_version.py::test_bump_dev_version_zero", "testing/test_version.py::test_bump_dev_version_nonzero_raises", "testing/test_version.py::test_tag_regex1[v1.0.0-1.0.0]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1-1.0.0rc1]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1+-25259o4382757gjurh54-1.0.0rc1]", "testing/test_version.py::test_tags_to_versions", "testing/test_version.py::test_version_bump_bad", "testing/test_version.py::test_format_version_schemes", "testing/test_version.py::test_calver_by_date[exact]", "testing/test_version.py::test_calver_by_date[exact", "testing/test_version.py::test_calver_by_date[leading", "testing/test_version.py::test_calver_by_date[dirty", "testing/test_version.py::test_calver_by_date[normal", "testing/test_version.py::test_calver_by_date[4", "testing/test_version.py::test_calver_by_date[release", "testing/test_version.py::test_calver_by_date[node", "testing/test_version.py::test_calver_by_date_semver[SemVer", "testing/test_version.py::test_calver_by_date_future_warning", "testing/test_version.py::test_custom_version_cls" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-06-17 16:16:04+00:00
mit
5,004
pypa__setuptools_scm-649
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6f40899..d6a2932 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/psf/black - rev: 21.9b0 + rev: 21.12b0 hooks: - id: black args: [--safe, --quiet] @@ -10,7 +10,7 @@ repos: - id: reorder-python-imports args: [ "--application-directories=.:src" , --py3-plus] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.0.1 + rev: v4.1.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -21,16 +21,16 @@ repos: hooks: - id: flake8 - repo: https://github.com/asottile/pyupgrade - rev: v2.29.0 + rev: v2.29.1 hooks: - id: pyupgrade args: [--py36-plus] - repo: https://github.com/asottile/setup-cfg-fmt - rev: v1.18.0 + rev: v1.20.0 hooks: - id: setup-cfg-fmt - repo: https://github.com/pre-commit/mirrors-mypy - rev: 'v0.910-1' + rev: 'v0.930' hooks: - id: mypy additional_dependencies: diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f4dd514..9704a01 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,8 @@ +6.3.4 +====== + +* compatibility adjustments for setuptools >58 + 6.3.3 ====== @@ -277,8 +282,8 @@ v3.0.0 * require parse results to be ScmVersion or None (breaking change) * fix #266 by requiring the prefix word to be a word again (breaking change as the bug allowed arbitrary prefixes while the original feature only allowed words") -* introduce a internal config object to allow the configruation fo tag parsing and prefixes - (thanks to @punkadiddle for introducing it and passing it trough) +* introduce an internal config object to allow the configuration for tag parsing and prefixes + (thanks to @punkadiddle for introducing it and passing it through) v2.1.0 ====== @@ -295,7 +300,7 @@ v2.0.0 * fix #237 - correct imports in code examples * improve mercurial commit detection (thanks Aaron) * breaking change: remove support for setuptools before parsed versions -* reintroduce manifest as the travis deploy cant use the file finder +* reintroduce manifest as the travis deploy can't use the file finder * reconfigure flake8 for future compatibility with black * introduce support for branch name in version metadata and support a opt-in simplified semver version scheme @@ -325,8 +330,8 @@ v1.16.0 ======= * drop support for eol python versions -* #214 - fix missuse in surogate-escape api -* add the node-and-timestamp local version sheme +* #214 - fix misuse in surogate-escape api +* add the node-and-timestamp local version scheme * respect git export ignores * avoid shlex.split on windows * fix #218 - better handling of mercurial edge-cases with tag commits @@ -355,7 +360,7 @@ v1.15.5 v1.15.4 ======= -* fix issue #164: iterate all found entry points to avoid erros when pip remakes egg-info +* fix issue #164: iterate all found entry points to avoid errors when pip remakes egg-info * enhance self-use to enable pip install from github again v1.15.3 @@ -386,7 +391,7 @@ v1.15.0 when considering distance in commits (thanks Petre Mierlutiu) * fix issue #114: stop trying to be smart for the sdist - and ensure its always correctly usign itself + and ensure its always correctly using itself * update trove classifiers * fix issue #84: document using the installed package metadata for sphinx * fix issue #81: fail more gracious when git/hg are missing @@ -401,7 +406,7 @@ v1.14.1 don't consider untracked file (this was a regression due to #86 in v1.13.1) * consider the distance 0 when the git node is unknown - (happens when you haven't commited anything) + (happens when you haven't committed anything) v1.14.0 ======= @@ -419,7 +424,7 @@ v1.13.0 * fix regression caused by the fix of #101 * assert types for version dumping - * strictly pass all versions trough parsed version metadata + * strictly pass all versions through parsed version metadata v1.12.0 ======= @@ -457,7 +462,7 @@ v1.10.0 * add support for overriding the version number via the environment variable SETUPTOOLS_SCM_PRETEND_VERSION -* fix isssue #63 by adding the --match parameter to the git describe call +* fix issue #63 by adding the --match parameter to the git describe call and prepare the possibility of passing more options to scm backends * fix issue #70 and #71 by introducing the parse keyword @@ -501,7 +506,7 @@ v1.6.0 before we would let the setup stay at version 0.0, now there is a ValueError -* propperly raise errors on write_to missuse (thanks Te-jé Rodgers) +* properly raise errors on write_to misuse (thanks Te-jé Rodgers) v1.5.5 ====== @@ -538,7 +543,7 @@ v1.5.0 v1.4.0 ====== -* propper handling for sdist +* proper handling for sdist * fix file-finder failure from windows * resuffle docs diff --git a/README.rst b/README.rst index fbfdb4c..20220d4 100644 --- a/README.rst +++ b/README.rst @@ -209,6 +209,39 @@ The underlying reason is, that services like *Read the Docs* sometimes change the working directory for good reasons and using the installed metadata prevents using needless volatile data there. +Usage from Docker +----------------- + +By default, docker will not copy the ``.git`` folder into your container. +Therefore, builds with version inference might fail. +Consequently, you can use the following snipped to infer the version from +the host os without copying the entire ``.git`` folder to your Dockerfile. + +.. code:: dockerfile + + RUN --mount=source=.git,target=.git,type=bind \ + pip install --no-cache-dir -e . + +However, this build step introduces a dependency to the state of your local +.git folder the build cache and triggers the long-running pip install process on every build. +To optimize build caching, one can use an environment variable to pretend a pseudo +version that is used to cache the results of the pip install process: + +.. code:: dockerfile + + FROM python + COPY pyproject.toml + ARG PSEUDO_VERSION=1 + RUN SETUPTOOLS_SCM_PRETEND_VERSION=${PSEUDO_VERSION} pip install -e .[test] + RUN --mount=source=.git,target=.git,type=bind pip install -e . + +Note that running this Dockerfile requires docker with BuildKit enabled +`[docs] <https://github.com/moby/buildkit/blob/v0.8.3/frontend/dockerfile/docs/syntax.md>`_. + +To avoid BuildKit and mounting of the .git folder altogether, one can also pass the desired +version as a build argument. Note that ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_${UPPERCASED_DIST_NAME}`` +is preferred over ``SETUPTOOLS_SCM_PRETEND_VERSION``. + Notable Plugins --------------- diff --git a/src/setuptools_scm/__main__.py b/src/setuptools_scm/__main__.py index f3377b0..ef64819 100644 --- a/src/setuptools_scm/__main__.py +++ b/src/setuptools_scm/__main__.py @@ -1,15 +1,68 @@ -import sys +import argparse +import os +import warnings -from setuptools_scm import get_version +from setuptools_scm import _get_version +from setuptools_scm.config import Configuration +from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: - print("Guessed Version", get_version()) - if "ls" in sys.argv: - for fname in find_files("."): + opts = _get_cli_opts() + root = opts.root or "." + + try: + pyproject = opts.config or _find_pyproject(root) + root = opts.root or os.path.relpath(os.path.dirname(pyproject)) + config = Configuration.from_file(pyproject) + config.root = root + except (LookupError, FileNotFoundError) as ex: + # no pyproject.toml OR no [tool.setuptools_scm] + warnings.warn(f"{ex}. Using default configuration.") + config = Configuration(root) + + print(_get_version(config)) + + if opts.command == "ls": + for fname in find_files(config.root): print(fname) +def _get_cli_opts(): + prog = "python -m setuptools_scm" + desc = "Print project version according to SCM metadata" + parser = argparse.ArgumentParser(prog, description=desc) + # By default, help for `--help` starts with lower case, so we keep the pattern: + parser.add_argument( + "-r", + "--root", + default=None, + help='directory managed by the SCM, default: inferred from config file, or "."', + ) + parser.add_argument( + "-c", + "--config", + default=None, + metavar="PATH", + help="path to 'pyproject.toml' with setuptools_scm config, " + "default: looked up in the current or parent directories", + ) + sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") + # We avoid `metavar` to prevent printing repetitive information + desc = "List files managed by the SCM" + sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) + return parser.parse_args() + + +def _find_pyproject(parent): + for directory in walk_potential_roots(os.path.abspath(parent)): + pyproject = os.path.join(directory, "pyproject.toml") + if os.path.exists(pyproject): + return pyproject + + raise FileNotFoundError("'pyproject.toml' was not found") + + if __name__ == "__main__": main() diff --git a/src/setuptools_scm/_overrides.py b/src/setuptools_scm/_overrides.py index 292936c..644e87d 100644 --- a/src/setuptools_scm/_overrides.py +++ b/src/setuptools_scm/_overrides.py @@ -12,7 +12,7 @@ PRETEND_KEY_NAMED = PRETEND_KEY + "_FOR_{name}" def _read_pretended_version_for(config: Configuration) -> Optional[ScmVersion]: - """read a a overriden version from the environment + """read a a overridden version from the environment tries ``SETUPTOOLS_SCM_PRETEND_VERSION`` and ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_$UPPERCASE_DIST_NAME`` diff --git a/src/setuptools_scm/hg_git.py b/src/setuptools_scm/hg_git.py index b871a39..323cdcb 100644 --- a/src/setuptools_scm/hg_git.py +++ b/src/setuptools_scm/hg_git.py @@ -73,7 +73,7 @@ class GitWorkdirHgClient(GitWorkdir, HgWorkdir): trace("Cannot get git node so we use hg node", hg_node) if hg_node == "0" * len(hg_node): - # mimick Git behavior + # mimic Git behavior return None return hg_node diff --git a/tox.ini b/tox.ini index 3f77ea9..e356153 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ filterwarnings= ignore:.*tool\.setuptools_scm.* markers= issue(id): reference to github issue - skip_commit: allows to skip commiting in the helpers + skip_commit: allows to skip committing in the helpers # disable unraisable until investigated addopts = -p no:unraisableexception
pypa/setuptools_scm
6a8dac10bb43de8a4a3bfaae5994c20c88249b18
diff --git a/testing/test_main.py b/testing/test_main.py index 97ea05e..ea1373f 100644 --- a/testing/test_main.py +++ b/testing/test_main.py @@ -1,4 +1,8 @@ import os.path +import sys +import textwrap + +import pytest def test_main(): @@ -8,3 +12,51 @@ def test_main(): with open(mainfile) as f: code = compile(f.read(), "__main__.py", "exec") exec(code) + + [email protected] +def repo(wd): + wd("git init") + wd("git config user.email user@host") + wd("git config user.name user") + wd.add_command = "git add ." + wd.commit_command = "git commit -m test-{reason}" + + wd.write("README.rst", "My example") + wd.add_and_commit() + wd("git tag v0.1.0") + + wd.write("file.txt", "file.txt") + wd.add_and_commit() + + return wd + + +def test_repo_with_config(repo): + pyproject = """\ + [tool.setuptools_scm] + version_scheme = "no-guess-dev" + + [project] + name = "example" + """ + repo.write("pyproject.toml", textwrap.dedent(pyproject)) + repo.add_and_commit() + res = repo((sys.executable, "-m", "setuptools_scm")) + assert res.startswith("0.1.0.post1.dev2") + + +def test_repo_without_config(repo): + res = repo((sys.executable, "-m", "setuptools_scm")) + assert res.startswith("0.1.1.dev1") + + +def test_repo_with_pyproject_missing_setuptools_scm(repo): + pyproject = """\ + [project] + name = "example" + """ + repo.write("pyproject.toml", textwrap.dedent(pyproject)) + repo.add_and_commit() + res = repo((sys.executable, "-m", "setuptools_scm")) + assert res.startswith("0.1.1.dev2") diff --git a/testing/test_mercurial.py b/testing/test_mercurial.py index 2352bf9..3276802 100644 --- a/testing/test_mercurial.py +++ b/testing/test_mercurial.py @@ -82,7 +82,7 @@ def test_version_from_hg_id(wd): wd("hg up v0.1") assert wd.version == "0.1" - # commit originating from the taged revision + # commit originating from the tagged revision # that is not a actual tag wd.commit_testfile() assert wd.version.startswith("0.2.dev1+") @@ -96,7 +96,7 @@ def test_version_from_hg_id(wd): def test_version_from_archival(wd): # entrypoints are unordered, - # cleaning the wd ensure this test wont break randomly + # cleaning the wd ensure this test won't break randomly wd.cwd.joinpath(".hg").rename(wd.cwd / ".nothg") wd.write(".hg_archival.txt", "node: 000000000000\n" "tag: 0.1\n") assert wd.version == "0.1" @@ -172,7 +172,7 @@ def test_version_bump_from_commit_including_hgtag_mods(wd): @pytest.mark.usefixtures("version_1_0") def test_latest_tag_detection(wd): """Tests that tags not containing a "." are ignored, the same as for git. - Note that will be superceded by the fix for pypa/setuptools_scm/issues/235 + Note that will be superseded by the fix for pypa/setuptools_scm/issues/235 """ wd('hg tag some-random-tag -u test -d "0 0"') assert wd.version == "1.0.0" diff --git a/testing/test_setuptools_support.py b/testing/test_setuptools_support.py index d6243db..b0c7230 100644 --- a/testing/test_setuptools_support.py +++ b/testing/test_setuptools_support.py @@ -7,9 +7,21 @@ import subprocess import sys import pytest -from virtualenv.run import cli_run -pytestmark = pytest.mark.filterwarnings(r"ignore:.*tool\.setuptools_scm.*") + +def cli_run(*k, **kw): + """this defers the virtualenv import + it helps to avoid warnings from the furthermore imported setuptools + """ + global cli_run + from virtualenv.run import cli_run + + return cli_run(*k, **kw) + + +pytestmark = pytest.mark.filterwarnings( + r"ignore:.*tool\.setuptools_scm.*", r"always:.*setup.py install is deprecated.*" +) ROOT = pathlib.Path(__file__).parent.parent @@ -88,7 +100,7 @@ def check(venv, expected_version, **env): @pytest.mark.skipif( - sys.version_info[:2] >= (3, 10), reason="old setuptools wont work on python 3.10" + sys.version_info[:2] >= (3, 10), reason="old setuptools won't work on python 3.10" ) def test_distlib_setuptools_works(venv_maker): venv = venv_maker.get_venv(setuptools="45.0.0", pip="9.0", python="3.6") @@ -137,7 +149,7 @@ def prepare_setup_py_config(pkg: pathlib.Path): @pytest.mark.skipif( - sys.version_info[:2] >= (3, 10), reason="old setuptools wont work on python 3.10" + sys.version_info[:2] >= (3, 10), reason="old setuptools won't work on python 3.10" ) @pytest.mark.parametrize("setuptools", [f"{v}.0" for v in range(31, 45)]) @pytest.mark.parametrize(
document painless git usage in buildkit docker usage For future reference (building only works in recent docker versions with buildkit support) you can avoid having `.git` in one of your layers by temporarily bind-mounting it during build time [[docs]](https://github.com/moby/buildkit/blob/v0.8.3/frontend/dockerfile/docs/syntax.md): ```dockerfile RUN --mount=source=.git,target=.git,type=bind \ pip install --no-cache-dir -e . ``` _Originally posted by @ddelange in https://github.com/pypa/setuptools_scm/issues/77#issuecomment-844927695_
0.0
6a8dac10bb43de8a4a3bfaae5994c20c88249b18
[ "testing/test_main.py::test_repo_with_config", "testing/test_main.py::test_repo_without_config", "testing/test_main.py::test_repo_with_pyproject_missing_setuptools_scm" ]
[ "testing/test_main.py::test_main", "testing/test_mercurial.py::test_archival_to_version[0.0-data0]", "testing/test_mercurial.py::test_archival_to_version[1.0-data1]", "testing/test_mercurial.py::test_archival_to_version[1.1.dev3+h000000000000-data2]", "testing/test_mercurial.py::test_archival_to_version[1.2.2-data3]", "testing/test_mercurial.py::test_archival_to_version[1.2.2.dev0-data4]", "testing/test_mercurial.py::test_hg_gone", "testing/test_mercurial.py::test_find_files_stop_at_root_hg", "testing/test_mercurial.py::test_version_from_hg_id", "testing/test_mercurial.py::test_version_from_archival", "testing/test_mercurial.py::test_version_in_merge", "testing/test_mercurial.py::test_parse_no_worktree", "testing/test_mercurial.py::test_version_bump_before_merge_commit", "testing/test_mercurial.py::test_version_bump_from_merge_commit", "testing/test_mercurial.py::test_version_bump_from_commit_including_hgtag_mods", "testing/test_mercurial.py::test_latest_tag_detection", "testing/test_mercurial.py::test_feature_branch_increments_major" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-11-15 21:09:21+00:00
mit
5,005
pypa__setuptools_scm-730
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 997d10b..4c9bd24 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,5 +1,10 @@ +v7.0.3 +======= +* fix mercurial usage when pip primes a isolated environment +* fix regression for branch names on git + add a test + v7.0.2 -====== +======= * fix #723 and #722: remove bootstrap dependencies * bugfix: ensure we read the distribution name from setup.cfg diff --git a/src/setuptools_scm/git.py b/src/setuptools_scm/git.py index 1f8984b..47e2a9e 100644 --- a/src/setuptools_scm/git.py +++ b/src/setuptools_scm/git.py @@ -82,10 +82,10 @@ class GitWorkdir(Workdir): return bool(out) def get_branch(self) -> str | None: - branch, err, ret = self.do_ex_git(["rev-parse", "--abbrev-ref", "HEAD", "--"]) + branch, err, ret = self.do_ex_git(["rev-parse", "--abbrev-ref", "HEAD"]) if ret: trace("branch err", branch, err, ret) - branch, err, ret = self.do_ex_git(["symbolic-ref", "--short", "HEAD", "--"]) + branch, err, ret = self.do_ex_git(["symbolic-ref", "--short", "HEAD"]) if ret: trace("branch err (symbolic-ref)", branch, err, ret) return None
pypa/setuptools_scm
1c00405a0e5075a2330c60a69f72d4c7aad88203
diff --git a/testing/test_git.py b/testing/test_git.py index 661a5ee..cb54f61 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -378,6 +378,14 @@ def test_git_archive_run_from_subdirectory( assert integration.find_files(".") == [opj(".", "test1.txt")] [email protected]("https://github.com/pypa/setuptools_scm/issues/728") +def test_git_branch_names_correct(wd: WorkDir) -> None: + wd.commit_testfile() + wd("git checkout -b test/fun") + wd_git = git.GitWorkdir(os.fspath(wd.cwd)) + assert wd_git.get_branch() == "test/fun" + + def test_git_feature_branch_increments_major(wd: WorkDir) -> None: wd.commit_testfile() wd("git tag 1.0.0")
7.0.0+ Regression: Calling GitWorkdir.git_branch inserts a newline We use a version scheme for development that adds a branch name when the package is built on a git branch. Recently we found 7.0.0+ changed the behavior of git_branch with the trailing `--` (apparently to add Hg support?)... Now, the "branch" variable consistently adds a newline and a trailing `--`, which breaks compatibility with PEP and causes other surprising failures downstream. The code traces to this line here which changed in the 7.0.0 merge: https://github.com/pypa/setuptools_scm/blob/main/src/setuptools_scm/git.py#L85 Running raw git command with Ubuntu 20.04, on a branch called "test-branch" results in: ``` $ git --version git version 2.25.1 $ git rev-parse --abbrev-ref HEAD -- test-branch -- $ ``` And then inside a python environment: ``` >>> from setuptools_scm import git >>> git.parse(".") <ScmVersion 7.0.2 dist=None node=gf1f35bd dirty=False branch=test-branch --> >>> ```
0.0
1c00405a0e5075a2330c60a69f72d4c7aad88203
[ "testing/test_git.py::test_git_branch_names_correct" ]
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_root_search_parent_directories", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_git_version_unnormalized_setuptools[false]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_created_class]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_named_import]", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_git.py::test_git_getdate", "testing/test_git.py::test_git_getdate_badgit", "testing/test_git.py::test_git_getdate_signed_commit", "testing/test_git.py::test_git_archival_to_version[1.0-from_data0]", "testing/test_git.py::test_git_archival_to_version[1.1.dev3+g0000-from_data1]", "testing/test_git.py::test_git_archival_to_version[0.0-from_data2]", "testing/test_git.py::test_git_archival_to_version[1.2.2-from_data3]", "testing/test_git.py::test_git_archival_to_version[1.2.2.dev0-from_data4]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-06-25 20:54:27+00:00
mit
5,006
pypa__setuptools_scm-731
diff --git a/src/setuptools_scm/_cli.py b/src/setuptools_scm/_cli.py index 88dd6d0..4883c4f 100644 --- a/src/setuptools_scm/_cli.py +++ b/src/setuptools_scm/_cli.py @@ -10,15 +10,15 @@ from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files -def main() -> None: - opts = _get_cli_opts() - root = opts.root or "." +def main(args: list[str] | None = None) -> None: + opts = _get_cli_opts(args) + inferred_root: str = opts.root or "." - pyproject = opts.config or _find_pyproject(root) + pyproject = opts.config or _find_pyproject(inferred_root) try: - root = opts.root or os.path.relpath(os.path.dirname(pyproject)) - config = Configuration.from_file(pyproject, root=root) + + config = Configuration.from_file(pyproject, root=opts.root) except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] print( @@ -27,10 +27,11 @@ def main() -> None: f" Reason: {ex}.", file=sys.stderr, ) - config = Configuration(root=root) + config = Configuration(inferred_root) version = _get_version(config) - assert version is not None + if version is None: + raise SystemExit("ERROR: no version found for", opts) if opts.strip_dev: version = version.partition(".dev")[0] print(version) @@ -40,7 +41,7 @@ def main() -> None: print(fname) -def _get_cli_opts() -> argparse.Namespace: +def _get_cli_opts(args: list[str] | None) -> argparse.Namespace: prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) @@ -68,7 +69,7 @@ def _get_cli_opts() -> argparse.Namespace: # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) - return parser.parse_args() + return parser.parse_args(args) def _find_pyproject(parent: str) -> str: diff --git a/src/setuptools_scm/config.py b/src/setuptools_scm/config.py index f73b905..fee652c 100644 --- a/src/setuptools_scm/config.py +++ b/src/setuptools_scm/config.py @@ -24,6 +24,7 @@ if TYPE_CHECKING: DEFAULT_TAG_REGEX = r"^(?:[\w-]+-)?(?P<version>[vV]?\d+(?:\.\d+){0,2}[^\+]*)(?:\+.*)?$" DEFAULT_VERSION_SCHEME = "guess-next-dev" DEFAULT_LOCAL_SCHEME = "node-and-date" +_ROOT = "root" def _check_tag_regex(value: str | Pattern[str] | None) -> Pattern[str]: @@ -213,6 +214,7 @@ class Configuration: with open(name, encoding="UTF-8") as strm: data = strm.read() + defn = _load_toml(data) try: section = defn.get("tool", {})["setuptools_scm"] @@ -220,6 +222,21 @@ class Configuration: raise LookupError( f"{name} does not contain a tool.setuptools_scm section" ) from e + + project = defn.get("project", {}) + dist_name = cls._cleanup_from_file_args_data( + project, dist_name, kwargs, section + ) + return cls(dist_name=dist_name, relative_to=name, **section, **kwargs) + + @staticmethod + def _cleanup_from_file_args_data( + project: dict[str, Any], + dist_name: str | None, + kwargs: dict[str, Any], + section: dict[str, Any], + ) -> str | None: + """drops problematic details and figures the distribution name""" if "dist_name" in section: if dist_name is None: dist_name = section.pop("dist_name") @@ -227,13 +244,21 @@ class Configuration: assert dist_name == section["dist_name"] del section["dist_name"] if dist_name is None: - if "project" in defn: - # minimal pep 621 support for figuring the pretend keys - dist_name = defn["project"].get("name") + # minimal pep 621 support for figuring the pretend keys + dist_name = project.get("name") if dist_name is None: dist_name = _read_dist_name_from_setup_cfg() - - return cls(dist_name=dist_name, **section, **kwargs) + if _ROOT in kwargs: + if kwargs[_ROOT] is None: + kwargs.pop(_ROOT, None) + elif _ROOT in section: + if section[_ROOT] != kwargs[_ROOT]: + warnings.warn( + f"root {section[_ROOT]} is overridden" + f" by the cli arg {kwargs[_ROOT]}" + ) + section.pop("root", None) + return dist_name def _read_dist_name_from_setup_cfg() -> str | None:
pypa/setuptools_scm
69909799fd2f1aeb295b3a74beeb7bd0c35fbe88
diff --git a/testing/conftest.py b/testing/conftest.py index c881042..d29b5dd 100644 --- a/testing/conftest.py +++ b/testing/conftest.py @@ -3,10 +3,10 @@ from __future__ import annotations import os from pathlib import Path from typing import Any -from typing import Generator import pytest +import setuptools_scm.utils from .wd_wrapper import WorkDir @@ -39,13 +39,25 @@ def pytest_addoption(parser: Any) -> None: ) [email protected](autouse=True) -def debug_mode() -> Generator[None, None, None]: - from setuptools_scm import utils +class DebugMode: + def __init__(self, monkeypatch: pytest.MonkeyPatch): + self.__monkeypatch = monkeypatch + self.__module = setuptools_scm.utils + + __monkeypatch: pytest.MonkeyPatch + + def enable(self) -> None: + self.__monkeypatch.setattr(self.__module, "DEBUG", True) - utils.DEBUG = True - yield - utils.DEBUG = False + def disable(self) -> None: + self.__monkeypatch.setattr(self.__module, "DEBUG", False) + + [email protected](autouse=True) +def debug_mode(monkeypatch: pytest.MonkeyPatch) -> DebugMode: + debug_mode = DebugMode(monkeypatch) + debug_mode.enable() + return debug_mode @pytest.fixture diff --git a/testing/test_cli.py b/testing/test_cli.py new file mode 100644 index 0000000..0198111 --- /dev/null +++ b/testing/test_cli.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import io +from contextlib import redirect_stdout + +import pytest + +from .conftest import DebugMode +from .test_git import wd as wd_fixture # NOQA evil fixture reuse +from .wd_wrapper import WorkDir +from setuptools_scm._cli import main + + +PYPROJECT_TOML = "pyproject.toml" +PYPROJECT_SIMPLE = "[tool.setuptools_scm]" +PYPROJECT_ROOT = '[tool.setuptools_scm]\nroot=".."' + + +def get_output(args: list[str]) -> str: + + with redirect_stdout(io.StringIO()) as out: + main(args) + return out.getvalue() + + +def test_cli_find_pyproject( + wd: WorkDir, monkeypatch: pytest.MonkeyPatch, debug_mode: DebugMode +) -> None: + debug_mode.disable() + wd.commit_testfile() + wd.write(PYPROJECT_TOML, PYPROJECT_SIMPLE) + monkeypatch.chdir(wd.cwd) + + out = get_output([]) + assert out.startswith("0.1.dev1+") + + with pytest.raises(SystemExit, match="no version found for"): + get_output(["--root=.."]) + + wd.write(PYPROJECT_TOML, PYPROJECT_ROOT) + with pytest.raises(SystemExit, match="no version found for"): + print(get_output(["-c", PYPROJECT_TOML])) + + with pytest.raises(SystemExit, match="no version found for"): + + get_output(["-c", PYPROJECT_TOML, "--root=.."]) + + with pytest.warns(UserWarning, match="root .. is overridden by the cli arg ."): + out = get_output(["-c", PYPROJECT_TOML, "--root=."]) + assert out.startswith("0.1.dev1+") diff --git a/testing/test_git.py b/testing/test_git.py index cb54f61..6663527 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -15,6 +15,7 @@ from unittest.mock import patch import pytest +from .conftest import DebugMode from .wd_wrapper import WorkDir from setuptools_scm import Configuration from setuptools_scm import format_version @@ -31,14 +32,16 @@ pytestmark = pytest.mark.skipif( ) [email protected] -def wd(wd: WorkDir, monkeypatch: pytest.MonkeyPatch) -> WorkDir: [email protected](name="wd") +def wd(wd: WorkDir, monkeypatch: pytest.MonkeyPatch, debug_mode: DebugMode) -> WorkDir: + debug_mode.disable() monkeypatch.delenv("HOME", raising=False) wd("git init") wd("git config user.email [email protected]") wd('git config user.name "a test"') wd.add_command = "git add ." wd.commit_command = "git commit -m test-{reason}" + debug_mode.enable() return wd
Using 'root' in `pyproject.toml` file raises a TypeError when invoked from `__main__.py` Hello, I'm using the following versions setuptools 50.3.2 setuptools-scm 6.4.2 I've a `pyproject.toml` file which setuptools_scm section is [tool.setuptools_scm] write_to = "_version.txt" root = "../.." relative_to = "__file__" When used with `python3 -m build` it works. However, when I run just tool to see the output version, I get the following $ python -m setuptools_scm Traceback (most recent call last): File "<some-path>/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "<some-path>/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "<some-path>/lib/python3.7/site-packages/setuptools_scm/__main__.py", line 83, in <module> main() File "<some-path>/lib/python3.7/site-packages/setuptools_scm/__main__.py", line 18, in main config = Configuration.from_file(pyproject, root=root) File "<some-path>/lib/python3.7/site-packages/setuptools_scm/config.py", line 216, in from_file return cls(dist_name=dist_name, **section, **kwargs) TypeError: type object got multiple values for keyword argument 'root' The variable "root" get defined twice, first by `__main__.py` when setting the default 'root' or the one from the command line (`--root`); and the second time by the user (me) when I add 'root' to my `pyproject.toml` file
0.0
69909799fd2f1aeb295b3a74beeb7bd0c35fbe88
[ "testing/test_git.py::test_git_branch_names_correct" ]
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_root_search_parent_directories", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_git_version_unnormalized_setuptools[false]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_created_class]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_named_import]", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_git.py::test_git_getdate", "testing/test_git.py::test_git_getdate_badgit", "testing/test_git.py::test_git_getdate_signed_commit", "testing/test_git.py::test_git_archival_to_version[1.0-from_data0]", "testing/test_git.py::test_git_archival_to_version[1.1.dev3+g0000-from_data1]", "testing/test_git.py::test_git_archival_to_version[0.0-from_data2]", "testing/test_git.py::test_git_archival_to_version[1.2.2-from_data3]", "testing/test_git.py::test_git_archival_to_version[1.2.2.dev0-from_data4]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-06-26 21:08:09+00:00
mit
5,007
pypa__setuptools_scm-739
diff --git a/src/setuptools_scm/_integration/pyproject_reading.py b/src/setuptools_scm/_integration/pyproject_reading.py index cd7149d..f43e6b1 100644 --- a/src/setuptools_scm/_integration/pyproject_reading.py +++ b/src/setuptools_scm/_integration/pyproject_reading.py @@ -18,6 +18,7 @@ TOML_LOADER: TypeAlias = Callable[[str], TOML_RESULT] class PyProjectData(NamedTuple): + name: str tool_name: str project: TOML_RESULT section: TOML_RESULT @@ -48,7 +49,7 @@ def read_pyproject( except LookupError as e: raise LookupError(f"{name} does not contain a tool.{tool_name} section") from e project = defn.get("project", {}) - return PyProjectData(tool_name, project, section) + return PyProjectData(name, tool_name, project, section) def get_args_for_pyproject( @@ -59,7 +60,13 @@ def get_args_for_pyproject( """drops problematic details and figures the distribution name""" section = pyproject.section.copy() kwargs = kwargs.copy() - + if "relative_to" in section: + relative = section.pop("relative_to") + warnings.warn( + f"{pyproject.name}: at [tool.{pyproject.tool_name}]\n" + f"ignoring value relative_to={relative!r}" + " as its always relative to the config file" + ) if "dist_name" in section: if dist_name is None: dist_name = section.pop("dist_name")
pypa/setuptools_scm
1b18371fc2fa672f39c758a103c4d12956b5964f
diff --git a/testing/test_config.py b/testing/test_config.py index d7aa3f4..97bb36e 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -51,3 +51,26 @@ def test_config_regex_init() -> None: tag_regex = re.compile(r"v(\d+)") conf = Configuration(tag_regex=tag_regex) assert conf.tag_regex is tag_regex + + +def test_config_from_file_protects_relative_to(tmp_path: Path) -> None: + fn = tmp_path / "pyproject.toml" + fn.write_text( + textwrap.dedent( + """ + [tool.setuptools_scm] + relative_to = "dont_use_me" + [project] + description = "Factory ⸻ A code generator 🏭" + authors = [{name = "Łukasz Langa"}] + """ + ), + encoding="utf-8", + ) + with pytest.warns( + UserWarning, + match=".*pyproject.toml: at \\[tool.setuptools_scm\\]\n" + "ignoring value relative_to='dont_use_me'" + " as its always relative to the config file", + ): + assert Configuration.from_file(str(fn))
TypeError: setuptools_scm.config.Configuration() got multiple values for keyword argument 'relative_to' My project build recently stopped working, failing with: > TypeError: setuptools_scm.config.Configuration() got multiple values for keyword argument 'relative_to' My setup.py looks like so: ```python import setuptools setuptools.setup() ``` ...and my pyproject.toml thusly: ```ini [build-system] requires = [ "setuptools>=42", "wheel", "setuptools_scm>=6.2" ] build-backend = "setuptools.build_meta" [tool.setuptools_scm] relative_to = "__file__" fallback_version = "0.0.0" ``` If I comment out the `relative_to` configuration line in `pyproject.toml`, the build completes.
0.0
1b18371fc2fa672f39c758a103c4d12956b5964f
[ "testing/test_config.py::test_config_from_file_protects_relative_to" ]
[ "testing/test_config.py::test_tag_regex[apache-arrow-0.9.0-0.9.0]", "testing/test_config.py::test_tag_regex[arrow-0.9.0-0.9.0]", "testing/test_config.py::test_tag_regex[arrow-0.9.0-rc-0.9.0-rc]", "testing/test_config.py::test_tag_regex[arrow-1-1]", "testing/test_config.py::test_tag_regex[arrow-1+-1]", "testing/test_config.py::test_tag_regex[arrow-1+foo-1]", "testing/test_config.py::test_tag_regex[arrow-1.1+foo-1.1]", "testing/test_config.py::test_tag_regex[v1.1-v1.1]", "testing/test_config.py::test_tag_regex[V1.1-V1.1]", "testing/test_config.py::test_config_from_pyproject", "testing/test_config.py::test_config_regex_init" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-06-30 20:40:07+00:00
mit
5,008
pypa__setuptools_scm-772
diff --git a/.git_archival.txt b/.git_archival.txt index 37d637d..8fb235d 100644 --- a/.git_archival.txt +++ b/.git_archival.txt @@ -1,4 +1,4 @@ node: $Format:%H$ node-date: $Format:%cI$ -describe-name: $Format:%(describe)$ +describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ ref-names: $Format:%D$ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index af10aef..9fe41b2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,12 +2,12 @@ default_language_version: python: python3.9 repos: - repo: https://github.com/psf/black - rev: 22.6.0 + rev: 22.10.0 hooks: - id: black args: [--safe, --quiet] - repo: https://github.com/asottile/reorder_python_imports - rev: v3.3.0 + rev: v3.9.0 hooks: - id: reorder-python-imports args: [ "--application-directories=.:src" , --py37-plus, --add-import, 'from __future__ import annotations'] @@ -19,20 +19,21 @@ repos: - id: check-yaml - id: debug-statements - repo: https://github.com/PyCQA/flake8 - rev: 4.0.1 + rev: 5.0.4 hooks: - id: flake8 - repo: https://github.com/asottile/pyupgrade - rev: v2.34.0 + rev: v3.2.0 hooks: - id: pyupgrade args: [--py37-plus] - repo: https://github.com/asottile/setup-cfg-fmt - rev: v1.20.1 + rev: v2.2.0 hooks: - id: setup-cfg-fmt + args: [ --include-version-classifiers ] - repo: https://github.com/pre-commit/mirrors-mypy - rev: 'v0.961' + rev: 'v0.982' hooks: - id: mypy args: [--strict] diff --git a/README.rst b/README.rst index a02caf7..18f763c 100644 --- a/README.rst +++ b/README.rst @@ -316,7 +316,7 @@ and copy-paste this into it:: node: $Format:%H$ node-date: $Format:%cI$ - describe-name: $Format:%(describe:tags=true)$ + describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ ref-names: $Format:%D$ Create the ``.gitattributes`` file in the root directory of your repository diff --git a/setup.cfg b/setup.cfg index 06c51ea..795bb21 100644 --- a/setup.cfg +++ b/setup.cfg @@ -19,6 +19,7 @@ classifiers = Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 Topic :: Software Development :: Libraries Topic :: Software Development :: Version Control Topic :: System :: Software Distribution diff --git a/src/setuptools_scm/.git_archival.txt b/src/setuptools_scm/.git_archival.txt index 37d637d..8fb235d 100644 --- a/src/setuptools_scm/.git_archival.txt +++ b/src/setuptools_scm/.git_archival.txt @@ -1,4 +1,4 @@ node: $Format:%H$ node-date: $Format:%cI$ -describe-name: $Format:%(describe)$ +describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ ref-names: $Format:%D$ diff --git a/src/setuptools_scm/git.py b/src/setuptools_scm/git.py index 27cb159..16ca378 100644 --- a/src/setuptools_scm/git.py +++ b/src/setuptools_scm/git.py @@ -232,9 +232,13 @@ def _git_parse_inner( ) -def _git_parse_describe(describe_output: str) -> tuple[str, int, str, bool]: +def _git_parse_describe( + describe_output: str, +) -> tuple[str, int | None, str | None, bool]: # 'describe_output' looks e.g. like 'v1.5.0-0-g4060507' or # 'v1.15.1rc1-37-g9bd1298-dirty'. + # It may also just be a bare tag name if this is a tagged commit and we are + # parsing a .git_archival.txt file. if describe_output.endswith("-dirty"): dirty = True @@ -242,8 +246,15 @@ def _git_parse_describe(describe_output: str) -> tuple[str, int, str, bool]: else: dirty = False - tag, number, node = describe_output.rsplit("-", 2) - return tag, int(number), node, dirty + split = describe_output.rsplit("-", 2) + if len(split) < 3: # probably a tagged commit + tag = describe_output + number = None + node = None + else: + tag, number_, node = split + number = int(number_) + return tag, number, node, dirty def search_parent(dirname: _t.PathT) -> GitWorkdir | None:
pypa/setuptools_scm
9a79676cd90ac9f7c1b1a2b0ce2baf39fc2655c5
diff --git a/testing/test_git.py b/testing/test_git.py index 321d658..412ce75 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -523,6 +523,7 @@ def test_git_getdate_signed_commit(signed_commit_wd: WorkDir) -> None: ("0.0", {"node": "0" * 20}), ("1.2.2", {"describe-name": "release-1.2.2-0-g00000"}), ("1.2.2.dev0", {"ref-names": "tag: release-1.2.2.dev"}), + ("1.2.2", {"describe-name": "v1.2.2"}), ], ) @pytest.mark.filterwarnings("ignore:git archive did not support describe output")
The suggested contents of `.git_archival.txt` do not include the `--match` flag (like the default git describe) I noticed a small discrepancy between the default git describe in `setuptools_scm` and the suggested contents of `.git_archival.txt` - the first one uses `--match *[0-9]*` while the second doesn't even though both support it: https://github.com/pypa/setuptools_scm/blob/e1283177b23ccf254739aa8292448154c54741c8/src/setuptools_scm/git.py#L42-L43 `%(describe:tags=true,match=*[0-9]*)` can be used to get an equivalent match in `.git_archival.txt`. I also see that the `.git_archival.txt` in the root of the repository and in `src/setuptools/.git_archival.txt` both do not include the `:tags=true` part, I'm unsure if that's intentional but it doesn't seem like this repository uses annotated tags (or at least not since v6.3.1).
0.0
9a79676cd90ac9f7c1b1a2b0ce2baf39fc2655c5
[ "testing/test_git.py::test_git_archival_to_version[1.2.2-from_data5]" ]
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_root_search_parent_directories", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_git_version_unnormalized_setuptools[false]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_created_class]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_named_import]", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_branch_names_correct", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_git.py::test_git_getdate", "testing/test_git.py::test_git_getdate_badgit", "testing/test_git.py::test_git_archival_to_version[1.0-from_data0]", "testing/test_git.py::test_git_archival_to_version[1.1.dev3+g0000-from_data1]", "testing/test_git.py::test_git_archival_to_version[0.0-from_data2]", "testing/test_git.py::test_git_archival_to_version[1.2.2-from_data3]", "testing/test_git.py::test_git_archival_to_version[1.2.2.dev0-from_data4]", "testing/test_git.py::test_git_archival_node_missing_no_version", "testing/test_git.py::test_git_archival_from_unfiltered" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-14 04:21:37+00:00
mit
5,009
pypa__setuptools_scm-803
diff --git a/README.rst b/README.rst index fd2f18c..bbfd90e 100644 --- a/README.rst +++ b/README.rst @@ -411,7 +411,7 @@ The currently supported configuration keys are: named ``version``, that captures the actual version information. Defaults to the value of ``setuptools_scm.config.DEFAULT_TAG_REGEX`` - (see `config.py <src/setuptools_scm/config.py>`_). + (see `_config.py <src/setuptools_scm/_config.py>`_). :parentdir_prefix_version: If the normal methods for detecting the version (SCM version, @@ -628,6 +628,25 @@ The callable must return the configuration. ) +Customizing Version Scheme with pyproject.toml +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To support custom version schemes in pyproject.toml, you may specify your own function as an entrypoint for getting the version. + +.. code:: toml + + # pyproject.toml + [tool.setuptools_scm] + version_scheme = "myproject.my_file:myversion_func" + +.. code:: python + + # myproject/my_file + def myversion_func(version: ScmVersion): + from setuptools_scm.version import guess_next_version + return version.format_next_version(guess_next_version, '{guessed}b{distance}') + + Note on testing non-installed versions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/setuptools_scm/_entrypoints.py b/src/setuptools_scm/_entrypoints.py index c236434..0b0b32c 100644 --- a/src/setuptools_scm/_entrypoints.py +++ b/src/setuptools_scm/_entrypoints.py @@ -46,9 +46,11 @@ def _version_from_entrypoints( try: from importlib.metadata import entry_points # type: ignore + from importlib.metadata import EntryPoint except ImportError: try: from importlib_metadata import entry_points + from importlib_metadata import EntryPoint except ImportError: from collections import defaultdict @@ -59,6 +61,10 @@ except ImportError: ) return defaultdict(list) + class EntryPoint: # type: ignore + def __init__(self, *args: Any, **kwargs: Any): + pass # entry_points() already provides the warning + def iter_entry_points( group: str, name: str | None = None @@ -83,6 +89,13 @@ def _get_ep(group: str, name: str) -> Any | None: return None +def _get_from_object_reference_str(path: str) -> Any | None: + try: + return EntryPoint(path, path, None).load() + except (AttributeError, ModuleNotFoundError): + return None + + def _iter_version_schemes( entrypoint: str, scheme_value: _t.VERSION_SCHEMES, @@ -93,7 +106,8 @@ def _iter_version_schemes( if isinstance(scheme_value, str): scheme_value = cast( "_t.VERSION_SCHEMES", - _get_ep(entrypoint, scheme_value), + _get_ep(entrypoint, scheme_value) + or _get_from_object_reference_str(scheme_value), ) if isinstance(scheme_value, (list, tuple)):
pypa/setuptools_scm
f620057203f1446c1dea2ce57f73dccdd6f28ee9
diff --git a/testing/test_version.py b/testing/test_version.py index 7c68d42..778b0c2 100644 --- a/testing/test_version.py +++ b/testing/test_version.py @@ -214,6 +214,16 @@ def test_format_version_schemes() -> None: ) +def test_custom_version_schemes() -> None: + version = meta("1.0", config=c) + custom_computed = format_version( + version, + local_scheme="no-local-version", + version_scheme="setuptools_scm.version:no_guess_dev_version", + ) + assert custom_computed == no_guess_dev_version(version) + + def date_to_str( date_: date | None = None, days_offset: int = 0,
Using a custom version_scheme outside setup.py setuptools_scm allows to use a custom version_scheme function. When not using `setup.py` this needs to be an entry-point name. However, this doesn't work logically. When the project is installed (e.g. `pip install -e .`), setuptools asks setuptools_scm for the version tp install the project. But the project is not installed at that point and therefore the entry point is not accessible. Then, the install will fail due to `assert main_version is not None`. Can you please check how to solve this chicken-egg issue? One idea - Support qualified names: Instead of an entry-point give the qualified name to a function and setuptools_scm will execute it
0.0
f620057203f1446c1dea2ce57f73dccdd6f28ee9
[ "testing/test_version.py::test_custom_version_schemes" ]
[ "testing/test_version.py::test_no_guess_version[dev_distance]", "testing/test_version.py::test_no_guess_version[dev_distance_after_dev_tag]", "testing/test_version.py::test_next_semver[normal_branch]", "testing/test_version.py::test_calver_by_date[leading", "testing/test_version.py::test_no_guess_version[dev_distance_short_tag]", "testing/test_version.py::test_calver_by_date_semver[SemVer", "testing/test_version.py::test_next_semver[normal_branch_short_tag]", "testing/test_version.py::test_no_guess_version[no_dev_distance]", "testing/test_version.py::test_next_release_branch_semver[release_branch_legacy_version]", "testing/test_version.py::test_calver_by_date[release", "testing/test_version.py::test_custom_version_cls", "testing/test_version.py::test_no_guess_version_bad[1.0.post1-already", "testing/test_version.py::test_calver_by_date[node", "testing/test_version.py::test_next_semver[feature_branch]", "testing/test_version.py::test_next_release_branch_semver[development_branch_release_candidate]", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_v_prefix]", "testing/test_version.py::test_calver_by_date[using", "testing/test_version.py::test_calver_by_date[exact", "testing/test_version.py::test_version_bump_bad", "testing/test_version.py::test_next_semver[feature_in_branch]", "testing/test_version.py::test_calver_by_date[dirty", "testing/test_version.py::test_next_semver[exact]", "testing/test_version.py::test_bump_dev_version_nonzero_raises", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1-1.0.0rc1]", "testing/test_version.py::test_calver_by_date[4", "testing/test_version.py::test_next_release_branch_semver[false_positive_release_branch]", "testing/test_version.py::test_calver_by_date[normal", "testing/test_version.py::test_next_semver[short_tag]", "testing/test_version.py::test_tag_regex1[v1.0.0-rc.1+-25259o4382757gjurh54-1.0.0rc1]", "testing/test_version.py::test_tag_regex1[v1.0.0-1.0.0]", "testing/test_version.py::test_bump_dev_version_zero", "testing/test_version.py::test_next_release_branch_semver[release_branch_with_prefix]", "testing/test_version.py::test_no_guess_version_bad[1.0.dev1-choosing", "testing/test_version.py::test_next_semver_bad_tag", "testing/test_version.py::test_format_version_schemes", "testing/test_version.py::test_next_semver[feature_branch_short_tag]", "testing/test_version.py::test_calver_by_date_future_warning", "testing/test_version.py::test_next_release_branch_semver[exact]", "testing/test_version.py::test_calver_by_date[exact]", "testing/test_version.py::test_next_release_branch_semver[development_branch]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-10 11:31:41+00:00
mit
5,010
pypa__setuptools_scm-901
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 70c92ee..ea3e6ea 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -38,6 +38,7 @@ features * support passing log levels to SETUPTOOLS_SCM_DEBUG * support using rich.logging as console log handler if installed * fix #527: type annotation in default version template +* fix #549: use fallbacks when scm search raises CommandNotFoundError bugfixes -------- diff --git a/src/setuptools_scm/_entrypoints.py b/src/setuptools_scm/_entrypoints.py index 8350968..e3be053 100644 --- a/src/setuptools_scm/_entrypoints.py +++ b/src/setuptools_scm/_entrypoints.py @@ -13,8 +13,8 @@ from . import _log from . import version if TYPE_CHECKING: - from ._config import Configuration from . import _types as _t + from ._config import Configuration, ParseFunction log = _log.log.getChild("entrypoints") @@ -27,21 +27,14 @@ class EntrypointProtocol(Protocol): pass -def _version_from_entrypoints( - config: Configuration, fallback: bool = False +def version_from_entrypoint( + config: Configuration, entrypoint: str, root: _t.PathT ) -> version.ScmVersion | None: - if fallback: - entrypoint = "setuptools_scm.parse_scm_fallback" - root = config.fallback_root - else: - entrypoint = "setuptools_scm.parse_scm" - root = config.absolute_root - from .discover import iter_matching_entrypoints log.debug("version_from_ep %s in %s", entrypoint, root) for ep in iter_matching_entrypoints(root, entrypoint, config): - fn = ep.load() + fn: ParseFunction = ep.load() maybe_version: version.ScmVersion | None = fn(root, config=config) log.debug("%s found %r", ep, maybe_version) if maybe_version is not None: diff --git a/src/setuptools_scm/_get_version.py b/src/setuptools_scm/_get_version.py index a1afe2d..d2fe9e1 100644 --- a/src/setuptools_scm/_get_version.py +++ b/src/setuptools_scm/_get_version.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging import re import warnings from pathlib import Path @@ -8,30 +9,41 @@ from typing import NoReturn from typing import Pattern from . import _config +from . import _entrypoints +from . import _run_cmd from . import _types as _t from ._config import Configuration -from ._entrypoints import _version_from_entrypoints from ._overrides import _read_pretended_version_for from ._version_cls import _validate_version_cls from .version import format_version as _format_version from .version import ScmVersion +_log = logging.getLogger(__name__) + def parse_scm_version(config: Configuration) -> ScmVersion | None: - if config.parse is not None: - parse_result = config.parse(config.absolute_root, config=config) - if parse_result is not None and not isinstance(parse_result, ScmVersion): - raise TypeError( - f"version parse result was {str!r}\n" - "please return a parsed version (ScmVersion)" - ) - return parse_result - else: - return _version_from_entrypoints(config) + try: + if config.parse is not None: + parse_result = config.parse(config.absolute_root, config=config) + if parse_result is not None and not isinstance(parse_result, ScmVersion): + raise TypeError( + f"version parse result was {str!r}\n" + "please return a parsed version (ScmVersion)" + ) + return parse_result + else: + entrypoint = "setuptools_scm.parse_scm" + root = config.absolute_root + return _entrypoints.version_from_entrypoint(config, entrypoint, root) + except _run_cmd.CommandNotFoundError as e: + _log.exception("command %s not found while parsing the scm, using fallbacks", e) + return None def parse_fallback_version(config: Configuration) -> ScmVersion | None: - return _version_from_entrypoints(config, fallback=True) + entrypoint = "setuptools_scm.parse_scm_fallback" + root = config.fallback_root + return _entrypoints.version_from_entrypoint(config, entrypoint, root) def _do_parse(config: Configuration) -> ScmVersion | None: diff --git a/src/setuptools_scm/_run_cmd.py b/src/setuptools_scm/_run_cmd.py index 3c938d8..046749a 100644 --- a/src/setuptools_scm/_run_cmd.py +++ b/src/setuptools_scm/_run_cmd.py @@ -189,6 +189,10 @@ def has_command( return res +class CommandNotFoundError(LookupError, FileNotFoundError): + pass + + def require_command(name: str) -> None: if not has_command(name, warn=False): - raise OSError(f"{name!r} was not found") + raise CommandNotFoundError(name)
pypa/setuptools_scm
2e5c2f8327bf2872e4a0e89cc2634a2bf73b3daf
diff --git a/testing/test_git.py b/testing/test_git.py index cec9afa..8bebd1e 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -24,6 +24,7 @@ from setuptools_scm import Configuration from setuptools_scm import git from setuptools_scm import NonNormalizedVersion from setuptools_scm._file_finders.git import git_find_files +from setuptools_scm._run_cmd import CommandNotFoundError from setuptools_scm._run_cmd import CompletedProcess from setuptools_scm._run_cmd import has_command from setuptools_scm._run_cmd import run @@ -93,8 +94,12 @@ setup(use_scm_version={"search_parent_directories": True}) def test_git_gone(wd: WorkDir, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("PATH", str(wd.cwd / "not-existing")) - with pytest.raises(EnvironmentError, match="'git' was not found"): - git.parse(str(wd.cwd), Configuration(), git.DEFAULT_DESCRIBE) + + wd.write("pyproject.toml", "[tool.setuptools_scm]") + with pytest.raises(CommandNotFoundError, match=r"git"): + git.parse(wd.cwd, Configuration(), git.DEFAULT_DESCRIBE) + + assert wd.get_version(fallback_version="1.0") == "1.0" @pytest.mark.issue("https://github.com/pypa/setuptools_scm/issues/298") diff --git a/testing/test_mercurial.py b/testing/test_mercurial.py index 1b35d11..3aa8594 100644 --- a/testing/test_mercurial.py +++ b/testing/test_mercurial.py @@ -7,6 +7,7 @@ import pytest import setuptools_scm._file_finders from setuptools_scm import Configuration +from setuptools_scm._run_cmd import CommandNotFoundError from setuptools_scm._run_cmd import has_command from setuptools_scm.hg import archival_to_version from setuptools_scm.hg import parse @@ -55,8 +56,11 @@ def test_archival_to_version(expected: str, data: dict[str, str]) -> None: def test_hg_gone(wd: WorkDir, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("PATH", str(wd.cwd / "not-existing")) config = Configuration() - with pytest.raises(EnvironmentError, match="'hg' was not found"): - parse(str(wd.cwd), config=config) + wd.write("pyproject.toml", "[tool.setuptools_scm]") + with pytest.raises(CommandNotFoundError, match=r"hg"): + parse(wd.cwd, config=config) + + assert wd.get_version(fallback_version="1.0") == "1.0" def test_find_files_stop_at_root_hg(
Use fallback_version if SCM isn't found I'm in some situation (testing my package in Docker) where git isn't available, and thought I could just use `fallback_version` argument, but it turns out I still get an exception `OSError: 'git' was not found`. I found I can overcome this by defining the `SETUPTOOLS_SCM_PRETEND_VERSION` environment variable, but I thought it would be easier to use `fallback_version` in this case as well? I'm not sure I understood the different cases where one should use `SETUPTOOLS_SCM_PRETEND_VERSION` or `fallback_version`?
0.0
2e5c2f8327bf2872e4a0e89cc2634a2bf73b3daf
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_root_relative_to", "testing/test_git.py::test_root_search_parent_directories", "testing/test_git.py::test_git_gone", "testing/test_git.py::test_file_finder_no_history", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_git_version_unnormalized_setuptools[false]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_created_class]", "testing/test_git.py::test_git_version_unnormalized_setuptools[with_named_import]", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag[False]", "testing/test_git.py::test_git_dirty_notag[True]", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_branch_names_correct", "testing/test_git.py::test_git_feature_branch_increments_major", "testing/test_git.py::test_not_matching_tags", "testing/test_git.py::test_non_dotted_version", "testing/test_git.py::test_non_dotted_version_with_updated_regex", "testing/test_git.py::test_non_dotted_tag_no_version_match", "testing/test_git.py::test_gitdir", "testing/test_git.py::test_git_getdate", "testing/test_git.py::test_git_getdate_badgit", "testing/test_git.py::test_git_getdate_signed_commit", "testing/test_git.py::test_git_archival_to_version[1.0-from_data0]", "testing/test_git.py::test_git_archival_to_version[1.1.dev3+g0000-from_data1]", "testing/test_git.py::test_git_archival_to_version[0.0-from_data2]", "testing/test_git.py::test_git_archival_to_version[1.2.2-from_data3]", "testing/test_git.py::test_git_archival_to_version[1.2.2.dev0-from_data4]", "testing/test_git.py::test_git_archival_to_version[1.2.2-from_data5]", "testing/test_git.py::test_git_archival_node_missing_no_version", "testing/test_git.py::test_git_archival_from_unfiltered", "testing/test_mercurial.py::test_archival_to_version[0.0-data0]", "testing/test_mercurial.py::test_archival_to_version[1.0-data1]", "testing/test_mercurial.py::test_archival_to_version[1.1.dev3+h000000000000-data2]", "testing/test_mercurial.py::test_archival_to_version[1.2.2-data3]", "testing/test_mercurial.py::test_archival_to_version[1.2.2.dev0-data4]", "testing/test_mercurial.py::test_hg_gone", "testing/test_mercurial.py::test_find_files_stop_at_root_hg", "testing/test_mercurial.py::test_version_from_hg_id", "testing/test_mercurial.py::test_version_from_archival", "testing/test_mercurial.py::test_version_in_merge", "testing/test_mercurial.py::test_parse_no_worktree", "testing/test_mercurial.py::test_version_bump_before_merge_commit", "testing/test_mercurial.py::test_version_bump_from_merge_commit", "testing/test_mercurial.py::test_version_bump_from_commit_including_hgtag_mods", "testing/test_mercurial.py::test_latest_tag_detection", "testing/test_mercurial.py::test_feature_branch_increments_major" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-09-13 21:41:49+00:00
mit
5,011
pypa__setuptools_scm-907
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ea3e6ea..9731a30 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,12 @@ + +v8.0.1 +====== + +bugfix +------ + +* update version file template to work on older python versions by using type comments + v8.0.0 ====== diff --git a/src/setuptools_scm/_integration/dump_version.py b/src/setuptools_scm/_integration/dump_version.py index a7ff4d3..421379b 100644 --- a/src/setuptools_scm/_integration/dump_version.py +++ b/src/setuptools_scm/_integration/dump_version.py @@ -15,10 +15,8 @@ TEMPLATES = { ".py": """\ # file generated by setuptools_scm # don't change, don't track in version control -from __future__ import annotations -__version__ : str = version : str = {version!r} -__version_tuple__ : 'tuple[int | str, ...]' = \\ - version_tuple : 'tuple[int | str, ...]' = {version_tuple!r} +__version__ = version = {version!r} # type: str +__version_tuple__ = version_tuple = {version_tuple!r} # type: tuple[int | str, ...] """, ".txt": "{version}", }
pypa/setuptools_scm
b5dbba7a154b90f401ac1b9ca37dc920b5e82c33
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index fa35e2c..6fa02fe 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -179,10 +179,10 @@ def test_dump_version(tmp_path: Path) -> None: scm_version = meta("1.0", distance=42, config=c) dump_version(tmp_path, version, "first.py", scm_version=scm_version) lines = read("first.py").splitlines() - assert lines[3:] == [ - "__version__ : str = version : str = '1.0.dev42'", - "__version_tuple__ : 'tuple[int | str, ...]' = \\", - " version_tuple : 'tuple[int | str, ...]' = (1, 0, 'dev42')", + assert lines[-2:] == [ + "__version__ = version = '1.0.dev42' # type: str", + "__version_tuple__ = version_tuple = (1, 0, 'dev42')" + " # type: tuple[int | str, ...]", ] version = "1.0.1+g4ac9d2c" diff --git a/testing/test_functions.py b/testing/test_functions.py index baf84d3..dfc22b6 100644 --- a/testing/test_functions.py +++ b/testing/test_functions.py @@ -1,5 +1,7 @@ from __future__ import annotations +import shutil +import subprocess from pathlib import Path import pytest @@ -108,6 +110,24 @@ def test_dump_version_modern(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> assert target.read_text() == version +def test_dump_version_on_old_python(tmp_path: Path) -> None: + python37 = shutil.which("python3.7") + if python37 is None: + pytest.skip("python3.7 not found") + from setuptools_scm._integration.dump_version import write_version_to_path + + version = "1.2.3" + scm_version = meta(version, config=c) + write_version_to_path( + tmp_path / "VERSION.py", template=None, version=version, scm_version=scm_version + ) + subprocess.run( + [python37, "-c", "import VERSION;print(VERSION.version)"], + cwd=tmp_path, + check=True, + ) + + def test_has_command() -> None: with pytest.warns(RuntimeWarning, match="yadayada"): assert not has_command("yadayada_setuptools_aint_ne")
generated _version.py breaks on python <3.8 I have this in my `pyproject.toml`: ``` [tool.setuptools_scm] write_to = "src/toolname/_version.py" ``` setuptools_scm 8.0.0 seems to incorrectly generate the `_version.py` file (it contains syntax errors): ``` # file generated by setuptools_scm # don't change, don't track in version control from __future__ import annotations __version__ : str = version : str = '4.5.dev38+g44c9a18' __version_tuple__ : 'tuple[int | str, ...]' = \ version_tuple : 'tuple[int | str, ...]' = (4, 5, 'dev38', 'g44c9a18') ``` [Logs for a failed GitHub Actions run](https://github.com/marcelm/cutadapt/actions/runs/6247483075/job/16960159583).
0.0
b5dbba7a154b90f401ac1b9ca37dc920b5e82c33
[ "testing/test_basic_api.py::test_dump_version" ]
[ "testing/test_basic_api.py::test_run_plain", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_parentdir_prefix", "testing/test_basic_api.py::test_fallback", "testing/test_basic_api.py::test_empty_pretend_version", "testing/test_basic_api.py::test_empty_pretend_version_named", "testing/test_basic_api.py::test_get_version_blank_tag_regex", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_parse_plain_fails", "testing/test_basic_api.py::test_custom_version_cls", "testing/test_functions.py::test_next_tag[1.1-1.2]", "testing/test_functions.py::test_next_tag[1.2.dev-1.2]", "testing/test_functions.py::test_next_tag[1.1a2-1.1a3]", "testing/test_functions.py::test_next_tag[23.24.post2+deadbeef-23.24.post3]", "testing/test_functions.py::test_format_version[exact-guess-next-dev-node-and-date-1.1]", "testing/test_functions.py::test_format_version[dirty-guess-next-dev-node-and-date-1.2.dev0+d20090213]", "testing/test_functions.py::test_format_version[dirty-guess-next-dev-no-local-version-1.2.dev0]", "testing/test_functions.py::test_format_version[distance-clean-guess-next-dev-node-and-date-1.2.dev3]", "testing/test_functions.py::test_format_version[distance-dirty-guess-next-dev-node-and-date-1.2.dev3+d20090213]", "testing/test_functions.py::test_format_version[exact-post-release-node-and-date-1.1]", "testing/test_functions.py::test_format_version[dirty-post-release-node-and-date-1.1.post0+d20090213]", "testing/test_functions.py::test_format_version[distance-clean-post-release-node-and-date-1.1.post3]", "testing/test_functions.py::test_format_version[distance-dirty-post-release-node-and-date-1.1.post3+d20090213]", "testing/test_functions.py::test_dump_version_doesnt_bail_on_value_error", "testing/test_functions.py::test_dump_version_works_with_pretend[1.0]", "testing/test_functions.py::test_dump_version_works_with_pretend[1.2.3.dev1+ge871260]", "testing/test_functions.py::test_dump_version_works_with_pretend[1.2.3.dev15+ge871260.d20180625]", "testing/test_functions.py::test_dump_version_modern", "testing/test_functions.py::test_has_command", "testing/test_functions.py::test_tag_to_version[1.1-1.1]", "testing/test_functions.py::test_tag_to_version[release-1.1-1.1]", "testing/test_functions.py::test_tag_to_version[3.3.1-rc26-3.3.1rc26]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-09-20 11:18:09+00:00
mit
5,012
pypa__setuptools_scm-924
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 3658763..cc663fd 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,9 @@ v8.0.2 bugfix ------ + +* fix #919: restore legacy version-file behaviour for external callers + add Deprecation warning +* fix #918: use packaging from setuptools for self-build * fix #914: ignore the deprecated git archival plugin as its integrated now * fix #912: ensure mypy safety of the version template + regression test * fix #913: use 240s timeout instead of 20 for git unshallow diff --git a/pyproject.toml b/pyproject.toml index dc5475c..983789f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,6 @@ build-backend = "_own_version_helper" requires = [ 'importlib-metadata>=4.6; python_version < "3.10"', - "packaging>=20", "rich", "setuptools>=61", 'tomli; python_version < "3.11"', diff --git a/src/setuptools_scm/_cli.py b/src/setuptools_scm/_cli.py index 560650c..66099b1 100644 --- a/src/setuptools_scm/_cli.py +++ b/src/setuptools_scm/_cli.py @@ -31,7 +31,7 @@ def main(args: list[str] | None = None) -> None: ) config = Configuration(inferred_root) - version = _get_version(config) + version = _get_version(config, force_write_version_files=False) if version is None: raise SystemExit("ERROR: no version found for", opts) if opts.strip_dev: diff --git a/src/setuptools_scm/_get_version_impl.py b/src/setuptools_scm/_get_version_impl.py index a5015c7..8be513a 100644 --- a/src/setuptools_scm/_get_version_impl.py +++ b/src/setuptools_scm/_get_version_impl.py @@ -84,12 +84,20 @@ def write_version_files( def _get_version( - config: Configuration, force_write_version_files: bool = False + config: Configuration, force_write_version_files: bool | None = None ) -> str | None: parsed_version = parse_version(config) if parsed_version is None: return None version_string = _format_version(parsed_version) + if force_write_version_files is None: + force_write_version_files = True + warnings.warn( + "force_write_version_files ought to be set," + " presuming the legacy True value", + DeprecationWarning, + ) + if force_write_version_files: write_version_files(config, version=version_string, scm_version=parsed_version) diff --git a/src/setuptools_scm/_version_cls.py b/src/setuptools_scm/_version_cls.py index e62c9fa..55c00c6 100644 --- a/src/setuptools_scm/_version_cls.py +++ b/src/setuptools_scm/_version_cls.py @@ -5,8 +5,12 @@ from typing import cast from typing import Type from typing import Union -from packaging.version import InvalidVersion -from packaging.version import Version as Version +try: + from packaging.version import InvalidVersion + from packaging.version import Version as Version +except ImportError: + from setuptools.extern.packaging.version import InvalidVersion # type: ignore + from setuptools.extern.packaging.version import Version as Version # type: ignore class NonNormalizedVersion(Version):
pypa/setuptools_scm
4bc06aca8139ca09b25a6bff2a2090f107ecb7cf
diff --git a/testing/test_basic_api.py b/testing/test_basic_api.py index 6fa02fe..95afa0f 100644 --- a/testing/test_basic_api.py +++ b/testing/test_basic_api.py @@ -242,3 +242,20 @@ def test_custom_version_cls() -> None: # to create a test? # monkeypatch.setenv(setuptools_scm.PRETEND_KEY, "1.0.1") # assert setuptools_scm.get_version(version_cls=MyVersion) == "1" + + +def test_internal_get_version_warns_for_version_files(tmp_path: Path) -> None: + tmp_path.joinpath("PKG-INFO").write_text("Version: 0.1") + c = Configuration(root=tmp_path, fallback_root=tmp_path) + with pytest.warns( + DeprecationWarning, + match="force_write_version_files ought to be set," + " presuming the legacy True value", + ): + ver = setuptools_scm._get_version(c) + assert ver == "0.1" + + # force write won't write as no version file is configured + assert setuptools_scm._get_version(c, force_write_version_files=False) == ver + + assert setuptools_scm._get_version(c, force_write_version_files=True) == ver
force_write_version_files added with different default in version 8 The parameter `force_write_version_files` was added to `_get_version` with a different default than in <8, which causes `_get_version` to no longer write out version files. Seen in https://github.com/scikit-build/scikit-build-core/issues/507
0.0
4bc06aca8139ca09b25a6bff2a2090f107ecb7cf
[ "testing/test_basic_api.py::test_internal_get_version_warns_for_version_files" ]
[ "testing/test_basic_api.py::test_run_plain", "testing/test_basic_api.py::test_data_from_mime", "testing/test_basic_api.py::test_version_from_pkginfo", "testing/test_basic_api.py::test_root_parameter_creation", "testing/test_basic_api.py::test_root_parameter_pass_by", "testing/test_basic_api.py::test_parentdir_prefix", "testing/test_basic_api.py::test_fallback", "testing/test_basic_api.py::test_empty_pretend_version", "testing/test_basic_api.py::test_empty_pretend_version_named", "testing/test_basic_api.py::test_get_version_blank_tag_regex", "testing/test_basic_api.py::test_pretended[1.0]", "testing/test_basic_api.py::test_pretended[1.2.3.dev1+ge871260]", "testing/test_basic_api.py::test_pretended[1.2.3.dev15+ge871260.d20180625]", "testing/test_basic_api.py::test_pretended[2345]", "testing/test_basic_api.py::test_root_relative_to", "testing/test_basic_api.py::test_dump_version", "testing/test_basic_api.py::test_parse_plain_fails", "testing/test_basic_api.py::test_custom_version_cls" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-09-21 08:35:44+00:00
mit
5,013
pypa__twine-369
diff --git a/twine/utils.py b/twine/utils.py index d83e080..4feca1b 100644 --- a/twine/utils.py +++ b/twine/utils.py @@ -21,6 +21,7 @@ import getpass import sys import argparse import warnings +import collections from requests.exceptions import HTTPError @@ -48,68 +49,52 @@ TEST_REPOSITORY = "https://test.pypi.org/legacy/" def get_config(path="~/.pypirc"): + # even if the config file does not exist, set up the parser + # variable to reduce the number of if/else statements + parser = configparser.RawConfigParser() + + # this list will only be used if index-servers + # is not defined in the config file + index_servers = ["pypi", "testpypi"] + + # default configuration for each repository + defaults = {"username": None, "password": None} + # Expand user strings in the path path = os.path.expanduser(path) - if not os.path.isfile(path): - return {"pypi": {"repository": DEFAULT_REPOSITORY, - "username": None, - "password": None - }, - "pypitest": {"repository": TEST_REPOSITORY, - "username": None, - "password": None - }, - } - # Parse the rc file - parser = configparser.RawConfigParser() - parser.read(path) - - # Get a list of repositories from the config file - # format: https://docs.python.org/3/distutils/packageindex.html#pypirc - if (parser.has_section("distutils") and - parser.has_option("distutils", "index-servers")): - repositories = parser.get("distutils", "index-servers").split() - elif parser.has_section("pypi"): - # Special case: if the .pypirc file has a 'pypi' section, - # even if there's no list of index servers, - # be lenient and include that in our list of repositories. - repositories = ['pypi'] - else: - repositories = [] + if os.path.isfile(path): + parser.read(path) - config = {} + # Get a list of index_servers from the config file + # format: https://docs.python.org/3/distutils/packageindex.html#pypirc + if parser.has_option("distutils", "index-servers"): + index_servers = parser.get("distutils", "index-servers").split() - defaults = {"username": None, "password": None} - if parser.has_section("server-login"): for key in ["username", "password"]: if parser.has_option("server-login", key): defaults[key] = parser.get("server-login", key) - for repository in repositories: - # Skip this repository if it doesn't exist in the config file - if not parser.has_section(repository): - continue + config = collections.defaultdict(lambda: defaults.copy()) - # Mandatory configuration and defaults - config[repository] = { - "repository": DEFAULT_REPOSITORY, - "username": None, - "password": None, - } + # don't require users to manually configure URLs for these repositories + config["pypi"]["repository"] = DEFAULT_REPOSITORY + if "testpypi" in index_servers: + config["testpypi"]["repository"] = TEST_REPOSITORY - # Optional configuration values + # optional configuration values for individual repositories + for repository in index_servers: for key in [ "username", "repository", "password", "ca_cert", "client_cert", ]: if parser.has_option(repository, key): config[repository][key] = parser.get(repository, key) - elif defaults.get(key): - config[repository][key] = defaults[key] - return config + # convert the defaultdict to a regular dict at this point + # to prevent surprising behavior later on + return dict(config) def get_repository_from_config(config_file, repository, repository_url=None):
pypa/twine
34c08ef97d05d219ae018f041cd37e1d409b7a4d
diff --git a/tests/test_utils.py b/tests/test_utils.py index 4cd45a6..4d60e04 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -72,6 +72,11 @@ def test_get_config_no_distutils(tmpdir): "username": "testuser", "password": "testpassword", }, + "testpypi": { + "repository": utils.TEST_REPOSITORY, + "username": None, + "password": None, + }, } @@ -97,6 +102,18 @@ def test_get_config_no_section(tmpdir): } +def test_get_config_override_pypi_url(tmpdir): + pypirc = os.path.join(str(tmpdir), ".pypirc") + + with open(pypirc, "w") as fp: + fp.write(textwrap.dedent(""" + [pypi] + repository = http://pypiproxy + """)) + + assert utils.get_config(pypirc)['pypi']['repository'] == 'http://pypiproxy' + + def test_get_config_missing(tmpdir): pypirc = os.path.join(str(tmpdir), ".pypirc") @@ -106,7 +123,7 @@ def test_get_config_missing(tmpdir): "username": None, "password": None, }, - "pypitest": { + "testpypi": { "repository": utils.TEST_REPOSITORY, "username": None, "password": None @@ -143,8 +160,13 @@ def test_get_config_deprecated_pypirc(): assert utils.get_config(deprecated_pypirc_path) == { "pypi": { "repository": utils.DEFAULT_REPOSITORY, - "username": 'testusername', - "password": 'testpassword', + "username": "testusername", + "password": "testpassword", + }, + "testpypi": { + "repository": utils.TEST_REPOSITORY, + "username": "testusername", + "password": "testpassword", }, }
Twine should have a built-in alias for testpypi Instead of needing to specify the full upload URL for Test PyPI we should always have an alias ready, for example: ``` twine upload --repository=testpypi dist/* ``` Should work even without a `-/.pypirc`. If `testpypi` is defined in `~/.pypic`, it should take precedence.
0.0
34c08ef97d05d219ae018f041cd37e1d409b7a4d
[ "tests/test_utils.py::test_get_config_no_distutils", "tests/test_utils.py::test_get_config_missing", "tests/test_utils.py::test_get_config_deprecated_pypirc" ]
[ "tests/test_utils.py::test_get_config", "tests/test_utils.py::test_get_config_no_section", "tests/test_utils.py::test_get_config_override_pypi_url", "tests/test_utils.py::test_get_repository_config_missing", "tests/test_utils.py::test_get_userpass_value[cli-config0-key-<lambda>-cli]", "tests/test_utils.py::test_get_userpass_value[None-config1-key-<lambda>-value]", "tests/test_utils.py::test_get_userpass_value[None-config2-key-<lambda>-fallback]", "tests/test_utils.py::test_default_to_environment_action[MY_PASSWORD-None-environ0-None]", "tests/test_utils.py::test_default_to_environment_action[MY_PASSWORD-None-environ1-foo]", "tests/test_utils.py::test_default_to_environment_action[URL-https://example.org-environ2-https://example.org]", "tests/test_utils.py::test_default_to_environment_action[URL-https://example.org-environ3-https://pypi.org]", "tests/test_utils.py::test_get_password_keyring_overrides_prompt", "tests/test_utils.py::test_get_password_keyring_defers_to_prompt", "tests/test_utils.py::test_get_password_keyring_missing_prompts", "tests/test_utils.py::test_get_password_runtime_error_suppressed", "tests/test_utils.py::test_no_positional_on_method", "tests/test_utils.py::test_no_positional_on_function" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-05-19 18:01:32+00:00
apache-2.0
5,014
pypa__twine-419
diff --git a/twine/commands/check.py b/twine/commands/check.py index f71b2c9..b55dabf 100644 --- a/twine/commands/check.py +++ b/twine/commands/check.py @@ -24,18 +24,16 @@ try: except ImportError: from _io import StringIO -import readme_renderer.markdown import readme_renderer.rst -import readme_renderer.txt from twine.commands import _find_dists from twine.package import PackageFile _RENDERERS = { None: readme_renderer.rst, # Default if description_content_type is None - "text/plain": readme_renderer.txt, + "text/plain": None, # Rendering cannot fail "text/x-rst": readme_renderer.rst, - "text/markdown": readme_renderer.markdown, + "text/markdown": None, # Rendering cannot fail } @@ -101,7 +99,11 @@ def check(dists, output_stream=sys.stdout): output_stream.write('warning: `long_description` missing.\n') output_stream.write("Passed\n") else: - if renderer.render(description, stream=stream, **params) is None: + if ( + renderer + and renderer.render(description, stream=stream, **params) + is None + ): failure = True output_stream.write("Failed\n") output_stream.write( diff --git a/twine/settings.py b/twine/settings.py index 8e270fd..d4e3d1a 100644 --- a/twine/settings.py +++ b/twine/settings.py @@ -235,7 +235,11 @@ class Settings(object): ) def _handle_authentication(self, username, password): - self.username = utils.get_username(username, self.repository_config) + self.username = utils.get_username( + self.repository_config['repository'], + username, + self.repository_config + ) self.password = utils.get_password( self.repository_config['repository'], self.username, diff --git a/twine/utils.py b/twine/utils.py index 57eefb3..a4f6419 100644 --- a/twine/utils.py +++ b/twine/utils.py @@ -203,6 +203,23 @@ def get_userpass_value(cli_value, config, key, prompt_strategy=None): return None +def get_username_from_keyring(system): + if 'keyring' not in sys.modules: + return + + try: + getter = sys.modules['keyring'].get_credential + except AttributeError: + return None + + try: + creds = getter(system, None) + if creds: + return creds.username + except Exception as exc: + warnings.warn(str(exc)) + + def password_prompt(prompt_text): # Always expects unicode for our own sanity prompt = prompt_text # Workaround for https://github.com/pypa/twine/issues/116 @@ -221,6 +238,13 @@ def get_password_from_keyring(system, username): warnings.warn(str(exc)) +def username_from_keyring_or_prompt(system): + return ( + get_username_from_keyring(system) + or input_func('Enter your username: ') + ) + + def password_from_keyring_or_prompt(system, username): return ( get_password_from_keyring(system, username) @@ -228,11 +252,18 @@ def password_from_keyring_or_prompt(system, username): ) -get_username = functools.partial( - get_userpass_value, - key='username', - prompt_strategy=functools.partial(input_func, 'Enter your username: '), -) +def get_username(system, cli_value, config): + return get_userpass_value( + cli_value, + config, + key='username', + prompt_strategy=functools.partial( + username_from_keyring_or_prompt, + system, + ), + ) + + get_cacert = functools.partial( get_userpass_value, key='ca_cert',
pypa/twine
bd1d8b0f3ffdae9b91672d075d58cf635aa0e0f6
diff --git a/tests/test_utils.py b/tests/test_utils.py index 520b78f..68d393d 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -229,6 +229,33 @@ def test_get_password_keyring_defers_to_prompt(monkeypatch): assert pw == 'entered pw' +def test_get_username_and_password_keyring_overrides_prompt(monkeypatch): + import collections + Credential = collections.namedtuple('Credential', 'username password') + + class MockKeyring: + @staticmethod + def get_credential(system, user): + return Credential( + 'real_user', + 'real_user@{system} sekure pa55word'.format(**locals()) + ) + + @staticmethod + def get_password(system, user): + cred = MockKeyring.get_credential(system, user) + if user != cred.username: + raise RuntimeError("unexpected username") + return cred.password + + monkeypatch.setitem(sys.modules, 'keyring', MockKeyring) + + user = utils.get_username('system', None, {}) + assert user == 'real_user' + pw = utils.get_password('system', user, None, {}) + assert pw == 'real_user@system sekure pa55word' + + @pytest.fixture def keyring_missing(monkeypatch): """ @@ -237,11 +264,31 @@ def keyring_missing(monkeypatch): monkeypatch.delitem(sys.modules, 'keyring', raising=False) [email protected] +def keyring_missing_get_credentials(monkeypatch): + """ + Simulate older versions of keyring that do not have the + 'get_credentials' API. + """ + monkeypatch.delattr('keyring.backends.KeyringBackend', + 'get_credential', raising=False) + + [email protected] +def entered_username(monkeypatch): + monkeypatch.setattr(utils, 'input_func', lambda prompt: 'entered user') + + @pytest.fixture def entered_password(monkeypatch): monkeypatch.setattr(utils, 'password_prompt', lambda prompt: 'entered pw') +def test_get_username_keyring_missing_get_credentials_prompts( + entered_username, keyring_missing_get_credentials): + assert utils.get_username('system', None, {}) == 'entered user' + + def test_get_password_keyring_missing_prompts( entered_password, keyring_missing): assert utils.get_password('system', 'user', None, {}) == 'entered pw' @@ -261,6 +308,28 @@ def keyring_no_backends(monkeypatch): monkeypatch.setitem(sys.modules, 'keyring', FailKeyring()) [email protected] +def keyring_no_backends_get_credential(monkeypatch): + """ + Simulate that keyring has no available backends. When keyring + has no backends for the system, the backend will be a + fail.Keyring, which raises RuntimeError on get_password. + """ + class FailKeyring(object): + @staticmethod + def get_credential(system, username): + raise RuntimeError("fail!") + monkeypatch.setitem(sys.modules, 'keyring', FailKeyring()) + + +def test_get_username_runtime_error_suppressed( + entered_username, keyring_no_backends_get_credential, recwarn): + assert utils.get_username('system', None, {}) == 'entered user' + assert len(recwarn) == 1 + warning = recwarn.pop(UserWarning) + assert 'fail!' in str(warning) + + def test_get_password_runtime_error_suppressed( entered_password, keyring_no_backends, recwarn): assert utils.get_password('system', 'user', None, {}) == 'entered pw'
Support keyring.get_username_and_password The next release of keyring will include a [get_username_and_password](https://github.com/jaraco/keyring/issues/350) API that allows backends to return both a username and password for a URL. By updating twine to use this API, we can enable backends for private feeds to use other mechanisms besides simple username/passwords to authenticate users.
0.0
bd1d8b0f3ffdae9b91672d075d58cf635aa0e0f6
[ "tests/test_utils.py::test_get_username_and_password_keyring_overrides_prompt", "tests/test_utils.py::test_get_username_keyring_missing_get_credentials_prompts", "tests/test_utils.py::test_get_username_runtime_error_suppressed" ]
[ "tests/test_utils.py::test_get_config", "tests/test_utils.py::test_get_config_no_distutils", "tests/test_utils.py::test_get_config_no_section", "tests/test_utils.py::test_get_config_override_pypi_url", "tests/test_utils.py::test_get_config_missing", "tests/test_utils.py::test_get_repository_config_missing", "tests/test_utils.py::test_get_config_deprecated_pypirc", "tests/test_utils.py::test_get_userpass_value[cli-config0-key-<lambda>-cli]", "tests/test_utils.py::test_get_userpass_value[None-config1-key-<lambda>-value]", "tests/test_utils.py::test_get_userpass_value[None-config2-key-<lambda>-fallback]", "tests/test_utils.py::test_default_to_environment_action[MY_PASSWORD-None-environ0-None]", "tests/test_utils.py::test_default_to_environment_action[MY_PASSWORD-None-environ1-foo]", "tests/test_utils.py::test_default_to_environment_action[URL-https://example.org-environ2-https://example.org]", "tests/test_utils.py::test_default_to_environment_action[URL-https://example.org-environ3-https://pypi.org]", "tests/test_utils.py::test_get_password_keyring_overrides_prompt", "tests/test_utils.py::test_get_password_keyring_defers_to_prompt", "tests/test_utils.py::test_get_password_keyring_missing_prompts", "tests/test_utils.py::test_get_password_runtime_error_suppressed", "tests/test_utils.py::test_no_positional_on_method", "tests/test_utils.py::test_no_positional_on_function" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-27 19:14:57+00:00
apache-2.0
5,015
pypa__wheel-213
diff --git a/CHANGES.txt b/CHANGES.txt index 5c3ceee..a182ed7 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,6 +1,7 @@ Unreleased ========== - Fixed displaying of errors on Python 3 +- Fixed single digit versions in wheel files not being properly recognized 0.30.0 ====== diff --git a/wheel/install.py b/wheel/install.py index 5c3e3d9..3d71d3d 100644 --- a/wheel/install.py +++ b/wheel/install.py @@ -34,9 +34,8 @@ VERSION_TOO_HIGH = (1, 0) # Non-greedy matching of an optional build number may be too clever (more # invalid wheel filenames will match). Separate regex for .dist-info? WHEEL_INFO_RE = re.compile( - r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?) - ((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?) - \.whl|\.dist-info)$""", + r"""^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?))(-(?P<build>\d.*?))? + -(?P<pyver>[a-z].+?)-(?P<abi>.+?)-(?P<plat>.+?)(\.whl|\.dist-info)$""", re.VERBOSE).match diff --git a/wheel/metadata.py b/wheel/metadata.py index 29638e7..75dce67 100644 --- a/wheel/metadata.py +++ b/wheel/metadata.py @@ -255,7 +255,7 @@ def generate_requirements(extras_require): if extra: yield ('Provides-Extra', extra) if condition: - condition += " and " + condition = "(" + condition + ") and " condition += "extra == '%s'" % extra if condition: condition = '; ' + condition
pypa/wheel
d120bf93a6ef38a8eae9580f18878ae8a29b4787
diff --git a/tests/test_install.py b/tests/test_install.py index 60b04e8..42db4f0 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -100,3 +100,9 @@ def test_install(): def test_install_tool(): """Slightly improve coverage of wheel.install""" wheel.tool.install([TESTWHEEL], force=True, dry_run=True) + + +def test_wheelfile_re(): + # Regression test for #208 + wf = WheelFile('foo-2-py3-none-any.whl') + assert wf.distinfo_name == 'foo-2.dist-info' diff --git a/tests/test_metadata.py b/tests/test_metadata.py new file mode 100644 index 0000000..842d1d3 --- /dev/null +++ b/tests/test_metadata.py @@ -0,0 +1,25 @@ +from wheel.metadata import generate_requirements + + +def test_generate_requirements(): + extras_require = { + 'test': ['ipykernel', 'ipython', 'mock'], + 'test:python_version == "3.3"': ['pytest<3.3.0'], + 'test:python_version >= "3.4" or python_version == "2.7"': ['pytest'], + } + expected_metadata = [ + ('Provides-Extra', + 'test'), + ('Requires-Dist', + "ipykernel; extra == 'test'"), + ('Requires-Dist', + "ipython; extra == 'test'"), + ('Requires-Dist', + "mock; extra == 'test'"), + ('Requires-Dist', + 'pytest (<3.3.0); (python_version == "3.3") and extra == \'test\''), + ('Requires-Dist', + 'pytest; (python_version >= "3.4" or python_version == "2.7") and extra == \'test\''), + ] + generated_metadata = sorted(set(generate_requirements(extras_require))) + assert generated_metadata == expected_metadata
"and extra" breaks environment marker logic In pypa/setuptools#1242, we discovered that wheel is allegedly simply appending ` and extra=="..."`, which will break the logic when the existing environment marker contains or expressions.
0.0
d120bf93a6ef38a8eae9580f18878ae8a29b4787
[ "tests/test_install.py::test_wheelfile_re", "tests/test_metadata.py::test_generate_requirements" ]
[ "tests/test_install.py::test_compatibility_tags", "tests/test_install.py::test_pick_best", "tests/test_install.py::test_install", "tests/test_install.py::test_install_tool" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-12-30 21:43:50+00:00
mit
5,016
pypa__wheel-250
diff --git a/wheel/metadata.py b/wheel/metadata.py index 4fa17cd..c6a3736 100644 --- a/wheel/metadata.py +++ b/wheel/metadata.py @@ -16,7 +16,10 @@ EXTRA_RE = re.compile("""^(?P<package>.*?)(;\s*(?P<condition>.*?)(extra == '(?P< def requires_to_requires_dist(requirement): - """Compose the version predicates for requirement in PEP 345 fashion.""" + """Return the version specifier for a requirement in PEP 345/566 fashion.""" + if requirement.url: + return " @ " + requirement.url + requires_dist = [] for op, ver in requirement.specs: requires_dist.append(op + ver)
pypa/wheel
f3855494f20724f1ae844631d08e34367e977661
diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 3421430..78fe40d 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -9,6 +9,7 @@ def test_pkginfo_to_metadata(tmpdir): ('Provides-Extra', 'test'), ('Provides-Extra', 'signatures'), ('Provides-Extra', 'faster-signatures'), + ('Requires-Dist', "pip @ https://github.com/pypa/pip/archive/1.3.1.zip"), ('Requires-Dist', "ed25519ll; extra == 'faster-signatures'"), ('Requires-Dist', "keyring; extra == 'signatures'"), ('Requires-Dist', "keyrings.alt; extra == 'signatures'"), @@ -28,6 +29,8 @@ Provides-Extra: faster-signatures""") egg_info_dir = tmpdir.ensure_dir('test.egg-info') egg_info_dir.join('requires.txt').write("""\ +pip@https://github.com/pypa/pip/archive/1.3.1.zip + [faster-signatures] ed25519ll
How should a PEP 508 requirement with an URL specifier be handled? Starting with pip 10.0, requirements with [URL specifiers](https://www.python.org/dev/peps/pep-0508/#examples) are now supported (as replacement for dependency links). With the following sample project' `setup.py`: ```python from setuptools import setup setup(name='projecta', version='42', install_requires=''' lazyImport@git+https://gitlab.com/KOLANICH1/lazyImport.py.git#egg=lazyImport-dev ''') ``` Installing from source work, but looking at the generated wheel metadata: ```shell > python setup.py -q bdist_wheel && unzip -p dist/projecta-42-py3-none-any.whl '*/METADATA' Metadata-Version: 2.1 Name: projecta Version: 42 Summary: Description! Home-page: UNKNOWN Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Platform: UNKNOWN Requires-Dist: lazyImport UNKNOWN ``` It works with the following patch: ```diff tests/test_metadata.py | 3 +++ wheel/metadata.py | 2 ++ 2 files changed, 5 insertions(+) diff --git i/tests/test_metadata.py w/tests/test_metadata.py index 3421430..2390e98 100644 --- i/tests/test_metadata.py +++ w/tests/test_metadata.py @@ -9,6 +9,7 @@ def test_pkginfo_to_metadata(tmpdir): ('Provides-Extra', 'test'), ('Provides-Extra', 'signatures'), ('Provides-Extra', 'faster-signatures'), + ('Requires-Dist', "pip @ https://github.com/pypa/pip/archive/1.3.1.zip"), ('Requires-Dist', "ed25519ll; extra == 'faster-signatures'"), ('Requires-Dist', "keyring; extra == 'signatures'"), ('Requires-Dist', "keyrings.alt; extra == 'signatures'"), @@ -28,6 +29,8 @@ def test_pkginfo_to_metadata(tmpdir): egg_info_dir = tmpdir.ensure_dir('test.egg-info') egg_info_dir.join('requires.txt').write("""\ +pip@ https://github.com/pypa/pip/archive/1.3.1.zip + [faster-signatures] ed25519ll diff --git i/wheel/metadata.py w/wheel/metadata.py index 4fa17cd..5b03e3e 100644 --- i/wheel/metadata.py +++ w/wheel/metadata.py @@ -17,6 +17,8 @@ def requires_to_requires_dist(requirement): """Compose the version predicates for requirement in PEP 345 fashion.""" + if requirement.url: + return " @ " + requirement.url requires_dist = [] for op, ver in requirement.specs: requires_dist.append(op + ver) ``` ```shell > python setup.py -q bdist_wheel && unzip -p dist/projecta-42-py3-none-any.whl '*/METADATA' Metadata-Version: 2.1 Name: projecta Version: 42 Summary: Description! Home-page: UNKNOWN Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Platform: UNKNOWN Requires-Dist: lazyImport @ git+https://gitlab.com/KOLANICH1/lazyImport.py.git UNKNOWN ``` Unfortunately, this is technically not valid [PEP 345](https://www.python.org/dev/peps/pep-0345/#requires-dist-multiple-use) metadata.
0.0
f3855494f20724f1ae844631d08e34367e977661
[ "tests/test_metadata.py::test_pkginfo_to_metadata" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-08-28 20:35:56+00:00
mit
5,017
pypa__wheel-489
diff --git a/src/wheel/bdist_wheel.py b/src/wheel/bdist_wheel.py index 4754fd1..7fcf4a3 100644 --- a/src/wheel/bdist_wheel.py +++ b/src/wheel/bdist_wheel.py @@ -15,6 +15,7 @@ import sysconfig import warnings from collections import OrderedDict from email.generator import BytesGenerator, Generator +from email.policy import EmailPolicy from glob import iglob from io import BytesIO from shutil import rmtree @@ -534,8 +535,13 @@ class bdist_wheel(Command): adios(dependency_links_path) pkg_info_path = os.path.join(distinfo_path, "METADATA") + serialization_policy = EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) with open(pkg_info_path, "w", encoding="utf-8") as out: - Generator(out, mangle_from_=False, maxheaderlen=0).flatten(pkg_info) + Generator(out, policy=serialization_policy).flatten(pkg_info) for license_path in self.license_paths: filename = os.path.basename(license_path)
pypa/wheel
daeb157c8207b1459fc7baa5f234c165a7a5faf4
diff --git a/tests/test_bdist_wheel.py b/tests/test_bdist_wheel.py index 531d9e6..5a6db16 100644 --- a/tests/test_bdist_wheel.py +++ b/tests/test_bdist_wheel.py @@ -72,6 +72,45 @@ def test_unicode_record(wheel_paths): assert "åäö_日本語.py".encode() in record +UTF8_PKG_INFO = """\ +Metadata-Version: 2.1 +Name: helloworld +Version: 42 +Author-email: "John X. Ãørçeč" <[email protected]>, Γαμα קּ 東 <[email protected]> + + +UTF-8 描述 説明 +""" + + +def test_preserve_unicode_metadata(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + egginfo = tmp_path / "dummy_dist.egg-info" + distinfo = tmp_path / "dummy_dist.dist-info" + + egginfo.mkdir() + (egginfo / "PKG-INFO").write_text(UTF8_PKG_INFO, encoding="utf-8") + (egginfo / "dependency_links.txt").touch() + + class simpler_bdist_wheel(bdist_wheel): + """Avoid messing with setuptools/distutils internals""" + + def __init__(self): + pass + + @property + def license_paths(self): + return [] + + cmd_obj = simpler_bdist_wheel() + cmd_obj.egg2dist(egginfo, distinfo) + + metadata = (distinfo / "METADATA").read_text(encoding="utf-8") + assert 'Author-email: "John X. Ãørçeč"' in metadata + assert "Γαμα קּ 東 " in metadata + assert "UTF-8 描述 説明" in metadata + + def test_licenses_default(dummy_dist, monkeypatch, tmpdir): monkeypatch.chdir(dummy_dist) subprocess.check_call(
Incorrect summary in produced wheels starting from 0.38.1 See https://pypi.org/search/?q=%3D%3Futf-8%3Fq%3F All wheels produced after 2022/11/04 (0.38.1 release date) have incorrect summaries.
0.0
daeb157c8207b1459fc7baa5f234c165a7a5faf4
[ "tests/test_bdist_wheel.py::test_preserve_unicode_metadata" ]
[ "tests/test_bdist_wheel.py::test_no_scripts", "tests/test_bdist_wheel.py::test_unicode_record", "tests/test_bdist_wheel.py::test_licenses_default", "tests/test_bdist_wheel.py::test_licenses_deprecated", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*\\n", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*,", "tests/test_bdist_wheel.py::test_licenses_override[setup.py-from", "tests/test_bdist_wheel.py::test_licenses_disabled", "tests/test_bdist_wheel.py::test_build_number", "tests/test_bdist_wheel.py::test_limited_abi", "tests/test_bdist_wheel.py::test_build_from_readonly_tree", "tests/test_bdist_wheel.py::test_compression[stored]", "tests/test_bdist_wheel.py::test_compression[deflated]", "tests/test_bdist_wheel.py::test_wheelfile_line_endings", "tests/test_bdist_wheel.py::test_unix_epoch_timestamps", "tests/test_bdist_wheel.py::test_get_abi_tag_old", "tests/test_bdist_wheel.py::test_get_abi_tag_new" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-11-09 18:30:13+00:00
mit
5,018
pypa__wheel-514
diff --git a/docs/news.rst b/docs/news.rst index 4961729..2fbe136 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -4,6 +4,7 @@ Release Notes **UNRELEASED** - Updated vendored ``packaging`` to 23.0 +- ``wheel unpack`` now preserves the executable attribute of extracted files - Fixed spaces in platform names not being converted to underscores (PR by David Tucker) - Fixed ``RECORD`` files in generated wheels missing the regular file attribute - Fixed ``DeprecationWarning`` about the use of the deprecated ``pkg_resources`` API diff --git a/src/wheel/cli/unpack.py b/src/wheel/cli/unpack.py index c6409d4..d48840e 100644 --- a/src/wheel/cli/unpack.py +++ b/src/wheel/cli/unpack.py @@ -18,6 +18,13 @@ def unpack(path: str, dest: str = ".") -> None: namever = wf.parsed_filename.group("namever") destination = Path(dest) / namever print(f"Unpacking to: {destination}...", end="", flush=True) - wf.extractall(destination) + for zinfo in wf.filelist: + wf.extract(zinfo, destination) + + # Set permissions to the same values as they were set in the archive + # We have to do this manually due to + # https://github.com/python/cpython/issues/59999 + permissions = zinfo.external_attr >> 16 & 0o777 + destination.joinpath(zinfo.filename).chmod(permissions) print("OK")
pypa/wheel
26d2e0d18830b31f42c67715b68504b50e13021c
diff --git a/tests/cli/test_unpack.py b/tests/cli/test_unpack.py index e6a38bb..ae584af 100644 --- a/tests/cli/test_unpack.py +++ b/tests/cli/test_unpack.py @@ -1,6 +1,12 @@ from __future__ import annotations +import platform +import stat + +import pytest + from wheel.cli.unpack import unpack +from wheel.wheelfile import WheelFile def test_unpack(wheel_paths, tmp_path): @@ -10,3 +16,21 @@ def test_unpack(wheel_paths, tmp_path): """ for wheel_path in wheel_paths: unpack(wheel_path, str(tmp_path)) + + [email protected]( + platform.system() == "Windows", reason="Windows does not support the executable bit" +) +def test_unpack_executable_bit(tmp_path): + wheel_path = tmp_path / "test-1.0-py3-none-any.whl" + script_path = tmp_path / "script" + script_path.write_bytes(b"test script") + script_path.chmod(0o755) + with WheelFile(wheel_path, "w") as wf: + wf.write(str(script_path), "nested/script") + + script_path.unlink() + script_path = tmp_path / "test-1.0" / "nested" / "script" + unpack(str(wheel_path), str(tmp_path)) + assert not script_path.is_dir() + assert stat.S_IMODE(script_path.stat().st_mode) == 0o755
wheel unpack doesn't preserve permissions I expected `wheel unpack` + `wheel pack` to result in similarly functioning wheels. However, `wheel unpack` doesn't seem to preserve permissions. That is, there's nothing in `wheel` that does this kind of thing: https://github.com/pypa/pip/blob/852deddb9c14afdb780e77ea28c2fa6d29f8c2e1/src/pip/_internal/utils/unpacking.py#L143 Is this intentional?
0.0
26d2e0d18830b31f42c67715b68504b50e13021c
[ "tests/cli/test_unpack.py::test_unpack_executable_bit" ]
[ "tests/cli/test_unpack.py::test_unpack" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-03-13 16:29:09+00:00
mit
5,019
pypa__wheel-528
diff --git a/.cirrus.yml b/.cirrus.yml index eed71be..7df7d08 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -1,5 +1,5 @@ freebsd_instance: - image_family: freebsd-13-0-snap + image_family: freebsd-13-1 test_task: only_if: "$CIRRUS_BRANCH == 'main' || $CIRRUS_PR != ''" diff --git a/docs/news.rst b/docs/news.rst index 0ddc562..97d7b65 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -1,6 +1,11 @@ Release Notes ============= +**UNRELEASED** + +- Added full support of the build tag syntax to ``wheel tags`` (you can now set a build + tag like ``123mytag``) + **0.40.0 (2023-03-14)** - Added a ``wheel tags`` command to modify tags on an existing wheel diff --git a/src/wheel/cli/__init__.py b/src/wheel/cli/__init__.py index fa1f10b..c09f839 100644 --- a/src/wheel/cli/__init__.py +++ b/src/wheel/cli/__init__.py @@ -7,6 +7,7 @@ from __future__ import annotations import argparse import os import sys +from argparse import ArgumentTypeError class WheelError(Exception): @@ -56,6 +57,15 @@ def version_f(args): print("wheel %s" % __version__) +def parse_build_tag(build_tag: str) -> str: + if not build_tag[0].isdigit(): + raise ArgumentTypeError("build tag must begin with a digit") + elif "-" in build_tag: + raise ArgumentTypeError("invalid character ('-') in build tag") + + return build_tag + + TAGS_HELP = """\ Make a new wheel with given tags. Any tags unspecified will remain the same. Starting the tags with a "+" will append to the existing tags. Starting with a @@ -117,7 +127,7 @@ def parser(): "--platform-tag", metavar="TAG", help="Specify a platform tag(s)" ) tags_parser.add_argument( - "--build", type=int, metavar="NUMBER", help="Specify a build number" + "--build", type=parse_build_tag, metavar="BUILD", help="Specify a build tag" ) tags_parser.set_defaults(func=tags_f) diff --git a/src/wheel/cli/tags.py b/src/wheel/cli/tags.py index 0ea0f44..b9094d7 100644 --- a/src/wheel/cli/tags.py +++ b/src/wheel/cli/tags.py @@ -27,7 +27,7 @@ def tags( python_tags: str | None = None, abi_tags: str | None = None, platform_tags: str | None = None, - build_number: int | None = None, + build_tag: str | None = None, remove: bool = False, ) -> str: """Change the tags on a wheel file. @@ -41,7 +41,7 @@ def tags( :param python_tags: The Python tags to set :param abi_tags: The ABI tags to set :param platform_tags: The platform tags to set - :param build_number: The build number to set + :param build_tag: The build tag to set :param remove: Remove the original wheel """ with WheelFile(wheel, "r") as f: @@ -56,7 +56,7 @@ def tags( original_abi_tags = f.parsed_filename.group("abi").split(".") original_plat_tags = f.parsed_filename.group("plat").split(".") - tags, existing_build_number = read_tags(wheel_info) + tags, existing_build_tag = read_tags(wheel_info) impls = {tag.split("-")[0] for tag in tags} abivers = {tag.split("-")[1] for tag in tags} @@ -76,16 +76,16 @@ def tags( ) raise AssertionError(msg) - if existing_build_number != build: + if existing_build_tag != build: msg = ( f"Incorrect filename '{build}' " - "& *.dist-info/WHEEL '{existing_build_number}' build numbers" + f"& *.dist-info/WHEEL '{existing_build_tag}' build numbers" ) raise AssertionError(msg) # Start changing as needed - if build_number is not None: - build = str(build_number) + if build_tag is not None: + build = build_tag final_python_tags = sorted(_compute_tags(original_python_tags, python_tags)) final_abi_tags = sorted(_compute_tags(original_abi_tags, abi_tags))
pypa/wheel
37bc83a2d8e733c3b51d440f685b3917bf617f6d
diff --git a/tests/cli/test_tags.py b/tests/cli/test_tags.py index 630c903..2454149 100644 --- a/tests/cli/test_tags.py +++ b/tests/cli/test_tags.py @@ -1,12 +1,13 @@ from __future__ import annotations import shutil +import sys from pathlib import Path from zipfile import ZipFile import pytest -from wheel.cli import parser +from wheel.cli import main, parser from wheel.cli.tags import tags from wheel.wheelfile import WheelFile @@ -110,20 +111,37 @@ def test_plat_tags(wheelpath): assert TESTWHEEL_NAME == newname -def test_build_number(wheelpath): - newname = tags(str(wheelpath), build_number=1) - assert TESTWHEEL_NAME.replace("-py2", "-1-py2") == newname +def test_build_tag(wheelpath): + newname = tags(str(wheelpath), build_tag="1bah") + assert TESTWHEEL_NAME.replace("-py2", "-1bah-py2") == newname output_file = wheelpath.parent / newname assert output_file.exists() output_file.unlink() [email protected]( + "build_tag, error", + [ + pytest.param("foo", "build tag must begin with a digit", id="digitstart"), + pytest.param("1-f", "invalid character ('-') in build tag", id="hyphen"), + ], +) +def test_invalid_build_tag(wheelpath, build_tag, error, monkeypatch, capsys): + monkeypatch.setattr(sys, "argv", [sys.argv[0], "tags", "--build", build_tag]) + with pytest.raises(SystemExit) as exc: + main() + + _, err = capsys.readouterr() + assert exc.value.args[0] == 2 + assert f"error: argument --build: {error}" in err + + def test_multi_tags(wheelpath): newname = tags( str(wheelpath), platform_tags="linux_x86_64", python_tags="+py4", - build_number=1, + build_tag="1", ) assert "test-1.0-1-py2.py3.py4-none-linux_x86_64.whl" == newname
Please allow full Python build tag syntax, including non-numeric data Python defines build tag nomenclature that would work out very well for preparing builds for a release, except that many tools, like `setuptool` fail to generate build tags, even though their syntax describes that it's possible. Fortunately, `wheel` just introduced `wheel tags --build` (thank you for that), but only supports numeric build numbers, which provides limited usability. Here's Python's description of the wheel naming nomenclature: https://packaging.python.org/en/latest/specifications/binary-distribution-format/#file-format , which looks like this: {distribution}-{version}(-{build tag})?-{python tag}-{abi tag}-{platform tag}.whl > Optional build number. Must start with a digit. ... two-item tuple with the first item being the initial digits as an int, and the second item being the remainder of the tag as a str Just for completeness, `setuptools` describe their syntax here. They confirmed that it's eggs that are deprecated, not build tags syntax, which simply doesn't work. https://setuptools.pypa.io/en/latest/deprecated/commands.html#release-tagging-options What I have been doing since I was able to update to `wheel` version 0.40.0 is building a wheel package and then using wheel tags --build 123 dist\abc-4.5.6-py3-none-any.whl , and it yields `abc-4.5.6-123-py3-none-any.whl`. This is great, but when CI runs against feature branches, there is no way to qualify builds with a branch name, so packages are being produced on a feature branch may appear more stable (i.e. greater build number) once they are downloaded by QA, but they likely to be far from it, being it a feature branch. It would be great if `wheel` allowed the string component of the Python build tag. This way packages built in feature branches can be easily distinguished from those built on main or release branches. NOTE: One important thing I want to mention is that build tags in this context are not intended for production package repositories, which is how many of these discussions are interpreted, but rather as a measure of a build maturity before some release, making packages that increase in quality/features with increasing build numbers. Artifactory is a good example of this - not a production repository, but a development one.
0.0
37bc83a2d8e733c3b51d440f685b3917bf617f6d
[ "tests/cli/test_tags.py::test_build_tag", "tests/cli/test_tags.py::test_invalid_build_tag[digitstart]", "tests/cli/test_tags.py::test_invalid_build_tag[hyphen]", "tests/cli/test_tags.py::test_multi_tags" ]
[ "tests/cli/test_tags.py::test_tags_no_args", "tests/cli/test_tags.py::test_python_tags", "tests/cli/test_tags.py::test_abi_tags", "tests/cli/test_tags.py::test_plat_tags", "tests/cli/test_tags.py::test_tags_command", "tests/cli/test_tags.py::test_tags_command_del", "tests/cli/test_tags.py::test_permission_bits" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-04-13 21:46:22+00:00
mit
5,020
pypa__wheel-529
diff --git a/docs/news.rst b/docs/news.rst index 97d7b65..543b3bc 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -5,6 +5,8 @@ Release Notes - Added full support of the build tag syntax to ``wheel tags`` (you can now set a build tag like ``123mytag``) +- Fixed warning on Python 3.12 about ``onerror`` deprecation. (PR by Henry Schreiner) +- Support testing on Python 3.12 betas (PR by Ewout ter Hoeven) **0.40.0 (2023-03-14)** diff --git a/src/wheel/bdist_wheel.py b/src/wheel/bdist_wheel.py index cb9c19f..604d5d6 100644 --- a/src/wheel/bdist_wheel.py +++ b/src/wheel/bdist_wheel.py @@ -131,7 +131,10 @@ def safer_version(version): def remove_readonly(func, path, excinfo): - print(str(excinfo[1])) + remove_readonly_exc(func, path, excinfo[1]) + + +def remove_readonly_exc(func, path, exc): os.chmod(path, stat.S_IWRITE) func(path) @@ -416,7 +419,10 @@ class bdist_wheel(Command): if not self.keep_temp: log.info(f"removing {self.bdist_dir}") if not self.dry_run: - rmtree(self.bdist_dir, onerror=remove_readonly) + if sys.version_info < (3, 12): + rmtree(self.bdist_dir, onerror=remove_readonly) + else: + rmtree(self.bdist_dir, onexc=remove_readonly_exc) def write_wheelfile( self, wheelfile_base, generator="bdist_wheel (" + wheel_version + ")"
pypa/wheel
e18afcfb218a2b339655abe486bf089c20886686
diff --git a/tests/test_bdist_wheel.py b/tests/test_bdist_wheel.py index d32a1fb..d202469 100644 --- a/tests/test_bdist_wheel.py +++ b/tests/test_bdist_wheel.py @@ -6,11 +6,17 @@ import stat import subprocess import sys import sysconfig +from unittest.mock import Mock from zipfile import ZipFile import pytest -from wheel.bdist_wheel import bdist_wheel, get_abi_tag +from wheel.bdist_wheel import ( + bdist_wheel, + get_abi_tag, + remove_readonly, + remove_readonly_exc, +) from wheel.vendored.packaging import tags from wheel.wheelfile import WheelFile @@ -296,3 +302,30 @@ def test_platform_with_space(dummy_dist, monkeypatch): subprocess.check_call( [sys.executable, "setup.py", "bdist_wheel", "--plat-name", "isilon onefs"] ) + + +def test_rmtree_readonly(monkeypatch, tmp_path, capsys): + """Verify onerr works as expected""" + + bdist_dir = tmp_path / "with_readonly" + bdist_dir.mkdir() + some_file = bdist_dir.joinpath("file.txt") + some_file.touch() + some_file.chmod(stat.S_IREAD) + + expected_count = 1 if sys.platform.startswith("win") else 0 + + if sys.version_info < (3, 12): + count_remove_readonly = Mock(side_effect=remove_readonly) + shutil.rmtree(bdist_dir, onerror=count_remove_readonly) + assert count_remove_readonly.call_count == expected_count + else: + count_remove_readonly_exc = Mock(side_effect=remove_readonly_exc) + shutil.rmtree(bdist_dir, onexc=count_remove_readonly_exc) + assert count_remove_readonly_exc.call_count == expected_count + + assert not bdist_dir.is_dir() + + if expected_count: + captured = capsys.readouterr() + assert "file.txt" in captured.stdout
onerror now producing warnings in Python 3.12 latest alpha Using `onerror` is producing warnings in the latest Python 3.12 alpha. I believe it's used here: https://github.com/pypa/wheel/blob/c87e6ed82b58b41b258a3e8c852af8bc1817bb00/src/wheel/bdist_wheel.py#L419 And deprecated here: https://github.com/python/cpython/pull/102829 & changelog: https://docs.python.org/zh-cn/3.12/whatsnew/3.12.html - to be removed in 3.14. (It's breaking my tests where I have warnings as errors on)
0.0
e18afcfb218a2b339655abe486bf089c20886686
[ "tests/test_bdist_wheel.py::test_no_scripts", "tests/test_bdist_wheel.py::test_unicode_record", "tests/test_bdist_wheel.py::test_preserve_unicode_metadata", "tests/test_bdist_wheel.py::test_licenses_default", "tests/test_bdist_wheel.py::test_licenses_deprecated", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*\\n", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*,", "tests/test_bdist_wheel.py::test_licenses_override[setup.py-from", "tests/test_bdist_wheel.py::test_licenses_disabled", "tests/test_bdist_wheel.py::test_build_number", "tests/test_bdist_wheel.py::test_limited_abi", "tests/test_bdist_wheel.py::test_build_from_readonly_tree", "tests/test_bdist_wheel.py::test_compression[stored]", "tests/test_bdist_wheel.py::test_compression[deflated]", "tests/test_bdist_wheel.py::test_wheelfile_line_endings", "tests/test_bdist_wheel.py::test_unix_epoch_timestamps", "tests/test_bdist_wheel.py::test_get_abi_tag_old", "tests/test_bdist_wheel.py::test_get_abi_tag_new", "tests/test_bdist_wheel.py::test_platform_with_space", "tests/test_bdist_wheel.py::test_rmtree_readonly" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-04-18 21:20:48+00:00
mit
5,021
pypa__wheel-552
diff --git a/docs/news.rst b/docs/news.rst index a76eb6c..df991f2 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -5,6 +5,7 @@ Release Notes - Fixed naming of the ``data_dir`` directory in the presence of local version segment given via ``egg_info.tag_build`` (PR by Anderson Bravalheri) +- Fixed version specifiers in ``Requires-Dist`` being wrapped in parentheses **0.41.0 (2023-07-22)** diff --git a/src/wheel/metadata.py b/src/wheel/metadata.py index b391c96..ddcb90e 100644 --- a/src/wheel/metadata.py +++ b/src/wheel/metadata.py @@ -92,7 +92,7 @@ def requires_to_requires_dist(requirement: Requirement) -> str: requires_dist.append(spec.operator + spec.version) if requires_dist: - return " (" + ",".join(sorted(requires_dist)) + ")" + return " " + ",".join(sorted(requires_dist)) else: return ""
pypa/wheel
fbd385c4eceb6ad0f95a58af1b0996ad8be062da
diff --git a/tests/test_metadata.py b/tests/test_metadata.py index e267f02..8480732 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -22,11 +22,11 @@ def test_pkginfo_to_metadata(tmp_path): ("Provides-Extra", "faster-signatures"), ("Requires-Dist", "ed25519ll ; extra == 'faster-signatures'"), ("Provides-Extra", "rest"), - ("Requires-Dist", "docutils (>=0.8) ; extra == 'rest'"), + ("Requires-Dist", "docutils >=0.8 ; extra == 'rest'"), ("Requires-Dist", "keyring ; extra == 'signatures'"), ("Requires-Dist", "keyrings.alt ; extra == 'signatures'"), ("Provides-Extra", "test"), - ("Requires-Dist", "pytest (>=3.0.0) ; extra == 'test'"), + ("Requires-Dist", "pytest >=3.0.0 ; extra == 'test'"), ("Requires-Dist", "pytest-cov ; extra == 'test'"), ]
Parens in metadata version specifiers The [packaging spec](https://packaging.python.org/en/latest/specifications/core-metadata/#requires-dist-multiple-use) says that Requires-Dist specifiers should not have parens, but wheel add the parens [here](https://github.com/pypa/wheel/blob/main/src/wheel/metadata.py#L95). I ran into this problem because of a super edge case installing a wheel that has exact identity (===) dependencies. Pip allows any character after an the identity specifier, which means that it also captures the closing paren and so a requirement like `requests (===1.2.3)` won't match. The identity specifiers are used for prereleases and some other special-case version specifiers.
0.0
fbd385c4eceb6ad0f95a58af1b0996ad8be062da
[ "tests/test_metadata.py::test_pkginfo_to_metadata" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-08-05 13:21:47+00:00
mit
5,022
pypa__wheel-560
diff --git a/docs/news.rst b/docs/news.rst index 6bd84f3..9f65f03 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -1,6 +1,11 @@ Release Notes ============= +**UNRELEASED** + +- Fixed platform tag detection for GraalPy and 32-bit python running on an aarch64 + kernel (PR by Matthieu Darbois) + **0.41.1 (2023-08-05)** - Fixed naming of the ``data_dir`` directory in the presence of local version segment diff --git a/src/wheel/bdist_wheel.py b/src/wheel/bdist_wheel.py index c385ebd..3ae01b3 100644 --- a/src/wheel/bdist_wheel.py +++ b/src/wheel/bdist_wheel.py @@ -10,6 +10,7 @@ import os import re import shutil import stat +import struct import sys import sysconfig import warnings @@ -57,6 +58,10 @@ setuptools_major_version = int(setuptools.__version__.split(".")[0]) PY_LIMITED_API_PATTERN = r"cp3\d" +def _is_32bit_interpreter(): + return struct.calcsize("P") == 4 + + def python_tag(): return f"py{sys.version_info[0]}" @@ -66,9 +71,15 @@ def get_platform(archive_root): result = sysconfig.get_platform() if result.startswith("macosx") and archive_root is not None: result = calculate_macosx_platform_tag(archive_root, result) - elif result == "linux-x86_64" and sys.maxsize == 2147483647: - # pip pull request #3497 - result = "linux-i686" + elif _is_32bit_interpreter(): + if result == "linux-x86_64": + # pip pull request #3497 + result = "linux-i686" + elif result == "linux-aarch64": + # packaging pull request #234 + # TODO armv8l, packaging pull request #690 => this did not land + # in pip/packaging yet + result = "linux-armv7l" return result.replace("-", "_") @@ -300,11 +311,13 @@ class bdist_wheel(Command): # modules, use the default platform name. plat_name = get_platform(self.bdist_dir) - if ( - plat_name in ("linux-x86_64", "linux_x86_64") - and sys.maxsize == 2147483647 - ): - plat_name = "linux_i686" + if _is_32bit_interpreter(): + if plat_name in ("linux-x86_64", "linux_x86_64"): + plat_name = "linux_i686" + if plat_name in ("linux-aarch64", "linux_aarch64"): + # TODO armv8l, packaging pull request #690 => this did not land + # in pip/packaging yet + plat_name = "linux_armv7l" plat_name = ( plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
pypa/wheel
2bf5bb07eed8a5844cee5d5ceef55934146b6981
diff --git a/tests/test_bdist_wheel.py b/tests/test_bdist_wheel.py index b7c04b2..ee664f9 100644 --- a/tests/test_bdist_wheel.py +++ b/tests/test_bdist_wheel.py @@ -3,6 +3,7 @@ from __future__ import annotations import os.path import shutil import stat +import struct import subprocess import sys import sysconfig @@ -11,6 +12,7 @@ from unittest.mock import Mock from zipfile import ZipFile import pytest +import setuptools from wheel.bdist_wheel import ( bdist_wheel, @@ -385,3 +387,17 @@ def test_data_dir_with_tag_build(monkeypatch, tmp_path): "test-1.0.dist-info/WHEEL", ): assert not_expected not in entries + + [email protected]( + "reported,expected", + [("linux-x86_64", "linux_i686"), ("linux-aarch64", "linux_armv7l")], +) +def test_platform_linux32(reported, expected, monkeypatch): + monkeypatch.setattr(struct, "calcsize", lambda x: 4) + dist = setuptools.Distribution() + cmd = bdist_wheel(dist) + cmd.plat_name = reported + cmd.root_is_pure = False + _, _, actual = cmd.get_tag() + assert actual == expected diff --git a/tests/test_macosx_libfile.py b/tests/test_macosx_libfile.py index fed3ebb..ef8dc96 100644 --- a/tests/test_macosx_libfile.py +++ b/tests/test_macosx_libfile.py @@ -1,9 +1,11 @@ from __future__ import annotations import os -import sys +import struct import sysconfig +import pytest + from wheel.bdist_wheel import get_platform from wheel.macosx_libfile import extract_macosx_min_system_version @@ -214,7 +216,11 @@ class TestGetPlatformMacosx: assert get_platform(dylib_dir) == "macosx_11_0_x86_64" -def test_get_platform_linux(monkeypatch): - monkeypatch.setattr(sysconfig, "get_platform", return_factory("linux-x86_64")) - monkeypatch.setattr(sys, "maxsize", 2147483647) - assert get_platform(None) == "linux_i686" [email protected]( + "reported,expected", + [("linux-x86_64", "linux_i686"), ("linux-aarch64", "linux_armv7l")], +) +def test_get_platform_linux32(reported, expected, monkeypatch): + monkeypatch.setattr(sysconfig, "get_platform", return_factory(reported)) + monkeypatch.setattr(struct, "calcsize", lambda x: 4) + assert get_platform(None) == expected
AssertionError: would build wheel with unsupported tag ('cp38', 'cp38', 'linux_aarch64') Experiencing this error when `pip install` _numpy_ and _cryptography_ in Docker container on Raspberry. While images built in May and June of 2020 worked well. Tried and it didn't work: - downgrading versions of _wheel_ and packages, - vice versa, upgrading _pip_, _wheel_ and packages to the very latest versions - `pip install cryptography --no-binary cryptography` Maybe it is an _arm64_ issue. For instance, _cryptography_ doesn't list this platform as supported https://cryptography.io/en/latest/installation/#build-on-linux --- **Workaround** ```shell pip install -e git+https://github.com/pyca/cryptography.git#egg=cryptography ``` --- **Details** ```shell File "/tmp/pip-build-env-n8ueeulb/overlay/lib/python3.8/site-packages/wheel/bdist_wheel.py", line 278, in get_tag assert tag in supported_tags, "would build wheel with unsupported tag {}".format(tag) AssertionError: would build wheel with unsupported tag ('cp38', 'cp38', 'linux_aarch64') ... ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly ``` OS : Raspbian GNU/Linux 10 (buster) Docker: 19.03.12 Base: python:3.8-buster
0.0
2bf5bb07eed8a5844cee5d5ceef55934146b6981
[ "tests/test_bdist_wheel.py::test_platform_linux32[linux-x86_64-linux_i686]", "tests/test_bdist_wheel.py::test_platform_linux32[linux-aarch64-linux_armv7l]", "tests/test_macosx_libfile.py::test_get_platform_linux32[linux-x86_64-linux_i686]", "tests/test_macosx_libfile.py::test_get_platform_linux32[linux-aarch64-linux_armv7l]" ]
[ "tests/test_bdist_wheel.py::test_no_scripts", "tests/test_bdist_wheel.py::test_unicode_record", "tests/test_bdist_wheel.py::test_preserve_unicode_metadata", "tests/test_bdist_wheel.py::test_licenses_default", "tests/test_bdist_wheel.py::test_licenses_deprecated", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*\\n", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*,", "tests/test_bdist_wheel.py::test_licenses_override[setup.py-from", "tests/test_bdist_wheel.py::test_licenses_disabled", "tests/test_bdist_wheel.py::test_build_number", "tests/test_bdist_wheel.py::test_limited_abi", "tests/test_bdist_wheel.py::test_build_from_readonly_tree", "tests/test_bdist_wheel.py::test_compression[stored]", "tests/test_bdist_wheel.py::test_compression[deflated]", "tests/test_bdist_wheel.py::test_wheelfile_line_endings", "tests/test_bdist_wheel.py::test_unix_epoch_timestamps", "tests/test_bdist_wheel.py::test_get_abi_tag_old", "tests/test_bdist_wheel.py::test_get_abi_tag_new", "tests/test_bdist_wheel.py::test_platform_with_space", "tests/test_bdist_wheel.py::test_rmtree_readonly", "tests/test_bdist_wheel.py::test_data_dir_with_tag_build", "tests/test_macosx_libfile.py::test_read_from_dylib", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_simple", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_version_bump", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_information_about_problematic_files_python_version", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_information_about_problematic_files_env_variable", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_bump_platform_tag_by_env_variable", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_bugfix_release_platform_tag", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_warning_on_to_low_env_variable", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_get_platform_bigsur_env", "tests/test_macosx_libfile.py::TestGetPlatformMacosx::test_get_platform_bigsur_platform" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-08-20 13:51:15+00:00
mit
5,023
pypa__wheel-578
diff --git a/docs/news.rst b/docs/news.rst index 9e5488a..05763f4 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -1,6 +1,10 @@ Release Notes ============= +**UNRELEASED** + +- Fixed ABI tag generation for CPython 3.13a1 on Windows (PR by Sam Gross) + **0.41.2 (2023-08-22)** - Fixed platform tag detection for GraalPy and 32-bit python running on an aarch64 diff --git a/src/wheel/bdist_wheel.py b/src/wheel/bdist_wheel.py index 586d876..3879019 100644 --- a/src/wheel/bdist_wheel.py +++ b/src/wheel/bdist_wheel.py @@ -117,8 +117,12 @@ def get_abi_tag(): m = "m" abi = f"{impl}{tags.interpreter_version()}{d}{m}{u}" - elif soabi and impl == "cp": + elif soabi and impl == "cp" and soabi.startswith("cpython"): + # non-Windows abi = "cp" + soabi.split("-")[1] + elif soabi and impl == "cp" and soabi.startswith("cp"): + # Windows + abi = soabi.split("-")[0] elif soabi and impl == "pp": # we want something like pypy36-pp73 abi = "-".join(soabi.split("-")[:2])
pypa/wheel
5960057fd716c84ed84ad592d690138cb4affded
diff --git a/tests/test_bdist_wheel.py b/tests/test_bdist_wheel.py index cebe0a3..7c8fedb 100644 --- a/tests/test_bdist_wheel.py +++ b/tests/test_bdist_wheel.py @@ -287,6 +287,12 @@ def test_unix_epoch_timestamps(dummy_dist, monkeypatch, tmp_path): ) +def test_get_abi_tag_windows(monkeypatch): + monkeypatch.setattr(tags, "interpreter_name", lambda: "cp") + monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313-win_amd64") + assert get_abi_tag() == "cp313" + + def test_get_abi_tag_pypy_old(monkeypatch): monkeypatch.setattr(tags, "interpreter_name", lambda: "pp") monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy36-pp73")
C-extension unable to be built on 3.13a1 (Windows) Hello, I'm one of the maintainers of pygame-ce. I downloaded the recent release of Python 3.13a1 to test if pygame-ce would build against it, and after I commented out all the cython modules (which all failed to build ofc), I got this error: ```py Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\charl\Desktop\pygame-ce\setup.py", line 1051, in <module> setup(**PACKAGEDATA) File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\setuptools\_distutils\core.py", line 185, in setup return run_commands(dist) ^^^^^^^^^^^^^^^^^^ File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\setuptools\_distutils\core.py", line 201, in run_commands dist.run_commands() File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\setuptools\_distutils\dist.py", line 969, in run_commands self.run_command(cmd) File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\setuptools\dist.py", line 989, in run_command super().run_command(command) File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\setuptools\_distutils\dist.py", line 988, in run_command cmd_obj.run() File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\wheel\bdist_wheel.py", line 401, in run impl_tag, abi_tag, plat_tag = self.get_tag() ^^^^^^^^^^^^^^ File "C:\Users\charl\AppData\Local\Programs\Python\Python313\Lib\site-packages\wheel\bdist_wheel.py", line 351, in get_tag tag in supported_tags AssertionError: would build wheel with unsupported tag ('cp313', 'cpwin_amd64', 'win_amd64') ``` I added a print for the supported tags and I got this: ``` [('cp313', 'cp313', 'win_amd64'), ('cp313', 'abi3', 'win_amd64'), ('cp313', 'none', 'win_amd64'), ('cp312', 'abi3', 'win_amd64'), ('cp311', 'abi3', 'win_amd64'), ('cp310', 'abi3', 'win_amd64'), ('cp39', 'abi3', 'win_amd64'), ('cp38', 'abi3', 'win_amd64'), ('cp37', 'abi3', 'win_amd64'), ('cp36', 'abi3', 'win_amd64'), ('cp35', 'abi3', 'win_amd64'), ('cp34', 'abi3', 'win_amd64'), ('cp33', 'abi3', 'win_amd64'), ('cp32', 'abi3', 'win_amd64'), ('py313', 'none', 'win_amd64'), ('py3', 'none', 'win_amd64'), ('py312', 'none', 'win_amd64'), ('py311', 'none', 'win_amd64'), ('py310', 'none', 'win_amd64'), ('py39', 'none', 'win_amd64'), ('py38', 'none', 'win_amd64'), ('py37', 'none', 'win_amd64'), ('py36', 'none', 'win_amd64'), ('py35', 'none', 'win_amd64'), ('py34', 'none', 'win_amd64'), ('py33', 'none', 'win_amd64'), ('py32', 'none', 'win_amd64'), ('py31', 'none', 'win_amd64'), ('py30', 'none', 'win_amd64'), ('cp313', 'none', 'win_amd64'), ('py313', 'none', 'win_amd64'), ('py3', 'none', 'win_amd64'), ('py312', 'none', 'win_amd64'), ('py311', 'none', 'win_amd64'), ('py310', 'none', 'win_amd64'), ('py39', 'none', 'win_amd64'), ('py38', 'none', 'win_amd64'), ('py37', 'none', 'win_amd64'), ('py36', 'none', 'win_amd64'), ('py35', 'none', 'in_amd64')] ``` Since pygame-ce is a C-extension and is not using the limited ABI, the correct abi_tag is "cp313." I tried going into bdist_wheel.py and hardcoding that and the build worked completely. Why has this changed? I looked at the logic to get the wheel tag and noticed that on Python 3.12, `sysconfig.get_config_var("SOABI")` returns `None`, but on Python 3.13a1 `sysconfig.get_config_var("SOABI")` returns `'cp313-win_amd64'`. This causes an invalid abi_tag to be generated and the build won't complete. The only other mention I was able to find of this on the internet was this Chinese forum post with someone unable to install PyQt5 with the same error message- https://ask.csdn.net/questions/8011982 I'm unsure if this would be considered a bug in CPython for the behavior change or a bug in wheel for not accommodating it. I'm putting it here for now.
0.0
5960057fd716c84ed84ad592d690138cb4affded
[ "tests/test_bdist_wheel.py::test_get_abi_tag_windows" ]
[ "tests/test_bdist_wheel.py::test_no_scripts", "tests/test_bdist_wheel.py::test_unicode_record", "tests/test_bdist_wheel.py::test_preserve_unicode_metadata", "tests/test_bdist_wheel.py::test_licenses_default", "tests/test_bdist_wheel.py::test_licenses_deprecated", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*\\n", "tests/test_bdist_wheel.py::test_licenses_override[setup.cfg-[metadata]\\nlicense_files=licenses/*,", "tests/test_bdist_wheel.py::test_licenses_override[setup.py-from", "tests/test_bdist_wheel.py::test_licenses_disabled", "tests/test_bdist_wheel.py::test_build_number", "tests/test_bdist_wheel.py::test_limited_abi", "tests/test_bdist_wheel.py::test_build_from_readonly_tree", "tests/test_bdist_wheel.py::test_compression[stored]", "tests/test_bdist_wheel.py::test_compression[deflated]", "tests/test_bdist_wheel.py::test_wheelfile_line_endings", "tests/test_bdist_wheel.py::test_unix_epoch_timestamps", "tests/test_bdist_wheel.py::test_get_abi_tag_pypy_old", "tests/test_bdist_wheel.py::test_get_abi_tag_pypy_new", "tests/test_bdist_wheel.py::test_get_abi_tag_graalpy", "tests/test_bdist_wheel.py::test_get_abi_tag_fallback", "tests/test_bdist_wheel.py::test_platform_with_space", "tests/test_bdist_wheel.py::test_rmtree_readonly", "tests/test_bdist_wheel.py::test_data_dir_with_tag_build", "tests/test_bdist_wheel.py::test_platform_linux32[linux-x86_64-linux_i686]", "tests/test_bdist_wheel.py::test_platform_linux32[linux-aarch64-linux_armv7l]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-10-19 16:59:32+00:00
mit
5,024
pypiserver__pypiserver-215
diff --git a/pypiserver/manage.py b/pypiserver/manage.py index 70d04b5..8b26e22 100644 --- a/pypiserver/manage.py +++ b/pypiserver/manage.py @@ -1,9 +1,16 @@ -import sys +"""Management operations for pypiserver.""" + +from __future__ import absolute_import, print_function, unicode_literals + +import itertools import os +import sys +from distutils.version import LooseVersion from subprocess import call +import pip + from . import core -import itertools if sys.version_info >= (3, 0): from xmlrpc.client import Server @@ -134,19 +141,64 @@ def find_updates(pkgset, stable_only=True): return need_update +class PipCmd(object): + """Methods for generating pip commands.""" + + @staticmethod + def update_root(pip_version): + """Yield an appropriate root command depending on pip version.""" + # legacy_pip = StrictVersion(pip_version) < StrictVersion('10.0') + legacy_pip = LooseVersion(pip_version) < LooseVersion('10.0') + for part in ('pip', '-q'): + yield part + yield 'install' if legacy_pip else 'download' + + @staticmethod + def update(cmd_root, destdir, pkg_name, pkg_version, + index='https://pypi.org/simple'): + """Yield an update command for pip.""" + for part in cmd_root: + yield part + for part in ('--no-deps', '-i', index, '-d', destdir): + yield part + yield '{}=={}'.format(pkg_name, pkg_version) + + +def update_package(pkg, destdir, dry_run=False): + """Print and optionally execute a package update.""" + print( + "# update {0.pkgname} from {0.replaces.version} to " + "{0.version}".format(pkg) + ) + + cmd = tuple( + PipCmd.update( + PipCmd.update_root(pip.__version__), + destdir or os.path.dirname(pkg.replaces.fn), + pkg.pkgname, + pkg.version + ) + ) + + print("{}\n".format(" ".join(cmd))) + if not dry_run: + call(cmd) + + def update(pkgset, destdir=None, dry_run=False, stable_only=True): + """Print and optionally execute pip update commands. + + :param pkgset: the set of currently available packages + :param str destdir: the destination directory for downloads + :param dry_run: whether commands should be executed (rather than + just being printed) + :param stable_only: whether only stable (non prerelease) updates + should be considered. + """ need_update = find_updates(pkgset, stable_only=stable_only) for pkg in sorted(need_update, key=lambda x: x.pkgname): - sys.stdout.write("# update %s from %s to %s\n" % - (pkg.pkgname, pkg.replaces.version, pkg.version)) - - cmd = ["pip", "-q", "install", "--no-deps", "-i", "https://pypi.org/simple", - "-d", destdir or os.path.dirname(pkg.replaces.fn), - "%s==%s" % (pkg.pkgname, pkg.version)] + update_package(pkg, destdir, dry_run=dry_run) - sys.stdout.write("%s\n\n" % (" ".join(cmd),)) - if not dry_run: - call(cmd) def update_all_packages(roots, destdir=None, dry_run=False, stable_only=True): packages = frozenset(itertools.chain(*[core.listdir(r) for r in roots]))
pypiserver/pypiserver
c86de256fb37ef552abac5c4f3d3cec7a5cb4b3c
diff --git a/tests/test_manage.py b/tests/test_manage.py index 34ea5f4..9735ac6 100755 --- a/tests/test_manage.py +++ b/tests/test_manage.py @@ -1,12 +1,34 @@ -#! /usr/bin/env py.test - -import pytest, py -from pypiserver.core import parse_version, PkgFile, guess_pkgname_and_version -from pypiserver.manage import is_stable_version, build_releases, filter_stable_releases, filter_latest_pkgs +#!/usr/bin/env py.test +"""Tests for manage.py.""" + +from __future__ import absolute_import, print_function, unicode_literals + +try: + from unittest.mock import Mock +except ImportError: + from mock import Mock + +import py +import pytest + +from pypiserver import manage +from pypiserver.core import ( + PkgFile, + guess_pkgname_and_version, + parse_version, +) +from pypiserver.manage import ( + PipCmd, + build_releases, + filter_stable_releases, + filter_latest_pkgs, + is_stable_version, + update_package, +) def touch_files(root, files): - root = py.path.local(root) + root = py.path.local(root) # pylint: disable=no-member for f in files: root.join(f).ensure() @@ -14,7 +36,7 @@ def touch_files(root, files): def pkgfile_from_path(fn): pkgname, version = guess_pkgname_and_version(fn) return PkgFile(pkgname=pkgname, version=version, - root=py.path.local(fn).parts()[1].strpath, + root=py.path.local(fn).parts()[1].strpath, # noqa pylint: disable=no-member fn=fn) @@ -69,3 +91,90 @@ def test_filter_latest_pkgs_case_insensitive(): pkgs = [pkgfile_from_path(x) for x in paths] assert frozenset(filter_latest_pkgs(pkgs)) == frozenset(pkgs[1:]) + + [email protected]('pip_ver, cmd_type', ( + ('10.0.0', 'd'), + ('10.0.0rc10', 'd'), + ('10.0.0b10', 'd'), + ('10.0.0a3', 'd'), + ('10.0.0.dev8', 'd'), + ('10.0.0.dev8', 'd'), + ('18.0', 'd'), + ('9.9.8', 'i'), + ('9.9.8rc10', 'i'), + ('9.9.8b10', 'i'), + ('9.9.8a10', 'i'), + ('9.9.8.dev10', 'i'), + ('9.9', 'i'), +)) +def test_pip_cmd_root(pip_ver, cmd_type): + """Verify correct determination of the command root by pip version.""" + exp_cmd = ( + 'pip', + '-q', + 'install' if cmd_type == 'i' else 'download', + ) + assert tuple(PipCmd.update_root(pip_ver)) == exp_cmd + + +def test_pip_cmd_update(): + """Verify the correct determination of a pip command.""" + index = 'https://pypi.org/simple' + destdir = 'foo/bar' + pkg_name = 'mypkg' + pkg_version = '12.0' + cmd_root = ('pip', '-q', 'download') + exp_cmd = cmd_root + ( + '--no-deps', + '-i', + index, + '-d', + destdir, + '{}=={}'.format(pkg_name, pkg_version) + ) + assert exp_cmd == tuple( + PipCmd.update(cmd_root, destdir, pkg_name, pkg_version) + ) + + +def test_pip_cmd_update_index_overridden(): + """Verify the correct determination of a pip command.""" + index = 'https://pypi.org/complex' + destdir = 'foo/bar' + pkg_name = 'mypkg' + pkg_version = '12.0' + cmd_root = ('pip', '-q', 'download') + exp_cmd = cmd_root + ( + '--no-deps', + '-i', index, + '-d', destdir, + '{}=={}'.format(pkg_name, pkg_version) + ) + assert exp_cmd == tuple( + PipCmd.update(cmd_root, destdir, pkg_name, pkg_version, index=index) + ) + + +def test_update_package(monkeypatch): + """Test generating an update command for a package.""" + monkeypatch.setattr(manage, 'call', Mock()) + pkg = PkgFile('mypkg', '1.0', replaces=PkgFile('mypkg', '0.9')) + update_package(pkg, '.') + manage.call.assert_called_once_with(( # pylint: disable=no-member + 'pip', + '-q', + 'download', + '--no-deps', + '-i', 'https://pypi.org/simple', + '-d', '.', + 'mypkg==1.0', + )) + + +def test_update_package_dry_run(monkeypatch): + """Test generating an update command for a package.""" + monkeypatch.setattr(manage, 'call', Mock()) + pkg = PkgFile('mypkg', '1.0', replaces=PkgFile('mypkg', '0.9')) + update_package(pkg, '.', dry_run=True) + assert not manage.call.mock_calls # pylint: disable=no-member
pypi-server -Ux command executes pip install -d which is not supported anymore Error: ``` Usage: pip install [options] <requirement specifier> [package-index-options] ... pip install [options] -r <requirements file> [package-index-options] ... pip install [options] [-e] <vcs project url> ... pip install [options] [-e] <local project path> ... pip install [options] <archive url/path> ... no such option: -d ``` pip Version: 18 pypi-server Version: 1.2.2 Workaround: Installing pip Version 9
0.0
c86de256fb37ef552abac5c4f3d3cec7a5cb4b3c
[ "tests/test_manage.py::test_is_stable_version[1.0-True]", "tests/test_manage.py::test_is_stable_version[0.0.0-True]", "tests/test_manage.py::test_is_stable_version[1.1beta1-False]", "tests/test_manage.py::test_is_stable_version[1.2.10-123-True]", "tests/test_manage.py::test_is_stable_version[5.5.0-DEV-False]", "tests/test_manage.py::test_is_stable_version[1.2-rc1-False]", "tests/test_manage.py::test_is_stable_version[1.0b1-False]", "tests/test_manage.py::test_build_releases", "tests/test_manage.py::test_filter_stable_releases", "tests/test_manage.py::test_filter_latest_pkgs", "tests/test_manage.py::test_filter_latest_pkgs_case_insensitive", "tests/test_manage.py::test_pip_cmd_root[10.0.0-d]", "tests/test_manage.py::test_pip_cmd_root[10.0.0rc10-d]", "tests/test_manage.py::test_pip_cmd_root[10.0.0b10-d]", "tests/test_manage.py::test_pip_cmd_root[10.0.0a3-d]", "tests/test_manage.py::test_pip_cmd_root[10.0.0.dev8-d0]", "tests/test_manage.py::test_pip_cmd_root[10.0.0.dev8-d1]", "tests/test_manage.py::test_pip_cmd_root[18.0-d]", "tests/test_manage.py::test_pip_cmd_root[9.9.8-i]", "tests/test_manage.py::test_pip_cmd_root[9.9.8rc10-i]", "tests/test_manage.py::test_pip_cmd_root[9.9.8b10-i]", "tests/test_manage.py::test_pip_cmd_root[9.9.8a10-i]", "tests/test_manage.py::test_pip_cmd_root[9.9.8.dev10-i]", "tests/test_manage.py::test_pip_cmd_root[9.9-i]", "tests/test_manage.py::test_pip_cmd_update", "tests/test_manage.py::test_pip_cmd_update_index_overridden", "tests/test_manage.py::test_update_package", "tests/test_manage.py::test_update_package_dry_run" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-08-01 13:14:21+00:00
mit
5,025
pypr__automan-12
diff --git a/automan/automation.py b/automan/automation.py index bf7b07f..bd2f330 100644 --- a/automan/automation.py +++ b/automan/automation.py @@ -39,7 +39,7 @@ class Task(object): """Return iterable of tasks this task requires. It is important that one either return tasks that are idempotent or - return the same instance as this method is called repeateadly. + return the same instance as this method is called repeatedly. """ return [] @@ -67,6 +67,8 @@ class TaskRunner(object): self.scheduler = scheduler self.todo = [] self.task_status = dict() + self.task_outputs = set() + self.repeat_tasks = set() for task in tasks: self.add_task(task) @@ -93,7 +95,22 @@ class TaskRunner(object): return complete def _get_tasks_with_status(self, status): - return [t for t, s in self.task_status.items() if s == status] + return [ + t for t, s in self.task_status.items() + if s == status and t not in self.repeat_tasks + ] + + def _is_output_registered(self, task): + # Note, this has a side-effect of registering the task's output + # when called. + output = task.output() + output_str = str(output) + if output and output_str in self.task_outputs: + self.repeat_tasks.add(task) + return True + else: + self.task_outputs.add(output_str) + return False def _run(self, task): try: @@ -130,6 +147,11 @@ class TaskRunner(object): # #### Public protocol ############################################## def add_task(self, task): + if task in self.task_status or self._is_output_registered(task): + # This task is already added or another task produces exactly + # the same output, so do nothing. + return + if not task.complete(): self.todo.append(task) self.task_status[task] = 'not started' @@ -165,14 +187,14 @@ class TaskRunner(object): class CommandTask(Task): - """Convenience class to run a command via the framework. The class provides a - method to run the simulation and also check if the simulation is completed. - The command should ideally produce all of its outputs inside an output - directory that is specified. + """Convenience class to run a command via the framework. The class provides + a method to run the simulation and also check if the simulation is + completed. The command should ideally produce all of its outputs inside an + output directory that is specified. """ - def __init__(self, command, output_dir, job_info=None): + def __init__(self, command, output_dir, job_info=None, depends=None): """Constructor **Parameters** @@ -180,6 +202,7 @@ class CommandTask(Task): command: str or list: command to run $output_dir is substituted. output_dir: str : path of output directory. job_info: dict: dictionary of job information. + depends: list: list of tasks this depends on. """ if isinstance(command, str): @@ -190,6 +213,7 @@ class CommandTask(Task): for x in self.command] self.output_dir = output_dir self.job_info = job_info if job_info is not None else {} + self.depends = depends if depends is not None else [] self.job_proxy = None self._copy_proc = None # This is a sentinel set to true when the job is finished @@ -231,6 +255,14 @@ class CommandTask(Task): if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir) + def output(self): + """Return list of output paths. + """ + return [self.output_dir] + + def requires(self): + return self.depends + # #### Private protocol ########################################### @property @@ -299,7 +331,7 @@ class PySPHTask(CommandTask): """ - def __init__(self, command, output_dir, job_info=None): + def __init__(self, command, output_dir, job_info=None, depends=None): """Constructor **Parameters** @@ -307,9 +339,10 @@ class PySPHTask(CommandTask): command: str or list: command to run $output_dir is substituted. output_dir: str : path of output directory. job_info: dict: dictionary of job information. + depends: list: list of tasks this depends on. """ - super(PySPHTask, self).__init__(command, output_dir, job_info) + super(PySPHTask, self).__init__(command, output_dir, job_info, depends) self.command += ['-d', output_dir] # #### Private protocol ########################################### @@ -351,8 +384,8 @@ class Problem(object): results and simulations are collected inside a directory with this name. - `get_commands(self)`: returns a sequence of (directory_name, - command_string, job_info) tuples. These are to be exeuted before the - `run` method is called. + command_string, job_info, depends) tuples. These are to be executed + before the `run` method is called. - `get_requires(self)`: returns a sequence of (name, task) tuples. These are to be exeuted before the `run` method is called. - `run(self)`: Processes the completed simulations to make plots etc. @@ -379,6 +412,32 @@ class Problem(object): self.cases = None self.setup() + def _make_depends(self, depends): + if not depends: + return [] + deps = [] + for x in depends: + if isinstance(x, Task): + deps.append(x) + elif isinstance(x, Simulation): + if x.depends: + my_depends = self._make_depends(x.depends) + else: + my_depends = None + task = self.task_cls( + x.command, self.input_path(x.name), x.job_info, + depends=my_depends + ) + deps.append(task) + else: + raise RuntimeError( + 'Invalid dependency: {0} for problem {1}'.format( + x, self + ) + ) + + return deps + # #### Public protocol ########################################### def input_path(self, *args): @@ -413,20 +472,27 @@ class Problem(object): return self.__class__.__name__ def get_commands(self): - """Return a sequence of (name, command_string, job_info_dict). + """Return a sequence of (name, command_string, job_info_dict) + or (name, command_string, job_info_dict, depends). - The name represents the command being run and is used as - a subdirectory for generated output. + The name represents the command being run and is used as a subdirectory + for generated output. The command_string is the command that needs to be run. The job_info_dict is a dictionary with any additional info to be used by the job, these are additional arguments to the - `automan.jobss.Job` class. It may be None if nothing special need + `automan.jobs.Job` class. It may be None if nothing special need be passed. + + The depends is any dependencies this simulation has in terms of other + simulations/tasks. + """ if self.cases is not None: - return [(x.name, x.command, x.job_info) for x in self.cases] + return [ + (x.name, x.command, x.job_info, x.depends) for x in self.cases + ] else: return [] @@ -440,9 +506,14 @@ class Problem(object): """ base = self.get_name() result = [] - for name, cmd, job_info in self.get_commands(): + for cmd_info in self.get_commands(): + name, cmd, job_info = cmd_info[:3] + deps = cmd_info[3] if len(cmd_info) == 4 else [] sim_output_dir = self.input_path(name) - task = self.task_cls(cmd, sim_output_dir, job_info) + depends = self._make_depends(deps) + task = self.task_cls( + cmd, sim_output_dir, job_info, depends=depends + ) task_name = '%s.%s' % (base, name) result.append((task_name, task)) return result @@ -457,7 +528,7 @@ class Problem(object): """Run any analysis code for the simulations completed. This is usually run after the simulation commands are completed. """ - raise NotImplementedError() + pass def clean(self): """Cleanup any generated output from the analysis code. This does not @@ -549,7 +620,7 @@ class Simulation(object): this is an extremely powerful way to automate and compare results. """ - def __init__(self, root, base_command, job_info=None, **kw): + def __init__(self, root, base_command, job_info=None, depends=None, **kw): """Constructor **Parameters** @@ -560,6 +631,8 @@ class Simulation(object): Base command to run. job_info: dict Extra arguments to the `automan.jobs.Job` class. + depends: list + List of other simulations/tasks this simulation depends on. **kw: dict Additional parameters to pass to command. """ @@ -567,6 +640,7 @@ class Simulation(object): self.name = os.path.basename(root) self.base_command = base_command self.job_info = job_info + self.depends = depends if depends is not None else [] self.params = dict(kw) self._results = None @@ -699,11 +773,26 @@ class SolveProblem(Task): self.problem = problem self.match = match self._requires = [ - task + self._make_task(task) for name, task in self.problem.get_requires() if len(match) == 0 or fnmatch(name, match) ] + def _make_task(self, obj): + if isinstance(obj, Task): + return obj + elif isinstance(obj, Problem): + return SolveProblem(problem=obj, match=self.match) + elif isinstance(obj, type) and issubclass(obj, Problem): + problem = obj(self.problem.sim_dir, self.problem.out_dir) + return SolveProblem(problem=problem, match=self.match) + else: + raise RuntimeError( + 'Unknown requirement: {0}, for problem: {1}.'.format( + obj, self.problem + ) + ) + def __str__(self): return 'Problem named %s' % self.problem.get_name() @@ -846,8 +935,8 @@ class Automator(object): self.parser.exit(1) def _get_exclude_paths(self): - """Returns a list of exclude paths suitable for passing on to rsync to exclude - syncing some directories on remote machines. + """Returns a list of exclude paths suitable for passing on to rsync to + exclude syncing some directories on remote machines. """ paths = [] for path in [self.simulation_dir, self.output_dir]: diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst index 55255f3..a65d9fc 100644 --- a/docs/source/tutorial.rst +++ b/docs/source/tutorial.rst @@ -84,16 +84,16 @@ Let us execute this to see what it does:: Writing config.json 4 tasks pending and 0 tasks running - Running task <automan.automation.CommandTask object at 0x10628d978>... + Running task CommandTask with output directory: 2 ... Starting worker on localhost. Job run by localhost Running python square.py 2 - Running task <automan.automation.CommandTask object at 0x10628d9b0>... + Running task CommandTask with output directory: 1 ... Job run by localhost Running python square.py 1 2 tasks pending and 2 tasks running - Running task <automan.automation.SolveProblem object at 0x10628d940>... + Running task Problem named squares... Running task <automan.automation.RunAll object at 0x10628d908>... Finished! @@ -499,12 +499,12 @@ availability. For example:: $ python automate4.py 14 tasks pending and 0 tasks running - Running task <automan.automation.CommandTask object at 0x1141da748>... + Running task CommandTask with output directory: 4 ... Starting worker on localhost. Job run by localhost Running python powers.py --output-dir outputs/powers/4 --power=4.0 - Running task <automan.automation.CommandTask object at 0x1141da6d8>... + Running task CommandTask with output directory: 3 ... Starting worker on 10.1.10.242. Job run by 10.1.10.242 Running python powers.py --output-dir outputs/powers/3 --power=3.0 @@ -653,6 +653,76 @@ https://github.com/pypr/automan/tree/master/examples/edm_conda_cluster The README in the directory tells you how to run the examples. +Specifying simulation dependencies +----------------------------------- + +There are times when one simulation uses the output from another and you wish +to execute them in the right order. This can be quite easily achieved. Here is +a simple example from the test suite that illustrates this:: + + class MyProblem(Problem): + def setup(self): + cmd = 'python -c "import time; print(time.time())"' + s1 = Simulation(self.input_path('1'), cmd) + s2 = Simulation(self.input_path('2'), cmd, depends=[s1]) + s3 = Simulation(self.input_path('3'), cmd, depends=[s1, s2]) + self.cases = [s1, s2, s3] + +Notice the extra keyword argument, ``depends=`` which specifies a list of +other simulations. In the above case, we could have also used ``self.cases = +[s3]`` and that would have automatically picked up the other simulations. + +When this problem is run, ``s1`` will run first followed by ``s2`` and then by +``s3``. Note that this will only execute ``s1`` once even though it is +declared as a dependency for two other simulations. This makes it possible to +easily define inter-dependent tasks/simulations. In general, the dependencies +could be any :py:class:`automan.automation.Simulation` or +:py:class:`automan.automation.Task` instance. + +Internally, these simulations create suitable task instances that support +dependencies see :py:class:`automan.automation.CommandTask` + + +Specifying inter-problem dependencies +-------------------------------------- + +Sometimes you may have a situation where one problem depends on the output of +another. These may be done by overriding the ``Problem.get_requires`` method. +Here is an example from the test suite:: + + class A(Problem): + def get_requires(self): + cmd = 'python -c "print(1)"' + ct = CommandTask(cmd, output_dir=self.sim_dir) + return [('task1', ct)] + + class B(Problem): + def get_requires(self): + # or return Problem instances ... + return [('a', A(self.sim_dir, self.out_dir))] + + class C(Problem): + def get_requires(self): + # ... or Problem subclasses + return [('a', A), ('b', B)] + +Normally, the ``get_requires`` method automatically creates tasks from the +simulations specified but in the above example we show a case (problem ``A``) +where we explicitly create command tasks. In the above example, the problem +``B`` depends on the problem ``A`` and simply returns an instance of ``A``. On +the other hand ``C`` only returns the problem class and not an instance. This +shows how one can specify inter problem dependencies. + +Note that if the problem performs some simulations (by setting +``self.cases``), you should call the parent method (via ``super``) and add +your additional dependencies to this. + +Also note that the dependencies are resolved based on the "outputs" of a task. +So two tasks with the same outputs are treated as the same. This is consistent +with the design of automan where each simulation's output goes in its own +directory. + + Using docker ------------
pypr/automan
d3bc2dc671597d3e48919ffddaeb30cadeecd0cb
diff --git a/automan/tests/test_automation.py b/automan/tests/test_automation.py index 4e07c93..f544148 100644 --- a/automan/tests/test_automation.py +++ b/automan/tests/test_automation.py @@ -1,7 +1,6 @@ from __future__ import print_function import os -import shutil import sys import tempfile import unittest @@ -12,8 +11,8 @@ except ImportError: import mock from automan.automation import ( - Automator, CommandTask, PySPHProblem, Simulation, SolveProblem, - TaskRunner, compare_runs, filter_cases + Automator, CommandTask, Problem, PySPHProblem, RunAll, Simulation, + SolveProblem, TaskRunner, compare_runs, filter_cases ) try: from automan.jobs import Scheduler, RemoteWorker @@ -35,8 +34,8 @@ class MySimulation(Simulation): class EllipticalDrop(PySPHProblem): - """We define a simple example problem which we will run using the automation - framework. + """We define a simple example problem which we will run using the + automation framework. In this case we run two variants of the elliptical drop problem. @@ -102,6 +101,168 @@ class TestAutomationBase(unittest.TestCase): safe_rmtree(self.root) +class TestTaskRunner(TestAutomationBase): + def _make_scheduler(self): + worker = dict(host='localhost') + s = Scheduler(root='.', worker_config=[worker]) + return s + + def _get_time(self, path): + with open(os.path.join(path, 'stdout.txt')) as f: + t = float(f.read()) + return t + + def test_task_runner_does_not_add_repeated_tasks(self): + # Given + s = self._make_scheduler() + cmd = 'python -c "print(1)"' + ct1 = CommandTask(cmd, output_dir=self.sim_dir) + ct2 = CommandTask(cmd, output_dir=self.sim_dir) + + # When + t = TaskRunner(tasks=[ct1, ct2, ct1], scheduler=s) + + # Then + self.assertEqual(len(t.todo), 1) + + def test_problem_depending_on_other_problems(self): + # Given + class A(Problem): + def get_requires(self): + cmd = 'python -c "print(1)"' + # Can return tasks ... + ct = CommandTask(cmd, output_dir=self.sim_dir) + return [('task1', ct)] + + def run(self): + self.make_output_dir() + + class B(Problem): + def get_requires(self): + # or return Problem instances ... + return [('a', A(self.sim_dir, self.out_dir))] + + def run(self): + self.make_output_dir() + + class C(Problem): + def get_requires(self): + # ... or Problem subclasses + return [('a', A), ('b', B)] + + def run(self): + self.make_output_dir() + + s = self._make_scheduler() + + # When + task = RunAll( + simulation_dir=self.sim_dir, output_dir=self.output_dir, + problem_classes=[A, B, C] + ) + t = TaskRunner(tasks=[task], scheduler=s) + + # Then + self.assertEqual(len(t.todo), 5) + # Basically only one instance of CommandTask should be created. + names = [x.__class__.__name__ for x in t.todo] + problems = [x.problem for x in t.todo if isinstance(x, SolveProblem)] + self.assertEqual(names.count('RunAll'), 1) + self.assertEqual(names.count('CommandTask'), 1) + self.assertEqual(names.count('SolveProblem'), 3) + self.assertEqual(len(problems), 3) + self.assertEqual( + sorted(x.__class__.__name__ for x in problems), + ['A', 'B', 'C'] + ) + + # When + t.run(wait=0.1) + + # Then. + self.assertEqual(t.todo, []) + + def test_problem_with_bad_requires_raises_error(self): + # Given + class D(Problem): + def get_requires(self): + return [('a', 'A')] + + # When + self.assertRaises( + RuntimeError, + SolveProblem, D(self.sim_dir, self.output_dir) + ) + + def test_tasks_with_dependencies(self): + # Given + s = self._make_scheduler() + cmd = 'python -c "import time; print(time.time())"' + ct1_dir = os.path.join(self.sim_dir, '1') + ct2_dir = os.path.join(self.sim_dir, '2') + ct3_dir = os.path.join(self.sim_dir, '3') + ct1 = CommandTask(cmd, output_dir=ct1_dir) + ct2 = CommandTask(cmd, output_dir=ct2_dir, depends=[ct1]) + ct3 = CommandTask(cmd, output_dir=ct3_dir, depends=[ct1, ct2]) + + # When + t = TaskRunner(tasks=[ct1, ct2, ct3], scheduler=s) + + # Then + self.assertEqual(len(t.todo), 3) + + # When + t.run(wait=0.1) + + wait_until(lambda: not ct3.complete()) + + # Then. + # Ensure that the tasks are run in the right order. + ct1_t, ct2_t, ct3_t = [ + self._get_time(x) for x in (ct1_dir, ct2_dir, ct3_dir) + ] + self.assertTrue(ct2_t > ct1_t) + self.assertTrue(ct3_t > ct2_t) + + def test_simulation_with_dependencies(self): + # Given + class A(Problem): + def setup(self): + cmd = 'python -c "import time; print(time.time())"' + s1 = Simulation(self.input_path('1'), cmd) + s2 = Simulation(self.input_path('2'), cmd, depends=[s1]) + s3 = Simulation(self.input_path('3'), cmd, depends=[s1, s2]) + self.cases = [s1, s2, s3] + + def run(self): + self.make_output_dir() + + s = self._make_scheduler() + + # When + problem = A(self.sim_dir, self.output_dir) + task = SolveProblem(problem) + t = TaskRunner(tasks=[task], scheduler=s) + + # Then + self.assertEqual(len(t.todo), 4) + # Basically only one instance of CommandTask should be created. + names = [x.__class__.__name__ for x in t.todo] + self.assertEqual(names.count('CommandTask'), 3) + self.assertEqual(names.count('SolveProblem'), 1) + + # When + t.run(wait=0.1) + wait_until(lambda: not task.complete()) + + # Then + ct1_t, ct2_t, ct3_t = [ + self._get_time(problem.input_path(x)) for x in ('1', '2', '3') + ] + self.assertTrue(ct2_t > ct1_t) + self.assertTrue(ct3_t > ct2_t) + + class TestLocalAutomation(TestAutomationBase): def _make_scheduler(self): worker = dict(host='localhost')
Add ability to specify inter-simulation dependencies With tasks one can have complex dependencies but there isn't an easy way to spell this out when creating simulations.
0.0
d3bc2dc671597d3e48919ffddaeb30cadeecd0cb
[ "automan/tests/test_automation.py::TestTaskRunner::test_problem_depending_on_other_problems", "automan/tests/test_automation.py::TestTaskRunner::test_problem_with_bad_requires_raises_error", "automan/tests/test_automation.py::TestTaskRunner::test_simulation_with_dependencies", "automan/tests/test_automation.py::TestTaskRunner::test_task_runner_does_not_add_repeated_tasks", "automan/tests/test_automation.py::TestTaskRunner::test_tasks_with_dependencies" ]
[ "automan/tests/test_automation.py::TestLocalAutomation::test_automation", "automan/tests/test_automation.py::TestLocalAutomation::test_nothing_is_run_when_output_exists", "automan/tests/test_automation.py::TestRemoteAutomation::test_automation", "automan/tests/test_automation.py::TestRemoteAutomation::test_job_with_error_is_handled_correctly", "automan/tests/test_automation.py::TestRemoteAutomation::test_nothing_is_run_when_output_exists", "automan/tests/test_automation.py::TestCommandTask::test_command_tasks_converts_dollar_output_dir", "automan/tests/test_automation.py::TestCommandTask::test_command_tasks_executes_simple_command", "automan/tests/test_automation.py::TestCommandTask::test_command_tasks_handles_errors_correctly", "automan/tests/test_automation.py::test_simulation_get_labels", "automan/tests/test_automation.py::test_compare_runs_calls_methods_when_given_names", "automan/tests/test_automation.py::test_compare_runs_works_when_given_callables", "automan/tests/test_automation.py::test_filter_cases_works_with_params", "automan/tests/test_automation.py::test_filter_cases_works_with_predicate", "automan/tests/test_automation.py::TestAutomator::test_automator", "automan/tests/test_automation.py::TestAutomator::test_automator_accepts_cluster_manager" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-10-16 05:34:39+00:00
bsd-3-clause
5,026
pyro-ppl__funsor-65
diff --git a/funsor/__init__.py b/funsor/__init__.py index 11a1812..64b0f35 100644 --- a/funsor/__init__.py +++ b/funsor/__init__.py @@ -5,8 +5,8 @@ from funsor.interpreter import reinterpret from funsor.terms import Funsor, Number, Variable, of_shape, to_funsor from funsor.torch import Function, Tensor, arange, function, torch_einsum -from . import adjoint, contract, distributions, domains, einsum, gaussian, \ - handlers, interpreter, minipyro, ops, terms, torch +from . import (adjoint, contract, delta, distributions, domains, einsum, gaussian, handlers, interpreter, minipyro, ops, + terms, torch) __all__ = [ 'Domain', @@ -20,6 +20,7 @@ __all__ = [ 'backward', 'bint', 'contract', + 'delta', 'distributions', 'domains', 'einsum', diff --git a/funsor/delta.py b/funsor/delta.py new file mode 100644 index 0000000..5102d38 --- /dev/null +++ b/funsor/delta.py @@ -0,0 +1,109 @@ +from __future__ import absolute_import, division, print_function + +from collections import OrderedDict + +from six import add_metaclass + +import funsor.ops as ops +from funsor.domains import reals +from funsor.ops import Op +from funsor.terms import Align, Binary, Funsor, FunsorMeta, Number, Variable, eager, to_funsor +from funsor.torch import Tensor + + +class DeltaMeta(FunsorMeta): + """ + Wrapper to fill in defaults. + """ + def __call__(cls, name, point, log_density=0): + point = to_funsor(point) + log_density = to_funsor(log_density) + return super(DeltaMeta, cls).__call__(name, point, log_density) + + +@add_metaclass(DeltaMeta) +class Delta(Funsor): + """ + Normalized delta distribution binding a single variable. + + :param str name: Name of the bound variable. + :param Funsor point: Value of the bound variable. + :param Funsor log_density: Optional log density to be added when evaluating + at a point. This is needed to make :class:`Delta` closed under + differentiable substitution. + """ + def __init__(self, name, point, log_density=0): + assert isinstance(name, str) + assert isinstance(point, Funsor) + assert isinstance(log_density, Funsor) + assert log_density.output == reals() + inputs = OrderedDict([(name, point.output)]) + inputs.update(point.inputs) + inputs.update(log_density.inputs) + output = reals() + super(Delta, self).__init__(inputs, output) + self.name = name + self.point = point + self.log_density = log_density + + def eager_subs(self, subs): + value = None + index_part = [] + for k, v in subs: + if k in self.inputs: + if k == self.name: + value = v + else: + assert self.name not in v.inputs + index_part.append((k, v)) + index_part = tuple(index_part) + if value is None and not index_part: + return self + + name = self.name + point = self.point.eager_subs(index_part) + log_density = self.log_density.eager_subs(index_part) + if value is not None: + if isinstance(value, Variable): + name = value.name + elif isinstance(value, (Number, Tensor)) and isinstance(point, (Number, Tensor)): + return (value == point).all().log() + log_density + else: + # TODO Compute a jacobian, update log_prob, and emit another Delta. + raise ValueError('Cannot substitute a {} into a Delta' + .format(type(value).__name__)) + return Delta(name, point, log_density) + + def eager_reduce(self, op, reduced_vars): + if op is ops.logaddexp: + if self.name in reduced_vars: + return Number(0) # Deltas are normalized. + + # TODO Implement ops.add to simulate .to_event(). + + return None # defer to default implementation + + [email protected](Binary, Op, Delta, (Funsor, Delta, Align)) +def eager_binary(op, lhs, rhs): + if op is ops.add or op is ops.sub: + if lhs.name in rhs.inputs: + rhs = rhs(**{lhs.name: lhs.point}) + return op(lhs, rhs) + + return None # defer to default implementation + + [email protected](Binary, Op, (Funsor, Align), Delta) +def eager_binary(op, lhs, rhs): + if op is ops.add: + if rhs.name in lhs.inputs: + lhs = lhs(**{rhs.name: rhs.point}) + return op(lhs, rhs) + + return None # defer to default implementation + + +__all__ = [ + 'Delta', +] diff --git a/funsor/distributions.py b/funsor/distributions.py index c958e01..26ad08c 100644 --- a/funsor/distributions.py +++ b/funsor/distributions.py @@ -7,6 +7,7 @@ import pyro.distributions as dist import torch from six import add_metaclass +import funsor.delta import funsor.ops as ops from funsor.domains import bint, reals from funsor.gaussian import Gaussian @@ -150,6 +151,19 @@ def eager_delta(v, log_density, value): return Tensor(data, inputs) [email protected](Delta, Funsor, Funsor, Variable) [email protected](Delta, Variable, Funsor, Variable) +def eager_delta(v, log_density, value): + assert v.output == value.output + return funsor.delta.Delta(value.name, v, log_density) + + [email protected](Delta, Variable, Funsor, Funsor) +def eager_delta(v, log_density, value): + assert v.output == value.output + return funsor.delta.Delta(v.name, value, log_density) + + class Normal(Distribution): dist_class = dist.Normal diff --git a/funsor/ops.py b/funsor/ops.py index 54ed23b..2f23cf7 100644 --- a/funsor/ops.py +++ b/funsor/ops.py @@ -67,7 +67,14 @@ def exp(x): @Op def log(x): - return np.log(x) if isinstance(x, Number) else x.log() + if isinstance(x, Number): + return np.log(x) + elif isinstance(x, torch.Tensor): + if x.dtype in (torch.uint8, torch.long): + x = x.float() + return x.log() + else: + return x.log() @Op diff --git a/funsor/terms.py b/funsor/terms.py index 76f57a3..cc8493a 100644 --- a/funsor/terms.py +++ b/funsor/terms.py @@ -137,6 +137,9 @@ class Funsor(object): def __hash__(self): return id(self) + def __repr__(self): + return '{}({})'.format(type(self).__name__, ', '.join(map(repr, self._ast_args))) + def __call__(self, *args, **kwargs): """ Partially evaluates this funsor by substituting dimensions.
pyro-ppl/funsor
34a1d9c45feaed2f2e9218a273efbcbb34bc7599
diff --git a/test/test_delta.py b/test/test_delta.py new file mode 100644 index 0000000..abe4f9c --- /dev/null +++ b/test/test_delta.py @@ -0,0 +1,51 @@ +from __future__ import absolute_import, division, print_function + +import pytest +import torch + +import funsor.ops as ops +from funsor.delta import Delta +from funsor.domains import reals +from funsor.terms import Number, Variable +from funsor.testing import check_funsor +from funsor.torch import Tensor + + +def test_eager_subs_variable(): + v = Variable('v', reals(3)) + point = Tensor(torch.randn(3)) + d = Delta('foo', v) + assert d(v=point) is Delta('foo', point) + + [email protected]('log_density', [0, 1.234]) +def test_eager_subs_ground(log_density): + point1 = Tensor(torch.randn(3)) + point2 = Tensor(torch.randn(3)) + d = Delta('foo', point1, log_density) + check_funsor(d(foo=point1), {}, reals(), torch.tensor(float(log_density))) + check_funsor(d(foo=point2), {}, reals(), torch.tensor(float('-inf'))) + + +def test_add_delta_funsor(): + x = Variable('x', reals(3)) + y = Variable('y', reals(3)) + d = Delta('x', y) + + expr = -(1 + x ** 2).log() + assert d + expr is d + expr(x=y) + assert expr + d is expr(x=y) + d + + +def test_reduce(): + point = Tensor(torch.randn(3)) + d = Delta('foo', point) + assert d.reduce(ops.logaddexp, frozenset(['foo'])) is Number(0) + + [email protected]('log_density', [0, 1.234]) +def test_reduce(log_density): + point = Tensor(torch.randn(3)) + d = Delta('foo', point, log_density) + # Note that log_density affects ground substitution but does not affect reduction. + assert d.reduce(ops.logaddexp, frozenset(['foo'])) is Number(0) diff --git a/test/test_distributions.py b/test/test_distributions.py index df86083..542940b 100644 --- a/test/test_distributions.py +++ b/test/test_distributions.py @@ -8,6 +8,7 @@ import torch import funsor import funsor.distributions as dist +from funsor.delta import Delta from funsor.domains import bint, reals from funsor.gaussian import Gaussian from funsor.terms import Variable @@ -80,6 +81,14 @@ def test_delta_density(batch_shape, event_shape): assert_close(actual, expected) +def test_delta_delta(): + v = Variable('v', reals(2)) + point = Tensor(torch.randn(2)) + log_density = Tensor(torch.tensor(0.5)) + d = dist.Delta(point, log_density, v) + assert d is Delta('v', point, log_density) + + def test_mvn_defaults(): loc = Variable('loc', reals()) scale = Variable('scale', reals())
Implement a Delta distribution and generalized Delta funsor It appears we may be able to represent joint samples as Delta distributions. This will require two new components: - [x] #49 a `dist.Delta` distribution wrapping a univariate PyTorch-style distribution, and - [ ] #65 a general `Delta` funsor similar to `Tensor` and `Gaussian`.
0.0
34a1d9c45feaed2f2e9218a273efbcbb34bc7599
[ "test/test_delta.py::test_eager_subs_variable", "test/test_delta.py::test_eager_subs_ground[0]", "test/test_delta.py::test_eager_subs_ground[1.234]", "test/test_delta.py::test_add_delta_funsor", "test/test_delta.py::test_reduce[0]", "test/test_delta.py::test_reduce[1.234]", "test/test_distributions.py::test_categorical_defaults", "test/test_distributions.py::test_categorical_density[()-4]", "test/test_distributions.py::test_categorical_density[(5,)-4]", "test/test_distributions.py::test_categorical_density[(2,", "test/test_distributions.py::test_delta_defaults", "test/test_distributions.py::test_delta_density[()-()]", "test/test_distributions.py::test_delta_density[()-(4,)]", "test/test_distributions.py::test_delta_density[()-(3,", "test/test_distributions.py::test_delta_density[(5,)-()]", "test/test_distributions.py::test_delta_density[(5,)-(4,)]", "test/test_distributions.py::test_delta_density[(5,)-(3,", "test/test_distributions.py::test_delta_density[(2,", "test/test_distributions.py::test_delta_delta", "test/test_distributions.py::test_mvn_defaults", "test/test_distributions.py::test_mvn_density[()]", "test/test_distributions.py::test_mvn_density[(5,)]", "test/test_distributions.py::test_mvn_density[(2,", "test/test_distributions.py::test_mvn_gaussian_1[()]", "test/test_distributions.py::test_mvn_gaussian_1[(5,)]", "test/test_distributions.py::test_mvn_gaussian_1[(2,", "test/test_distributions.py::test_mvn_gaussian_2[()]", "test/test_distributions.py::test_mvn_gaussian_2[(5,)]", "test/test_distributions.py::test_mvn_gaussian_2[(2,", "test/test_distributions.py::test_mvn_gaussian_3[()]", "test/test_distributions.py::test_mvn_gaussian_3[(5,)]", "test/test_distributions.py::test_mvn_gaussian_3[(2,", "test/test_distributions.py::test_mvn_gaussian[()]", "test/test_distributions.py::test_mvn_gaussian[(5,)]", "test/test_distributions.py::test_mvn_gaussian[(2," ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-03-09 22:17:19+00:00
mit
5,027
pyro-ppl__funsor-82
diff --git a/examples/ss_vae_delayed.py b/examples/ss_vae_delayed.py index 6548979..4671887 100644 --- a/examples/ss_vae_delayed.py +++ b/examples/ss_vae_delayed.py @@ -23,9 +23,9 @@ class SalientEncoder(nn.Module): pass # TODO -decoder = funsor.function((), (), ())(Decoder()) -nuisance_encoder = funsor.function((), ('loc_scale',))(NuisanceEncoder()) -salient_encoder = funsor.function((), (), ())(SalientEncoder()) +decoder = funsor.torch.function((), (), ())(Decoder()) +nuisance_encoder = funsor.torch.function((), ('loc_scale',))(NuisanceEncoder()) +salient_encoder = funsor.torch.function((), (), ())(SalientEncoder()) def model(image=None): diff --git a/funsor/__init__.py b/funsor/__init__.py index a65ec82..be891ff 100644 --- a/funsor/__init__.py +++ b/funsor/__init__.py @@ -3,14 +3,13 @@ from __future__ import absolute_import, division, print_function from funsor.domains import Domain, bint, find_domain, reals from funsor.interpreter import reinterpret from funsor.terms import Funsor, Number, Variable, of_shape, to_funsor -from funsor.torch import Function, Tensor, arange, function, torch_einsum +from funsor.torch import Tensor, arange, torch_einsum from . import (adjoint, delta, distributions, domains, einsum, gaussian, handlers, interpreter, joint, minipyro, ops, sum_product, terms, torch) __all__ = [ 'Domain', - 'Function', 'Funsor', 'Number', 'Tensor', @@ -24,7 +23,6 @@ __all__ = [ 'domains', 'einsum', 'find_domain', - 'function', 'gaussian', 'handlers', 'interpreter', diff --git a/funsor/torch.py b/funsor/torch.py index 7e71503..7e8439b 100644 --- a/funsor/torch.py +++ b/funsor/torch.py @@ -93,8 +93,9 @@ class Tensor(Funsor): def __init__(self, data, inputs=None, dtype="real"): assert isinstance(data, torch.Tensor) assert isinstance(inputs, tuple) - assert all(isinstance(d.dtype, integer_types) for k, d in inputs) assert len(inputs) <= data.dim() + for (k, d), size in zip(inputs, data.shape): + assert d.dtype == size inputs = OrderedDict(inputs) output = Domain(data.shape[len(inputs):], dtype) super(Tensor, self).__init__(inputs, output) @@ -375,18 +376,23 @@ def materialize(x): return x.eager_subs(subs) +class LazyTuple(tuple): + def __call__(self, *args, **kwargs): + return LazyTuple(x(*args, **kwargs) for x in self) + + class Function(Funsor): r""" Funsor wrapped by a PyTorch function. - Functions are support broadcasting and can be eagerly evaluated on funsors - with free variables of int type (i.e. batch dimensions). + Functions are assumed to support broadcasting and can be eagerly evaluated + on funsors with free variables of int type (i.e. batch dimensions). - :class:`Function`s are often created via the :func:`function` decorator. + :class:`Function`s are usually created via the :func:`function` decorator. :param callable fn: A PyTorch function to wrap. :param funsor.domains.Domain output: An output domain. - :param Funsor \*args: Funsor arguments. + :param Funsor args: Funsor arguments. """ def __init__(self, fn, output, args): assert callable(fn) @@ -400,12 +406,12 @@ class Function(Funsor): self.args = args def __repr__(self): - return 'Function({})'.format(', '.join( - [type(self).__name__, repr(self.output)] + list(map(repr, self.args)))) + return '{}({}, {}, {})'.format(type(self).__name__, self.fn.__name__, + repr(self.output), repr(self.args)) def __str__(self): - return 'Function({})'.format(', '.join( - [type(self).__name__, str(self.output)] + list(map(str, self.args)))) + return '{}({}, {}, {})'.format(type(self).__name__, self.fn.__name__, + str(self.output), str(self.args)) def eager_subs(self, subs): if not any(k in self.inputs for k, v in subs): @@ -425,11 +431,54 @@ def eager_function(fn, output, args): return result +def _select(fn, i, *args): + result = fn(*args) + assert isinstance(result, tuple) + return result[i] + + +def _nested_function(fn, args, output): + if isinstance(output, Domain): + return Function(fn, output, args) + elif isinstance(output, tuple): + result = [] + for i, output_i in enumerate(output): + fn_i = functools.partial(_select, fn, i) + fn_i.__name__ = "{}_{}".format(fn_i, i) + result.append(_nested_function(fn_i, args, output_i)) + return LazyTuple(result) + raise TypeError("Invalid output: {}".format(output)) + + +class _Memoized(object): + def __init__(self, fn): + self.fn = fn + self._cache = None + + def __call__(self, *args): + if self._cache is not None: + old_args, old_result = self._cache + if all(x is y for x, y in zip(args, old_args)): + return old_result + result = self.fn(*args) + self._cache = args, result + return result + + @property + def __name__(self): + return self.fn.__name__ + + def _function(inputs, output, fn): names = getargspec(fn)[0] args = tuple(Variable(name, domain) for (name, domain) in zip(names, inputs)) assert len(args) == len(inputs) - return Function(fn, output, args) + if not isinstance(output, Domain): + assert isinstance(output, tuple) + # Memoize multiple-output functions so that invocations can be shared among + # all outputs. This is not foolproof, but does work in simple situations. + fn = _Memoized(fn) + return _nested_function(fn, args, output) def function(*signature): @@ -438,21 +487,29 @@ def function(*signature): Example:: - @funsor.function(reals(3,4), reals(4,5), reals(3,5)) + @funsor.torch.function(reals(3,4), reals(4,5), reals(3,5)) def matmul(x, y): return torch.matmul(x, y) - @funsor.function(reals(10), reals(10, 10), reals()) + @funsor.torch.function(reals(10), reals(10, 10), reals()) def mvn_log_prob(loc, scale_tril, x): d = torch.distributions.MultivariateNormal(loc, scale_tril) return d.log_prob(x) + To support functions that output nested tuples of tensors, specify a nested + tuple of output types, for example: + + @funsor.torch.function(reals(8), (reals(), bint(8))) + def max_and_argmax(x): + return torch.max(x, dim=-1) + :param \*signature: A sequence if input domains followed by a final output domain. """ assert signature - assert all(isinstance(d, Domain) for d in signature) inputs, output = signature[:-1], signature[-1] + assert all(isinstance(d, Domain) for d in inputs) + assert isinstance(output, (Domain, tuple)) return functools.partial(_function, inputs, output) @@ -479,7 +536,9 @@ def torch_einsum(equation, *operands): return Function(fn, output, operands) +################################################################################ # Register Ops +################################################################################ @ops.abs.register(torch.Tensor) def _abs(x): @@ -585,13 +644,13 @@ REDUCE_OP_TO_TORCH = { __all__ = [ - 'REDUCE_OP_TO_TORCH', 'Function', + 'REDUCE_OP_TO_TORCH', 'Tensor', 'align_tensor', 'align_tensors', 'arange', - 'torch_einsum', 'function', 'materialize', + 'torch_einsum', ]
pyro-ppl/funsor
2b8c0e5611b5a120ca8559bfd8adac799f1cae95
diff --git a/test/test_distributions.py b/test/test_distributions.py index 8f9de6a..d72ec1a 100644 --- a/test/test_distributions.py +++ b/test/test_distributions.py @@ -59,7 +59,7 @@ def test_delta_density(batch_shape, event_shape): batch_dims = ('i', 'j', 'k')[:len(batch_shape)] inputs = OrderedDict((k, bint(v)) for k, v in zip(batch_dims, batch_shape)) - @funsor.function(reals(*event_shape), reals(), reals(*event_shape), reals()) + @funsor.torch.function(reals(*event_shape), reals(), reals(*event_shape), reals()) def delta(v, log_density, value): eq = (v == value) for _ in range(len(event_shape)): @@ -198,7 +198,7 @@ def test_mvn_density(batch_shape): batch_dims = ('i', 'j', 'k')[:len(batch_shape)] inputs = OrderedDict((k, bint(v)) for k, v in zip(batch_dims, batch_shape)) - @funsor.function(reals(3), reals(3, 3), reals(3), reals()) + @funsor.torch.function(reals(3), reals(3, 3), reals(3), reals()) def mvn(loc, scale_tril, value): return torch.distributions.MultivariateNormal(loc, scale_tril=scale_tril).log_prob(value) diff --git a/test/test_torch.py b/test/test_torch.py index 684c6a9..2bb6cb6 100644 --- a/test/test_torch.py +++ b/test/test_torch.py @@ -384,7 +384,7 @@ def test_all_equal(shape): def test_function_matmul(): - @funsor.function(reals(3, 4), reals(4, 5), reals(3, 5)) + @funsor.torch.function(reals(3, 4), reals(4, 5), reals(3, 5)) def matmul(x, y): return torch.matmul(x, y) @@ -399,15 +399,15 @@ def test_function_matmul(): def test_function_lazy_matmul(): - @funsor.function(reals(3, 4), reals(4, 5), reals(3, 5)) + @funsor.torch.function(reals(3, 4), reals(4, 5), reals(3, 5)) def matmul(x, y): return torch.matmul(x, y) - x_lazy = funsor.Variable('x', reals(3, 4)) + x_lazy = Variable('x', reals(3, 4)) y = Tensor(torch.randn(4, 5)) actual_lazy = matmul(x_lazy, y) check_funsor(actual_lazy, {'x': reals(3, 4)}, reals(3, 5)) - assert isinstance(actual_lazy, funsor.Function) + assert isinstance(actual_lazy, funsor.torch.Function) x = Tensor(torch.randn(3, 4)) actual = actual_lazy(x=x) @@ -415,6 +415,45 @@ def test_function_lazy_matmul(): check_funsor(actual, {}, reals(3, 5), expected_data) +def test_function_nested_eager(): + + @funsor.torch.function(reals(8), (reals(), bint(8))) + def max_and_argmax(x): + return torch.max(x, dim=-1) + + inputs = OrderedDict([('i', bint(2)), ('j', bint(3))]) + x = Tensor(torch.randn(2, 3, 8), inputs) + m, a = x.data.max(dim=-1) + expected_max = Tensor(m, inputs, 'real') + expected_argmax = Tensor(a, inputs, 8) + + actual_max, actual_argmax = max_and_argmax(x) + assert_close(actual_max, expected_max) + assert_close(actual_argmax, expected_argmax) + + +def test_function_nested_lazy(): + + @funsor.torch.function(reals(8), (reals(), bint(8))) + def max_and_argmax(x): + return torch.max(x, dim=-1) + + x_lazy = Variable('x', reals(8)) + lazy_max, lazy_argmax = max_and_argmax(x_lazy) + assert isinstance(lazy_max, funsor.torch.Function) + assert isinstance(lazy_argmax, funsor.torch.Function) + check_funsor(lazy_max, {'x': reals(8)}, reals()) + check_funsor(lazy_argmax, {'x': reals(8)}, bint(8)) + + inputs = OrderedDict([('i', bint(2)), ('j', bint(3))]) + y = Tensor(torch.randn(2, 3, 8), inputs) + actual_max = lazy_max(x=y) + actual_argmax = lazy_argmax(x=y) + expected_max, expected_argmax = max_and_argmax(y) + assert_close(actual_max, expected_max) + assert_close(actual_argmax, expected_argmax) + + def test_align(): x = Tensor(torch.randn(2, 3, 4), OrderedDict([ ('i', bint(2)),
Support torch.nn.Module with multiple outputs
0.0
2b8c0e5611b5a120ca8559bfd8adac799f1cae95
[ "test/test_torch.py::test_function_nested_eager", "test/test_torch.py::test_function_nested_lazy" ]
[ "test/test_distributions.py::test_categorical_defaults", "test/test_distributions.py::test_categorical_density[()-4]", "test/test_distributions.py::test_categorical_density[(5,)-4]", "test/test_distributions.py::test_categorical_density[(2,", "test/test_distributions.py::test_delta_defaults", "test/test_distributions.py::test_delta_density[()-()]", "test/test_distributions.py::test_delta_density[()-(4,)]", "test/test_distributions.py::test_delta_density[()-(3,", "test/test_distributions.py::test_delta_density[(5,)-()]", "test/test_distributions.py::test_delta_density[(5,)-(4,)]", "test/test_distributions.py::test_delta_density[(5,)-(3,", "test/test_distributions.py::test_delta_density[(2,", "test/test_distributions.py::test_delta_delta", "test/test_distributions.py::test_normal_defaults", "test/test_distributions.py::test_normal_density[()]", "test/test_distributions.py::test_normal_density[(5,)]", "test/test_distributions.py::test_normal_density[(2,", "test/test_distributions.py::test_normal_gaussian_1[()]", "test/test_distributions.py::test_normal_gaussian_1[(5,)]", "test/test_distributions.py::test_normal_gaussian_1[(2,", "test/test_distributions.py::test_normal_gaussian_2[()]", "test/test_distributions.py::test_normal_gaussian_2[(5,)]", "test/test_distributions.py::test_normal_gaussian_2[(2,", "test/test_distributions.py::test_normal_gaussian_3[()]", "test/test_distributions.py::test_normal_gaussian_3[(5,)]", "test/test_distributions.py::test_normal_gaussian_3[(2,", "test/test_distributions.py::test_mvn_defaults", "test/test_distributions.py::test_mvn_density[()]", "test/test_distributions.py::test_mvn_density[(5,)]", "test/test_distributions.py::test_mvn_density[(2,", "test/test_distributions.py::test_mvn_gaussian[()]", "test/test_distributions.py::test_mvn_gaussian[(5,)]", "test/test_distributions.py::test_mvn_gaussian[(2,", "test/test_torch.py::test_to_funsor[dtype0-shape0]", "test/test_torch.py::test_to_funsor[dtype0-shape1]", "test/test_torch.py::test_to_funsor[dtype0-shape2]", "test/test_torch.py::test_to_funsor[dtype1-shape0]", "test/test_torch.py::test_to_funsor[dtype1-shape1]", "test/test_torch.py::test_to_funsor[dtype1-shape2]", "test/test_torch.py::test_to_funsor[dtype2-shape0]", "test/test_torch.py::test_to_funsor[dtype2-shape1]", "test/test_torch.py::test_to_funsor[dtype2-shape2]", "test/test_torch.py::test_cons_hash", "test/test_torch.py::test_indexing", "test/test_torch.py::test_advanced_indexing_shape", "test/test_torch.py::test_advanced_indexing_tensor[output_shape0]", "test/test_torch.py::test_advanced_indexing_tensor[output_shape1]", "test/test_torch.py::test_advanced_indexing_tensor[output_shape2]", "test/test_torch.py::test_advanced_indexing_lazy[output_shape0]", "test/test_torch.py::test_advanced_indexing_lazy[output_shape1]", "test/test_torch.py::test_advanced_indexing_lazy[output_shape2]", "test/test_torch.py::test_unary[~-dims0]", "test/test_torch.py::test_unary[~-dims1]", "test/test_torch.py::test_unary[~-dims2]", "test/test_torch.py::test_unary[--dims0]", "test/test_torch.py::test_unary[--dims1]", "test/test_torch.py::test_unary[--dims2]", "test/test_torch.py::test_unary[abs-dims0]", "test/test_torch.py::test_unary[abs-dims1]", "test/test_torch.py::test_unary[abs-dims2]", "test/test_torch.py::test_unary[sqrt-dims0]", "test/test_torch.py::test_unary[sqrt-dims1]", "test/test_torch.py::test_unary[sqrt-dims2]", "test/test_torch.py::test_unary[exp-dims0]", "test/test_torch.py::test_unary[exp-dims1]", "test/test_torch.py::test_unary[exp-dims2]", "test/test_torch.py::test_unary[log-dims0]", "test/test_torch.py::test_unary[log-dims1]", "test/test_torch.py::test_unary[log-dims2]", "test/test_torch.py::test_unary[log1p-dims0]", "test/test_torch.py::test_unary[log1p-dims1]", "test/test_torch.py::test_unary[log1p-dims2]", "test/test_torch.py::test_binary_funsor_funsor[+-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[+-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[+-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[+-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[+-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[+-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[+-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[+-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[+-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[+-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[+-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[+-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[+-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[+-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[+-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[+-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[--dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[--dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[--dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[--dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[--dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[--dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[--dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[--dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[--dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[--dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[--dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[--dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[--dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[--dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[--dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[--dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[*-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[*-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[*-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[*-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[*-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[*-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[*-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[*-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[*-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[*-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[*-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[*-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[*-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[*-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[*-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[*-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[/-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[/-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[/-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[/-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[/-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[/-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[/-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[/-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[/-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[/-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[/-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[/-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[/-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[/-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[/-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[/-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[**-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[**-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[**-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[**-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[**-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[**-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[**-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[**-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[**-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[**-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[**-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[**-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[**-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[**-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[**-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[**-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[==-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[==-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[==-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[==-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[==-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[==-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[==-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[==-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[==-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[==-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[==-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[==-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[==-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[==-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[==-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[==-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[!=-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[<=-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[>=-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[min-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[min-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[min-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[min-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[min-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[min-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[min-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[min-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[min-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[min-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[min-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[min-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[min-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[min-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[min-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[min-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[max-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[max-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[max-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[max-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[max-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[max-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[max-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[max-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[max-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[max-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[max-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[max-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[max-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[max-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[max-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[max-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[&-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[&-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[&-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[&-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[&-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[&-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[&-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[&-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[&-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[&-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[&-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[&-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[&-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[&-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[&-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[&-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[|-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[|-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[|-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[|-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[|-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[|-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[|-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[|-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[|-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[|-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[|-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[|-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[|-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[|-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[|-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[|-dims13-dims23]", "test/test_torch.py::test_binary_funsor_funsor[^-dims10-dims20]", "test/test_torch.py::test_binary_funsor_funsor[^-dims10-dims21]", "test/test_torch.py::test_binary_funsor_funsor[^-dims10-dims22]", "test/test_torch.py::test_binary_funsor_funsor[^-dims10-dims23]", "test/test_torch.py::test_binary_funsor_funsor[^-dims11-dims20]", "test/test_torch.py::test_binary_funsor_funsor[^-dims11-dims21]", "test/test_torch.py::test_binary_funsor_funsor[^-dims11-dims22]", "test/test_torch.py::test_binary_funsor_funsor[^-dims11-dims23]", "test/test_torch.py::test_binary_funsor_funsor[^-dims12-dims20]", "test/test_torch.py::test_binary_funsor_funsor[^-dims12-dims21]", "test/test_torch.py::test_binary_funsor_funsor[^-dims12-dims22]", "test/test_torch.py::test_binary_funsor_funsor[^-dims12-dims23]", "test/test_torch.py::test_binary_funsor_funsor[^-dims13-dims20]", "test/test_torch.py::test_binary_funsor_funsor[^-dims13-dims21]", "test/test_torch.py::test_binary_funsor_funsor[^-dims13-dims22]", "test/test_torch.py::test_binary_funsor_funsor[^-dims13-dims23]", "test/test_torch.py::test_binary_funsor_scalar[+-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[+-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[+-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[+-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[--dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[--dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[--dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[--dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[*-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[*-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[*-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[*-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[/-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[/-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[/-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[/-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[**-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[**-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[**-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[**-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[==-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[==-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[==-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[==-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[!=-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[!=-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[!=-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[!=-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<=-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<=-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<=-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[<=-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>=-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>=-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>=-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[>=-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[min-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[min-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[min-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[min-dims3-0.5]", "test/test_torch.py::test_binary_funsor_scalar[max-dims0-0.5]", "test/test_torch.py::test_binary_funsor_scalar[max-dims1-0.5]", "test/test_torch.py::test_binary_funsor_scalar[max-dims2-0.5]", "test/test_torch.py::test_binary_funsor_scalar[max-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[+-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[+-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[+-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[+-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[--dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[--dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[--dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[--dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[*-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[*-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[*-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[*-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[/-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[/-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[/-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[/-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[**-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[**-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[**-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[**-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[==-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[==-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[==-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[==-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[!=-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[!=-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[!=-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[!=-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<=-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<=-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<=-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[<=-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>=-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>=-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>=-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[>=-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[min-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[min-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[min-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[min-dims3-0.5]", "test/test_torch.py::test_binary_scalar_funsor[max-dims0-0.5]", "test/test_torch.py::test_binary_scalar_funsor[max-dims1-0.5]", "test/test_torch.py::test_binary_scalar_funsor[max-dims2-0.5]", "test/test_torch.py::test_binary_scalar_funsor[max-dims3-0.5]", "test/test_torch.py::test_reduce_all[<dispatched", "test/test_torch.py::test_reduce_subset[add-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[add-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[add-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[add-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[add-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[add-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[add-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[add-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[add-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[add-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[add-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[add-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[add-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[add-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_subset[mul-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[mul-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[mul-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[mul-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[mul-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[mul-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[mul-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[mul-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[mul-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[mul-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[mul-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[mul-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[mul-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[mul-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_subset[and_-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[and_-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[and_-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[and_-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[and_-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[and_-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[and_-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[and_-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[and_-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[and_-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[and_-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[and_-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[and_-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[and_-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_subset[or_-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[or_-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[or_-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[or_-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[or_-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[or_-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[or_-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[or_-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[or_-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[or_-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[or_-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[or_-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[or_-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[or_-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_subset[logaddexp-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[logaddexp-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[logaddexp-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[logaddexp-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[logaddexp-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[logaddexp-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[logaddexp-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[logaddexp-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[logaddexp-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[logaddexp-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[logaddexp-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[logaddexp-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[logaddexp-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[logaddexp-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_subset[min-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[min-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[min-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[min-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[min-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[min-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[min-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[min-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[min-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[min-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[min-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[min-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[min-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[min-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_subset[max-dims0-reduced_vars0]", "test/test_torch.py::test_reduce_subset[max-dims1-reduced_vars1]", "test/test_torch.py::test_reduce_subset[max-dims2-reduced_vars2]", "test/test_torch.py::test_reduce_subset[max-dims3-reduced_vars3]", "test/test_torch.py::test_reduce_subset[max-dims4-reduced_vars4]", "test/test_torch.py::test_reduce_subset[max-dims5-reduced_vars5]", "test/test_torch.py::test_reduce_subset[max-dims6-reduced_vars6]", "test/test_torch.py::test_reduce_subset[max-dims7-reduced_vars7]", "test/test_torch.py::test_reduce_subset[max-dims8-reduced_vars8]", "test/test_torch.py::test_reduce_subset[max-dims9-reduced_vars9]", "test/test_torch.py::test_reduce_subset[max-dims10-reduced_vars10]", "test/test_torch.py::test_reduce_subset[max-dims11-reduced_vars11]", "test/test_torch.py::test_reduce_subset[max-dims12-reduced_vars12]", "test/test_torch.py::test_reduce_subset[max-dims13-reduced_vars13]", "test/test_torch.py::test_reduce_event[<dispatched", "test/test_torch.py::test_all_equal[shape0]", "test/test_torch.py::test_all_equal[shape1]", "test/test_torch.py::test_all_equal[shape2]", "test/test_torch.py::test_function_matmul", "test/test_torch.py::test_function_lazy_matmul", "test/test_torch.py::test_align", "test/test_torch.py::test_einsum[a->a]", "test/test_torch.py::test_einsum[a,a->a]", "test/test_torch.py::test_einsum[a,b->]", "test/test_torch.py::test_einsum[a,b->a]", "test/test_torch.py::test_einsum[a,b->b]", "test/test_torch.py::test_einsum[a,b->ab]", "test/test_torch.py::test_einsum[a,b->ba]", "test/test_torch.py::test_einsum[ab,ba->]", "test/test_torch.py::test_einsum[ab,ba->a]", "test/test_torch.py::test_einsum[ab,ba->b]", "test/test_torch.py::test_einsum[ab,ba->ab]", "test/test_torch.py::test_einsum[ab,ba->ba]", "test/test_torch.py::test_einsum[ab,bc->ac]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-03-19 23:31:50+00:00
mit
5,028
pysal__esda-235
diff --git a/esda/adbscan.py b/esda/adbscan.py index dbb69e2..6d8444b 100644 --- a/esda/adbscan.py +++ b/esda/adbscan.py @@ -247,9 +247,12 @@ def _one_draw(pars): if sample_weight is not None: thin_sample_weight = sample_weight.iloc[rids] + min_samples = min_samples * pct_exact + min_samples = 1 if min_samples < 1 else int(np.floor(min_samples)) + dbs = DBSCAN( eps=eps, - min_samples=int(np.round(min_samples * pct_exact)), + min_samples=min_samples, algorithm=algorithm, n_jobs=n_jobs, ).fit(X_thin[xy], sample_weight=thin_sample_weight)
pysal/esda
ec12837871b20b7b79c2c7bef813025459f22188
diff --git a/esda/tests/test_adbscan.py b/esda/tests/test_adbscan.py index 8440012..ea2434a 100644 --- a/esda/tests/test_adbscan.py +++ b/esda/tests/test_adbscan.py @@ -2,7 +2,6 @@ import unittest import numpy as np import pandas -import pytest from .. import adbscan @@ -73,9 +72,6 @@ class ADBSCAN_Tester(unittest.TestCase): ] ) - @pytest.mark.xfail( - raises=ValueError, reason="**NEEDS ATTENTION**. Change in scikit-learn>=1.1." - ) def test_adbscan(self): # ------------------------# # # Single Core # @@ -264,9 +260,6 @@ class Get_Cluster_Boundary_Tester(unittest.TestCase): _ = ads.fit(self.db, xy=["x", "y"]) self.labels = pandas.Series(ads.labels_, index=self.db.index) - @pytest.mark.xfail( - raises=ValueError, reason="**NEEDS ATTENTION**. Change in scikit-learn>=1.1." - ) def test_get_cluster_boundary(self): # ------------------------# # # Single Core #
Bug: ADBSCAN.fit is broken https://github.com/pysal/esda/actions/runs/3071277058/jobs/4961813274#step:4:210 It appears that `min_samples` is no longer getting set properly: ``` E ValueError: min_samples == 0, must be >= 1. ```
0.0
ec12837871b20b7b79c2c7bef813025459f22188
[ "esda/tests/test_adbscan.py::ADBSCAN_Tester::test_adbscan", "esda/tests/test_adbscan.py::Get_Cluster_Boundary_Tester::test_get_cluster_boundary" ]
[ "esda/tests/test_adbscan.py::Remap_lbls_Tester::test_remap_lbls", "esda/tests/test_adbscan.py::Ensemble_Tester::test_ensemble", "esda/tests/test_adbscan.py::i::test_ensemble" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-11-23 18:22:00+00:00
bsd-3-clause
5,029
pyscript__pyscript-cli-46
diff --git a/src/pyscript/__init__.py b/src/pyscript/__init__.py index 471235c..dd9dfc1 100644 --- a/src/pyscript/__init__.py +++ b/src/pyscript/__init__.py @@ -7,13 +7,13 @@ from rich.console import Console APPNAME = "pyscript" APPAUTHOR = "python" -DEFAULT_CONFIG_FILENAME = "pyscript.json" +DEFAULT_CONFIG_FILENAME = ".pyscriptconfig" # Default initial data for the command line. DEFAULT_CONFIG = { # Name of config file for PyScript projects. - "project_config_filename": "manifest.json", + "project_config_filename": "pyscript.toml", } diff --git a/src/pyscript/_generator.py b/src/pyscript/_generator.py index 1a949ba..86b8e4e 100644 --- a/src/pyscript/_generator.py +++ b/src/pyscript/_generator.py @@ -4,6 +4,7 @@ from pathlib import Path from typing import Optional import jinja2 +import toml from pyscript import config @@ -50,6 +51,10 @@ def create_project( app_dir.mkdir() manifest_file = app_dir / config["project_config_filename"] with manifest_file.open("w", encoding="utf-8") as fp: - json.dump(context, fp) + if str(manifest_file).endswith(".json"): + json.dump(context, fp) + else: + toml.dump(context, fp) + index_file = app_dir / "index.html" string_to_html('print("Hello, world!")', app_name, index_file)
pyscript/pyscript-cli
0ae6a4b4bc4df9b37315c8833932e51177e7ff74
diff --git a/tests/test_generator.py b/tests/test_generator.py index 1664ce7..da8c9ef 100644 --- a/tests/test_generator.py +++ b/tests/test_generator.py @@ -8,41 +8,126 @@ from pathlib import Path from typing import Any import pytest +import toml from pyscript import _generator as gen from pyscript import config +TESTS_AUTHOR_NAME = "A.Coder" +TESTS_AUTHOR_EMAIL = "[email protected]" + def test_create_project(tmp_cwd: Path, is_not_none: Any) -> None: app_name = "app_name" app_description = "A longer, human friendly, app description." - author_name = "A.Coder" - author_email = "[email protected]" - gen.create_project(app_name, app_description, author_name, author_email) - manifest_path = tmp_cwd / app_name / config["project_config_filename"] - assert manifest_path.exists() + # GIVEN a a new project + gen.create_project(app_name, app_description, TESTS_AUTHOR_NAME, TESTS_AUTHOR_EMAIL) - with manifest_path.open() as fp: - contents = json.load(fp) + # with a default config path + manifest_path = tmp_cwd / app_name / config["project_config_filename"] - assert contents == { - "name": "app_name", - "description": "A longer, human friendly, app description.", - "type": "app", - "author_name": "A.Coder", - "author_email": "[email protected]", - "version": is_not_none, - } + check_project_manifest(manifest_path, toml, app_name, is_not_none) def test_create_project_twice_raises_error(tmp_cwd: Path) -> None: """We get a FileExistsError when we try to create an existing project.""" app_name = "app_name" app_description = "A longer, human friendly, app description." - author_name = "A.Coder" - author_email = "[email protected]" - gen.create_project(app_name, app_description, author_name, author_email) + gen.create_project(app_name, app_description, TESTS_AUTHOR_NAME, TESTS_AUTHOR_EMAIL) with pytest.raises(FileExistsError): - gen.create_project(app_name, app_description, author_name, author_email) + gen.create_project( + app_name, app_description, TESTS_AUTHOR_NAME, TESTS_AUTHOR_EMAIL + ) + + +def test_create_project_explicit_json( + tmp_cwd: Path, is_not_none: Any, monkeypatch +) -> None: + app_name = "JSON_app_name" + app_description = "A longer, human friendly, app description." + + # Let's patch the config so that the project config file is a JSON file + config_file_name = "pyscript.json" + monkeypatch.setitem(gen.config, "project_config_filename", config_file_name) + + # GIVEN a new project + gen.create_project(app_name, app_description, TESTS_AUTHOR_NAME, TESTS_AUTHOR_EMAIL) + + # get the path where the config file is being created + manifest_path = tmp_cwd / app_name / config["project_config_filename"] + + check_project_manifest(manifest_path, json, app_name, is_not_none) + + +def test_create_project_explicit_toml( + tmp_cwd: Path, is_not_none: Any, monkeypatch +) -> None: + app_name = "TOML_app_name" + app_description = "A longer, human friendly, app description." + + # Let's patch the config so that the project config file is a JSON file + config_file_name = "mypyscript.toml" + monkeypatch.setitem(gen.config, "project_config_filename", config_file_name) + + # GIVEN a new project + gen.create_project(app_name, app_description, TESTS_AUTHOR_NAME, TESTS_AUTHOR_EMAIL) + + # get the path where the config file is being created + manifest_path = tmp_cwd / app_name / config["project_config_filename"] + + check_project_manifest(manifest_path, toml, app_name, is_not_none) + + +def check_project_manifest( + config_path: Path, + serializer: Any, + app_name: str, + is_not_none: Any, + app_description: str = "A longer, human friendly, app description.", + author_name: str = TESTS_AUTHOR_NAME, + author_email: str = TESTS_AUTHOR_EMAIL, + project_type: str = "app", +): + """ + Perform the following: + + * checks that `config_path` exists + * loads the contents of `config_path` using `serializer.load` + * check that the contents match with the values provided in input. Specifically: + * "name" == app_name + * "description" == app_description + * "type" == app_type + * "author_name" == author_name + * "author_email" == author_email + * "version" == is_not_none + + Params: + * config_path(Path): path to the app config file + * serializer(json|toml): serializer to be used to load contents of `config_path`. + Supported values are either modules `json` or `toml` + * app_name(str): name of application + * is_not_none(any): pytest fixture + * app_description(str): application description + * author_name(str): application author name + * author_email(str): application author email + * project_type(str): project type + + """ + # assert that the new project config file exists + assert config_path.exists() + + # assert that we can load it as a TOML file (TOML is the default config format) + # and that the contents of the config are as we expect + with config_path.open() as fp: + contents = serializer.load(fp) + + assert contents == { + "name": app_name, + "description": app_description, + "type": project_type, + "author_name": author_name, + "author_email": author_email, + "version": is_not_none, + }
CLI config file and Default project config file names Naming is hard but necessary! We need a place to PyScript CLI global configurations (that I'm referring to as CLI config file) and PyScript apps now have [a JSON/[TOML]](https://github.com/pyscript/pyscript/pull/754) format for Apps configuration. So we need to choose a default name for that file when the CLI creates a new project (referring to as project config). My proposal here is that: 1. we use TOML for the CLI config file format 2. we name it `pyscript.config.toml` or `.pyscriptconfig` 3. we name the default project config file to `pyscript.json` /cc @ntoll @mattkram
0.0
0ae6a4b4bc4df9b37315c8833932e51177e7ff74
[ "tests/test_generator.py::test_create_project", "tests/test_generator.py::test_create_project_explicit_toml" ]
[ "tests/test_generator.py::test_create_project_twice_raises_error", "tests/test_generator.py::test_create_project_explicit_json" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-01-05 19:21:11+00:00
apache-2.0
5,030
pyscript__pyscript-cli-67
diff --git a/src/pyscript/__init__.py b/src/pyscript/__init__.py index eb2c702..6b07387 100644 --- a/src/pyscript/__init__.py +++ b/src/pyscript/__init__.py @@ -5,11 +5,11 @@ from pathlib import Path import platformdirs from rich.console import Console +LATEST_PYSCRIPT_VERSION = "2022.12.1" APPNAME = "pyscript" APPAUTHOR = "python" DEFAULT_CONFIG_FILENAME = ".pyscriptconfig" - # Default initial data for the command line. DEFAULT_CONFIG = { # Name of config file for PyScript projects. diff --git a/src/pyscript/_generator.py b/src/pyscript/_generator.py index aedac05..e46d373 100644 --- a/src/pyscript/_generator.py +++ b/src/pyscript/_generator.py @@ -6,7 +6,7 @@ from typing import Optional import jinja2 import toml -from pyscript import config +from pyscript import LATEST_PYSCRIPT_VERSION, config _env = jinja2.Environment(loader=jinja2.PackageLoader("pyscript")) TEMPLATE_PYTHON_CODE = """# Replace the code below with your own @@ -15,7 +15,11 @@ print("Hello, world!") def create_project_html( - title: str, python_file_path: str, config_file_path: str, output_file_path: Path + title: str, + python_file_path: str, + config_file_path: str, + output_file_path: Path, + pyscript_version: str = LATEST_PYSCRIPT_VERSION, ) -> None: """Write a Python script string to an HTML file template.""" template = _env.get_template("basic.html") @@ -25,6 +29,7 @@ def create_project_html( python_file_path=python_file_path, config_file_path=config_file_path, title=title, + pyscript_version=pyscript_version, ) ) @@ -49,7 +54,11 @@ def save_config_file(config_file: Path, configuration: dict): def string_to_html( - code: str, title: str, output_path: Path, template_name: str = "basic.html" + code: str, + title: str, + output_path: Path, + template_name: str = "basic.html", + pyscript_version: str = LATEST_PYSCRIPT_VERSION, ) -> None: """Write a Python script string to an HTML file template. @@ -59,14 +68,18 @@ def string_to_html( PyScript app template - title(str): application title, that will be placed as title of the html app template + - output_path(Path): path where to write the new html file - template_name(str): name of the template to be used + - pyscript_version(str): version of pyscript to be used Output: (None) """ template = _env.get_template(template_name) with output_path.open("w") as fp: - fp.write(template.render(code=code, title=title)) + fp.write( + template.render(code=code, title=title, pyscript_version=pyscript_version) + ) def file_to_html( @@ -74,11 +87,12 @@ def file_to_html( title: str, output_path: Optional[Path], template_name: str = "basic.html", + pyscript_version: str = LATEST_PYSCRIPT_VERSION, ) -> None: """Write a Python script string to an HTML file template.""" output_path = output_path or input_path.with_suffix(".html") with input_path.open("r") as fp: - string_to_html(fp.read(), title, output_path, template_name) + string_to_html(fp.read(), title, output_path, template_name, pyscript_version) def create_project( @@ -86,6 +100,7 @@ def create_project( app_description: str, author_name: str, author_email: str, + pyscript_version: str = LATEST_PYSCRIPT_VERSION, ) -> None: """ New files created: @@ -124,4 +139,5 @@ def create_project( config["project_main_filename"], config["project_config_filename"], index_file, + pyscript_version=pyscript_version, ) diff --git a/src/pyscript/plugins/create.py b/src/pyscript/plugins/create.py index aeed292..e51ecd0 100644 --- a/src/pyscript/plugins/create.py +++ b/src/pyscript/plugins/create.py @@ -1,4 +1,4 @@ -from pyscript import app, cli, plugins +from pyscript import LATEST_PYSCRIPT_VERSION, app, cli, plugins from pyscript._generator import create_project try: @@ -13,6 +13,11 @@ def create( app_description: str = typer.Option(..., prompt=True), author_name: str = typer.Option(..., prompt=True), author_email: str = typer.Option(..., prompt=True), + pyscript_version: str = typer.Option( + LATEST_PYSCRIPT_VERSION, + "--pyscript-version", + help="If provided, defines what version of pyscript will be used to create the app", + ), ): """ Create a new pyscript project with the passed in name, creating a new @@ -21,7 +26,9 @@ def create( TODO: Agree on the metadata to be collected from the user. """ try: - create_project(app_name, app_description, author_name, author_email) + create_project( + app_name, app_description, author_name, author_email, pyscript_version + ) except FileExistsError: raise cli.Abort( f"A directory called {app_name} already exists in this location." diff --git a/src/pyscript/plugins/wrap.py b/src/pyscript/plugins/wrap.py index 931f406..d4f68a7 100644 --- a/src/pyscript/plugins/wrap.py +++ b/src/pyscript/plugins/wrap.py @@ -3,7 +3,7 @@ import webbrowser from pathlib import Path from typing import Optional -from pyscript import app, cli, console, plugins +from pyscript import LATEST_PYSCRIPT_VERSION, app, cli, console, plugins from pyscript._generator import file_to_html, string_to_html try: @@ -29,6 +29,11 @@ def wrap( ), show: Optional[bool] = typer.Option(None, help="Open output file in web browser."), title: Optional[str] = typer.Option(None, help="Add title to HTML file."), + pyscript_version: str = typer.Option( + LATEST_PYSCRIPT_VERSION, + "--pyscript-version", + help="If provided, defines what version of pyscript will be used to create the app", + ), ) -> None: """Wrap a Python script inside an HTML file.""" title = title or "PyScript App" @@ -52,9 +57,21 @@ def wrap( else: raise cli.Abort("Must provide an output file or use `--show` option") if input_file is not None: - file_to_html(input_file, title, output, template_name="wrap.html") + file_to_html( + input_file, + title, + output, + template_name="wrap.html", + pyscript_version=pyscript_version, + ) if command: - string_to_html(command, title, output, template_name="wrap.html") + string_to_html( + command, + title, + output, + template_name="wrap.html", + pyscript_version=pyscript_version, + ) if output: if show: console.print("Opening in web browser!") diff --git a/src/pyscript/templates/basic.html b/src/pyscript/templates/basic.html index 82817fa..256a406 100644 --- a/src/pyscript/templates/basic.html +++ b/src/pyscript/templates/basic.html @@ -2,8 +2,8 @@ <html lang="en"> <head> <title>{{ title }}</title> - <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css"/> - <script defer src="https://pyscript.net/alpha/pyscript.js"></script> + <link rel="stylesheet" href="https://pyscript.net/releases/{{ pyscript_version }}/pyscript.css"/> + <script defer src="https://pyscript.net/releases/{{ pyscript_version }}/pyscript.js"></script> </head> <body> <py-config src="./{{ config_file_path }}"></py-config> diff --git a/src/pyscript/templates/wrap.html b/src/pyscript/templates/wrap.html index 16c1a3a..2b84760 100644 --- a/src/pyscript/templates/wrap.html +++ b/src/pyscript/templates/wrap.html @@ -2,8 +2,8 @@ <html lang="en"> <head> <title>{{ title }}</title> - <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css"/> - <script defer src="https://pyscript.net/alpha/pyscript.js"></script> + <link rel="stylesheet" href="https://pyscript.net/releases/{{ pyscript_version }}/pyscript.css"/> + <script defer src="https://pyscript.net/releases/{{ pyscript_version }}/pyscript.js"></script> </head> <body> <py-script>
pyscript/pyscript-cli
1dfecebe75740e7c0c50ecb58e2354df9393b626
diff --git a/tests/test_cli.py b/tests/test_cli.py index 115bf94..2919986 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -8,7 +8,7 @@ import pytest from mypy_extensions import VarArg from typer.testing import CliRunner, Result -from pyscript import __version__ +from pyscript import LATEST_PYSCRIPT_VERSION, __version__, config from pyscript.cli import app if TYPE_CHECKING: @@ -167,3 +167,166 @@ def test_wrap_title( assert f"<py-script>\n{command}\n</py-script>" in html_text assert f"<title>{expected_title}</title>" in html_text + + [email protected]( + "version, expected_version", + [(None, LATEST_PYSCRIPT_VERSION), ("2022.9.1", "2022.9.1")], +) +def test_wrap_pyscript_version( + invoke_cli: CLIInvoker, + version: Optional[str], + expected_version: str, + tmp_path: Path, +) -> None: + """ + Test that when wrap is called passing a string code input and an explicit pyscript version + the project is created correctly + """ + command = 'print("Hello World!")' + args = ["wrap", "-c", command, "-o", "output.html"] + if version is not None: + args.extend(["--pyscript-version", version]) + + # GIVEN a call to wrap with a cmd input and specific pyscript version as arguments + result = invoke_cli(*args) + assert result.exit_code == 0 + + # EXPECT the output file to exist + expected_html_path = tmp_path / "output.html" + assert expected_html_path.exists() + + with expected_html_path.open() as fp: + html_text = fp.read() + + # EXPECT the right cmd to be present in the output file + assert f"<py-script>\n{command}\n</py-script>" in html_text + + # EXPECT the right JS and CSS version to be present in the output file + version_str = ( + f'<script defer src="https://pyscript.net/releases/{expected_version}' + '/pyscript.js"></script>' + ) + css_version_str = ( + '<link rel="stylesheet" href="https://pyscript.net/releases/' + f'{expected_version}/pyscript.css"/>' + ) + assert version_str in html_text + assert css_version_str in html_text + + [email protected]( + "version, expected_version", + [(None, LATEST_PYSCRIPT_VERSION), ("2022.9.1", "2022.9.1")], +) +def test_wrap_pyscript_version_file( + invoke_cli: CLIInvoker, + version: Optional[str], + expected_version: str, + tmp_path: Path, +) -> None: + """ + Test that when wrap is called passing a file input and an explicit pyscript version + the project is created correctly + """ + command = 'print("Hello World!")' + input_file = tmp_path / "hello.py" + with input_file.open("w") as fp: + fp.write(command) + + args = ["wrap", str(input_file), "-o", "output.html"] + + if version is not None: + args.extend(["--pyscript-version", version]) + + # GIVEN a call to wrap with a file and specific pyscript version as arguments + result = invoke_cli(*args) + assert result.exit_code == 0 + + # EXPECT the output file to exist + expected_html_path = tmp_path / "output.html" + assert expected_html_path.exists() + + with expected_html_path.open() as fp: + html_text = fp.read() + + # EXPECT the right cmd to be present in the output file + assert f"<py-script>\n{command}\n</py-script>" in html_text + + # EXPECT the right JS and CSS version to be present in the output file + version_str = ( + f'<script defer src="https://pyscript.net/releases/{expected_version}' + '/pyscript.js"></script>' + ) + css_version_str = ( + '<link rel="stylesheet" href="https://pyscript.net/releases/' + f'{expected_version}/pyscript.css"/>' + ) + assert version_str in html_text + assert css_version_str in html_text + + [email protected]( + "create_args, expected_version", + [ + (("myapp1",), LATEST_PYSCRIPT_VERSION), + (("myapp-w-version", "--pyscript-version", "2022.9.1"), "2022.9.1"), + ], +) +def test_create_project_version( + invoke_cli: CLIInvoker, + tmp_path: Path, + create_args: tuple[str], + expected_version: str, +) -> None: + """ + Test that project created with an explicit pyscript version are created correctly + """ + command = 'print("Hello World!")' + + input_file = tmp_path / "hello.py" + with input_file.open("w") as fp: + fp.write(command) + + cmd_args = list(create_args) + [ + "--app-description", + "", + "--author-name", + "tester", + "--author-email", + "[email protected]", + ] + + # GIVEN a call to wrap with a file and specific pyscript version as arguments + result = invoke_cli("create", *cmd_args) + assert result.exit_code == 0 + + # EXPECT the app folder to exist + expected_app_path = tmp_path / create_args[0] + assert expected_app_path.exists() + + # EXPECT the app folder to contain the right index.html file + app_file = expected_app_path / "index.html" + assert app_file.exists() + with app_file.open() as fp: + html_text = fp.read() + + # EXPECT the right JS and CSS version to be present in the html file + version_str = ( + f'<script defer src="https://pyscript.net/releases/{expected_version}' + '/pyscript.js"></script>' + ) + css_version_str = ( + '<link rel="stylesheet" href="https://pyscript.net/releases/' + f'{expected_version}/pyscript.css"/>' + ) + assert version_str in html_text + assert css_version_str in html_text + + # EXPECT the folder to also contain the python main file + py_file = expected_app_path / config["project_main_filename"] + assert py_file.exists() + + # EXPECT the folder to also contain the config file + config_file = expected_app_path / config["project_config_filename"] + assert config_file.exists()
create template still uses https://pyscript.net/alpha/pyscript.js As the title mentions, HTML template references alpha https://pyscript.net/alpha/pyscript.js. Ideally, the `create` cmd should be able to hit an API or something so that it can dynamically determine what's the latest release and pin/use that. Since we don't have an API right now, the scope of this issue is to pin the latest version statically as `default` value and add a new `create` cmd argument called `pyscript-version` that allows users to specify a different version instead of the `default`
0.0
1dfecebe75740e7c0c50ecb58e2354df9393b626
[ "tests/test_cli.py::test_version", "tests/test_cli.py::test_wrap_command[-c]", "tests/test_cli.py::test_wrap_command[--command]", "tests/test_cli.py::test_wrap_abort[empty_args]", "tests/test_cli.py::test_wrap_abort[command_and_script]", "tests/test_cli.py::test_wrap_abort[command_no_output_or_show]", "tests/test_cli.py::test_wrap_file[wrap_args0-output.html]", "tests/test_cli.py::test_wrap_file[wrap_args1-hello.html]", "tests/test_cli.py::test_wrap_show[hello.py-additional_args0-output.html]", "tests/test_cli.py::test_wrap_show[hello.py-additional_args1-None]", "tests/test_cli.py::test_wrap_show[None-additional_args2-None]", "tests/test_cli.py::test_wrap_title[test-title-test-title]", "tests/test_cli.py::test_wrap_title[None-PyScript", "tests/test_cli.py::test_wrap_title[-PyScript", "tests/test_cli.py::test_wrap_pyscript_version[None-2022.12.1]", "tests/test_cli.py::test_wrap_pyscript_version[2022.9.1-2022.9.1]", "tests/test_cli.py::test_wrap_pyscript_version_file[None-2022.12.1]", "tests/test_cli.py::test_wrap_pyscript_version_file[2022.9.1-2022.9.1]", "tests/test_cli.py::test_create_project_version[create_args0-2022.12.1]", "tests/test_cli.py::test_create_project_version[create_args1-2022.9.1]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-11 21:19:22+00:00
apache-2.0
5,031
pyscript__pyscript-cli-84
diff --git a/src/pyscript/cli.py b/src/pyscript/cli.py index 398f381..01fc547 100644 --- a/src/pyscript/cli.py +++ b/src/pyscript/cli.py @@ -7,7 +7,7 @@ from pluggy import PluginManager from pyscript import __version__, app, console, plugins, typer from pyscript.plugins import hookspecs -DEFAULT_PLUGINS = ["create", "wrap"] +DEFAULT_PLUGINS = ["create", "wrap", "run"] def ok(msg: str = ""): diff --git a/src/pyscript/plugins/run.py b/src/pyscript/plugins/run.py new file mode 100644 index 0000000..182e71e --- /dev/null +++ b/src/pyscript/plugins/run.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import socketserver +import threading +import webbrowser +from functools import partial +from http.server import SimpleHTTPRequestHandler +from pathlib import Path + +from pyscript import app, cli, console, plugins + +try: + import rich_click.typer as typer +except ImportError: # pragma: no cover + import typer # type: ignore + + +def get_folder_based_http_request_handler( + folder: Path, +) -> type[SimpleHTTPRequestHandler]: + """ + Returns a FolderBasedHTTPRequestHandler with the specified directory. + + Args: + folder (str): The folder that will be served. + + Returns: + FolderBasedHTTPRequestHandler: The SimpleHTTPRequestHandler with the + specified directory. + """ + + class FolderBasedHTTPRequestHandler(SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=folder, **kwargs) + + return FolderBasedHTTPRequestHandler + + +def split_path_and_filename(path: Path) -> tuple[Path, str]: + """Receives a path to a pyscript project or file and returns the base + path of the project and the filename that should be opened (filename defaults + to "" (empty string) if the path points to a folder). + + Args: + path (str): The path to the pyscript project or file. + + + Returns: + tuple(str, str): The base path of the project and the filename + """ + abs_path = path.absolute() + if path.is_file(): + return Path("/".join(abs_path.parts[:-1])), abs_path.parts[-1] + else: + return abs_path, "" + + +def start_server(path: Path, show: bool, port: int): + """ + Creates a local server to run the app on the path and port specified. + + Args: + path(str): The path of the project that will run. + show(bool): Open the app in web browser. + port(int): The port that the app will run on. + + Returns: + None + """ + # We need to set the allow_resuse_address to True because socketserver will + # keep the port in use for a while after the server is stopped. + # see https://stackoverflow.com/questions/31745040/ + socketserver.TCPServer.allow_reuse_address = True + + app_folder, filename = split_path_and_filename(path) + CustomHTTPRequestHandler = get_folder_based_http_request_handler(app_folder) + + # Start the server within a context manager to make sure we clean up after + with socketserver.TCPServer(("", port), CustomHTTPRequestHandler) as httpd: + console.print( + f"Serving from {app_folder} at port {port}. To stop, press Ctrl+C.", + style="green", + ) + + if show: + # Open the web browser in a separate thread after 0.5 seconds. + open_browser = partial( + webbrowser.open_new_tab, f"http://localhost:{port}/{filename}" + ) + threading.Timer(0.5, open_browser).start() + + try: + httpd.serve_forever() + except KeyboardInterrupt: + console.print("\nStopping server... Bye bye!") + + # Clean after ourselves.... + httpd.shutdown() + httpd.socket.close() + raise typer.Exit(1) + + [email protected]() +def run( + path: Path = typer.Argument( + Path("."), help="The path of the project that will run." + ), + silent: bool = typer.Option(False, help="Open the app in web browser."), + port: int = typer.Option(8000, help="The port that the app will run on."), +): + """ + Creates a local server to run the app on the path and port specified. + """ + + # First thing we need to do is to check if the path exists + if not path.exists(): + raise cli.Abort(f"Error: Path {str(path)} does not exist.", style="red") + + try: + start_server(path, not silent, port) + except OSError as e: + if e.errno == 48: + console.print( + f"Error: Port {port} is already in use! :( Please, stop the process using that port" + f"or ry another port using the --port option.", + style="red", + ) + else: + console.print(f"Error: {e.strerror}", style="red") + + raise cli.Abort("") + + [email protected] +def pyscript_subcommand(): + return run
pyscript/pyscript-cli
9ad671434a51cc0f5bdbe968c2e61251f335912b
diff --git a/tests/test_run_cli_cmd.py b/tests/test_run_cli_cmd.py new file mode 100644 index 0000000..88cbc46 --- /dev/null +++ b/tests/test_run_cli_cmd.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +from pathlib import Path +from unittest import mock + +import pytest +from utils import CLIInvoker, invoke_cli # noqa: F401 + +BASEPATH = str(Path(__file__).parent) + + [email protected]( + "path", + ["non_existing_folder", "non_existing_file.html"], +) +def test_run_bad_paths(invoke_cli: CLIInvoker, path: str): # noqa: F811 + """ + Test that when wrap is called passing a bad path as input the command fails + """ + # GIVEN a call to wrap with a bad path as argument + result = invoke_cli("run", path) + # EXPECT the command to fail + assert result.exit_code == 1 + # EXPECT the right error message to be printed + assert f"Error: Path {path} does not exist." in result.stdout + + +def test_run_server_bad_port(invoke_cli: CLIInvoker): # noqa: F811 + """ + Test that when run is called passing a bad port as input the command fails + """ + # GIVEN a call to run with a bad port as argument + result = invoke_cli("run", "--port", "bad_port") + # EXPECT the command to fail + assert result.exit_code == 2 + # EXPECT the right error message to be printed + assert "Error" in result.stdout + assert ( + "Invalid value for '--port': 'bad_port' is not a valid integer" in result.stdout + ) + + [email protected]("pyscript.plugins.run.start_server") +def test_run_server_with_default_values( + start_server_mock, invoke_cli: CLIInvoker # noqa: F811 +): + """ + Test that when run is called without arguments the command runs with the + default values + """ + # GIVEN a call to run without arguments + result = invoke_cli("run") + # EXPECT the command to succeed + assert result.exit_code == 0 + # EXPECT start_server_mock function to be called with the default values: + # Path("."): path to local folder + # show=True: the opposite of the --silent option (which default to False) + # port=8000: that is the default port + start_server_mock.assert_called_once_with(Path("."), True, 8000) + + [email protected]("pyscript.plugins.run.start_server") +def test_run_server_with_silent_flag( + start_server_mock, invoke_cli: CLIInvoker # noqa: F811 +): + """ + Test that when run is called without arguments the command runs with the + default values + """ + # GIVEN a call to run without arguments + result = invoke_cli("run", "--silent") + # EXPECT the command to succeed + assert result.exit_code == 0 + # EXPECT start_server_mock function to be called with the default values: + # Path("."): path to local folder + # show=False: the opposite of the --silent option + # port=8000: that is the default port + start_server_mock.assert_called_once_with(Path("."), False, 8000) + + [email protected]( + "run_args, expected_values", + [ + (("--silent",), (Path("."), False, 8000)), + ((BASEPATH,), (Path(BASEPATH), True, 8000)), + (("--port=8001",), (Path("."), True, 8001)), + (("--silent", "--port=8001"), (Path("."), False, 8001)), + ((BASEPATH, "--silent"), (Path(BASEPATH), False, 8000)), + ((BASEPATH, "--port=8001"), (Path(BASEPATH), True, 8001)), + ((BASEPATH, "--silent", "--port=8001"), (Path(BASEPATH), False, 8001)), + ((BASEPATH, "--port=8001"), (Path(BASEPATH), True, 8001)), + ], +) [email protected]("pyscript.plugins.run.start_server") +def test_run_server_with_valid_combinations( + start_server_mock, invoke_cli: CLIInvoker, run_args, expected_values # noqa: F811 +): + """ + Test that when run is called without arguments the command runs with the + default values + """ + # GIVEN a call to run without arguments + result = invoke_cli("run", *run_args) + # EXPECT the command to succeed + assert result.exit_code == 0 + # EXPECT start_server_mock function to be called with the expected values + start_server_mock.assert_called_once_with(*expected_values) diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 0000000..5abc565 --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING, Callable + +import pytest +from mypy_extensions import VarArg +from typer.testing import CliRunner, Result + +from pyscript.cli import app + +if TYPE_CHECKING: + from _pytest.monkeypatch import MonkeyPatch + +CLIInvoker = Callable[[VarArg(str)], Result] + + [email protected]() +def invoke_cli(tmp_path: Path, monkeypatch: "MonkeyPatch") -> CLIInvoker: + """Returns a function, which can be used to call the CLI from within a temporary directory.""" + runner = CliRunner() + + monkeypatch.chdir(tmp_path) + + def f(*args: str) -> Result: + return runner.invoke(app, args) + + return f
Add `pyscript serve` subcommand Command will run a simple HTTP server in order to host the files dynamically. This is required in order to allow `<py-script src="./my_module.py">` to work. ```shell $ pyscript serve my_file.html --show --autoreload ``` The `--autoreload` is a nice-to-have, but not necessary right now.
0.0
9ad671434a51cc0f5bdbe968c2e61251f335912b
[ "tests/test_run_cli_cmd.py::test_run_bad_paths[non_existing_folder]", "tests/test_run_cli_cmd.py::test_run_bad_paths[non_existing_file.html]", "tests/test_run_cli_cmd.py::test_run_server_bad_port", "tests/test_run_cli_cmd.py::test_run_server_with_default_values", "tests/test_run_cli_cmd.py::test_run_server_with_silent_flag", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args0-expected_values0]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args1-expected_values1]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args2-expected_values2]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args3-expected_values3]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args4-expected_values4]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args5-expected_values5]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args6-expected_values6]", "tests/test_run_cli_cmd.py::test_run_server_with_valid_combinations[run_args7-expected_values7]" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-05-15 21:27:35+00:00
apache-2.0
5,032
pyserial__pyserial-693
diff --git a/serial/serialutil.py b/serial/serialutil.py index f554472..87aaad9 100644 --- a/serial/serialutil.py +++ b/serial/serialutil.py @@ -557,6 +557,16 @@ class SerialBase(io.RawIOBase): b[:n] = array.array('b', data) return n + def close(self): + # Do not call RawIOBase.close() as that will try to flush(). + pass + + @property + def closed(self): + # Overrides RawIOBase.closed, as RawIOBase can only be closed once, + # but a Serial object can be opened/closed multiple times. + return not self.is_open + # - - - - - - - - - - - - - - - - - - - - - - - - # context manager
pyserial/pyserial
31fa4807d73ed4eb9891a88a15817b439c4eea2d
diff --git a/test/test_close.py b/test/test_close.py new file mode 100644 index 0000000..27b049e --- /dev/null +++ b/test/test_close.py @@ -0,0 +1,58 @@ +#! /usr/bin/env python +# +# This file is part of pySerial - Cross platform serial port support for Python +# (C) 2001-2015 Chris Liechti <[email protected]> +# (C) 2023 Google LLC +# +# SPDX-License-Identifier: BSD-3-Clause +import sys +import unittest +import serial + +# on which port should the tests be performed: +PORT = 'loop://' + +class TestClose(unittest.TestCase): + + def test_closed_true(self): + # closed is True if a Serial port is not open + s = serial.Serial() + self.assertFalse(s.is_open) + self.assertTrue(s.closed) + + def test_closed_false(self): + # closed is False if a Serial port is open + s = serial.serial_for_url(PORT, timeout=1) + self.assertTrue(s.is_open) + self.assertFalse(s.closed) + + s.close() + self.assertTrue(s.closed) + + def test_close_not_called_by_finalize_if_closed(self): + close_calls = 0 + + class TestSerial(serial.Serial): + def close(self): + nonlocal close_calls + close_calls += 1 + + with TestSerial() as s: + pass + # close() should be called here + + # Trigger RawIOBase finalization. + # Because we override .closed, close() should not be called + # if Serial says it is already closed. + del s + + self.assertEqual(close_calls, 1) + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +if __name__ == '__main__': + if len(sys.argv) > 1: + PORT = sys.argv[1] + sys.stdout.write("Testing port: {!r}\n".format(PORT)) + sys.argv[1:] = ['-v'] + # When this module is executed from the command-line, it runs all its tests + unittest.main()
SerialBase does not call RawIOBase.close() # TL;DR Neither `SerialBase` nor any of its derived classes call the ultimate parent class' `io.RawIOBase.close()` method. This leads to an extraneous `close()` call from the finalizer. # Problem Version info: ```pyi >>> sys.version '3.10.7 (main, Sep 8 2022, 14:34:29) [GCC 12.2.0]' >>> serial.__version__ '3.5' ``` Let's start with this surprising behavior: ```python import serial class MySerial(serial.Serial): def close(self): print('MySerial.close(): Enter') super().close() print('MySerial.close(): Exit') s = MySerial() print('end of script\n') ``` ```console $ python3 serialwtf_1.py end of script MySerial.close(): Enter MySerial.close(): Exit ``` :question: Surprisingly, there was a ghost call to `MySerial.close()` after the end of Python code execution. That is a clue that some destructor/finalizer is running. Even more surprising, any exceptions thrown from `close()` during this ghost call are swallowed and ignored. Painfully, none of these inspection tools could show me the source of this ghost call: - [`inspect.stack()`](https://docs.python.org/3/library/inspect.html#inspect.stack) -- Showed only the line where I called it - [`traceback.print_stack()`](https://docs.python.org/3/library/traceback.html#traceback.print_stack) -- Showed only the line where I called it - [`breakpoint()`](https://docs.python.org/3/library/functions.html#breakpoint) -- Ignored ## Explanation Note that [`SerialBase`](https://github.com/pyserial/pyserial/blob/v3.5/serial/serialutil.py#L165) inherits from [`io.RawIOBase`](https://docs.python.org/3/library/io.html#io.RawIOBase). It turns out that [`iobase_finalize()`](https://github.com/python/cpython/blob/v3.10.8/Modules/_io/iobase.c#L256-L307) (from the C module) will [call `.close()`](https://github.com/python/cpython/blob/v3.10.8/Modules/_io/iobase.c#L284) on the object if it has not already been marked as [`closed`](https://docs.python.org/3/library/io.html#io.IOBase.closed). It's worth noting that the C code will [set a `_finalizing` attribute to `True`](https://github.com/python/cpython/blob/v3.10.8/Modules/_io/iobase.c#L282) to let `close()` know it is called from the finalizer. This lets us prove our understanding: ```python import serial class MySerial(serial.Serial): def close(self): print('MySerial.close(): Enter: closed={} finalizing={}'.format( self.closed, getattr(self, '_finalizing', False))) super().close() print('MySerial.close(): Exit') s = MySerial() with s: print('exiting `with`') print('end of script\n') ``` ```console $ python3 serialwtf_2.py exiting `with` MySerial.close(): Enter: closed=False finalizing=False MySerial.close(): Exit end of script MySerial.close(): Enter: closed=False finalizing=True MySerial.close(): Exit ``` ## Root Cause `IOBase.closed` needs to be set, but the only way to do so is to call `IOBase.close()` (via `super()`). This indicates that `SerialBase` is not calling `IOBase.close()`, which is indeed the case. In fact, `SerialBase` does not implement `close()`, and `Serial` (from `serialposix.py` at least) does not call `super().close()`. # Solution The `Serial` classes should be good Python citizens and always call `super().close()` in their `close()` implementations. This example shows that this will fix the problem: ```python import serial import io class MySerial(serial.Serial): def close(self): print('MySerial.close(): Enter: closed={} finalizing={}'.format( self.closed, getattr(self, '_finalizing', False))) super().close() io.RawIOBase.close(self) # <<<<<<<< print('MySerial.close(): Exit') def flush(self): print('MySerial.flush(): skip') s = MySerial() print(f'Before with: s.closed={s.closed}') with s: print('exiting `with`') print(f'After with: s.closed={s.closed}') print('end of script\n') ``` ```console $ python3 serialwtf_3.py Before with: s.closed=False exiting `with` MySerial.close(): Enter: closed=False finalizing=False MySerial.flush(): skip MySerial.close(): Exit After with: s.closed=True end of script ``` Note that, for this example, I also had to neuter `flush()` because `IOBase.close()` essentially does this [(but in C)](https://github.com/python/cpython/blob/v3.10.8/Modules/_io/iobase.c#L212-L225): ```python def close(self): self.flush() self.closed = True ``` ...and [`serialposix.py:Serial.flush()`](https://github.com/pyserial/pyserial/blob/v3.5/serial/serialposix.py#L666-L673) will raise an exception if it is not open. I'm not yet sure how to fix this aspect. It seems like `IOBase` doesn't like the idea of being constructed but *not* open (unlike `Serial`).
0.0
31fa4807d73ed4eb9891a88a15817b439c4eea2d
[ "test/test_close.py::TestClose::test_close_not_called_by_finalize_if_closed", "test/test_close.py::TestClose::test_closed_true" ]
[ "test/test_close.py::TestClose::test_closed_false" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-03-23 17:49:06+00:00
bsd-3-clause
5,033
pysmt__pysmt-243
diff --git a/make_distrib.sh b/make_distrib.sh index a6bba27..a007ea0 100755 --- a/make_distrib.sh +++ b/make_distrib.sh @@ -6,7 +6,8 @@ python setup.py sdist --format=gztar # Wheel file python setup.py bdist_wheel --universal -wget https://bitbucket.org/gutworth/six/raw/8a545f4e906f6f479a6eb8837f31d03731597687/six.py -O dist/six.py + +wget https://bitbucket.org/gutworth/six/raw/e5218c3f66a2614acb7572204a27e2b508682168/six.py -O dist/six.py echo "To create a self-contained wheel pkg, manually add six:" echo " $ zip PySMT-version.whl six.py" echo "A copy of six.py has been downloaded in dist/" diff --git a/pysmt/formula.py b/pysmt/formula.py index 0a4dcd3..4fdcbfe 100644 --- a/pysmt/formula.py +++ b/pysmt/formula.py @@ -477,7 +477,7 @@ class FormulaManager(object): A -> !(B \/ C) B -> !(C) """ - args = list(*args) + args = self._polymorph_args_to_tuple(args) return self.And(self.Or(*args), self.AtMostOne(*args))
pysmt/pysmt
2abfb4538fa93379f9b2671bce30f27967dedbcf
diff --git a/pysmt/test/test_formula.py b/pysmt/test/test_formula.py index 0ddbec4..924328a 100644 --- a/pysmt/test/test_formula.py +++ b/pysmt/test/test_formula.py @@ -494,6 +494,16 @@ class TestFormulaManager(TestCase): self.assertEqual(c, self.mgr.Bool(False), "ExactlyOne should not allow 2 symbols to be True") + s1 = self.mgr.Symbol("x") + s2 = self.mgr.Symbol("x") + f1 = self.mgr.ExactlyOne((s for s in [s1,s2])) + f2 = self.mgr.ExactlyOne([s1,s2]) + f3 = self.mgr.ExactlyOne(s1,s2) + + self.assertEqual(f1,f2) + self.assertEqual(f2,f3) + + @skipIfNoSolverForLogic(QF_BOOL) def test_exactly_one_is_sat(self): symbols = [ self.mgr.Symbol("s%d"%i, BOOL) for i in range(5) ] diff --git a/pysmt/test/test_regressions.py b/pysmt/test/test_regressions.py index 2fecd04..67bfc3d 100644 --- a/pysmt/test/test_regressions.py +++ b/pysmt/test/test_regressions.py @@ -311,6 +311,14 @@ class TestRegressions(TestCase): close_l = get_closer_smtlib_logic(logics.BOOL) self.assertEqual(close_l, logics.LRA) + def test_exactly_one_unpacking(self): + s1,s2 = Symbol("x"), Symbol("y") + f1 = ExactlyOne((s for s in [s1,s2])) + f2 = ExactlyOne([s1,s2]) + f3 = ExactlyOne(s1,s2) + + self.assertEqual(f1,f2) + self.assertEqual(f2,f3) if __name__ == "__main__": main()
issue in processing arguments for ExactlyOne() Hi, I noticed that instantiating shortcuts.ExactlyOne() throws e.g. TypeError: list() takes at most 1 argument (3 given) at formula.py, line 480. I believe args shouldn't be unpacked in the list constructor. Martin
0.0
2abfb4538fa93379f9b2671bce30f27967dedbcf
[ "pysmt/test/test_formula.py::TestFormulaManager::test_exactly_one", "pysmt/test/test_regressions.py::TestRegressions::test_exactly_one_unpacking" ]
[ "pysmt/test/test_formula.py::TestFormulaManager::test_0arity_function", "pysmt/test/test_formula.py::TestFormulaManager::test_all_different", "pysmt/test/test_formula.py::TestFormulaManager::test_and_node", "pysmt/test/test_formula.py::TestFormulaManager::test_at_most_one", "pysmt/test/test_formula.py::TestFormulaManager::test_bconstant", "pysmt/test/test_formula.py::TestFormulaManager::test_constant", "pysmt/test/test_formula.py::TestFormulaManager::test_div_node", "pysmt/test/test_formula.py::TestFormulaManager::test_div_non_linear", "pysmt/test/test_formula.py::TestFormulaManager::test_equals", "pysmt/test/test_formula.py::TestFormulaManager::test_equals_or_iff", "pysmt/test/test_formula.py::TestFormulaManager::test_formula_in_formula_manager", "pysmt/test/test_formula.py::TestFormulaManager::test_function", "pysmt/test/test_formula.py::TestFormulaManager::test_ge_node", "pysmt/test/test_formula.py::TestFormulaManager::test_ge_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_get_or_create_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_get_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_gt_node", "pysmt/test/test_formula.py::TestFormulaManager::test_gt_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_iff_node", "pysmt/test/test_formula.py::TestFormulaManager::test_implies_node", "pysmt/test/test_formula.py::TestFormulaManager::test_infix", "pysmt/test/test_formula.py::TestFormulaManager::test_infix_extended", "pysmt/test/test_formula.py::TestFormulaManager::test_is_term", "pysmt/test/test_formula.py::TestFormulaManager::test_ite", "pysmt/test/test_formula.py::TestFormulaManager::test_le_node", "pysmt/test/test_formula.py::TestFormulaManager::test_le_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_lt_node", "pysmt/test/test_formula.py::TestFormulaManager::test_lt_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_max", "pysmt/test/test_formula.py::TestFormulaManager::test_min", "pysmt/test/test_formula.py::TestFormulaManager::test_minus_node", "pysmt/test/test_formula.py::TestFormulaManager::test_new_fresh_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_not_node", "pysmt/test/test_formula.py::TestFormulaManager::test_or_node", "pysmt/test/test_formula.py::TestFormulaManager::test_pickling", "pysmt/test/test_formula.py::TestFormulaManager::test_plus_node", "pysmt/test/test_formula.py::TestFormulaManager::test_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_times_node", "pysmt/test/test_formula.py::TestFormulaManager::test_toReal", "pysmt/test/test_formula.py::TestFormulaManager::test_typing", "pysmt/test/test_formula.py::TestFormulaManager::test_xor", "pysmt/test/test_formula.py::TestShortcuts::test_shortcut_is_using_global_env", "pysmt/test/test_regressions.py::TestRegressions::test_cnf_as_set", "pysmt/test/test_regressions.py::TestRegressions::test_dependencies_not_includes_toreal", "pysmt/test/test_regressions.py::TestRegressions::test_determinism", "pysmt/test/test_regressions.py::TestRegressions::test_empty_string_symbol", "pysmt/test/test_regressions.py::TestRegressions::test_exactlyone_w_generator", "pysmt/test/test_regressions.py::TestRegressions::test_infix_notation_wrong_le", "pysmt/test/test_regressions.py::TestRegressions::test_is_one", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_declaration_w_same_functiontype", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_exit", "pysmt/test/test_regressions.py::TestRegressions::test_qf_bool_smt2", "pysmt/test/test_regressions.py::TestRegressions::test_simplifying_int_plus_changes_type_of_expression", "pysmt/test/test_regressions.py::TestRegressions::test_smtlib_info_quoting", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_memoization", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_to_real" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2016-04-15 16:24:27+00:00
apache-2.0
5,034